title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
jQuery | submit() with Examples
21 Sep, 2018 The submit() method is an inbuilt method in jQuery which is used to submit event or the attaches a function to run when a submit event occurs. This method can only apply on the form elements.Syntax: $(selector).submit(parameters); Parameter: The parameters is optional for this method. Return Value: This method return the selected element along with the attached event. Program 1: jQuery code to show the working of the submit() method <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> // jQuery code to show the working of this method $(document).ready(function() { $("form").submit(function() { alert("Form submitted Successfully"); }); }); </script> <style> .gfg { font-size:40px; color:green; font-weight:bold; text-align:center; } .geeks { font-size:17px; text-align:center; margin-bottom:20px; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <form action = ""> <table border = 1 align = "center"> <tr> <!-- Enter Username --> <td>Username:</td> <td><input type = text name = name size = 25</td> </tr> <tr> <!-- Enter Password. --> <td>Password:</td> <td><input type = password name = password1 size = 25</td> </tr> <tr> <!-- To Confirm Password. --> <td>Confirm Password:</td> <td><input type = password name = password2 size = 25></td> </tr> <tr> <td colspan = 2 align = right> <input type = submit value = "Submit"></td> </tr> </table> </form> </body></html> Output: Program 2: <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> // jQuery code to show the working of this method $(document).ready(function() { $("form").submit(function() { alert("Form submitted Successfully"); }); $("button").click(function() { $("form").submit(); }); }); </script> <style> .gfg { font-size:40px; color:green; font-weight:bold; text-align:center; } .geeks { font-size:17px; text-align:center; margin-bottom:20px; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <form action = ""> <table border = 1 align = "center"> <tr> <!-- Enter Username --> <td>Username:</td> <td><input type = text name = name size = 25</td> </tr> <tr> <!-- Enter Password. --> <td>Password:</td> <td><input type = password name = password1 size = 25</td> </tr> <tr> <!-- To Confirm Password. --> <td>Confirm Password:</td> <td><input type = password name = password2 size = 25></td> </tr> <tr> <td colspan = 2 align = right> <button>Click me !</button> </tr> </table> </form> </body></html> Output: JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery jQuery | children() with Examples Scroll to the top of the page using JavaScript/jQuery How to get the value in an input text box using jQuery ? How to prevent Body from scrolling when a modal is opened using jQuery ? 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": "\n21 Sep, 2018" }, { "code": null, "e": 227, "s": 28, "text": "The submit() method is an inbuilt method in jQuery which is used to submit event or the attaches a function to run when a submit event occurs. This method can only apply on the form elements.Syntax:" }, { "code": null, "e": 259, "s": 227, "text": "$(selector).submit(parameters);" }, { "code": null, "e": 314, "s": 259, "text": "Parameter: The parameters is optional for this method." }, { "code": null, "e": 399, "s": 314, "text": "Return Value: This method return the selected element along with the attached event." }, { "code": null, "e": 465, "s": 399, "text": "Program 1: jQuery code to show the working of the submit() method" }, { "code": "<html> <head> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> // jQuery code to show the working of this method $(document).ready(function() { $(\"form\").submit(function() { alert(\"Form submitted Successfully\"); }); }); </script> <style> .gfg { font-size:40px; color:green; font-weight:bold; text-align:center; } .geeks { font-size:17px; text-align:center; margin-bottom:20px; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <form action = \"\"> <table border = 1 align = \"center\"> <tr> <!-- Enter Username --> <td>Username:</td> <td><input type = text name = name size = 25</td> </tr> <tr> <!-- Enter Password. --> <td>Password:</td> <td><input type = password name = password1 size = 25</td> </tr> <tr> <!-- To Confirm Password. --> <td>Confirm Password:</td> <td><input type = password name = password2 size = 25></td> </tr> <tr> <td colspan = 2 align = right> <input type = submit value = \"Submit\"></td> </tr> </table> </form> </body></html>", "e": 2137, "s": 465, "text": null }, { "code": null, "e": 2145, "s": 2137, "text": "Output:" }, { "code": null, "e": 2156, "s": 2145, "text": "Program 2:" }, { "code": "<html> <head> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> // jQuery code to show the working of this method $(document).ready(function() { $(\"form\").submit(function() { alert(\"Form submitted Successfully\"); }); $(\"button\").click(function() { $(\"form\").submit(); }); }); </script> <style> .gfg { font-size:40px; color:green; font-weight:bold; text-align:center; } .geeks { font-size:17px; text-align:center; margin-bottom:20px; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <form action = \"\"> <table border = 1 align = \"center\"> <tr> <!-- Enter Username --> <td>Username:</td> <td><input type = text name = name size = 25</td> </tr> <tr> <!-- Enter Password. --> <td>Password:</td> <td><input type = password name = password1 size = 25</td> </tr> <tr> <!-- To Confirm Password. --> <td>Confirm Password:</td> <td><input type = password name = password2 size = 25></td> </tr> <tr> <td colspan = 2 align = right> <button>Click me !</button> </tr> </table> </form> </body></html>", "e": 3916, "s": 2156, "text": null }, { "code": null, "e": 3924, "s": 3916, "text": "Output:" }, { "code": null, "e": 3931, "s": 3924, "text": "JQuery" }, { "code": null, "e": 3948, "s": 3931, "text": "Web Technologies" }, { "code": null, "e": 4046, "s": 3948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4075, "s": 4046, "text": "Form validation using jQuery" }, { "code": null, "e": 4109, "s": 4075, "text": "jQuery | children() with Examples" }, { "code": null, "e": 4163, "s": 4109, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 4220, "s": 4163, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 4293, "s": 4220, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 4355, "s": 4293, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4388, "s": 4355, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4449, "s": 4388, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4499, "s": 4449, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Program for sorting variables of any data type
27 Jan, 2018 Write a program for sorting variables of any datatype without the use of std::sort . Examples: Input : 2000, 456, -10, 0 Output : -10 0 456 2000 Input : "We do nothing" "Hi I have something" "Hello Join something!" "(Why to do work)" Output :(Why to do work) Hello Join something! Hi I have something We do nothing The examples above show, we can have any data type elements present as an input and output will be in a sorted form of the input data.The idea here to solve this problem is to make a template. Method 1 (Writing our own sort) In below code, we have implemented Bubble Sort to sort the array. // CPP program to sort array of any data types.#include <bits/stdc++.h>using namespace std; // Template formed so that sorting of any // type variable is possibletemplate <class T>void sortArray(T a[], int n){ // boolean variable to check that // whether it is sorted or not bool b = true; while (b) { b = false; for (size_t i=0; i<n-1; i++) { // swapping the variable // for sorting order if (a[i] > a[i + 1]) { T temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; b = true; } } }} // Template formed so that sorting of any // type variable is possibletemplate <class T>void printArray(T a[], int n){ for (size_t i = 0; i < n; ++i) cout << a[i] << " "; cout << endl;} // Driver codeint main(){ int n = 4; int intArr[n] = { 2000, 456, -10, 0 }; sortArray(intArr, n); printArray(intArr, n); string strArr[n] = { "We do nothing", "Hi I have something", "Hello Join something!", "(Why to do work)" }; sortArray(strArr, n); printArray(strArr, n); float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 }; sortArray(floatArr, n); printArray(floatArr, n); return 0;} -10 0 456 2000 (Why to do work) Hello Join something! Hi I have something We do nothing -9.7 11.17 11.4 23.4 Method 2 (Using Library Function)We can use std::sort in C++ to sort array of any data type. // CPP program to sort array of any data types.#include <bits/stdc++.h>using namespace std; // Template formed so that sorting of any // type variable is possibletemplate <class T>void printArray(T a[], int n){ for (size_t i = 0; i < n; ++i) cout << a[i] << " "; cout << endl;} // Driver codeint main(){ int n = 4; int intArr[n] = { 2000, 456, -10, 0 }; sort(intArr, intArr + n); printArray(intArr, n); string strArr[n] = { "We do nothing", "Hi I have something", "Hello Join something!", "(Why to do work)" }; sort(strArr, strArr + n); printArray(strArr, n); float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 }; sort(floatArr, floatArr+n); printArray(floatArr, n); return 0;} -10 0 456 2000 (Why to do work) Hello Join something! Hi I have something We do nothing -9.7 11.17 11.4 23.4 cpp-template Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Longest Common Prefix using Sorting Sort a nearly sorted (or K sorted) array Segregate 0s and 1s in an array Sorting in Java Find whether an array is subset of another array Quick Sort vs Merge Sort Stability in sorting algorithms Find all triplets with zero sum
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jan, 2018" }, { "code": null, "e": 139, "s": 54, "text": "Write a program for sorting variables of any datatype without the use of std::sort ." }, { "code": null, "e": 149, "s": 139, "text": "Examples:" }, { "code": null, "e": 443, "s": 149, "text": "Input : 2000, 456, -10, 0\nOutput : -10 0 456 2000 \n\nInput : \"We do nothing\"\n \"Hi I have something\"\n \"Hello Join something!\"\n \"(Why to do work)\"\nOutput :(Why to do work) \n Hello Join something!\n Hi I have something\n We do nothing \n" }, { "code": null, "e": 636, "s": 443, "text": "The examples above show, we can have any data type elements present as an input and output will be in a sorted form of the input data.The idea here to solve this problem is to make a template." }, { "code": null, "e": 734, "s": 636, "text": "Method 1 (Writing our own sort) In below code, we have implemented Bubble Sort to sort the array." }, { "code": "// CPP program to sort array of any data types.#include <bits/stdc++.h>using namespace std; // Template formed so that sorting of any // type variable is possibletemplate <class T>void sortArray(T a[], int n){ // boolean variable to check that // whether it is sorted or not bool b = true; while (b) { b = false; for (size_t i=0; i<n-1; i++) { // swapping the variable // for sorting order if (a[i] > a[i + 1]) { T temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; b = true; } } }} // Template formed so that sorting of any // type variable is possibletemplate <class T>void printArray(T a[], int n){ for (size_t i = 0; i < n; ++i) cout << a[i] << \" \"; cout << endl;} // Driver codeint main(){ int n = 4; int intArr[n] = { 2000, 456, -10, 0 }; sortArray(intArr, n); printArray(intArr, n); string strArr[n] = { \"We do nothing\", \"Hi I have something\", \"Hello Join something!\", \"(Why to do work)\" }; sortArray(strArr, n); printArray(strArr, n); float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 }; sortArray(floatArr, n); printArray(floatArr, n); return 0;}", "e": 2061, "s": 734, "text": null }, { "code": null, "e": 2195, "s": 2061, "text": "-10 0 456 2000 \n(Why to do work) Hello Join something! Hi I have something We do nothing \n-9.7 11.17 11.4 23.4\n" }, { "code": null, "e": 2288, "s": 2195, "text": "Method 2 (Using Library Function)We can use std::sort in C++ to sort array of any data type." }, { "code": "// CPP program to sort array of any data types.#include <bits/stdc++.h>using namespace std; // Template formed so that sorting of any // type variable is possibletemplate <class T>void printArray(T a[], int n){ for (size_t i = 0; i < n; ++i) cout << a[i] << \" \"; cout << endl;} // Driver codeint main(){ int n = 4; int intArr[n] = { 2000, 456, -10, 0 }; sort(intArr, intArr + n); printArray(intArr, n); string strArr[n] = { \"We do nothing\", \"Hi I have something\", \"Hello Join something!\", \"(Why to do work)\" }; sort(strArr, strArr + n); printArray(strArr, n); float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 }; sort(floatArr, floatArr+n); printArray(floatArr, n); return 0;}", "e": 3093, "s": 2288, "text": null }, { "code": null, "e": 3227, "s": 3093, "text": "-10 0 456 2000 \n(Why to do work) Hello Join something! Hi I have something We do nothing \n-9.7 11.17 11.4 23.4\n" }, { "code": null, "e": 3240, "s": 3227, "text": "cpp-template" }, { "code": null, "e": 3248, "s": 3240, "text": "Sorting" }, { "code": null, "e": 3256, "s": 3248, "text": "Sorting" }, { "code": null, "e": 3354, "s": 3256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3385, "s": 3354, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 3421, "s": 3385, "text": "Longest Common Prefix using Sorting" }, { "code": null, "e": 3462, "s": 3421, "text": "Sort a nearly sorted (or K sorted) array" }, { "code": null, "e": 3494, "s": 3462, "text": "Segregate 0s and 1s in an array" }, { "code": null, "e": 3510, "s": 3494, "text": "Sorting in Java" }, { "code": null, "e": 3559, "s": 3510, "text": "Find whether an array is subset of another array" }, { "code": null, "e": 3584, "s": 3559, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 3616, "s": 3584, "text": "Stability in sorting algorithms" } ]
Array Copy in Java
26 Oct, 2021 Given an array, we need to copy its elements in a different array, to a naive user below way comes into mind which is however incorrect as depicted below as follows: // Java Program to Illustrate Wrong Way Of Copying an Array // Input array int a[] = { 1, 8, 3 }; // Creating an array b[] of same size as a[] int b[] = new int[a.length]; // Doesn't copy elements of a[] to b[], only makes // b refer to same location b = a; Output: Output Explanation: When we do “b = a”, we are actually assigning a reference to the array. Hence, if we make any change to one array, it would be reflected in other arrays as well because both a and b refer to the same location. We can also verify it with code as shown below as follows: Example: Java // A Java program to demonstrate that simply// assigning one array reference is incorrectpublic class Test { public static void main(String[] args) { int a[] = { 1, 8, 3 }; // Create an array b[] of same size as a[] int b[] = new int[a.length]; // Doesn't copy elements of a[] to b[], // only makes b refer to same location b = a; // Change to b[] will also reflect in a[] // as 'a' and 'b' refer to same location. b[0]++; System.out.println("Contents of a[] "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println("\n\nContents of b[] "); for (int i = 0; i < b.length; i++) System.out.print(b[i] + " "); }} Contents of a[] 2 8 3 Contents of b[] 2 8 3 Methods: We have seen internal working while copying elements and edge cases to be taken into consideration after getting through errors as generated above, so now we can propose out correct ways to copy array as listed below as follows: Iterating each element of the given original array and copy one element at a timeUsing clone() methodUsing arraycopy() methodUsing copyOf() method of Arrays classUsing copyOfRange() method of Arrays class Iterating each element of the given original array and copy one element at a time Using clone() method Using arraycopy() method Using copyOf() method of Arrays class Using copyOfRange() method of Arrays class Method 1: Iterating each element of the given original array and copy one element at a time. With the usage of this method, it guarantees that any modifications to b, will not alter the original array a, as shown in below example as follows: Example: Java // Java program to demonstrate copying by// one by one assigning elements between arrays // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input array a[] int a[] = { 1, 8, 3 }; // Create an array b[] of same size as a[] int b[] = new int[a.length]; // Copying elements of a[] to b[] for (int i = 0; i < a.length; i++) b[i] = a[i]; // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message only System.out.println("Contents of a[] "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); // Display message only System.out.println("\n\nContents of b[] "); for (int i = 0; i < b.length; i++) System.out.print(b[i] + " "); }} Contents of a[] 1 8 3 Contents of b[] 2 8 3 Method 2: Using Clone() method In the previous method we had to iterate over the entire array to make a copy, can we do better? Yes, we can use the clone method in Java. Example: Java // Java program to demonstrate Copying of Array// using clone() method // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input array a[] int a[] = { 1, 8, 3 }; // Copying elements of a[] to b[] int b[] = a.clone(); // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message for better readability System.out.println("Contents of a[] "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); // Display message for better readability System.out.println("\n\nContents of b[] "); for (int i = 0; i < b.length; i++) System.out.print(b[i] + " "); }} Contents of a[] 1 8 3 Contents of b[] 2 8 3 Method 3: Using arraycopy() method We can also use System.arraycopy() Method. The system is present in java.lang package. Its signature is as : public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) Parameters: src denotes the source array. srcPos is the index from which copying starts. dest denotes the destination array destPos is the index from which the copied elements are placed in the destination array. length is the length of the subarray to be copied. Example: Java // Java program to demonstrate array// copy using System.arraycopy() // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array int a[] = { 1, 8, 3 }; // Creating an array b[] of same size as a[] int b[] = new int[a.length]; // Copying elements of a[] to b[] System.arraycopy(a, 0, b, 0, 3); // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message only System.out.println("Contents of a[] "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); // Display message only System.out.println("\n\nContents of b[] "); for (int i = 0; i < b.length; i++) System.out.print(b[i] + " "); }} Contents of a[] 1 8 3 Contents of b[] 2 8 3 Method 4: Using copyOf() method of Arrays class If we want to copy the first few elements of an array or a full copy of the array, you can use this method. Syntax: public static int[] copyOf​(int[] original, int newLength) Parameters: Original array Length of the array to get copied. Example: Java // Java program to demonstrate array// copy using Arrays.copyOf() // Importing Arrays class from utility classimport java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom input array int a[] = { 1, 8, 3 }; // Create an array b[] of same size as a[] // Copy elements of a[] to b[] int b[] = Arrays.copyOf(a, 3); // Change b[] to verify that // b[] is different from a[] b[0]++; System.out.println("Contents of a[] "); // Iterating over array. a[] for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println("\n\nContents of b[] "); // Iterating over array b[] for (int i = 0; i < b.length; i++) System.out.print(b[i] + " "); }} Contents of a[] 1 8 3 Contents of b[] 2 8 3 Method 5: Using copyOfRange() method of Arrays class This method copies the specified range of the specified array into a new array. public static int[] copyOfRange​(int[] original, int from, int to) Parameters: Original array from which a range is to be copied Initial index of the range to be copied Final index of the range to be copied, exclusive Example: Java // Java program to demonstrate array// copy using Arrays.copyOfRange() // Importing Arrays class from utility packageimport java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom input array int a[] = { 1, 8, 3, 5, 9, 10 }; // Creating an array b[] and // copying elements of a[] to b[] int b[] = Arrays.copyOfRange(a, 2, 6); // Changing b[] to verify that // b[] is different from a[] // Iterating over array a[] System.out.println("Contents of a[] "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); // Iterating over array b[] System.out.println("\n\nContents of b[] "); for (int i = 0; i < b.length; i++) System.out.print(b[i] + " "); }} Contents of a[] 1 8 3 5 9 10 Contents of b[] 3 5 9 10 Lastly, let us do discuss the overview of the above methods: Simply assigning references is wrong The array can be copied by iterating over an array, and one by one assigning elements. We can avoid iteration over elements using clone() or System.arraycopy() clone() creates a new array of the same size, but System.arraycopy() can be used to copy from a source range to a destination range. System.arraycopy() is faster than clone() as it uses Java Native Interface If you want to copy the first few elements of an array or a full copy of an array, you can use Arrays.copyOf() method. Arrays.copyOfRange() is used to copy a specified range of an array. If the starting index is not 0, you can use this method to copy a partial array. This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. se_prashant solankimayank adnanirshad158 Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Oct, 2021" }, { "code": null, "e": 218, "s": 52, "text": "Given an array, we need to copy its elements in a different array, to a naive user below way comes into mind which is however incorrect as depicted below as follows:" }, { "code": null, "e": 479, "s": 218, "text": "// Java Program to Illustrate Wrong Way Of Copying an Array\n\n// Input array\nint a[] = { 1, 8, 3 };\n\n// Creating an array b[] of same size as a[]\nint b[] = new int[a.length];\n\n// Doesn't copy elements of a[] to b[], only makes\n// b refer to same location\nb = a;" }, { "code": null, "e": 488, "s": 479, "text": "Output: " }, { "code": null, "e": 777, "s": 488, "text": "Output Explanation: When we do “b = a”, we are actually assigning a reference to the array. Hence, if we make any change to one array, it would be reflected in other arrays as well because both a and b refer to the same location. We can also verify it with code as shown below as follows:" }, { "code": null, "e": 786, "s": 777, "text": "Example:" }, { "code": null, "e": 791, "s": 786, "text": "Java" }, { "code": "// A Java program to demonstrate that simply// assigning one array reference is incorrectpublic class Test { public static void main(String[] args) { int a[] = { 1, 8, 3 }; // Create an array b[] of same size as a[] int b[] = new int[a.length]; // Doesn't copy elements of a[] to b[], // only makes b refer to same location b = a; // Change to b[] will also reflect in a[] // as 'a' and 'b' refer to same location. b[0]++; System.out.println(\"Contents of a[] \"); for (int i = 0; i < a.length; i++) System.out.print(a[i] + \" \"); System.out.println(\"\\n\\nContents of b[] \"); for (int i = 0; i < b.length; i++) System.out.print(b[i] + \" \"); }}", "e": 1558, "s": 791, "text": null }, { "code": null, "e": 1607, "s": 1558, "text": "Contents of a[] \n2 8 3 \n\nContents of b[] \n2 8 3 " }, { "code": null, "e": 1616, "s": 1607, "text": "Methods:" }, { "code": null, "e": 1845, "s": 1616, "text": "We have seen internal working while copying elements and edge cases to be taken into consideration after getting through errors as generated above, so now we can propose out correct ways to copy array as listed below as follows:" }, { "code": null, "e": 2050, "s": 1845, "text": "Iterating each element of the given original array and copy one element at a timeUsing clone() methodUsing arraycopy() methodUsing copyOf() method of Arrays classUsing copyOfRange() method of Arrays class" }, { "code": null, "e": 2132, "s": 2050, "text": "Iterating each element of the given original array and copy one element at a time" }, { "code": null, "e": 2153, "s": 2132, "text": "Using clone() method" }, { "code": null, "e": 2178, "s": 2153, "text": "Using arraycopy() method" }, { "code": null, "e": 2216, "s": 2178, "text": "Using copyOf() method of Arrays class" }, { "code": null, "e": 2259, "s": 2216, "text": "Using copyOfRange() method of Arrays class" }, { "code": null, "e": 2501, "s": 2259, "text": "Method 1: Iterating each element of the given original array and copy one element at a time. With the usage of this method, it guarantees that any modifications to b, will not alter the original array a, as shown in below example as follows:" }, { "code": null, "e": 2510, "s": 2501, "text": "Example:" }, { "code": null, "e": 2515, "s": 2510, "text": "Java" }, { "code": "// Java program to demonstrate copying by// one by one assigning elements between arrays // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input array a[] int a[] = { 1, 8, 3 }; // Create an array b[] of same size as a[] int b[] = new int[a.length]; // Copying elements of a[] to b[] for (int i = 0; i < a.length; i++) b[i] = a[i]; // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message only System.out.println(\"Contents of a[] \"); for (int i = 0; i < a.length; i++) System.out.print(a[i] + \" \"); // Display message only System.out.println(\"\\n\\nContents of b[] \"); for (int i = 0; i < b.length; i++) System.out.print(b[i] + \" \"); }}", "e": 3386, "s": 2515, "text": null }, { "code": null, "e": 3435, "s": 3386, "text": "Contents of a[] \n1 8 3 \n\nContents of b[] \n2 8 3 " }, { "code": null, "e": 3467, "s": 3435, "text": "Method 2: Using Clone() method " }, { "code": null, "e": 3607, "s": 3467, "text": "In the previous method we had to iterate over the entire array to make a copy, can we do better? Yes, we can use the clone method in Java. " }, { "code": null, "e": 3616, "s": 3607, "text": "Example:" }, { "code": null, "e": 3621, "s": 3616, "text": "Java" }, { "code": "// Java program to demonstrate Copying of Array// using clone() method // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input array a[] int a[] = { 1, 8, 3 }; // Copying elements of a[] to b[] int b[] = a.clone(); // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message for better readability System.out.println(\"Contents of a[] \"); for (int i = 0; i < a.length; i++) System.out.print(a[i] + \" \"); // Display message for better readability System.out.println(\"\\n\\nContents of b[] \"); for (int i = 0; i < b.length; i++) System.out.print(b[i] + \" \"); }}", "e": 4385, "s": 3621, "text": null }, { "code": null, "e": 4434, "s": 4385, "text": "Contents of a[] \n1 8 3 \n\nContents of b[] \n2 8 3 " }, { "code": null, "e": 4469, "s": 4434, "text": "Method 3: Using arraycopy() method" }, { "code": null, "e": 4579, "s": 4469, "text": "We can also use System.arraycopy() Method. The system is present in java.lang package. Its signature is as : " }, { "code": null, "e": 4700, "s": 4579, "text": "public static void arraycopy(Object src, int srcPos, Object dest, \n int destPos, int length)" }, { "code": null, "e": 4712, "s": 4700, "text": "Parameters:" }, { "code": null, "e": 4742, "s": 4712, "text": "src denotes the source array." }, { "code": null, "e": 4789, "s": 4742, "text": "srcPos is the index from which copying starts." }, { "code": null, "e": 4824, "s": 4789, "text": "dest denotes the destination array" }, { "code": null, "e": 4913, "s": 4824, "text": "destPos is the index from which the copied elements are placed in the destination array." }, { "code": null, "e": 4964, "s": 4913, "text": "length is the length of the subarray to be copied." }, { "code": null, "e": 4973, "s": 4964, "text": "Example:" }, { "code": null, "e": 4978, "s": 4973, "text": "Java" }, { "code": "// Java program to demonstrate array// copy using System.arraycopy() // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array int a[] = { 1, 8, 3 }; // Creating an array b[] of same size as a[] int b[] = new int[a.length]; // Copying elements of a[] to b[] System.arraycopy(a, 0, b, 0, 3); // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message only System.out.println(\"Contents of a[] \"); for (int i = 0; i < a.length; i++) System.out.print(a[i] + \" \"); // Display message only System.out.println(\"\\n\\nContents of b[] \"); for (int i = 0; i < b.length; i++) System.out.print(b[i] + \" \"); }}", "e": 5808, "s": 4978, "text": null }, { "code": null, "e": 5857, "s": 5808, "text": "Contents of a[] \n1 8 3 \n\nContents of b[] \n2 8 3 " }, { "code": null, "e": 5906, "s": 5857, "text": "Method 4: Using copyOf() method of Arrays class " }, { "code": null, "e": 6014, "s": 5906, "text": "If we want to copy the first few elements of an array or a full copy of the array, you can use this method." }, { "code": null, "e": 6023, "s": 6014, "text": "Syntax: " }, { "code": null, "e": 6083, "s": 6023, "text": "public static int[] copyOf​(int[] original, int newLength) " }, { "code": null, "e": 6095, "s": 6083, "text": "Parameters:" }, { "code": null, "e": 6110, "s": 6095, "text": "Original array" }, { "code": null, "e": 6145, "s": 6110, "text": "Length of the array to get copied." }, { "code": null, "e": 6154, "s": 6145, "text": "Example:" }, { "code": null, "e": 6159, "s": 6154, "text": "Java" }, { "code": "// Java program to demonstrate array// copy using Arrays.copyOf() // Importing Arrays class from utility classimport java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom input array int a[] = { 1, 8, 3 }; // Create an array b[] of same size as a[] // Copy elements of a[] to b[] int b[] = Arrays.copyOf(a, 3); // Change b[] to verify that // b[] is different from a[] b[0]++; System.out.println(\"Contents of a[] \"); // Iterating over array. a[] for (int i = 0; i < a.length; i++) System.out.print(a[i] + \" \"); System.out.println(\"\\n\\nContents of b[] \"); // Iterating over array b[] for (int i = 0; i < b.length; i++) System.out.print(b[i] + \" \"); }}", "e": 7011, "s": 6159, "text": null }, { "code": null, "e": 7060, "s": 7011, "text": "Contents of a[] \n1 8 3 \n\nContents of b[] \n2 8 3 " }, { "code": null, "e": 7113, "s": 7060, "text": "Method 5: Using copyOfRange() method of Arrays class" }, { "code": null, "e": 7193, "s": 7113, "text": "This method copies the specified range of the specified array into a new array." }, { "code": null, "e": 7260, "s": 7193, "text": "public static int[] copyOfRange​(int[] original, int from, int to)" }, { "code": null, "e": 7272, "s": 7260, "text": "Parameters:" }, { "code": null, "e": 7322, "s": 7272, "text": "Original array from which a range is to be copied" }, { "code": null, "e": 7362, "s": 7322, "text": "Initial index of the range to be copied" }, { "code": null, "e": 7411, "s": 7362, "text": "Final index of the range to be copied, exclusive" }, { "code": null, "e": 7420, "s": 7411, "text": "Example:" }, { "code": null, "e": 7425, "s": 7420, "text": "Java" }, { "code": "// Java program to demonstrate array// copy using Arrays.copyOfRange() // Importing Arrays class from utility packageimport java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom input array int a[] = { 1, 8, 3, 5, 9, 10 }; // Creating an array b[] and // copying elements of a[] to b[] int b[] = Arrays.copyOfRange(a, 2, 6); // Changing b[] to verify that // b[] is different from a[] // Iterating over array a[] System.out.println(\"Contents of a[] \"); for (int i = 0; i < a.length; i++) System.out.print(a[i] + \" \"); // Iterating over array b[] System.out.println(\"\\n\\nContents of b[] \"); for (int i = 0; i < b.length; i++) System.out.print(b[i] + \" \"); }}", "e": 8275, "s": 7425, "text": null }, { "code": null, "e": 8334, "s": 8275, "text": "Contents of a[] \n1 8 3 5 9 10 \n\nContents of b[] \n3 5 9 10 " }, { "code": null, "e": 8396, "s": 8334, "text": "Lastly, let us do discuss the overview of the above methods: " }, { "code": null, "e": 8433, "s": 8396, "text": "Simply assigning references is wrong" }, { "code": null, "e": 8520, "s": 8433, "text": "The array can be copied by iterating over an array, and one by one assigning elements." }, { "code": null, "e": 8593, "s": 8520, "text": "We can avoid iteration over elements using clone() or System.arraycopy()" }, { "code": null, "e": 8726, "s": 8593, "text": "clone() creates a new array of the same size, but System.arraycopy() can be used to copy from a source range to a destination range." }, { "code": null, "e": 8801, "s": 8726, "text": "System.arraycopy() is faster than clone() as it uses Java Native Interface" }, { "code": null, "e": 8920, "s": 8801, "text": "If you want to copy the first few elements of an array or a full copy of an array, you can use Arrays.copyOf() method." }, { "code": null, "e": 9069, "s": 8920, "text": "Arrays.copyOfRange() is used to copy a specified range of an array. If the starting index is not 0, you can use this method to copy a partial array." }, { "code": null, "e": 9241, "s": 9069, "text": "This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9253, "s": 9241, "text": "se_prashant" }, { "code": null, "e": 9267, "s": 9253, "text": "solankimayank" }, { "code": null, "e": 9282, "s": 9267, "text": "adnanirshad158" }, { "code": null, "e": 9294, "s": 9282, "text": "Java-Arrays" }, { "code": null, "e": 9299, "s": 9294, "text": "Java" }, { "code": null, "e": 9304, "s": 9299, "text": "Java" } ]
HTML applet Tag
27 Apr, 2021 The <applet> tag in HTML was used to embed Java applets into any HTML document. The <applet> tag was deprecated in HTML 4.01, and it’s support has been completely discontinued starting from HTML 5. Alternatives available in HTML 5 are the <embed> and the <object> tags. There are still some browsers that support the <applet> tag with the help of some additional plug-ins/installations to work. Internet Explorer 11 and earlier versions with the help of plug-ins.Applet Tag is not supported in HTML5. The <applet> tag takes a number of attributes, with one of the most important being the code attribute. This code attribute is used to link a Java applet to the concerned HTML document. It specifies the file name of the Java applet. Attributes: This tag accepts the following attributes: align: Specifies the alignment of an applet. alt: Specifies an alternate text for an applet. archive: Specifies the location of an archive file. border: Specifies the border around the applet panel. codebase: Specifies a relative base URL for applets specified in the code attribute. height: Specifies the height of an applet. hspace: Defines the horizontal spacing around an applet. mayscript: Indicates whether the Java applet is allowed to access the scripting objects of the web page. name: Defines the name for an applet (to use in scripts) vspace: Defines the vertical spacing around an applet. width: Specifies the width of an applet. Syntax: <applet attribute1 attribute2....> <param parameter1> <param parameter2> .... </applet> The following Examples explain the applet tag: Example 1: Here, HelloWorld is the class file, which contains the applet. The width and height attributes determine the width and height of the applet in pixels when it is opened in the browser. Attributes available to be used in conjunction with the <applet> tag are as follows: HTML <!DOCTYPE html><html><!-- applet code starts here --> <applet code="HelloWorld"><!-- applet code ends here --> </applet></html> Parameters: Parameters are quite similar to command-line arguments in the sense that they provide a way to pass information to the applet after it has started. All the information available to the applet before it starts is said to be hard-coded i.e. embedded within it. Parameters make it possible to generate and use data during run-time of the applet. Syntax: <param name=parameter_name value=parameter_value> The name assigned to the name attribute of the param tag is used by the applet code as a variable to access the parameter value specified in the value attribute. In this way, the applet is able to interact with the HTML page where it is embedded, and can work on values provided to it by the page during run-time. Example 2: In this piece of code, the applet file HelloWorld can use the variable named message to access the value stored in it, which is “HelloWorld”. HTML <!DOCTYPE html><html><!-- applet code starts here --><applet code="HelloWorld"> <param name="message" value="HelloWorld"><!-- applet code ends here --></applet> </html> Supported Browsers: Firefox Safari nidhi_biet shubhamyadav4 HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2021" }, { "code": null, "e": 762, "s": 28, "text": "The <applet> tag in HTML was used to embed Java applets into any HTML document. The <applet> tag was deprecated in HTML 4.01, and it’s support has been completely discontinued starting from HTML 5. Alternatives available in HTML 5 are the <embed> and the <object> tags. There are still some browsers that support the <applet> tag with the help of some additional plug-ins/installations to work. Internet Explorer 11 and earlier versions with the help of plug-ins.Applet Tag is not supported in HTML5. The <applet> tag takes a number of attributes, with one of the most important being the code attribute. This code attribute is used to link a Java applet to the concerned HTML document. It specifies the file name of the Java applet." }, { "code": null, "e": 817, "s": 762, "text": "Attributes: This tag accepts the following attributes:" }, { "code": null, "e": 862, "s": 817, "text": "align: Specifies the alignment of an applet." }, { "code": null, "e": 910, "s": 862, "text": "alt: Specifies an alternate text for an applet." }, { "code": null, "e": 962, "s": 910, "text": "archive: Specifies the location of an archive file." }, { "code": null, "e": 1016, "s": 962, "text": "border: Specifies the border around the applet panel." }, { "code": null, "e": 1101, "s": 1016, "text": "codebase: Specifies a relative base URL for applets specified in the code attribute." }, { "code": null, "e": 1144, "s": 1101, "text": "height: Specifies the height of an applet." }, { "code": null, "e": 1201, "s": 1144, "text": "hspace: Defines the horizontal spacing around an applet." }, { "code": null, "e": 1306, "s": 1201, "text": "mayscript: Indicates whether the Java applet is allowed to access the scripting objects of the web page." }, { "code": null, "e": 1363, "s": 1306, "text": "name: Defines the name for an applet (to use in scripts)" }, { "code": null, "e": 1418, "s": 1363, "text": "vspace: Defines the vertical spacing around an applet." }, { "code": null, "e": 1460, "s": 1418, "text": "width: Specifies the width of an applet. " }, { "code": null, "e": 1470, "s": 1460, "text": "Syntax: " }, { "code": null, "e": 1567, "s": 1470, "text": "<applet attribute1 attribute2....>\n <param parameter1>\n <param parameter2>\n ....\n</applet>" }, { "code": null, "e": 1615, "s": 1567, "text": "The following Examples explain the applet tag: " }, { "code": null, "e": 1895, "s": 1615, "text": "Example 1: Here, HelloWorld is the class file, which contains the applet. The width and height attributes determine the width and height of the applet in pixels when it is opened in the browser. Attributes available to be used in conjunction with the <applet> tag are as follows:" }, { "code": null, "e": 1900, "s": 1895, "text": "HTML" }, { "code": "<!DOCTYPE html><html><!-- applet code starts here --> <applet code=\"HelloWorld\"><!-- applet code ends here --> </applet></html> ", "e": 2068, "s": 1900, "text": null }, { "code": null, "e": 2424, "s": 2068, "text": "Parameters: Parameters are quite similar to command-line arguments in the sense that they provide a way to pass information to the applet after it has started. All the information available to the applet before it starts is said to be hard-coded i.e. embedded within it. Parameters make it possible to generate and use data during run-time of the applet. " }, { "code": null, "e": 2434, "s": 2424, "text": "Syntax: " }, { "code": null, "e": 2484, "s": 2434, "text": "<param name=parameter_name value=parameter_value>" }, { "code": null, "e": 2799, "s": 2484, "text": "The name assigned to the name attribute of the param tag is used by the applet code as a variable to access the parameter value specified in the value attribute. In this way, the applet is able to interact with the HTML page where it is embedded, and can work on values provided to it by the page during run-time. " }, { "code": null, "e": 2952, "s": 2799, "text": "Example 2: In this piece of code, the applet file HelloWorld can use the variable named message to access the value stored in it, which is “HelloWorld”." }, { "code": null, "e": 2957, "s": 2952, "text": "HTML" }, { "code": "<!DOCTYPE html><html><!-- applet code starts here --><applet code=\"HelloWorld\"> <param name=\"message\" value=\"HelloWorld\"><!-- applet code ends here --></applet> </html>", "e": 3129, "s": 2957, "text": null }, { "code": null, "e": 3152, "s": 3131, "text": "Supported Browsers: " }, { "code": null, "e": 3160, "s": 3152, "text": "Firefox" }, { "code": null, "e": 3167, "s": 3160, "text": "Safari" }, { "code": null, "e": 3178, "s": 3167, "text": "nidhi_biet" }, { "code": null, "e": 3192, "s": 3178, "text": "shubhamyadav4" }, { "code": null, "e": 3202, "s": 3192, "text": "HTML-Tags" }, { "code": null, "e": 3209, "s": 3202, "text": "Picked" }, { "code": null, "e": 3214, "s": 3209, "text": "HTML" }, { "code": null, "e": 3231, "s": 3214, "text": "Web Technologies" }, { "code": null, "e": 3236, "s": 3231, "text": "HTML" } ]
ML – Nearest Centroid Classifier
01 Jun, 2021 The Nearest Centroid (NC) Classifier is one of the most underrated and underutilised classifiers in Machine Learning. However, it is quite powerful and is highly efficient for certain Machine Learning classification tasks. The Nearest Centroid classifier is somewhat similar to the K-Nearest Neighbours classifier. To know more about the K-Nearest Neighbours (KNN) classifier, you can refer to the link below : K-Nearest-Neighbours/ An often-overlooked principle in Machine Learning is to build simple algorithms off of simple, yet meaningful data, that can do specific tasks efficiently, instead of using complex models. This is also called the principle of sufficiency in statistics. The Nearest Centroid classifier is arguably the simplest Classification algorithm in Machine Learning. The Nearest Centroid classifier works on a simple principle : Given a data point (observation), the Nearest Centroid classifier simply assign it the label (class) of the training sample whose mean or centroid is closest to it. When applied on text classification, the Nearest Centroid classifier is also called the Rochhio classifier. The scikit-learn library in Python offers a simple function to implement the Nearest Centroid Classifier. How the nearest centroid classifier works? Basically, what the nearest centroid classifier does can be explained in three steps: The centroid for each target class is computed while training. After training, given any point, say ‘X’. The distances between the point X and each class’ centroid is calculated. Out of all the calculated distances, the minimum distance is picked. The centroid to which the given point’s distance is minimum, it’s class is assigned to the given point. The Nearest Centroid Classifier is quite easy to understand and is one of the simplest classifier algorithms. Implementation of Nearest Centroid Classifier in Python: For this example, we will be using the popular ‘iris’ dataset that is available in the scikit-learn library. After training the classifier, we will print the accuracy of the classifier on the training and test sets. Then, we print the classifier report. Code: Python code implementing NearestCentroid classifier python3 # Importing the required librariesfrom sklearn.neighbors import NearestCentroidfrom sklearn.datasets import load_irisfrom sklearn.metrics import classification_reportfrom sklearn.model_selection import train_test_splitimport pandas as pd # Loading the datasetdataset = load_iris() # Separating data and target labelsX = pd.DataFrame(dataset.data)y = pd.DataFrame(dataset.target) # Splitting training and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, shuffle = True, random_state = 0) # Creating the Nearest Centroid Classifiermodel = NearestCentroid() # Training the classifiermodel.fit(X_train, y_train.values.ravel()) # Printing Accuracy on Training and Test setsprint(f"Training Set Score : {model.score(X_train, y_train) * 100} %")print(f"Test Set Score : {model.score(X_test, y_test) * 100} %") # Printing classification report of classifier on the test set set dataprint(f"Model Classification Report : \n{classification_report(y_test, model.predict(X_test))}") Output: Training Set Score : 94.16666666666667 % Test Set Score : 90.0 % Model Classification Report : precision recall f1-score support 0 1.00 1.00 1.00 11 1 0.86 0.92 0.89 13 2 0.80 0.67 0.73 6 accuracy 0.90 30 macro avg 0.89 0.86 0.87 30 weighted avg 0.90 0.90 0.90 30 So, we have managed to achieve an accuracy of 94.17% and 90% on the training and test sets respectively. Conclusion: Now that you know what a Nearest Centroid Classifier is and how to implement it, you should try using it next time when you have some simple classification tasks that require a light-weight and simple classifier. simmytarika5 saurabh1990aror Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2021" }, { "code": null, "e": 1413, "s": 52, "text": "The Nearest Centroid (NC) Classifier is one of the most underrated and underutilised classifiers in Machine Learning. However, it is quite powerful and is highly efficient for certain Machine Learning classification tasks. The Nearest Centroid classifier is somewhat similar to the K-Nearest Neighbours classifier. To know more about the K-Nearest Neighbours (KNN) classifier, you can refer to the link below : K-Nearest-Neighbours/ An often-overlooked principle in Machine Learning is to build simple algorithms off of simple, yet meaningful data, that can do specific tasks efficiently, instead of using complex models. This is also called the principle of sufficiency in statistics. The Nearest Centroid classifier is arguably the simplest Classification algorithm in Machine Learning. The Nearest Centroid classifier works on a simple principle : Given a data point (observation), the Nearest Centroid classifier simply assign it the label (class) of the training sample whose mean or centroid is closest to it. When applied on text classification, the Nearest Centroid classifier is also called the Rochhio classifier. The scikit-learn library in Python offers a simple function to implement the Nearest Centroid Classifier. How the nearest centroid classifier works? Basically, what the nearest centroid classifier does can be explained in three steps: " }, { "code": null, "e": 1476, "s": 1413, "text": "The centroid for each target class is computed while training." }, { "code": null, "e": 1592, "s": 1476, "text": "After training, given any point, say ‘X’. The distances between the point X and each class’ centroid is calculated." }, { "code": null, "e": 1765, "s": 1592, "text": "Out of all the calculated distances, the minimum distance is picked. The centroid to which the given point’s distance is minimum, it’s class is assigned to the given point." }, { "code": null, "e": 2246, "s": 1765, "text": "The Nearest Centroid Classifier is quite easy to understand and is one of the simplest classifier algorithms. Implementation of Nearest Centroid Classifier in Python: For this example, we will be using the popular ‘iris’ dataset that is available in the scikit-learn library. After training the classifier, we will print the accuracy of the classifier on the training and test sets. Then, we print the classifier report. Code: Python code implementing NearestCentroid classifier " }, { "code": null, "e": 2254, "s": 2246, "text": "python3" }, { "code": "# Importing the required librariesfrom sklearn.neighbors import NearestCentroidfrom sklearn.datasets import load_irisfrom sklearn.metrics import classification_reportfrom sklearn.model_selection import train_test_splitimport pandas as pd # Loading the datasetdataset = load_iris() # Separating data and target labelsX = pd.DataFrame(dataset.data)y = pd.DataFrame(dataset.target) # Splitting training and test dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, shuffle = True, random_state = 0) # Creating the Nearest Centroid Classifiermodel = NearestCentroid() # Training the classifiermodel.fit(X_train, y_train.values.ravel()) # Printing Accuracy on Training and Test setsprint(f\"Training Set Score : {model.score(X_train, y_train) * 100} %\")print(f\"Test Set Score : {model.score(X_test, y_test) * 100} %\") # Printing classification report of classifier on the test set set dataprint(f\"Model Classification Report : \\n{classification_report(y_test, model.predict(X_test))}\")", "e": 3260, "s": 2254, "text": null }, { "code": null, "e": 3270, "s": 3260, "text": "Output: " }, { "code": null, "e": 3746, "s": 3270, "text": "Training Set Score : 94.16666666666667 %\nTest Set Score : 90.0 %\nModel Classification Report : \n precision recall f1-score support\n\n 0 1.00 1.00 1.00 11\n 1 0.86 0.92 0.89 13\n 2 0.80 0.67 0.73 6\n\n accuracy 0.90 30\n macro avg 0.89 0.86 0.87 30\nweighted avg 0.90 0.90 0.90 30" }, { "code": null, "e": 4078, "s": 3746, "text": "So, we have managed to achieve an accuracy of 94.17% and 90% on the training and test sets respectively. Conclusion: Now that you know what a Nearest Centroid Classifier is and how to implement it, you should try using it next time when you have some simple classification tasks that require a light-weight and simple classifier. " }, { "code": null, "e": 4091, "s": 4078, "text": "simmytarika5" }, { "code": null, "e": 4107, "s": 4091, "text": "saurabh1990aror" }, { "code": null, "e": 4124, "s": 4107, "text": "Machine Learning" }, { "code": null, "e": 4131, "s": 4124, "text": "Python" }, { "code": null, "e": 4148, "s": 4131, "text": "Machine Learning" } ]
vector capacity() function in C++ STL
09 Jun, 2022 The vector::capacity() function is a built-in function which returns the size of the storage space currently allocated for the vector, expressed in terms of elements. This capacity is not necessarily equal to the vector size. It can be equal to or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion. The capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size. Syntax: vector_name.capacity() Parameters: The function does not accept any parameters. Return Value: The function returns the size of the storage space currently allocated for the vector, expressed in terms of elements. Time Complexity – Constant O(1) Below programs illustrate the above functions: Program 1: CPP // C++ program to illustrate the// vector::capacity() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; // inserts elements for (int i = 0; i < 10; i++) { v.push_back(i * 10); } cout << "The size of vector is " << v.size(); cout << "\nThe maximum capacity is " << v.capacity(); return 0;} The size of vector is 10 The maximum capacity is 16 Program 2: CPP // C++ program to illustrate the// vector::capacity() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; // inserts elements for (int i = 0; i < 100; i++) { v.push_back(i * 10); } cout << "The size of vector is " << v.size(); cout << "\nThe maximum capacity is " << v.capacity(); return 0;} The size of vector is 100 The maximum capacity is 128 utkarshgupta110092 CPP-Functions cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Writing First C++ Program - Hello World Example Functions that cannot be overloaded in C++ Basic Input / Output in C++ C++ Data Types unordered_map in C++ STL vector erase() and clear() in C++ Polymorphism in C++ Switch Statement in C/C++ Set in C++ Standard Template Library (STL)
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Jun, 2022" }, { "code": null, "e": 696, "s": 53, "text": "The vector::capacity() function is a built-in function which returns the size of the storage space currently allocated for the vector, expressed in terms of elements. This capacity is not necessarily equal to the vector size. It can be equal to or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion. The capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size. Syntax: " }, { "code": null, "e": 719, "s": 696, "text": "vector_name.capacity()" }, { "code": null, "e": 910, "s": 719, "text": "Parameters: The function does not accept any parameters. Return Value: The function returns the size of the storage space currently allocated for the vector, expressed in terms of elements. " }, { "code": null, "e": 942, "s": 910, "text": "Time Complexity – Constant O(1)" }, { "code": null, "e": 1001, "s": 942, "text": "Below programs illustrate the above functions: Program 1: " }, { "code": null, "e": 1005, "s": 1001, "text": "CPP" }, { "code": "// C++ program to illustrate the// vector::capacity() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; // inserts elements for (int i = 0; i < 10; i++) { v.push_back(i * 10); } cout << \"The size of vector is \" << v.size(); cout << \"\\nThe maximum capacity is \" << v.capacity(); return 0;}", "e": 1354, "s": 1005, "text": null }, { "code": null, "e": 1406, "s": 1354, "text": "The size of vector is 10\nThe maximum capacity is 16" }, { "code": null, "e": 1418, "s": 1406, "text": "Program 2: " }, { "code": null, "e": 1422, "s": 1418, "text": "CPP" }, { "code": "// C++ program to illustrate the// vector::capacity() function#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v; // inserts elements for (int i = 0; i < 100; i++) { v.push_back(i * 10); } cout << \"The size of vector is \" << v.size(); cout << \"\\nThe maximum capacity is \" << v.capacity(); return 0;}", "e": 1772, "s": 1422, "text": null }, { "code": null, "e": 1826, "s": 1772, "text": "The size of vector is 100\nThe maximum capacity is 128" }, { "code": null, "e": 1845, "s": 1826, "text": "utkarshgupta110092" }, { "code": null, "e": 1859, "s": 1845, "text": "CPP-Functions" }, { "code": null, "e": 1870, "s": 1859, "text": "cpp-vector" }, { "code": null, "e": 1874, "s": 1870, "text": "STL" }, { "code": null, "e": 1878, "s": 1874, "text": "C++" }, { "code": null, "e": 1882, "s": 1878, "text": "STL" }, { "code": null, "e": 1886, "s": 1882, "text": "CPP" }, { "code": null, "e": 1984, "s": 1886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2008, "s": 1984, "text": "C++ Classes and Objects" }, { "code": null, "e": 2056, "s": 2008, "text": "Writing First C++ Program - Hello World Example" }, { "code": null, "e": 2099, "s": 2056, "text": "Functions that cannot be overloaded in C++" }, { "code": null, "e": 2127, "s": 2099, "text": "Basic Input / Output in C++" }, { "code": null, "e": 2142, "s": 2127, "text": "C++ Data Types" }, { "code": null, "e": 2167, "s": 2142, "text": "unordered_map in C++ STL" }, { "code": null, "e": 2201, "s": 2167, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 2221, "s": 2201, "text": "Polymorphism in C++" }, { "code": null, "e": 2247, "s": 2221, "text": "Switch Statement in C/C++" } ]
Matrix Multiplication With 1 MapReduce Step
12 Nov, 2020 MapReduce is a technique in which a huge program is subdivided into small tasks and run parallelly to make computation faster, save time, and mostly used in distributed systems. It has 2 important parts: Mapper: It takes raw data input and organizes into key, value pairs. For example, In a dictionary, you search for the word “Data” and its associated meaning is “facts and statistics collected together for reference or analysis”. Here the Key is Data and the Value associated with is facts and statistics collected together for reference or analysis. Reducer: It is responsible for processing data in parallel and produce final output. Let us consider the matrix multiplication example to visualize MapReduce. Consider the following matrix: 2×2 matrices A and B Here matrix A is a 2×2 matrix which means the number of rows(i)=2 and the number of columns(j)=2. Matrix B is also a 2×2 matrix where number of rows(j)=2 and number of columns(k)=2. Each cell of the matrix is labelled as Aij and Bij. Ex. element 3 in matrix A is called A21 i.e. 2nd-row 1st column. Now One step matrix multiplication has 1 mapper and 1 reducer. The Formula is: Mapper for Matrix A (k, v)=((i, k), (A, j, Aij)) for all k Mapper for Matrix B (k, v)=((i, k), (B, j, Bjk)) for all i Therefore computing the mapper for Matrix A: # k, i, j computes the number of times it occurs. # Here all are 2, therefore when k=1, i can have # 2 values 1 & 2, each case can have 2 further # values of j=1 and j=2. Substituting all values # in formula k=1 i=1 j=1 ((1, 1), (A, 1, 1)) j=2 ((1, 1), (A, 2, 2)) i=2 j=1 ((2, 1), (A, 1, 3)) j=2 ((2, 1), (A, 2, 4)) k=2 i=1 j=1 ((1, 2), (A, 1, 1)) j=2 ((1, 2), (A, 2, 2)) i=2 j=1 ((2, 2), (A, 1, 3)) j=2 ((2, 2), (A, 2, 4)) Computing the mapper for Matrix B i=1 j=1 k=1 ((1, 1), (B, 1, 5)) k=2 ((1, 2), (B, 1, 6)) j=2 k=1 ((1, 1), (B, 2, 7)) j=2 ((1, 2), (B, 2, 8)) i=2 j=1 k=1 ((2, 1), (B, 1, 5)) k=2 ((2, 2), (B, 1, 6)) j=2 k=1 ((2, 1), (B, 2, 7)) k=2 ((2, 2), (B, 2, 8)) The formula for Reducer is: Reducer(k, v)=(i, k)=>Make sorted Alist and Blist (i, k) => Summation (Aij * Bjk)) for j Output =>((i, k), sum) Therefore computing the reducer: # We can observe from Mapper computation # that 4 pairs are common (1, 1), (1, 2), # (2, 1) and (2, 2) # Make a list separate for Matrix A & # B with adjoining values taken from # Mapper step above: (1, 1) =>Alist ={(A, 1, 1), (A, 2, 2)} Blist ={(B, 1, 5), (B, 2, 7)} Now Aij x Bjk: [(1*5) + (2*7)] =19 -------(i) (1, 2) =>Alist ={(A, 1, 1), (A, 2, 2)} Blist ={(B, 1, 6), (B, 2, 8)} Now Aij x Bjk: [(1*6) + (2*8)] =22 -------(ii) (2, 1) =>Alist ={(A, 1, 3), (A, 2, 4)} Blist ={(B, 1, 5), (B, 2, 7)} Now Aij x Bjk: [(3*5) + (4*7)] =43 -------(iii) (2, 2) =>Alist ={(A, 1, 3), (A, 2, 4)} Blist ={(B, 1, 6), (B, 2, 8)} Now Aij x Bjk: [(3*6) + (4*8)] =50 -------(iv) From (i), (ii), (iii) and (iv) we conclude that ((1, 1), 19) ((1, 2), 22) ((2, 1), 43) ((2, 2), 50) Therefore the Final Matrix is: Final output of Matrix multiplication. abhijith umesh Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Nov, 2020" }, { "code": null, "e": 259, "s": 54, "text": "MapReduce is a technique in which a huge program is subdivided into small tasks and run parallelly to make computation faster, save time, and mostly used in distributed systems. It has 2 important parts: " }, { "code": null, "e": 609, "s": 259, "text": "Mapper: It takes raw data input and organizes into key, value pairs. For example, In a dictionary, you search for the word “Data” and its associated meaning is “facts and statistics collected together for reference or analysis”. Here the Key is Data and the Value associated with is facts and statistics collected together for reference or analysis." }, { "code": null, "e": 694, "s": 609, "text": "Reducer: It is responsible for processing data in parallel and produce final output." }, { "code": null, "e": 800, "s": 694, "text": "Let us consider the matrix multiplication example to visualize MapReduce. Consider the following matrix: " }, { "code": null, "e": 821, "s": 800, "text": "2×2 matrices A and B" }, { "code": null, "e": 1200, "s": 821, "text": "Here matrix A is a 2×2 matrix which means the number of rows(i)=2 and the number of columns(j)=2. Matrix B is also a 2×2 matrix where number of rows(j)=2 and number of columns(k)=2. Each cell of the matrix is labelled as Aij and Bij. Ex. element 3 in matrix A is called A21 i.e. 2nd-row 1st column. Now One step matrix multiplication has 1 mapper and 1 reducer. The Formula is: " }, { "code": null, "e": 1319, "s": 1200, "text": "Mapper for Matrix A (k, v)=((i, k), (A, j, Aij)) for all k Mapper for Matrix B (k, v)=((i, k), (B, j, Bjk)) for all i " }, { "code": null, "e": 1365, "s": 1319, "text": "Therefore computing the mapper for Matrix A: " }, { "code": null, "e": 1875, "s": 1365, "text": "# k, i, j computes the number of times it occurs.\n# Here all are 2, therefore when k=1, i can have \n# 2 values 1 & 2, each case can have 2 further\n# values of j=1 and j=2. Substituting all values \n# in formula\n\nk=1 i=1 j=1 ((1, 1), (A, 1, 1)) \n j=2 ((1, 1), (A, 2, 2)) \n i=2 j=1 ((2, 1), (A, 1, 3))\n j=2 ((2, 1), (A, 2, 4)) \n\nk=2 i=1 j=1 ((1, 2), (A, 1, 1))\n j=2 ((1, 2), (A, 2, 2)) \n i=2 j=1 ((2, 2), (A, 1, 3))\n j=2 ((2, 2), (A, 2, 4)) \n" }, { "code": null, "e": 1910, "s": 1875, "text": "Computing the mapper for Matrix B " }, { "code": null, "e": 2209, "s": 1910, "text": "i=1 j=1 k=1 ((1, 1), (B, 1, 5)) \n k=2 ((1, 2), (B, 1, 6)) \n j=2 k=1 ((1, 1), (B, 2, 7))\n j=2 ((1, 2), (B, 2, 8)) \n\ni=2 j=1 k=1 ((2, 1), (B, 1, 5))\n k=2 ((2, 2), (B, 1, 6)) \n j=2 k=1 ((2, 1), (B, 2, 7))\n k=2 ((2, 2), (B, 2, 8)) \n" }, { "code": null, "e": 2238, "s": 2209, "text": "The formula for Reducer is: " }, { "code": null, "e": 2351, "s": 2238, "text": "Reducer(k, v)=(i, k)=>Make sorted Alist and Blist (i, k) => Summation (Aij * Bjk)) for j Output =>((i, k), sum) " }, { "code": null, "e": 2385, "s": 2351, "text": "Therefore computing the reducer: " }, { "code": null, "e": 3221, "s": 2385, "text": "# We can observe from Mapper computation \n# that 4 pairs are common (1, 1), (1, 2),\n# (2, 1) and (2, 2)\n# Make a list separate for Matrix A & \n# B with adjoining values taken from \n# Mapper step above:\n\n(1, 1) =>Alist ={(A, 1, 1), (A, 2, 2)}\n Blist ={(B, 1, 5), (B, 2, 7)}\n Now Aij x Bjk: [(1*5) + (2*7)] =19 -------(i)\n\n(1, 2) =>Alist ={(A, 1, 1), (A, 2, 2)}\n Blist ={(B, 1, 6), (B, 2, 8)}\n Now Aij x Bjk: [(1*6) + (2*8)] =22 -------(ii)\n\n(2, 1) =>Alist ={(A, 1, 3), (A, 2, 4)}\n Blist ={(B, 1, 5), (B, 2, 7)}\n Now Aij x Bjk: [(3*5) + (4*7)] =43 -------(iii)\n\n(2, 2) =>Alist ={(A, 1, 3), (A, 2, 4)}\n Blist ={(B, 1, 6), (B, 2, 8)}\n Now Aij x Bjk: [(3*6) + (4*8)] =50 -------(iv)\n\nFrom (i), (ii), (iii) and (iv) we conclude that\n((1, 1), 19)\n((1, 2), 22)\n((2, 1), 43)\n((2, 2), 50)\n" }, { "code": null, "e": 3253, "s": 3221, "text": "Therefore the Final Matrix is: " }, { "code": null, "e": 3292, "s": 3253, "text": "Final output of Matrix multiplication." }, { "code": null, "e": 3307, "s": 3292, "text": "abhijith umesh" }, { "code": null, "e": 3314, "s": 3307, "text": "Hadoop" }, { "code": null, "e": 3321, "s": 3314, "text": "Hadoop" } ]
random.weibullvariate() function in Python
26 May, 2020 random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. weibullvariate() is an inbuilt method of the random module. It is used to return a random floating point number with Weibull distribution. Syntax : random.weibullvariate(alpha, beta) Parameters :alpha : scale parameterbeta : shape parameter Returns : a random Weibull distribution floating number Example 1: # import the random moduleimport random # determining the values of the parametersalpha = 1beta = 1.5 # using the weibullvariate() methodprint(random.weibullvariate(alpha, beta)) Output : 0.7231214446591137 Example 2: We can generate the number multiple times and plot a graph to observe the Weibull distribution. # import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] alpha = 1beta = 1.5 for i in range(100): temp = random.weibullvariate(alpha, beta) nums.append(temp) # plotting a graph plt.plot(nums) plt.show() Output :Example 3: We can create a histogram to observe the density of the Weibull distribution. # import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] alpha = 1beta = 1.5 for i in range(10000): temp = random.weibullvariate(alpha, beta) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show() Output : Python-random Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2020" }, { "code": null, "e": 234, "s": 28, "text": "random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined." }, { "code": null, "e": 373, "s": 234, "text": "weibullvariate() is an inbuilt method of the random module. It is used to return a random floating point number with Weibull distribution." }, { "code": null, "e": 417, "s": 373, "text": "Syntax : random.weibullvariate(alpha, beta)" }, { "code": null, "e": 475, "s": 417, "text": "Parameters :alpha : scale parameterbeta : shape parameter" }, { "code": null, "e": 531, "s": 475, "text": "Returns : a random Weibull distribution floating number" }, { "code": null, "e": 542, "s": 531, "text": "Example 1:" }, { "code": "# import the random moduleimport random # determining the values of the parametersalpha = 1beta = 1.5 # using the weibullvariate() methodprint(random.weibullvariate(alpha, beta))", "e": 723, "s": 542, "text": null }, { "code": null, "e": 732, "s": 723, "text": "Output :" }, { "code": null, "e": 751, "s": 732, "text": "0.7231214446591137" }, { "code": null, "e": 858, "s": 751, "text": "Example 2: We can generate the number multiple times and plot a graph to observe the Weibull distribution." }, { "code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] alpha = 1beta = 1.5 for i in range(100): temp = random.weibullvariate(alpha, beta) nums.append(temp) # plotting a graph plt.plot(nums) plt.show()", "e": 1154, "s": 858, "text": null }, { "code": null, "e": 1251, "s": 1154, "text": "Output :Example 3: We can create a histogram to observe the density of the Weibull distribution." }, { "code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] alpha = 1beta = 1.5 for i in range(10000): temp = random.weibullvariate(alpha, beta) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show()", "e": 1559, "s": 1251, "text": null }, { "code": null, "e": 1568, "s": 1559, "text": "Output :" }, { "code": null, "e": 1582, "s": 1568, "text": "Python-random" }, { "code": null, "e": 1589, "s": 1582, "text": "Python" }, { "code": null, "e": 1687, "s": 1589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1715, "s": 1687, "text": "Read JSON file using Python" }, { "code": null, "e": 1737, "s": 1715, "text": "Python map() function" }, { "code": null, "e": 1787, "s": 1737, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1805, "s": 1787, "text": "Python Dictionary" }, { "code": null, "e": 1849, "s": 1805, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 1891, "s": 1849, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1914, "s": 1891, "text": "Taking input in Python" }, { "code": null, "e": 1936, "s": 1914, "text": "Enumerate() in Python" }, { "code": null, "e": 1971, "s": 1936, "text": "Read a file line by line in Python" } ]
Java Character charCount() with Examples
06 Dec, 2018 The java.lang.Character.charCount() is an inbuilt function in java which is used to determine number of characters needed to represent the specified character. If the character is equal to or greater than 0x10000, the method returns 2 otherwise 1. Syntax: public static int charCount(int code) Parameters: The function accepts a single parameter code. It represents the tested character. Return Value: It returns 2 if the character is valid otherwise 1. Errors and Exceptions: This method doesn’t validate the specified character to be a valid Unicode code point. Non-static method is can be called by declaring method_name(argv) in this such case method is static, it should be called by adding the class name as the suffix. We will be get a compilation problem if we call charCount method non-statically. Examples: Input : 0x12456 Output : 2 Explanation: the code is greater than 0x10000 Input : 0x9456 Output : 1 Explanation: The code is smaller then 0x10000 Below Programs illustrates the java.lang.Character.charCount() function:Program 1: // Java program that demonstrates the use of// Character.charCount() function // include lang packageimport java.lang.*; class GFG { public static void main(String[] args) { int code = 0x9000; int ans = Character.charCount(code); // prints 2 if character is greater than 0x10000 // otherwise 1 System.out.println(ans); }} 1 Program 2: // Java program that demonstrates the use of// Character.charCount() function // include lang packageimport java.lang.*; class GFG { public static void main(String[] args) { int code = 0x12456; int ans = Character.charCount(code); // prints 2 if character is greater than 0x10000 // otherwise 1 System.out.println(ans); }} 2 Java-Character Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 276, "s": 28, "text": "The java.lang.Character.charCount() is an inbuilt function in java which is used to determine number of characters needed to represent the specified character. If the character is equal to or greater than 0x10000, the method returns 2 otherwise 1." }, { "code": null, "e": 284, "s": 276, "text": "Syntax:" }, { "code": null, "e": 323, "s": 284, "text": "public static int charCount(int code)\n" }, { "code": null, "e": 417, "s": 323, "text": "Parameters: The function accepts a single parameter code. It represents the tested character." }, { "code": null, "e": 483, "s": 417, "text": "Return Value: It returns 2 if the character is valid otherwise 1." }, { "code": null, "e": 506, "s": 483, "text": "Errors and Exceptions:" }, { "code": null, "e": 593, "s": 506, "text": "This method doesn’t validate the specified character to be a valid Unicode code point." }, { "code": null, "e": 836, "s": 593, "text": "Non-static method is can be called by declaring method_name(argv) in this such case method is static, it should be called by adding the class name as the suffix. We will be get a compilation problem if we call charCount method non-statically." }, { "code": null, "e": 846, "s": 836, "text": "Examples:" }, { "code": null, "e": 993, "s": 846, "text": "Input : 0x12456\nOutput : 2\nExplanation: the code is greater than 0x10000\n\nInput : 0x9456\nOutput : 1\nExplanation: The code is smaller then 0x10000\n" }, { "code": null, "e": 1076, "s": 993, "text": "Below Programs illustrates the java.lang.Character.charCount() function:Program 1:" }, { "code": "// Java program that demonstrates the use of// Character.charCount() function // include lang packageimport java.lang.*; class GFG { public static void main(String[] args) { int code = 0x9000; int ans = Character.charCount(code); // prints 2 if character is greater than 0x10000 // otherwise 1 System.out.println(ans); }}", "e": 1448, "s": 1076, "text": null }, { "code": null, "e": 1451, "s": 1448, "text": "1\n" }, { "code": null, "e": 1462, "s": 1451, "text": "Program 2:" }, { "code": "// Java program that demonstrates the use of// Character.charCount() function // include lang packageimport java.lang.*; class GFG { public static void main(String[] args) { int code = 0x12456; int ans = Character.charCount(code); // prints 2 if character is greater than 0x10000 // otherwise 1 System.out.println(ans); }}", "e": 1835, "s": 1462, "text": null }, { "code": null, "e": 1838, "s": 1835, "text": "2\n" }, { "code": null, "e": 1853, "s": 1838, "text": "Java-Character" }, { "code": null, "e": 1868, "s": 1853, "text": "Java-Functions" }, { "code": null, "e": 1886, "s": 1868, "text": "Java-lang package" }, { "code": null, "e": 1891, "s": 1886, "text": "Java" }, { "code": null, "e": 1896, "s": 1891, "text": "Java" }, { "code": null, "e": 1994, "s": 1896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2009, "s": 1994, "text": "Stream In Java" }, { "code": null, "e": 2030, "s": 2009, "text": "Introduction to Java" }, { "code": null, "e": 2051, "s": 2030, "text": "Constructors in Java" }, { "code": null, "e": 2070, "s": 2051, "text": "Exceptions in Java" }, { "code": null, "e": 2087, "s": 2070, "text": "Generics in Java" }, { "code": null, "e": 2117, "s": 2087, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2143, "s": 2117, "text": "Java Programming Examples" }, { "code": null, "e": 2159, "s": 2143, "text": "Strings in Java" }, { "code": null, "e": 2196, "s": 2159, "text": "Differences between JDK, JRE and JVM" } ]
Scala Char toString() method with example
29 Oct, 2019 The toString() method is utilized to convert a stated character into String. Method Definition: def toString: String Return Type: It returns the String representation of the stated character. Example: 1# // Scala program of toString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toString method val result = 'B'.toString // Displays output println(result) }} B Example: 2# // Scala program of toString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toString method val result = 'b'.toString // Displays output println(result) }} b Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in Scala How to Install Scala with VSCode? Hello World in Scala Scala | Traits Scala | Option Scala ListBuffer Scala | Functions - Basics Introduction to Scala Scala Sequence Scala | Case Class and Case Object
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2019" }, { "code": null, "e": 105, "s": 28, "text": "The toString() method is utilized to convert a stated character into String." }, { "code": null, "e": 145, "s": 105, "text": "Method Definition: def toString: String" }, { "code": null, "e": 220, "s": 145, "text": "Return Type: It returns the String representation of the stated character." }, { "code": null, "e": 232, "s": 220, "text": "Example: 1#" }, { "code": "// Scala program of toString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toString method val result = 'B'.toString // Displays output println(result) }} ", "e": 507, "s": 232, "text": null }, { "code": null, "e": 510, "s": 507, "text": "B\n" }, { "code": null, "e": 522, "s": 510, "text": "Example: 2#" }, { "code": "// Scala program of toString()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toString method val result = 'b'.toString // Displays output println(result) }} ", "e": 801, "s": 522, "text": null }, { "code": null, "e": 804, "s": 801, "text": "b\n" }, { "code": null, "e": 810, "s": 804, "text": "Scala" }, { "code": null, "e": 823, "s": 810, "text": "Scala-Method" }, { "code": null, "e": 829, "s": 823, "text": "Scala" }, { "code": null, "e": 927, "s": 829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 948, "s": 927, "text": "Inheritance in Scala" }, { "code": null, "e": 982, "s": 948, "text": "How to Install Scala with VSCode?" }, { "code": null, "e": 1003, "s": 982, "text": "Hello World in Scala" }, { "code": null, "e": 1018, "s": 1003, "text": "Scala | Traits" }, { "code": null, "e": 1033, "s": 1018, "text": "Scala | Option" }, { "code": null, "e": 1050, "s": 1033, "text": "Scala ListBuffer" }, { "code": null, "e": 1077, "s": 1050, "text": "Scala | Functions - Basics" }, { "code": null, "e": 1099, "s": 1077, "text": "Introduction to Scala" }, { "code": null, "e": 1114, "s": 1099, "text": "Scala Sequence" } ]
React-Bootstrap NavBar Component
04 May, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. NavBar Component is a navigation header that is responsive and powerful. It supports navigation, branding, and many more other related features. We can use the following approach in ReactJS to use the react-bootstrap NavBar Component. NavBar Props: as: It can be used as a custom element type for this component. bg: It is used to add bg-* utility classes. collapseOnSelect: It is used to collapse the Navbar on click onSelect function is triggered of a descendant of a child <nav> element. expand: It is used to denote the breakpoint below which our Navbar will collapse. expanded: The visibility of the navbar body is controlled through it. fixed: It is used to create a fixed navbar that stays along the bottom of the screen or top of the screen. onSelect: It is a callback that is triggered when a descendant of a child <nav> is selected. onToggle: A callback fired when the <Navbar> body collapses or expands role: It is used to define the ARIA role for the navbar. sticky: It is used to position our given navbar at the viewport’s top. variant: It indicates the visual variant of the navbar. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Navbar.Brand Props: as: It can be used as a custom element type for this component. href: It is used to pass the href attribute to this element. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Navbar.Toggle Props: as: It can be used as a custom element type for this component. children: It is used to define the toggle content. label: For the toggler button, it is used as an accessible ARIA label. onClick: It is the callback function that is triggered on click event. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Navbar.Collapse Props: bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Navbar from 'react-bootstrap/Navbar'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap NavBar Component</h4> <Navbar bg="dark" variant="dark"> <Navbar.Brand href="#home"> <imgsrc="https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png" alt="Sample Brand Logo" width="35" className="align-top d-inline-block" height="35" />Test Company </Navbar.Brand> </Navbar> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/components/navbar/ React-Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 May, 2021" }, { "code": null, "e": 345, "s": 28, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. NavBar Component is a navigation header that is responsive and powerful. It supports navigation, branding, and many more other related features. We can use the following approach in ReactJS to use the react-bootstrap NavBar Component." }, { "code": null, "e": 359, "s": 345, "text": "NavBar Props:" }, { "code": null, "e": 423, "s": 359, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 467, "s": 423, "text": "bg: It is used to add bg-* utility classes." }, { "code": null, "e": 601, "s": 467, "text": "collapseOnSelect: It is used to collapse the Navbar on click onSelect function is triggered of a descendant of a child <nav> element." }, { "code": null, "e": 683, "s": 601, "text": "expand: It is used to denote the breakpoint below which our Navbar will collapse." }, { "code": null, "e": 753, "s": 683, "text": "expanded: The visibility of the navbar body is controlled through it." }, { "code": null, "e": 860, "s": 753, "text": "fixed: It is used to create a fixed navbar that stays along the bottom of the screen or top of the screen." }, { "code": null, "e": 953, "s": 860, "text": "onSelect: It is a callback that is triggered when a descendant of a child <nav> is selected." }, { "code": null, "e": 1024, "s": 953, "text": "onToggle: A callback fired when the <Navbar> body collapses or expands" }, { "code": null, "e": 1081, "s": 1024, "text": "role: It is used to define the ARIA role for the navbar." }, { "code": null, "e": 1152, "s": 1081, "text": "sticky: It is used to position our given navbar at the viewport’s top." }, { "code": null, "e": 1208, "s": 1152, "text": "variant: It indicates the visual variant of the navbar." }, { "code": null, "e": 1292, "s": 1208, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1312, "s": 1292, "text": "Navbar.Brand Props:" }, { "code": null, "e": 1376, "s": 1312, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 1437, "s": 1376, "text": "href: It is used to pass the href attribute to this element." }, { "code": null, "e": 1521, "s": 1437, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1542, "s": 1521, "text": "Navbar.Toggle Props:" }, { "code": null, "e": 1606, "s": 1542, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 1657, "s": 1606, "text": "children: It is used to define the toggle content." }, { "code": null, "e": 1728, "s": 1657, "text": "label: For the toggler button, it is used as an accessible ARIA label." }, { "code": null, "e": 1799, "s": 1728, "text": "onClick: It is the callback function that is triggered on click event." }, { "code": null, "e": 1883, "s": 1799, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1906, "s": 1883, "text": "Navbar.Collapse Props:" }, { "code": null, "e": 1990, "s": 1906, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 2040, "s": 1990, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 2135, "s": 2040, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 2199, "s": 2135, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 2231, "s": 2199, "text": "npx create-react-app foldername" }, { "code": null, "e": 2344, "s": 2231, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 2444, "s": 2344, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 2458, "s": 2444, "text": "cd foldername" }, { "code": null, "e": 2613, "s": 2458, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 2718, "s": 2613, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 2769, "s": 2718, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 2821, "s": 2769, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 2839, "s": 2821, "text": "Project Structure" }, { "code": null, "e": 2969, "s": 2839, "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": 2976, "s": 2969, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Navbar from 'react-bootstrap/Navbar'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap NavBar Component</h4> <Navbar bg=\"dark\" variant=\"dark\"> <Navbar.Brand href=\"#home\"> <imgsrc=\"https://media.geeksforgeeks.org/wp-content/uploads/20210425000233/test-300x297.png\" alt=\"Sample Brand Logo\" width=\"35\" className=\"align-top d-inline-block\" height=\"35\" />Test Company </Navbar.Brand> </Navbar> </div> );}", "e": 3623, "s": 2976, "text": null }, { "code": null, "e": 3736, "s": 3623, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 3746, "s": 3736, "text": "npm start" }, { "code": null, "e": 3845, "s": 3746, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3909, "s": 3845, "text": "Reference: https://react-bootstrap.github.io/components/navbar/" }, { "code": null, "e": 3925, "s": 3909, "text": "React-Bootstrap" }, { "code": null, "e": 3933, "s": 3925, "text": "ReactJS" }, { "code": null, "e": 3950, "s": 3933, "text": "Web Technologies" } ]
Print all subsequences of a string | Iterative Method
06 Jul, 2022 Given a string s, print all possible subsequences of the given string in an iterative manner. We have already discussed Recursive method to print all subsequences of a string. Examples: Input : abc Output : a, b, c, ab, ac, bc, abc Input : aab Output : a, b, aa, ab, aab Approach 1 : Here, we discuss much easier and simpler iterative approach which is similar to Power Set. We use bit pattern from binary representation of 1 to 2^length(s) – 1. input = “abc” Binary representation to consider 1 to (2^3-1), i.e 1 to 7. Start from left (MSB) to right (LSB) of binary representation and append characters from input string which corresponds to bit value 1 in binary representation to Final subsequence string sub. Example: 001 => abc . Only c corresponds to bit 1. So, subsequence = c. 101 => abc . a and c corresponds to bit 1. So, subsequence = ac.binary_representation (1) = 001 => c binary_representation (2) = 010 => b binary_representation (3) = 011 => bc binary_representation (4) = 100 => a binary_representation (5) = 101 => ac binary_representation (6) = 110 => ab binary_representation (7) = 111 => abc Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to print all Subsequences// of a string in iterative manner#include <bits/stdc++.h>using namespace std; // function to find subsequencestring subsequence(string s, int binary, int len){ string sub = ""; for (int j = 0; j < len; j++) // check if jth bit in binary is 1 if (binary & (1 << j)) // if jth bit is 1, include it // in subsequence sub += s[j]; return sub;} // function to print all subsequencesvoid possibleSubsequences(string s){ // map to store subsequence // lexicographically by length map<int, set<string> > sorted_subsequence; int len = s.size(); // Total number of non-empty subsequence // in string is 2^len-1 int limit = pow(2, len); // i=0, corresponds to empty subsequence for (int i = 1; i <= limit - 1; i++) { // subsequence for binary pattern i string sub = subsequence(s, i, len); // storing sub in map sorted_subsequence[sub.length()].insert(sub); } for (auto it : sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> cout << "Subsequences of length = " << it.first << " are:" << endl; for (auto ii : it.second) // ii is iterator of type set<string> cout << ii << " "; cout << endl; }} // driver functionint main(){ string s = "aabc"; possibleSubsequences(s); return 0;} // Java program to print all Subsequences// of a String in iterative mannerimport java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.SortedMap;import java.util.TreeMap; class Graph{ // Function to find subsequencestatic String subsequence(String s, int binary, int len){ String sub = ""; for(int j = 0; j < len; j++) // Check if jth bit in binary is 1 if ((binary & (1 << j)) != 0) // If jth bit is 1, include it // in subsequence sub += s.charAt(j); return sub;} // Function to print all subsequencesstatic void possibleSubsequences(String s){ // Map to store subsequence // lexicographically by length SortedMap<Integer, HashSet<String>> sorted_subsequence = new TreeMap<Integer, HashSet<String>>(); int len = s.length(); // Total number of non-empty subsequence // in String is 2^len-1 int limit = (int) Math.pow(2, len); // i=0, corresponds to empty subsequence for(int i = 1; i <= limit - 1; i++) { // Subsequence for binary pattern i String sub = subsequence(s, i, len); // Storing sub in map if (!sorted_subsequence.containsKey(sub.length())) sorted_subsequence.put( sub.length(), new HashSet<>()); sorted_subsequence.get( sub.length()).add(sub); } for(Map.Entry<Integer, HashSet<String>> it : sorted_subsequence.entrySet()) { // it.first is length of Subsequence // it.second is set<String> System.out.println("Subsequences of length = " + it.getKey() + " are:"); for(String ii : it.getValue()) // ii is iterator of type set<String> System.out.print(ii + " "); System.out.println(); }} // Driver codepublic static void main(String[] args){ String s = "aabc"; possibleSubsequences(s);}} // This code is contributed by sanjeev2552 # Python3 program to print all Subsequences# of a string in iterative manner # function to find subsequencedef subsequence(s, binary, length): sub = "" for j in range(length): # check if jth bit in binary is 1 if (binary & (1 << j)): # if jth bit is 1, include it # in subsequence sub += s[j] return sub # function to print all subsequencesdef possibleSubsequences(s): # map to store subsequence # lexicographically by length sorted_subsequence = {} length = len(s) # Total number of non-empty subsequence # in string is 2^len-1 limit = 2 ** length # i=0, corresponds to empty subsequence for i in range(1, limit): # subsequence for binary pattern i sub = subsequence(s, i, length) # storing sub in map if len(sub) in sorted_subsequence.keys(): sorted_subsequence[len(sub)] = \ tuple(list(sorted_subsequence[len(sub)]) + [sub]) else: sorted_subsequence[len(sub)] = [sub] for it in sorted_subsequence: # it.first is length of Subsequence # it.second is set<string> print("Subsequences of length =", it, "are:") for ii in sorted(set(sorted_subsequence[it])): # ii is iterator of type set<string> print(ii, end = ' ') print() # Driver Codes = "aabc"possibleSubsequences(s) # This code is contributed by ankush_953 // C# program to print all Subsequences// of a String in iterative mannerusing System;using System.Collections.Generic; class Graph { // Function to find subsequence static string subsequence(string s, int binary, int len) { string sub = ""; for (int j = 0; j < len; j++) // Check if jth bit in binary is 1 if ((binary & (1 << j)) != 0) // If jth bit is 1, include it // in subsequence sub += s[j]; return sub; } // Function to print all subsequences static void possibleSubsequences(string s) { // Map to store subsequence // lexicographically by length SortedDictionary<int, HashSet<string> > sorted_subsequence = new SortedDictionary<int, HashSet<string> >(); int len = s.Length; // Total number of non-empty subsequence // in String is 2^len-1 int limit = (int)Math.Pow(2, len); // i=0, corresponds to empty subsequence for (int i = 1; i <= limit - 1; i++) { // Subsequence for binary pattern i string sub = subsequence(s, i, len); // Storing sub in map if (!sorted_subsequence.ContainsKey(sub.Length)) sorted_subsequence[sub.Length] = new HashSet<string>(); sorted_subsequence[sub.Length].Add(sub); } foreach(var it in sorted_subsequence) { // it.first is length of Subsequence // it.second is set<String> Console.WriteLine("Subsequences of length = " + it.Key + " are:"); foreach(String ii in it.Value) // ii is iterator of type set<String> Console.Write(ii + " "); Console.WriteLine(); } } // Driver code public static void Main(string[] args) { string s = "aabc"; possibleSubsequences(s); }} // This code is contributed by phasing17 <script> // Javascript program to print all Subsequences// of a string in iterative manner // function to find subsequencefunction subsequence(s, binary, len){ let sub = ""; for(let j = 0; j < len; j++) // Check if jth bit in binary is 1 if (binary & (1 << j)) // If jth bit is 1, include it // in subsequence sub += s[j]; return sub;} // Function to print all subsequencesfunction possibleSubsequences(s){ // map to store subsequence // lexicographically by length let sorted_subsequence = new Map(); let len = s.length; // Total number of non-empty subsequence // in string is 2^len-1 let limit = Math.pow(2, len); // i=0, corresponds to empty subsequence for(let i = 1; i <= limit - 1; i++) { // Subsequence for binary pattern i let sub = subsequence(s, i, len); // Storing sub in map if (!sorted_subsequence.has(sub.length)) sorted_subsequence.set(sub.length, new Set()); sorted_subsequence.get(sub.length).add(sub); } for(let it of sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> document.write("Subsequences of length = " + it[0] + " are:" + "<br>"); for(let ii of it[1]) // ii is iterator of type set<string> document.write(ii + " "); document.write("<br>"); }} // Driver codelet s = "aabc"; possibleSubsequences(s); // This code is contributed by gfgking </script> Output: Subsequences of length = 1 are: a b c Subsequences of length = 2 are: aa ab ac bc Subsequences of length = 3 are: aab aac abc Subsequences of length = 4 are: aabc Time Complexity : , where n is length of string to find subsequences and l is length of binary string. Space Complexity: O(1) Approach 2 : Approach is to get the position of rightmost set bit and reset that bit after appending corresponding character from given string to the subsequence and will repeat the same thing till corresponding binary pattern has no set bits. If input is s = “abc” Binary representation to consider 1 to (2^3-1), i.e 1 to 7. 001 => abc . Only c corresponds to bit 1. So, subsequence = c 101 => abc . a and c corresponds to bit 1. So, subsequence = ac.Let us use Binary representation of 5, i.e 101. Rightmost bit is at position 1, append character at beginning of sub = c ,reset position 1 => 100 Rightmost bit is at position 3, append character at beginning of sub = ac ,reset position 3 => 000 As now we have no set bit left, we stop computing subsequence. Example :binary_representation (1) = 001 => c binary_representation (2) = 010 => b binary_representation (3) = 011 => bc binary_representation (4) = 100 => a binary_representation (5) = 101 => ac binary_representation (6) = 110 => ab binary_representation (7) = 111 => abc Below is the implementation of above approach : C++ Python3 C# Javascript // C++ code all Subsequences of a// string in iterative manner#include <bits/stdc++.h>using namespace std; // function to find subsequencestring subsequence(string s, int binary){ string sub = ""; int pos; // loop while binary is greater than 0 while(binary>0) { // get the position of rightmost set bit pos=log2(binary&-binary)+1; // append at beginning as we are // going from LSB to MSB sub=s[pos-1]+sub; // resets bit at pos in binary binary= (binary & ~(1 << (pos-1))); } reverse(sub.begin(),sub.end()); return sub;} // function to print all subsequencesvoid possibleSubsequences(string s){ // map to store subsequence // lexicographically by length map<int, set<string> > sorted_subsequence; int len = s.size(); // Total number of non-empty subsequence // in string is 2^len-1 int limit = pow(2, len); // i=0, corresponds to empty subsequence for (int i = 1; i <= limit - 1; i++) { // subsequence for binary pattern i string sub = subsequence(s, i); // storing sub in map sorted_subsequence[sub.length()].insert(sub); } for (auto it : sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> cout << "Subsequences of length = " << it.first << " are:" << endl; for (auto ii : it.second) // ii is iterator of type set<string> cout << ii << " "; cout << endl; }} // driver functionint main(){ string s = "aabc"; possibleSubsequences(s); return 0;} # Python3 program to print all Subsequences# of a string in an iterative mannerfrom math import log2, floor # function to find subsequencedef subsequence(s, binary): sub = "" # loop while binary is greater than while(binary > 0): # get the position of rightmost set bit pos=floor(log2(binary&-binary) + 1) # append at beginning as we are # going from LSB to MSB sub = s[pos - 1] + sub # resets bit at pos in binary binary= (binary & ~(1 << (pos - 1))) sub = sub[::-1] return sub # function to print all subsequencesdef possibleSubsequences(s): # map to store subsequence # lexicographically by length sorted_subsequence = {} length = len(s) # Total number of non-empty subsequence # in string is 2^len-1 limit = 2 ** length # i=0, corresponds to empty subsequence for i in range(1, limit): # subsequence for binary pattern i sub = subsequence(s, i) # storing sub in map if len(sub) in sorted_subsequence.keys(): sorted_subsequence[len(sub)] = \ tuple(list(sorted_subsequence[len(sub)]) + [sub]) else: sorted_subsequence[len(sub)] = [sub] for it in sorted_subsequence: # it.first is length of Subsequence # it.second is set<string> print("Subsequences of length =", it, "are:") for ii in sorted(set(sorted_subsequence[it])): # ii is iterator of type set<string> print(ii, end = ' ') print() # Driver Codes = "aabc"possibleSubsequences(s) # This code is contributed by ankush_953 // C# program to print all Subsequences// of a string in an iterative manner using System;using System.Collections.Generic;using System.Linq; class GFG{ // function to find subsequence static string subsequence(string s, int binary) { string sub = ""; // loop while binary is greater than while (binary > 0) { // get the position of rightmost set bit var pos = (int)Math.Floor( Math.Log(binary & (-binary)) / Math.Log(2)) + 1; // append at beginning as we are // going from LSB to MSB sub = s[pos - 1] + sub; // resets bit at pos in binary binary = (binary & ~(1 << (pos - 1))); } char[] charArray = sub.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } // function to print all subsequences static void possibleSubsequences(string s) { // map to store subsequence // lexicographically by length Dictionary<int, HashSet<string> > sorted_subsequence = new Dictionary<int, HashSet<string> >(); int length = s.Length; // Total number of non-empty subsequence // in string is 2^len-1 int limit = (int)Math.Pow(2, length); // i=0, corresponds to empty subsequence for (int i = 1; i < limit; i++) { // subsequence for binary pattern i string sub = subsequence(s, i); // storing sub in map if (sorted_subsequence.ContainsKey( sub.Length)) { sorted_subsequence[sub.Length].Add(sub); } else { sorted_subsequence[sub.Length] = new HashSet<string>(); sorted_subsequence[sub.Length].Add(sub); } } foreach(var it in sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> Console.WriteLine("Subsequences of length = " + it.Key + " are:"); var arr = (it.Value).ToArray(); Array.Sort(arr); for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); } } // Driver Code public static void Main(string[] args) { string s = "aabc"; possibleSubsequences(s); }} // This code is contributed by phasing17 // JavaScript program to print all Subsequences// of a string in an iterative manner // function to find subsequencefunction subsequence(s, binary){ var sub = ""; // loop while binary is greater than while(binary > 0) { // get the position of rightmost set bit var pos= Math.floor(Math.log2(binary&-binary) + 1); // append at beginning as we are // going from LSB to MSB sub = s[pos - 1] + sub; // resets bit at pos in binary binary= (binary & ~(1 << (pos - 1))); } sub = sub.split(""); sub = sub.reverse(); return sub.join("");} // function to print all subsequencesfunction possibleSubsequences(s){ // map to store subsequence // lexicographically by length var sorted_subsequence = {}; var length = s.length; // Total number of non-empty subsequence // in string is 2^len-1 var limit = 2 ** length; // i=0, corresponds to empty subsequence for (var i = 1; i < limit; i++) { // subsequence for binary pattern i var sub = subsequence(s, i); // storing sub in map if (sorted_subsequence.hasOwnProperty(sub.length)) { //var list = sorted_subsequence[sub.length]; //list.push(sub); sorted_subsequence[sub.length].push(sub); } else sorted_subsequence[sub.length] = [sub]; } for (const it in sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> console.log("Subsequences of length =", it, "are:"); var arr = sorted_subsequence[it]; arr.sort(); var set = new Set(arr); for (const ii of set) // ii is iterator of type set<string> process.stdout.write(ii + " "); console.log() }} // Driver Codevar s = "aabc";possibleSubsequences(s); // This code is contributed by phasing17 Output: Subsequences of length = 1 are: a b c Subsequences of length = 2 are: aa ab ac bc Subsequences of length = 3 are: aab aac abc Subsequences of length = 4 are: aabc Time Complexity: , where n is the length of string to find subsequence and b is the number of set bits in binary string. Auxiliary Space: O(n) ankush_953 Akanksha_Rai sanjeev2552 gfgking surinderdawra388 phasing17 ranjanrohit840 subsequence Bit Magic Competitive Programming Strings Technical Scripter Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find whether a given number is power of 2 Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 231, "s": 54, "text": "Given a string s, print all possible subsequences of the given string in an iterative manner. We have already discussed Recursive method to print all subsequences of a string. " }, { "code": null, "e": 243, "s": 231, "text": "Examples: " }, { "code": null, "e": 329, "s": 243, "text": "Input : abc\nOutput : a, b, c, ab, ac, bc, abc\n\nInput : aab\nOutput : a, b, aa, ab, aab" }, { "code": null, "e": 504, "s": 329, "text": "Approach 1 : Here, we discuss much easier and simpler iterative approach which is similar to Power Set. We use bit pattern from binary representation of 1 to 2^length(s) – 1." }, { "code": null, "e": 771, "s": 504, "text": "input = “abc” Binary representation to consider 1 to (2^3-1), i.e 1 to 7. Start from left (MSB) to right (LSB) of binary representation and append characters from input string which corresponds to bit value 1 in binary representation to Final subsequence string sub." }, { "code": null, "e": 1171, "s": 771, "text": "Example: 001 => abc . Only c corresponds to bit 1. So, subsequence = c. 101 => abc . a and c corresponds to bit 1. So, subsequence = ac.binary_representation (1) = 001 => c binary_representation (2) = 010 => b binary_representation (3) = 011 => bc binary_representation (4) = 100 => a binary_representation (5) = 101 => ac binary_representation (6) = 110 => ab binary_representation (7) = 111 => abc" }, { "code": null, "e": 1219, "s": 1171, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 1223, "s": 1219, "text": "C++" }, { "code": null, "e": 1228, "s": 1223, "text": "Java" }, { "code": null, "e": 1236, "s": 1228, "text": "Python3" }, { "code": null, "e": 1239, "s": 1236, "text": "C#" }, { "code": null, "e": 1250, "s": 1239, "text": "Javascript" }, { "code": "// C++ program to print all Subsequences// of a string in iterative manner#include <bits/stdc++.h>using namespace std; // function to find subsequencestring subsequence(string s, int binary, int len){ string sub = \"\"; for (int j = 0; j < len; j++) // check if jth bit in binary is 1 if (binary & (1 << j)) // if jth bit is 1, include it // in subsequence sub += s[j]; return sub;} // function to print all subsequencesvoid possibleSubsequences(string s){ // map to store subsequence // lexicographically by length map<int, set<string> > sorted_subsequence; int len = s.size(); // Total number of non-empty subsequence // in string is 2^len-1 int limit = pow(2, len); // i=0, corresponds to empty subsequence for (int i = 1; i <= limit - 1; i++) { // subsequence for binary pattern i string sub = subsequence(s, i, len); // storing sub in map sorted_subsequence[sub.length()].insert(sub); } for (auto it : sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> cout << \"Subsequences of length = \" << it.first << \" are:\" << endl; for (auto ii : it.second) // ii is iterator of type set<string> cout << ii << \" \"; cout << endl; }} // driver functionint main(){ string s = \"aabc\"; possibleSubsequences(s); return 0;}", "e": 2772, "s": 1250, "text": null }, { "code": "// Java program to print all Subsequences// of a String in iterative mannerimport java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.SortedMap;import java.util.TreeMap; class Graph{ // Function to find subsequencestatic String subsequence(String s, int binary, int len){ String sub = \"\"; for(int j = 0; j < len; j++) // Check if jth bit in binary is 1 if ((binary & (1 << j)) != 0) // If jth bit is 1, include it // in subsequence sub += s.charAt(j); return sub;} // Function to print all subsequencesstatic void possibleSubsequences(String s){ // Map to store subsequence // lexicographically by length SortedMap<Integer, HashSet<String>> sorted_subsequence = new TreeMap<Integer, HashSet<String>>(); int len = s.length(); // Total number of non-empty subsequence // in String is 2^len-1 int limit = (int) Math.pow(2, len); // i=0, corresponds to empty subsequence for(int i = 1; i <= limit - 1; i++) { // Subsequence for binary pattern i String sub = subsequence(s, i, len); // Storing sub in map if (!sorted_subsequence.containsKey(sub.length())) sorted_subsequence.put( sub.length(), new HashSet<>()); sorted_subsequence.get( sub.length()).add(sub); } for(Map.Entry<Integer, HashSet<String>> it : sorted_subsequence.entrySet()) { // it.first is length of Subsequence // it.second is set<String> System.out.println(\"Subsequences of length = \" + it.getKey() + \" are:\"); for(String ii : it.getValue()) // ii is iterator of type set<String> System.out.print(ii + \" \"); System.out.println(); }} // Driver codepublic static void main(String[] args){ String s = \"aabc\"; possibleSubsequences(s);}} // This code is contributed by sanjeev2552", "e": 4991, "s": 2772, "text": null }, { "code": "# Python3 program to print all Subsequences# of a string in iterative manner # function to find subsequencedef subsequence(s, binary, length): sub = \"\" for j in range(length): # check if jth bit in binary is 1 if (binary & (1 << j)): # if jth bit is 1, include it # in subsequence sub += s[j] return sub # function to print all subsequencesdef possibleSubsequences(s): # map to store subsequence # lexicographically by length sorted_subsequence = {} length = len(s) # Total number of non-empty subsequence # in string is 2^len-1 limit = 2 ** length # i=0, corresponds to empty subsequence for i in range(1, limit): # subsequence for binary pattern i sub = subsequence(s, i, length) # storing sub in map if len(sub) in sorted_subsequence.keys(): sorted_subsequence[len(sub)] = \\ tuple(list(sorted_subsequence[len(sub)]) + [sub]) else: sorted_subsequence[len(sub)] = [sub] for it in sorted_subsequence: # it.first is length of Subsequence # it.second is set<string> print(\"Subsequences of length =\", it, \"are:\") for ii in sorted(set(sorted_subsequence[it])): # ii is iterator of type set<string> print(ii, end = ' ') print() # Driver Codes = \"aabc\"possibleSubsequences(s) # This code is contributed by ankush_953", "e": 6477, "s": 4991, "text": null }, { "code": "// C# program to print all Subsequences// of a String in iterative mannerusing System;using System.Collections.Generic; class Graph { // Function to find subsequence static string subsequence(string s, int binary, int len) { string sub = \"\"; for (int j = 0; j < len; j++) // Check if jth bit in binary is 1 if ((binary & (1 << j)) != 0) // If jth bit is 1, include it // in subsequence sub += s[j]; return sub; } // Function to print all subsequences static void possibleSubsequences(string s) { // Map to store subsequence // lexicographically by length SortedDictionary<int, HashSet<string> > sorted_subsequence = new SortedDictionary<int, HashSet<string> >(); int len = s.Length; // Total number of non-empty subsequence // in String is 2^len-1 int limit = (int)Math.Pow(2, len); // i=0, corresponds to empty subsequence for (int i = 1; i <= limit - 1; i++) { // Subsequence for binary pattern i string sub = subsequence(s, i, len); // Storing sub in map if (!sorted_subsequence.ContainsKey(sub.Length)) sorted_subsequence[sub.Length] = new HashSet<string>(); sorted_subsequence[sub.Length].Add(sub); } foreach(var it in sorted_subsequence) { // it.first is length of Subsequence // it.second is set<String> Console.WriteLine(\"Subsequences of length = \" + it.Key + \" are:\"); foreach(String ii in it.Value) // ii is iterator of type set<String> Console.Write(ii + \" \"); Console.WriteLine(); } } // Driver code public static void Main(string[] args) { string s = \"aabc\"; possibleSubsequences(s); }} // This code is contributed by phasing17", "e": 8245, "s": 6477, "text": null }, { "code": "<script> // Javascript program to print all Subsequences// of a string in iterative manner // function to find subsequencefunction subsequence(s, binary, len){ let sub = \"\"; for(let j = 0; j < len; j++) // Check if jth bit in binary is 1 if (binary & (1 << j)) // If jth bit is 1, include it // in subsequence sub += s[j]; return sub;} // Function to print all subsequencesfunction possibleSubsequences(s){ // map to store subsequence // lexicographically by length let sorted_subsequence = new Map(); let len = s.length; // Total number of non-empty subsequence // in string is 2^len-1 let limit = Math.pow(2, len); // i=0, corresponds to empty subsequence for(let i = 1; i <= limit - 1; i++) { // Subsequence for binary pattern i let sub = subsequence(s, i, len); // Storing sub in map if (!sorted_subsequence.has(sub.length)) sorted_subsequence.set(sub.length, new Set()); sorted_subsequence.get(sub.length).add(sub); } for(let it of sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> document.write(\"Subsequences of length = \" + it[0] + \" are:\" + \"<br>\"); for(let ii of it[1]) // ii is iterator of type set<string> document.write(ii + \" \"); document.write(\"<br>\"); }} // Driver codelet s = \"aabc\"; possibleSubsequences(s); // This code is contributed by gfgking </script>", "e": 9831, "s": 8245, "text": null }, { "code": null, "e": 9840, "s": 9831, "text": "Output: " }, { "code": null, "e": 10006, "s": 9840, "text": "Subsequences of length = 1 are:\na b c \nSubsequences of length = 2 are:\naa ab ac bc \nSubsequences of length = 3 are:\naab aac abc \nSubsequences of length = 4 are:\naabc" }, { "code": null, "e": 10109, "s": 10006, "text": "Time Complexity : , where n is length of string to find subsequences and l is length of binary string." }, { "code": null, "e": 10132, "s": 10109, "text": "Space Complexity: O(1)" }, { "code": null, "e": 10376, "s": 10132, "text": "Approach 2 : Approach is to get the position of rightmost set bit and reset that bit after appending corresponding character from given string to the subsequence and will repeat the same thing till corresponding binary pattern has no set bits." }, { "code": null, "e": 10892, "s": 10376, "text": "If input is s = “abc” Binary representation to consider 1 to (2^3-1), i.e 1 to 7. 001 => abc . Only c corresponds to bit 1. So, subsequence = c 101 => abc . a and c corresponds to bit 1. So, subsequence = ac.Let us use Binary representation of 5, i.e 101. Rightmost bit is at position 1, append character at beginning of sub = c ,reset position 1 => 100 Rightmost bit is at position 3, append character at beginning of sub = ac ,reset position 3 => 000 As now we have no set bit left, we stop computing subsequence." }, { "code": null, "e": 11165, "s": 10892, "text": "Example :binary_representation (1) = 001 => c binary_representation (2) = 010 => b binary_representation (3) = 011 => bc binary_representation (4) = 100 => a binary_representation (5) = 101 => ac binary_representation (6) = 110 => ab binary_representation (7) = 111 => abc" }, { "code": null, "e": 11214, "s": 11165, "text": "Below is the implementation of above approach : " }, { "code": null, "e": 11218, "s": 11214, "text": "C++" }, { "code": null, "e": 11226, "s": 11218, "text": "Python3" }, { "code": null, "e": 11229, "s": 11226, "text": "C#" }, { "code": null, "e": 11240, "s": 11229, "text": "Javascript" }, { "code": "// C++ code all Subsequences of a// string in iterative manner#include <bits/stdc++.h>using namespace std; // function to find subsequencestring subsequence(string s, int binary){ string sub = \"\"; int pos; // loop while binary is greater than 0 while(binary>0) { // get the position of rightmost set bit pos=log2(binary&-binary)+1; // append at beginning as we are // going from LSB to MSB sub=s[pos-1]+sub; // resets bit at pos in binary binary= (binary & ~(1 << (pos-1))); } reverse(sub.begin(),sub.end()); return sub;} // function to print all subsequencesvoid possibleSubsequences(string s){ // map to store subsequence // lexicographically by length map<int, set<string> > sorted_subsequence; int len = s.size(); // Total number of non-empty subsequence // in string is 2^len-1 int limit = pow(2, len); // i=0, corresponds to empty subsequence for (int i = 1; i <= limit - 1; i++) { // subsequence for binary pattern i string sub = subsequence(s, i); // storing sub in map sorted_subsequence[sub.length()].insert(sub); } for (auto it : sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> cout << \"Subsequences of length = \" << it.first << \" are:\" << endl; for (auto ii : it.second) // ii is iterator of type set<string> cout << ii << \" \"; cout << endl; }} // driver functionint main(){ string s = \"aabc\"; possibleSubsequences(s); return 0;}", "e": 12938, "s": 11240, "text": null }, { "code": "# Python3 program to print all Subsequences# of a string in an iterative mannerfrom math import log2, floor # function to find subsequencedef subsequence(s, binary): sub = \"\" # loop while binary is greater than while(binary > 0): # get the position of rightmost set bit pos=floor(log2(binary&-binary) + 1) # append at beginning as we are # going from LSB to MSB sub = s[pos - 1] + sub # resets bit at pos in binary binary= (binary & ~(1 << (pos - 1))) sub = sub[::-1] return sub # function to print all subsequencesdef possibleSubsequences(s): # map to store subsequence # lexicographically by length sorted_subsequence = {} length = len(s) # Total number of non-empty subsequence # in string is 2^len-1 limit = 2 ** length # i=0, corresponds to empty subsequence for i in range(1, limit): # subsequence for binary pattern i sub = subsequence(s, i) # storing sub in map if len(sub) in sorted_subsequence.keys(): sorted_subsequence[len(sub)] = \\ tuple(list(sorted_subsequence[len(sub)]) + [sub]) else: sorted_subsequence[len(sub)] = [sub] for it in sorted_subsequence: # it.first is length of Subsequence # it.second is set<string> print(\"Subsequences of length =\", it, \"are:\") for ii in sorted(set(sorted_subsequence[it])): # ii is iterator of type set<string> print(ii, end = ' ') print() # Driver Codes = \"aabc\"possibleSubsequences(s) # This code is contributed by ankush_953", "e": 14621, "s": 12938, "text": null }, { "code": "// C# program to print all Subsequences// of a string in an iterative manner using System;using System.Collections.Generic;using System.Linq; class GFG{ // function to find subsequence static string subsequence(string s, int binary) { string sub = \"\"; // loop while binary is greater than while (binary > 0) { // get the position of rightmost set bit var pos = (int)Math.Floor( Math.Log(binary & (-binary)) / Math.Log(2)) + 1; // append at beginning as we are // going from LSB to MSB sub = s[pos - 1] + sub; // resets bit at pos in binary binary = (binary & ~(1 << (pos - 1))); } char[] charArray = sub.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } // function to print all subsequences static void possibleSubsequences(string s) { // map to store subsequence // lexicographically by length Dictionary<int, HashSet<string> > sorted_subsequence = new Dictionary<int, HashSet<string> >(); int length = s.Length; // Total number of non-empty subsequence // in string is 2^len-1 int limit = (int)Math.Pow(2, length); // i=0, corresponds to empty subsequence for (int i = 1; i < limit; i++) { // subsequence for binary pattern i string sub = subsequence(s, i); // storing sub in map if (sorted_subsequence.ContainsKey( sub.Length)) { sorted_subsequence[sub.Length].Add(sub); } else { sorted_subsequence[sub.Length] = new HashSet<string>(); sorted_subsequence[sub.Length].Add(sub); } } foreach(var it in sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> Console.WriteLine(\"Subsequences of length = \" + it.Key + \" are:\"); var arr = (it.Value).ToArray(); Array.Sort(arr); for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); } } // Driver Code public static void Main(string[] args) { string s = \"aabc\"; possibleSubsequences(s); }} // This code is contributed by phasing17", "e": 16784, "s": 14621, "text": null }, { "code": "// JavaScript program to print all Subsequences// of a string in an iterative manner // function to find subsequencefunction subsequence(s, binary){ var sub = \"\"; // loop while binary is greater than while(binary > 0) { // get the position of rightmost set bit var pos= Math.floor(Math.log2(binary&-binary) + 1); // append at beginning as we are // going from LSB to MSB sub = s[pos - 1] + sub; // resets bit at pos in binary binary= (binary & ~(1 << (pos - 1))); } sub = sub.split(\"\"); sub = sub.reverse(); return sub.join(\"\");} // function to print all subsequencesfunction possibleSubsequences(s){ // map to store subsequence // lexicographically by length var sorted_subsequence = {}; var length = s.length; // Total number of non-empty subsequence // in string is 2^len-1 var limit = 2 ** length; // i=0, corresponds to empty subsequence for (var i = 1; i < limit; i++) { // subsequence for binary pattern i var sub = subsequence(s, i); // storing sub in map if (sorted_subsequence.hasOwnProperty(sub.length)) { //var list = sorted_subsequence[sub.length]; //list.push(sub); sorted_subsequence[sub.length].push(sub); } else sorted_subsequence[sub.length] = [sub]; } for (const it in sorted_subsequence) { // it.first is length of Subsequence // it.second is set<string> console.log(\"Subsequences of length =\", it, \"are:\"); var arr = sorted_subsequence[it]; arr.sort(); var set = new Set(arr); for (const ii of set) // ii is iterator of type set<string> process.stdout.write(ii + \" \"); console.log() }} // Driver Codevar s = \"aabc\";possibleSubsequences(s); // This code is contributed by phasing17", "e": 18736, "s": 16784, "text": null }, { "code": null, "e": 18745, "s": 18736, "text": "Output: " }, { "code": null, "e": 18911, "s": 18745, "text": "Subsequences of length = 1 are:\na b c \nSubsequences of length = 2 are:\naa ab ac bc \nSubsequences of length = 3 are:\naab aac abc \nSubsequences of length = 4 are:\naabc" }, { "code": null, "e": 19032, "s": 18911, "text": "Time Complexity: , where n is the length of string to find subsequence and b is the number of set bits in binary string." }, { "code": null, "e": 19055, "s": 19032, "text": "Auxiliary Space: O(n) " }, { "code": null, "e": 19066, "s": 19055, "text": "ankush_953" }, { "code": null, "e": 19079, "s": 19066, "text": "Akanksha_Rai" }, { "code": null, "e": 19091, "s": 19079, "text": "sanjeev2552" }, { "code": null, "e": 19099, "s": 19091, "text": "gfgking" }, { "code": null, "e": 19116, "s": 19099, "text": "surinderdawra388" }, { "code": null, "e": 19126, "s": 19116, "text": "phasing17" }, { "code": null, "e": 19141, "s": 19126, "text": "ranjanrohit840" }, { "code": null, "e": 19153, "s": 19141, "text": "subsequence" }, { "code": null, "e": 19163, "s": 19153, "text": "Bit Magic" }, { "code": null, "e": 19187, "s": 19163, "text": "Competitive Programming" }, { "code": null, "e": 19195, "s": 19187, "text": "Strings" }, { "code": null, "e": 19214, "s": 19195, "text": "Technical Scripter" }, { "code": null, "e": 19222, "s": 19214, "text": "Strings" }, { "code": null, "e": 19232, "s": 19222, "text": "Bit Magic" }, { "code": null, "e": 19330, "s": 19232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19383, "s": 19330, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 19413, "s": 19383, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 19451, "s": 19413, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 19491, "s": 19451, "text": "Binary representation of a given number" }, { "code": null, "e": 19534, "s": 19491, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 19577, "s": 19534, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 19620, "s": 19577, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 19661, "s": 19620, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 19688, "s": 19661, "text": "Modulo 10^9+7 (1000000007)" } ]
Python | Pandas Series.agg()
19 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.agg() is used to pass a function or list of function to be applied on a series or even each element of series separately. In case of list of function, multiple results are returned by agg() method. Syntax: Series.agg(func, axis=0) Parameters:func: Function, list of function or string of function name to be called on Series.axis:0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation. Return Type: The return type depends on return type of function passed as parameter. Example #1:In this example, a lambda function is passed which simply adds 2 to each value of series. Since the function will be applied to each value of series, the return type is also series. A random series of 10 elements is generated by passing array generated using Numpy random method. # importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating random arr of 10 elementsarr=np.random.randn(10) # creating series from arrayseries=pd.Series(arr) # calling .agg() methodresult=series.agg(lambda num : num + 2) # displayprint('Array before operation: \n', series, '\n\nArray after operation: \n',result) Output:As shown in output, the function was applied to each value and 2 was added to each value of series. Example #2: Passing List of functions In this example, a list of some Python’s default function is passed and multiple results are returned by agg() method into multiple variables. # importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating random arr of 10 elementsarr=np.random.randn(10) # creating series from arrayseries=pd.Series(arr) # creating list of function namesfunc_list=[min, max, sorted] # calling .agg() method# passing list of functionsresult1, result2, result3= series.agg(func_list) # displayprint('Series before operation: \n', series)print('\nMin = {}\n\nMax = {},\ \n\nSorted Series:\n{}'.format(result1,result2,result3)) Output:As shown in output, multiple results were returned. Min, Max and Sorted array were returned into different variables result1, result2, result3 respectively. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 454, "s": 242, "text": "Pandas Series.agg() is used to pass a function or list of function to be applied on a series or even each element of series separately. In case of list of function, multiple results are returned by agg() method." }, { "code": null, "e": 487, "s": 454, "text": "Syntax: Series.agg(func, axis=0)" }, { "code": null, "e": 668, "s": 487, "text": "Parameters:func: Function, list of function or string of function name to be called on Series.axis:0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation." }, { "code": null, "e": 753, "s": 668, "text": "Return Type: The return type depends on return type of function passed as parameter." }, { "code": null, "e": 1044, "s": 753, "text": "Example #1:In this example, a lambda function is passed which simply adds 2 to each value of series. Since the function will be applied to each value of series, the return type is also series. A random series of 10 elements is generated by passing array generated using Numpy random method." }, { "code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating random arr of 10 elementsarr=np.random.randn(10) # creating series from arrayseries=pd.Series(arr) # calling .agg() methodresult=series.agg(lambda num : num + 2) # displayprint('Array before operation: \\n', series, '\\n\\nArray after operation: \\n',result)", "e": 1414, "s": 1044, "text": null }, { "code": null, "e": 1521, "s": 1414, "text": "Output:As shown in output, the function was applied to each value and 2 was added to each value of series." }, { "code": null, "e": 1560, "s": 1521, "text": " Example #2: Passing List of functions" }, { "code": null, "e": 1703, "s": 1560, "text": "In this example, a list of some Python’s default function is passed and multiple results are returned by agg() method into multiple variables." }, { "code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # creating random arr of 10 elementsarr=np.random.randn(10) # creating series from arrayseries=pd.Series(arr) # creating list of function namesfunc_list=[min, max, sorted] # calling .agg() method# passing list of functionsresult1, result2, result3= series.agg(func_list) # displayprint('Series before operation: \\n', series)print('\\nMin = {}\\n\\nMax = {},\\ \\n\\nSorted Series:\\n{}'.format(result1,result2,result3))", "e": 2222, "s": 1703, "text": null }, { "code": null, "e": 2386, "s": 2222, "text": "Output:As shown in output, multiple results were returned. Min, Max and Sorted array were returned into different variables result1, result2, result3 respectively." }, { "code": null, "e": 2407, "s": 2386, "text": "Python pandas-series" }, { "code": null, "e": 2436, "s": 2407, "text": "Python pandas-series-methods" }, { "code": null, "e": 2450, "s": 2436, "text": "Python-pandas" }, { "code": null, "e": 2457, "s": 2450, "text": "Python" } ]
How to pass variables to the next middleware using next() in Express.js ? - GeeksforGeeks
17 Feb, 2021 The following example covers how to pass variables to the next middleware using next() in Express.js. Approach: We cannot directly pass data to the next middleware, but we can send data through the request object. [Middleware 1] [Middleware 2]request.mydata = someData; ——-> let dataFromMiddleware1 = request.mydata; Installation of Express module: You can visit the link Install express module. You can install this package by using this command. npm install express After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command. node index.js Filename: index.js Javascript // Requiring moduleconst express = require("express");const app = express(); function middleware1(req, res, next) { // Set data req.dataFromMiddleware1 = "Data of Middleware 1"; // Go to next middleware next();} function middleware2(req, res, next) { console.log("We are in Middleware 2."); // Get Data of Middleware1 console.log(req.dataFromMiddleware1); // Go to next middleware next();} // Handling Get Request '/'app.get("/", middleware1, middleware2, (req, res) => { return res.send(req.dataFromMiddleware1);}); // Server Setupapp.listen(5000, () => { console.log(`Server is up and running on 5000 ...`);}); Steps to run the program: Run the index.js file using the following command: node index.js Output: We will see the following output on the console: Server is up and running on 5000 ... Now open the browser and go to http://localhost:5000/, you will see the following output on screen: Output on Browser Now again check the terminal output, it will look like the following: Server is up and running on 5000 ... We are in Middleware 2. Data of Middleware 1 Express.js Picked Technical Scripter 2020 Node.js Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Mongoose Populate() Method Difference between npm i and npm ci in Node.js How to build a basic CRUD app with Node.js and ReactJS ? Mongoose find() Function Node.js Export Module How to connect Node.js with React.js ? Node.js fs.createReadStream() Method
[ { "code": null, "e": 25026, "s": 24998, "text": "\n17 Feb, 2021" }, { "code": null, "e": 25128, "s": 25026, "text": "The following example covers how to pass variables to the next middleware using next() in Express.js." }, { "code": null, "e": 25138, "s": 25128, "text": "Approach:" }, { "code": null, "e": 25240, "s": 25138, "text": "We cannot directly pass data to the next middleware, but we can send data through the request object." }, { "code": null, "e": 25343, "s": 25240, "text": "[Middleware 1] [Middleware 2]request.mydata = someData; ——-> let dataFromMiddleware1 = request.mydata;" }, { "code": null, "e": 25375, "s": 25343, "text": "Installation of Express module:" }, { "code": null, "e": 25474, "s": 25375, "text": "You can visit the link Install express module. You can install this package by using this command." }, { "code": null, "e": 25494, "s": 25474, "text": "npm install express" }, { "code": null, "e": 25628, "s": 25494, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command." }, { "code": null, "e": 25642, "s": 25628, "text": "node index.js" }, { "code": null, "e": 25661, "s": 25642, "text": "Filename: index.js" }, { "code": null, "e": 25672, "s": 25661, "text": "Javascript" }, { "code": "// Requiring moduleconst express = require(\"express\");const app = express(); function middleware1(req, res, next) { // Set data req.dataFromMiddleware1 = \"Data of Middleware 1\"; // Go to next middleware next();} function middleware2(req, res, next) { console.log(\"We are in Middleware 2.\"); // Get Data of Middleware1 console.log(req.dataFromMiddleware1); // Go to next middleware next();} // Handling Get Request '/'app.get(\"/\", middleware1, middleware2, (req, res) => { return res.send(req.dataFromMiddleware1);}); // Server Setupapp.listen(5000, () => { console.log(`Server is up and running on 5000 ...`);});", "e": 26306, "s": 25672, "text": null }, { "code": null, "e": 26332, "s": 26306, "text": "Steps to run the program:" }, { "code": null, "e": 26383, "s": 26332, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 26397, "s": 26383, "text": "node index.js" }, { "code": null, "e": 26406, "s": 26397, "text": "Output: " }, { "code": null, "e": 26455, "s": 26406, "text": "We will see the following output on the console:" }, { "code": null, "e": 26493, "s": 26455, "text": "Server is up and running on 5000 ...\n" }, { "code": null, "e": 26593, "s": 26493, "text": "Now open the browser and go to http://localhost:5000/, you will see the following output on screen:" }, { "code": null, "e": 26611, "s": 26593, "text": "Output on Browser" }, { "code": null, "e": 26682, "s": 26611, "text": "Now again check the terminal output, it will look like the following: " }, { "code": null, "e": 26764, "s": 26682, "text": "Server is up and running on 5000 ...\nWe are in Middleware 2.\nData of Middleware 1" }, { "code": null, "e": 26775, "s": 26764, "text": "Express.js" }, { "code": null, "e": 26782, "s": 26775, "text": "Picked" }, { "code": null, "e": 26806, "s": 26782, "text": "Technical Scripter 2020" }, { "code": null, "e": 26814, "s": 26806, "text": "Node.js" }, { "code": null, "e": 26833, "s": 26814, "text": "Technical Scripter" }, { "code": null, "e": 26931, "s": 26833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26968, "s": 26931, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27000, "s": 26968, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 27031, "s": 27000, "text": "Express.js req.params Property" }, { "code": null, "e": 27058, "s": 27031, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27105, "s": 27058, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 27162, "s": 27105, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 27187, "s": 27162, "text": "Mongoose find() Function" }, { "code": null, "e": 27209, "s": 27187, "text": "Node.js Export Module" }, { "code": null, "e": 27248, "s": 27209, "text": "How to connect Node.js with React.js ?" } ]
OpenCV - The IMREAD_XXX Flag
OpenCV supports various types of images such as colored, binary, grayscale, etc. Using the imread() method and predefined fields of the Imgcodecs class, you can read a given image as another type. In the earlier chapters, we have seen the syntax of imread() method of the Imgcodecs class. It accepts a string argument representing the location of the image that is to be read. imread(filename) The imread() method has another syntax. imread(filename, int flags) This syntax accepts two parameters − filename − It accepts an argument (filename), a variable of the String type representing the path of the file that is to be read. filename − It accepts an argument (filename), a variable of the String type representing the path of the file that is to be read. flags − An integer value representing a predefined flag value. For each value, this reads the given image as a specific type (gray scale color etc.) flags − An integer value representing a predefined flag value. For each value, this reads the given image as a specific type (gray scale color etc.) Following is the table listing various fields provided in the Imgproc class as values for this parameter. IMREAD_COLOR If the flag is set to this value, the loaded image will be converted to a 3-channel BGR (Blue Green Red) color image. IMREAD_GRAYSCALE If the flag is set to this value, the loaded image will be converted to a single-channel grayscale image. IMREAD_LOAD_GDAL If the flag is set to this value, you can load the image using the gdal driver. IMREAD_ANYCOLOR If the flag is set to this value, the image is read in any possible color format. IMREAD_REDUCED_COLOR_2 IMREAD_REDUCED_COLOR_4 IMREAD_REDUCED_COLOR_8 If the flag is set to this value, the image is read as three-channel BGR, and the size of the image is reduced to 1⁄2, 1⁄4th or 1⁄8th of the original size of the image with respect to the field used. IMREAD_REDUCED_GRAYSCALE_2 IMREAD_REDUCED_GRAYSCALE_4 IMREAD_REDUCED_GRAYSCALE_8 If the flag is set to this value, the image is read as a single-channel grayscale image, and the size of the image is reduced to 1⁄2, 1⁄4th or 1⁄8th of the original size of the image with respect to the field used. IMREAD_UNCHANGED If the flag is set to this value, the loaded image is returned as it is. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3201, "s": 3004, "text": "OpenCV supports various types of images such as colored, binary, grayscale, etc. Using the imread() method and predefined fields of the Imgcodecs class, you can read a given image as another type." }, { "code": null, "e": 3381, "s": 3201, "text": "In the earlier chapters, we have seen the syntax of imread() method of the Imgcodecs class. It accepts a string argument representing the location of the image that is to be read." }, { "code": null, "e": 3399, "s": 3381, "text": "imread(filename)\n" }, { "code": null, "e": 3439, "s": 3399, "text": "The imread() method has another syntax." }, { "code": null, "e": 3468, "s": 3439, "text": "imread(filename, int flags)\n" }, { "code": null, "e": 3505, "s": 3468, "text": "This syntax accepts two parameters −" }, { "code": null, "e": 3635, "s": 3505, "text": "filename − It accepts an argument (filename), a variable of the String type representing the path of the file that is to be read." }, { "code": null, "e": 3765, "s": 3635, "text": "filename − It accepts an argument (filename), a variable of the String type representing the path of the file that is to be read." }, { "code": null, "e": 3914, "s": 3765, "text": "flags − An integer value representing a predefined flag value. For each value, this reads the given image as a specific type (gray scale color etc.)" }, { "code": null, "e": 4063, "s": 3914, "text": "flags − An integer value representing a predefined flag value. For each value, this reads the given image as a specific type (gray scale color etc.)" }, { "code": null, "e": 4169, "s": 4063, "text": "Following is the table listing various fields provided in the Imgproc class as values for this parameter." }, { "code": null, "e": 4182, "s": 4169, "text": "IMREAD_COLOR" }, { "code": null, "e": 4300, "s": 4182, "text": "If the flag is set to this value, the loaded image will be converted to a 3-channel BGR (Blue Green Red) color image." }, { "code": null, "e": 4317, "s": 4300, "text": "IMREAD_GRAYSCALE" }, { "code": null, "e": 4423, "s": 4317, "text": "If the flag is set to this value, the loaded image will be converted to a single-channel grayscale image." }, { "code": null, "e": 4440, "s": 4423, "text": "IMREAD_LOAD_GDAL" }, { "code": null, "e": 4520, "s": 4440, "text": "If the flag is set to this value, you can load the image using the gdal driver." }, { "code": null, "e": 4536, "s": 4520, "text": "IMREAD_ANYCOLOR" }, { "code": null, "e": 4618, "s": 4536, "text": "If the flag is set to this value, the image is read in any possible color format." }, { "code": null, "e": 4641, "s": 4618, "text": "IMREAD_REDUCED_COLOR_2" }, { "code": null, "e": 4664, "s": 4641, "text": "IMREAD_REDUCED_COLOR_4" }, { "code": null, "e": 4687, "s": 4664, "text": "IMREAD_REDUCED_COLOR_8" }, { "code": null, "e": 4888, "s": 4687, "text": "If the flag is set to this value, the image is read as three-channel BGR, and the size of the image is reduced to 1⁄2, 1⁄4th or 1⁄8th of the original size of the image with respect to the field used." }, { "code": null, "e": 4915, "s": 4888, "text": "IMREAD_REDUCED_GRAYSCALE_2" }, { "code": null, "e": 4942, "s": 4915, "text": "IMREAD_REDUCED_GRAYSCALE_4" }, { "code": null, "e": 4969, "s": 4942, "text": "IMREAD_REDUCED_GRAYSCALE_8" }, { "code": null, "e": 5184, "s": 4969, "text": "If the flag is set to this value, the image is read as a single-channel grayscale image, and the size of the image is reduced to 1⁄2, 1⁄4th or 1⁄8th of the original size of the image with respect to the field used." }, { "code": null, "e": 5201, "s": 5184, "text": "IMREAD_UNCHANGED" }, { "code": null, "e": 5274, "s": 5201, "text": "If the flag is set to this value, the loaded image is returned as it is." }, { "code": null, "e": 5307, "s": 5274, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5324, "s": 5307, "text": " Abhilash Nelson" }, { "code": null, "e": 5357, "s": 5324, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 5374, "s": 5357, "text": " Abhilash Nelson" }, { "code": null, "e": 5407, "s": 5374, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5421, "s": 5407, "text": " Spotle Learn" }, { "code": null, "e": 5453, "s": 5421, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 5470, "s": 5453, "text": " Srikanth Guskra" }, { "code": null, "e": 5503, "s": 5470, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5518, "s": 5503, "text": " Haithem Gasmi" }, { "code": null, "e": 5553, "s": 5518, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5571, "s": 5553, "text": " Gianluca Mottola" }, { "code": null, "e": 5578, "s": 5571, "text": " Print" }, { "code": null, "e": 5589, "s": 5578, "text": " Add Notes" } ]
Turbo-charge your spaCy NLP pipeline | by Prashanth Rao | Towards Data Science
Consider you have a large text dataset on which you want to apply some non-trivial NLP transformations, such as stopword removal followed by lemmatizing the words (i.e. reducing them to root form) in the text. spaCy is an industrial-strength NLP library designed for just such a task. In this post, the New York Times dataset is used to showcase how to significantly speed up a spaCy NLP pipeline. The goal is to take in an article’s text, and speedily return a list of lemmas as well as unnecessary words, i.e. stopwords, removed. Pandas DataFrames provide a convenient interface to work with tabular data of this nature — the spaCy NLP methods can be conveniently applied directly to the relevant column of the DataFrame. First, the news data is obtained by running the preprocessing notebook (./data/preprocessing.ipynb), which processes the raw text file downloaded from Kaggle and performs some basic cleaning on it. This step generates a file that contains the tabular data (stored as nytimes.tsv). A curated stopword file is also provided in the same directory. Since we will not be doing any specialized tasks such as dependency parsing and named entity recognition in this exercise, these components are disabled when loading the spaCy model. Tip: spaCy has a sentencizer component that can be plugged into a blank pipeline. The sentencizer pipeline simply performs tokenization and sentence boundary detection, following which lemmas can be extracted as token properties. A method is defined to read in stopwords from a text file and convert it to a set in Python (for efficient lookup). The pre-processed version of the NYT news dataset is read in as a Pandas DataFrame. The columns are named date, headline and content - the text present in the content column is what will be preprocessed to remove stopwords and generate token lemmas. Since the news article data comes from a raw HTML dump, it is very messy and contains a host of unnecessary symbols, social media handles, URLs and other artifacts. An easy way to clean it up is to use a regex that parses only alphanumeric strings and hyphens (so as to include hyphenated words) that are between a given length (3 and 50). This filters each document down to only meaningful text for the lemmatizer. Now that we have just the clean, alphanumeric tokens left over, these can be further cleaned up by removing stopwords before proceeding to lemmatization. The straightforward way to process this text is to use an existing method, in this case, the lemmatize method shown below, and apply it to the clean column of the DataFrame using pandas.Series.apply. Lemmatization is done using the spaCy's underlying Doc representation of each token, which contains a lemma_ property. Stopwords are removed simultaneously with the lemmatization process, as each of these steps involves iterating through the same list of tokens. The resulting lemmas are stored as a list in a separate column preproc as shown below. %%timedf_preproc['preproc'] = df_preproc['clean'].apply(lemmatize)df_preproc[['date', 'content', 'preproc']].head(3)CPU times: user 48.5 s, sys: 146 ms, total: 48.6 s Wall time: 48.6 s Applying this method to the clean column of the DataFrame and timing it shows that it takes almost a minute to run on 8,800 news articles. Can we do better? in the spaCy documentation, it is stated that “processing texts as a stream is usually more efficient than processing them one-by-one”. This is done by calling a language pipe, which internally divides the data into batches to reduce the number of pure-Python function calls. This means that the larger the data, the better the performance gain that can be obtained by nlp.pipe. To use the language pipe to stream texts, a new lemmatizer method is defined that directly works on a spaCy Doc object. This method is then called in batches to work on a sequence of Doc objects that are streamed through the pipe as shown below. Just as before, a new column is created by passing data from the clean column of the existing DataFrame. Note that unlike in workflow #1 above, we do not use the apply method here - instead, the column of data (an iterable) is directly passed as an argument to the preprocessor pipe method. %%timedf_preproc['preproc_pipe'] = preprocess_pipe(df_preproc['clean'])df_preproc[['date', 'content', 'preproc_pipe']].head(3)CPU times: user 51.6 s, sys: 144 ms, total: 51.8 s Wall time: 51.8 s Timing this workflow doesn’t seem to show improvement over the previous workflow, but as per the spaCy documentation, one would expect that as we work on bigger and bigger datasets, this approach should show some timing improvement (on average). We can do still better! The previous workflows sequentially worked through each news document to produce the lemma lists, which were then appended to the DataFrame as a new column. Because each row’s output is completely independent of the other, this is an embarrassingly parallel problem, making it ideal for using multiple cores. The joblib library is recommended by spaCy for processing blocks of an NLP pipeline in parallel. Make sure that you pip install joblib before running the below section. To parallelize the workflow, a few more helper methods must be defined. Chunking: The news article content is a list of (long) strings where each document represents a single article’s text. This data must be fed in “chunks” to each worker process started by joblib. Each call of the chunker method returns a generator that only contains that particular chunk's text as a list of strings. During lemmatization, each new chunk is retrieved based on the iterator index (with the previous chunks being "forgotten"). Flattening: Once joblib creates a set of worker processes that work on each chunk, each worker returns a “list of lists” containing lemmas for each document. These lists are then combined by the executor to provide a 3-level nested final “list of lists of lists”. To ensure that the length of the output from the executor is the same as the actual number of articles, a “flatten” method is defined to combine the result into a list of lists containing lemmas. As an example, two parallel executors would return a final nested list of the form: [[[a, b, c], [d, e, f]], [[g, h, i], [j, k, l]]], where [[a, b, c], [d, e, f]] and [[g, h, i], [j, k, l]] refer to the output from each executor (the final output is then concatenated to a single list by joblib). A flattened version of this result would be [[a, b, c], [d, e, f], [g, h, i], [j, k, l]], i.e. with one level of nesting removed. In addition to the above methods, a similar nlp.pipe method is used as in workflow #2, on each chunk of texts. Each of these methods is wrapped into a preprocess_parallel method that defines the number of worker processes to be used (7 in this case), breaks the input data into chunks and returns a flattened result that can then be appended to the DataFrame. For machines with a higher number of physical cores, the number of worker processes can be increased further. The parallelized workflow using joblib is shown below. %%timedf_preproc['preproc_parallel'] = preprocess_parallel(df_preproc['clean'], chunksize=1000)CPU times: user 683 ms, sys: 248 ms, total: 932 ms Wall time: 17.2 s Timing this parallelized workflow shows significant performance gains (almost 3x reduction in run time)! As the number of documents becomes larger, the additional overhead of starting multiple worker processes with joblib is quickly paid for, and this method can significantly outperform the sequential methods. Note that in the parallelized workflow, two parameters need to be specified — the optimum number can vary depending on the dataset. The chunksize controls the size of each chunk being worked on by each process. In this example, for 8,800 documents, a chunksize of 1000 is used. Too small a chunksize would mean that a large number of workers would spawn to deal with the large number of chunks overall, which can slow down execution. Generally, a chunksize of several hundred documents to a few thousand is a good starting point (of course, this depends on how big each document in the data is so that the chunks can fit into memory). The batch size is parameter specific to nlp.pipe, and again, a good value depends on the data being worked on. For reasonably long-sized text such as news articles, it makes sense to keep the batch size reasonably small (so that each batch doesn't contain really long texts), so in this case 20 was chosen for the batch size. For other cases (e.g. Tweets) where each document is much shorter in length, a larger batch size can be used. It is recommended to experiment with either parameter to see which combination produces the best performance. Important: Use sets over lists for lookups wherever possible. Note that in the get_stopwords() method defined earlier on, the list of stopwords read in from the stopword file was converted to a set before using it in the lemmatizer method for stopword removal via lookups. This is a very useful trick in general, but specifically for stopword removal, the use of sets becomes all the more important. Why? In any realistic stopword list, such as this one for a news dataset, it’s reasonable to expect several hundred stopwords. This is because for downstream tasks such as topic modelling or sentiment analysis, there are a number of domain-specific words that need to be removed (very common verbs, useless abbreviations such as timezones, days of the week, etc.). Each word in each and every document needs to be compared against every word in the stopword list, which is an expensive operation over tens of thousands of documents. It’s well known that sets have O(1) (i.e. constant) lookup time as opposed to lists, which have O(n) lookup time. In the lemmatize() method, since we're checking each word for membership in the set of stopwords, we would expect sets to be much better than lists. To test this, we can rerun workflow #1 but this time, use a stopword list instead. stopwords = list(stopwords)%%timedf_preproc['preproc_stopword_list'] = df_preproc['clean'].apply(lemmatize)df_preproc[['date', 'content', 'preproc_stopword_list']].head(3)CPU times: user 1min 17s, sys: 108 ms, total: 1min 18s Wall time: 1min 18s With a stopword list, producing the same result now takes ~ 50% longer than it did before (with the set), which is a 1.5x increase in run time! This makes sense because in this case, the stopword list is about 500 words long, and each and every word in the corpus needs to be checked for membership in this reasonable-sized list. In this exercise, a news article dataset (NY Times) was processed using a spaCy pipeline to output a list of lemmas representing the useful tokens present in each article’s content. Because real-world news datasets are almost certainly bigger than this one, and can be unbounded in size, a fast, efficient NLP pipeline is necessary to perform any meaningful analysis on the data. The following steps are very useful in speeding up the spaCy pipeline. Disable unnecessary components in spaCy model: The standard spaCy model’s pipeline contains the tagger (to assign part-of-speech tags), the parser (to generate a dependency parse) and named entity recognition components. If any or none of these actions are desired, these components must be disabled immediately after loading the model (as shown above). Use sets over lists for lookups: When performing lookups to compare one set of tokens against another, always perform membership checks using sets — lists are significantly slower for lookups! The larger the list/set of stopwords, the bigger the performance gain seen when using sets. Use custom language pipes when possible: Setting up a language pipe using nlp.pipe is an extremely flexible and efficient way to process large blocks of text. Even better, spaCy allows you to individually disable components for each specific sub-task, for example, when you need to separately perform part-of-speech tagging and named entity recognition (NER). See the spaCy docs for examples on how to disable pipeline components during model loading, processing or handling custom blocks. Use multiple cores when possible: When processing individual documents completely independent of one another, consider parallelizing the workflow by dividing the computation across multiple cores. As the number of documents becomes larger and larger, the performance gains can be tremendous. One just needs to ensure that the documents are divided up into chunks, all of which must fit into memory at any given time. I hope this was useful — have fun testing these out in your next NLP project! Originally published at https://prrao87.github.io on May 2, 2020.
[ { "code": null, "e": 456, "s": 171, "text": "Consider you have a large text dataset on which you want to apply some non-trivial NLP transformations, such as stopword removal followed by lemmatizing the words (i.e. reducing them to root form) in the text. spaCy is an industrial-strength NLP library designed for just such a task." }, { "code": null, "e": 703, "s": 456, "text": "In this post, the New York Times dataset is used to showcase how to significantly speed up a spaCy NLP pipeline. The goal is to take in an article’s text, and speedily return a list of lemmas as well as unnecessary words, i.e. stopwords, removed." }, { "code": null, "e": 1240, "s": 703, "text": "Pandas DataFrames provide a convenient interface to work with tabular data of this nature — the spaCy NLP methods can be conveniently applied directly to the relevant column of the DataFrame. First, the news data is obtained by running the preprocessing notebook (./data/preprocessing.ipynb), which processes the raw text file downloaded from Kaggle and performs some basic cleaning on it. This step generates a file that contains the tabular data (stored as nytimes.tsv). A curated stopword file is also provided in the same directory." }, { "code": null, "e": 1423, "s": 1240, "text": "Since we will not be doing any specialized tasks such as dependency parsing and named entity recognition in this exercise, these components are disabled when loading the spaCy model." }, { "code": null, "e": 1505, "s": 1423, "text": "Tip: spaCy has a sentencizer component that can be plugged into a blank pipeline." }, { "code": null, "e": 1653, "s": 1505, "text": "The sentencizer pipeline simply performs tokenization and sentence boundary detection, following which lemmas can be extracted as token properties." }, { "code": null, "e": 1769, "s": 1653, "text": "A method is defined to read in stopwords from a text file and convert it to a set in Python (for efficient lookup)." }, { "code": null, "e": 2019, "s": 1769, "text": "The pre-processed version of the NYT news dataset is read in as a Pandas DataFrame. The columns are named date, headline and content - the text present in the content column is what will be preprocessed to remove stopwords and generate token lemmas." }, { "code": null, "e": 2435, "s": 2019, "text": "Since the news article data comes from a raw HTML dump, it is very messy and contains a host of unnecessary symbols, social media handles, URLs and other artifacts. An easy way to clean it up is to use a regex that parses only alphanumeric strings and hyphens (so as to include hyphenated words) that are between a given length (3 and 50). This filters each document down to only meaningful text for the lemmatizer." }, { "code": null, "e": 2589, "s": 2435, "text": "Now that we have just the clean, alphanumeric tokens left over, these can be further cleaned up by removing stopwords before proceeding to lemmatization." }, { "code": null, "e": 3052, "s": 2589, "text": "The straightforward way to process this text is to use an existing method, in this case, the lemmatize method shown below, and apply it to the clean column of the DataFrame using pandas.Series.apply. Lemmatization is done using the spaCy's underlying Doc representation of each token, which contains a lemma_ property. Stopwords are removed simultaneously with the lemmatization process, as each of these steps involves iterating through the same list of tokens." }, { "code": null, "e": 3139, "s": 3052, "text": "The resulting lemmas are stored as a list in a separate column preproc as shown below." }, { "code": null, "e": 3324, "s": 3139, "text": "%%timedf_preproc['preproc'] = df_preproc['clean'].apply(lemmatize)df_preproc[['date', 'content', 'preproc']].head(3)CPU times: user 48.5 s, sys: 146 ms, total: 48.6 s Wall time: 48.6 s" }, { "code": null, "e": 3463, "s": 3324, "text": "Applying this method to the clean column of the DataFrame and timing it shows that it takes almost a minute to run on 8,800 news articles." }, { "code": null, "e": 3860, "s": 3463, "text": "Can we do better? in the spaCy documentation, it is stated that “processing texts as a stream is usually more efficient than processing them one-by-one”. This is done by calling a language pipe, which internally divides the data into batches to reduce the number of pure-Python function calls. This means that the larger the data, the better the performance gain that can be obtained by nlp.pipe." }, { "code": null, "e": 4106, "s": 3860, "text": "To use the language pipe to stream texts, a new lemmatizer method is defined that directly works on a spaCy Doc object. This method is then called in batches to work on a sequence of Doc objects that are streamed through the pipe as shown below." }, { "code": null, "e": 4397, "s": 4106, "text": "Just as before, a new column is created by passing data from the clean column of the existing DataFrame. Note that unlike in workflow #1 above, we do not use the apply method here - instead, the column of data (an iterable) is directly passed as an argument to the preprocessor pipe method." }, { "code": null, "e": 4592, "s": 4397, "text": "%%timedf_preproc['preproc_pipe'] = preprocess_pipe(df_preproc['clean'])df_preproc[['date', 'content', 'preproc_pipe']].head(3)CPU times: user 51.6 s, sys: 144 ms, total: 51.8 s Wall time: 51.8 s" }, { "code": null, "e": 4838, "s": 4592, "text": "Timing this workflow doesn’t seem to show improvement over the previous workflow, but as per the spaCy documentation, one would expect that as we work on bigger and bigger datasets, this approach should show some timing improvement (on average)." }, { "code": null, "e": 5171, "s": 4838, "text": "We can do still better! The previous workflows sequentially worked through each news document to produce the lemma lists, which were then appended to the DataFrame as a new column. Because each row’s output is completely independent of the other, this is an embarrassingly parallel problem, making it ideal for using multiple cores." }, { "code": null, "e": 5340, "s": 5171, "text": "The joblib library is recommended by spaCy for processing blocks of an NLP pipeline in parallel. Make sure that you pip install joblib before running the below section." }, { "code": null, "e": 5412, "s": 5340, "text": "To parallelize the workflow, a few more helper methods must be defined." }, { "code": null, "e": 5853, "s": 5412, "text": "Chunking: The news article content is a list of (long) strings where each document represents a single article’s text. This data must be fed in “chunks” to each worker process started by joblib. Each call of the chunker method returns a generator that only contains that particular chunk's text as a list of strings. During lemmatization, each new chunk is retrieved based on the iterator index (with the previous chunks being \"forgotten\")." }, { "code": null, "e": 6740, "s": 5853, "text": "Flattening: Once joblib creates a set of worker processes that work on each chunk, each worker returns a “list of lists” containing lemmas for each document. These lists are then combined by the executor to provide a 3-level nested final “list of lists of lists”. To ensure that the length of the output from the executor is the same as the actual number of articles, a “flatten” method is defined to combine the result into a list of lists containing lemmas. As an example, two parallel executors would return a final nested list of the form: [[[a, b, c], [d, e, f]], [[g, h, i], [j, k, l]]], where [[a, b, c], [d, e, f]] and [[g, h, i], [j, k, l]] refer to the output from each executor (the final output is then concatenated to a single list by joblib). A flattened version of this result would be [[a, b, c], [d, e, f], [g, h, i], [j, k, l]], i.e. with one level of nesting removed." }, { "code": null, "e": 7210, "s": 6740, "text": "In addition to the above methods, a similar nlp.pipe method is used as in workflow #2, on each chunk of texts. Each of these methods is wrapped into a preprocess_parallel method that defines the number of worker processes to be used (7 in this case), breaks the input data into chunks and returns a flattened result that can then be appended to the DataFrame. For machines with a higher number of physical cores, the number of worker processes can be increased further." }, { "code": null, "e": 7265, "s": 7210, "text": "The parallelized workflow using joblib is shown below." }, { "code": null, "e": 7429, "s": 7265, "text": "%%timedf_preproc['preproc_parallel'] = preprocess_parallel(df_preproc['clean'], chunksize=1000)CPU times: user 683 ms, sys: 248 ms, total: 932 ms Wall time: 17.2 s" }, { "code": null, "e": 7741, "s": 7429, "text": "Timing this parallelized workflow shows significant performance gains (almost 3x reduction in run time)! As the number of documents becomes larger, the additional overhead of starting multiple worker processes with joblib is quickly paid for, and this method can significantly outperform the sequential methods." }, { "code": null, "e": 8376, "s": 7741, "text": "Note that in the parallelized workflow, two parameters need to be specified — the optimum number can vary depending on the dataset. The chunksize controls the size of each chunk being worked on by each process. In this example, for 8,800 documents, a chunksize of 1000 is used. Too small a chunksize would mean that a large number of workers would spawn to deal with the large number of chunks overall, which can slow down execution. Generally, a chunksize of several hundred documents to a few thousand is a good starting point (of course, this depends on how big each document in the data is so that the chunks can fit into memory)." }, { "code": null, "e": 8812, "s": 8376, "text": "The batch size is parameter specific to nlp.pipe, and again, a good value depends on the data being worked on. For reasonably long-sized text such as news articles, it makes sense to keep the batch size reasonably small (so that each batch doesn't contain really long texts), so in this case 20 was chosen for the batch size. For other cases (e.g. Tweets) where each document is much shorter in length, a larger batch size can be used." }, { "code": null, "e": 8922, "s": 8812, "text": "It is recommended to experiment with either parameter to see which combination produces the best performance." }, { "code": null, "e": 8984, "s": 8922, "text": "Important: Use sets over lists for lookups wherever possible." }, { "code": null, "e": 9327, "s": 8984, "text": "Note that in the get_stopwords() method defined earlier on, the list of stopwords read in from the stopword file was converted to a set before using it in the lemmatizer method for stopword removal via lookups. This is a very useful trick in general, but specifically for stopword removal, the use of sets becomes all the more important. Why?" }, { "code": null, "e": 9855, "s": 9327, "text": "In any realistic stopword list, such as this one for a news dataset, it’s reasonable to expect several hundred stopwords. This is because for downstream tasks such as topic modelling or sentiment analysis, there are a number of domain-specific words that need to be removed (very common verbs, useless abbreviations such as timezones, days of the week, etc.). Each word in each and every document needs to be compared against every word in the stopword list, which is an expensive operation over tens of thousands of documents." }, { "code": null, "e": 10201, "s": 9855, "text": "It’s well known that sets have O(1) (i.e. constant) lookup time as opposed to lists, which have O(n) lookup time. In the lemmatize() method, since we're checking each word for membership in the set of stopwords, we would expect sets to be much better than lists. To test this, we can rerun workflow #1 but this time, use a stopword list instead." }, { "code": null, "e": 10447, "s": 10201, "text": "stopwords = list(stopwords)%%timedf_preproc['preproc_stopword_list'] = df_preproc['clean'].apply(lemmatize)df_preproc[['date', 'content', 'preproc_stopword_list']].head(3)CPU times: user 1min 17s, sys: 108 ms, total: 1min 18s Wall time: 1min 18s" }, { "code": null, "e": 10777, "s": 10447, "text": "With a stopword list, producing the same result now takes ~ 50% longer than it did before (with the set), which is a 1.5x increase in run time! This makes sense because in this case, the stopword list is about 500 words long, and each and every word in the corpus needs to be checked for membership in this reasonable-sized list." }, { "code": null, "e": 11228, "s": 10777, "text": "In this exercise, a news article dataset (NY Times) was processed using a spaCy pipeline to output a list of lemmas representing the useful tokens present in each article’s content. Because real-world news datasets are almost certainly bigger than this one, and can be unbounded in size, a fast, efficient NLP pipeline is necessary to perform any meaningful analysis on the data. The following steps are very useful in speeding up the spaCy pipeline." }, { "code": null, "e": 11582, "s": 11228, "text": "Disable unnecessary components in spaCy model: The standard spaCy model’s pipeline contains the tagger (to assign part-of-speech tags), the parser (to generate a dependency parse) and named entity recognition components. If any or none of these actions are desired, these components must be disabled immediately after loading the model (as shown above)." }, { "code": null, "e": 11867, "s": 11582, "text": "Use sets over lists for lookups: When performing lookups to compare one set of tokens against another, always perform membership checks using sets — lists are significantly slower for lookups! The larger the list/set of stopwords, the bigger the performance gain seen when using sets." }, { "code": null, "e": 12357, "s": 11867, "text": "Use custom language pipes when possible: Setting up a language pipe using nlp.pipe is an extremely flexible and efficient way to process large blocks of text. Even better, spaCy allows you to individually disable components for each specific sub-task, for example, when you need to separately perform part-of-speech tagging and named entity recognition (NER). See the spaCy docs for examples on how to disable pipeline components during model loading, processing or handling custom blocks." }, { "code": null, "e": 12774, "s": 12357, "text": "Use multiple cores when possible: When processing individual documents completely independent of one another, consider parallelizing the workflow by dividing the computation across multiple cores. As the number of documents becomes larger and larger, the performance gains can be tremendous. One just needs to ensure that the documents are divided up into chunks, all of which must fit into memory at any given time." }, { "code": null, "e": 12852, "s": 12774, "text": "I hope this was useful — have fun testing these out in your next NLP project!" } ]
Databases — SQL and NoSQL. Introduction to NoSQL databases with a... | by Anuradha Wickramarachchi | Towards Data Science
SQL came in to play with the research paper “A Relational Model of Data for Large Shared Data Banks” in 1970 by Dr. E. F. Codd. Yes!! that’s the Codd in Boyce-Codd normalization. NoSQL came into play on late 1990’s. Yet, there has been such databased even before. NoSQL was introduced with the motive of breaking the bottle neck of traditional transactional databases. A common misconception is that NoSQL databases are not relational, which is not quite right. Relationships do exist in data, which would be useless otherwise. Let’s see what changed and how. CAP theorem tries to demonstrate the properties expected by a NoSQL database. Most of the databases are designed to achieve two of these properties at the cost of another property. C — ConsistencyThis demonstrates the guarantee on the execution of updates and the availability of the updates as soon as they are acknowledged to the updater. In simpler terms if a database is consistent, updates are available as soon as they are completed, which is not a guarantee in a distributed environment. A — AvailabilityThis demonstrates the property of a database where it is capable to serve a request. Most of the SQL databases drop queries if the load/execution times are greater. Availability is expected to be very high and response times are expected to be very low in NoSQL databases by elimination of transactional properties that are present in SQL databases. P — Partition toleranceThe property of databases being able to function with failures among nodes due to network issues. For an example a database may contain several nodes (MongoDB nodes) that work together (By a mechanism such as Mapreduce). The property is preserved if the database as a whole can operate even one or more nodes are unreachable in a distributed environment. ACID properties are the expected properties in a traditional relational databases such as MySQL, MS SQL or Oracle databases. A — AtomicityThe property which guarantees atomic operations, either a set of queries can complete as a whole or none does. This is the key feature for transactions. C — ConsistencyData are available as soon as they are completely inserted or updated. I — IsolationImplies that, transactions are independent. Therefore data will not be negatively affected by two transactions happening on same set of data. D — DurabilityCommitted data after a transaction or any other operation is never lost. Either they get inserted or failure is notified (Failed transactions). NoSQL databases are guaranteed to adhere to two of the CAP properties. Such databases are of several types. Key-Value Store — Stores in the form of a hash table {Example- Riak, Amazon S3 (Dynamo), Redis}Document-based Store — Stores objects, mostly JSON, which is web friendly or supports ODM (Object Document Mappings). {Example- CouchDB, MongoDB}Column-based Store — Each storage block contains data from only one column {Example- HBase, Cassandra}Graph-based — Graph representation of relationships, mostly used by social networks. {Example- Neo4J} Key-Value Store — Stores in the form of a hash table {Example- Riak, Amazon S3 (Dynamo), Redis} Document-based Store — Stores objects, mostly JSON, which is web friendly or supports ODM (Object Document Mappings). {Example- CouchDB, MongoDB} Column-based Store — Each storage block contains data from only one column {Example- HBase, Cassandra} Graph-based — Graph representation of relationships, mostly used by social networks. {Example- Neo4J} MongoDB is one of the widely used document database. It obeys the C and A in the CAP thoerem. MongoDB is heavily used with NodeJS due to its JSON friendly API. Installation instructions are available at Mongo Official website: https://www.mongodb.com. Let’s consider a few commands using the MongoDB CLI. Entering the CLI: mongo and press enter. If installation is successful you should see the following output. Usually mongo DB runs on port 27017. # mongoMongoDB shell version v3.4.5connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.5Server has startup warnings:2017-09-15T11:42:04.673+0000 I STORAGE [initandlisten]2017-09-15T11:42:04.673+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine2017-09-15T11:42:04.673+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten]2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten]> Show databases: show dbs InsertingEnter use mydb and a new database name mydb will be created. Unlike tables in MySQL, Mongo has collections. Documents (JSON) are inserted into such collections. Let’s create the dogs collection and add a dog name Molly with weight 50kg. Since we have selected mydb we can call it as db and perform operations. db.dogs.insert({name: ‘Molly’, weight:50}) Viewing dataUsing the pretty method formats the output for a more readable format. As you can see mongo add an id name _id as an index to each of the documents. > db.dogs.find(){ "_id" : ObjectId("59bbce8288b6c364cefd9de6"), "name" : "Molly", "weight" : 50 }> db.dogs.find().pretty(){ "_id" : ObjectId("59bbce8288b6c364cefd9de6"), "name" : "Molly", "weight" : 50}> Updating dataThe command below updates the entry we made and set the name to Tommy. > db.dogs.update({_id: ObjectId('59bbce8288b6c364cefd9de6')}, {$set: {name:'Tommy'}}) Deleting dataLets delete what we have inserted > db.dogs.remove({_id:ObjectId('59bbce8288b6c364cefd9de6')})WriteResult({ "nRemoved" : 1 })> Those are the basic operations of any database, or simply the CRUD operations. C — CreateR — ReadU — UpdateD — Delete
[ { "code": null, "e": 351, "s": 172, "text": "SQL came in to play with the research paper “A Relational Model of Data for Large Shared Data Banks” in 1970 by Dr. E. F. Codd. Yes!! that’s the Codd in Boyce-Codd normalization." }, { "code": null, "e": 732, "s": 351, "text": "NoSQL came into play on late 1990’s. Yet, there has been such databased even before. NoSQL was introduced with the motive of breaking the bottle neck of traditional transactional databases. A common misconception is that NoSQL databases are not relational, which is not quite right. Relationships do exist in data, which would be useless otherwise. Let’s see what changed and how." }, { "code": null, "e": 913, "s": 732, "text": "CAP theorem tries to demonstrate the properties expected by a NoSQL database. Most of the databases are designed to achieve two of these properties at the cost of another property." }, { "code": null, "e": 1227, "s": 913, "text": "C — ConsistencyThis demonstrates the guarantee on the execution of updates and the availability of the updates as soon as they are acknowledged to the updater. In simpler terms if a database is consistent, updates are available as soon as they are completed, which is not a guarantee in a distributed environment." }, { "code": null, "e": 1593, "s": 1227, "text": "A — AvailabilityThis demonstrates the property of a database where it is capable to serve a request. Most of the SQL databases drop queries if the load/execution times are greater. Availability is expected to be very high and response times are expected to be very low in NoSQL databases by elimination of transactional properties that are present in SQL databases." }, { "code": null, "e": 1971, "s": 1593, "text": "P — Partition toleranceThe property of databases being able to function with failures among nodes due to network issues. For an example a database may contain several nodes (MongoDB nodes) that work together (By a mechanism such as Mapreduce). The property is preserved if the database as a whole can operate even one or more nodes are unreachable in a distributed environment." }, { "code": null, "e": 2096, "s": 1971, "text": "ACID properties are the expected properties in a traditional relational databases such as MySQL, MS SQL or Oracle databases." }, { "code": null, "e": 2262, "s": 2096, "text": "A — AtomicityThe property which guarantees atomic operations, either a set of queries can complete as a whole or none does. This is the key feature for transactions." }, { "code": null, "e": 2348, "s": 2262, "text": "C — ConsistencyData are available as soon as they are completely inserted or updated." }, { "code": null, "e": 2503, "s": 2348, "text": "I — IsolationImplies that, transactions are independent. Therefore data will not be negatively affected by two transactions happening on same set of data." }, { "code": null, "e": 2661, "s": 2503, "text": "D — DurabilityCommitted data after a transaction or any other operation is never lost. Either they get inserted or failure is notified (Failed transactions)." }, { "code": null, "e": 2769, "s": 2661, "text": "NoSQL databases are guaranteed to adhere to two of the CAP properties. Such databases are of several types." }, { "code": null, "e": 3213, "s": 2769, "text": "Key-Value Store — Stores in the form of a hash table {Example- Riak, Amazon S3 (Dynamo), Redis}Document-based Store — Stores objects, mostly JSON, which is web friendly or supports ODM (Object Document Mappings). {Example- CouchDB, MongoDB}Column-based Store — Each storage block contains data from only one column {Example- HBase, Cassandra}Graph-based — Graph representation of relationships, mostly used by social networks. {Example- Neo4J}" }, { "code": null, "e": 3309, "s": 3213, "text": "Key-Value Store — Stores in the form of a hash table {Example- Riak, Amazon S3 (Dynamo), Redis}" }, { "code": null, "e": 3455, "s": 3309, "text": "Document-based Store — Stores objects, mostly JSON, which is web friendly or supports ODM (Object Document Mappings). {Example- CouchDB, MongoDB}" }, { "code": null, "e": 3558, "s": 3455, "text": "Column-based Store — Each storage block contains data from only one column {Example- HBase, Cassandra}" }, { "code": null, "e": 3660, "s": 3558, "text": "Graph-based — Graph representation of relationships, mostly used by social networks. {Example- Neo4J}" }, { "code": null, "e": 3820, "s": 3660, "text": "MongoDB is one of the widely used document database. It obeys the C and A in the CAP thoerem. MongoDB is heavily used with NodeJS due to its JSON friendly API." }, { "code": null, "e": 3965, "s": 3820, "text": "Installation instructions are available at Mongo Official website: https://www.mongodb.com. Let’s consider a few commands using the MongoDB CLI." }, { "code": null, "e": 4110, "s": 3965, "text": "Entering the CLI: mongo and press enter. If installation is successful you should see the following output. Usually mongo DB runs on port 27017." }, { "code": null, "e": 4930, "s": 4110, "text": "# mongoMongoDB shell version v3.4.5connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.5Server has startup warnings:2017-09-15T11:42:04.673+0000 I STORAGE [initandlisten]2017-09-15T11:42:04.673+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine2017-09-15T11:42:04.673+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten]2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.2017-09-15T11:42:05.313+0000 I CONTROL [initandlisten]>" }, { "code": null, "e": 4955, "s": 4930, "text": "Show databases: show dbs" }, { "code": null, "e": 5274, "s": 4955, "text": "InsertingEnter use mydb and a new database name mydb will be created. Unlike tables in MySQL, Mongo has collections. Documents (JSON) are inserted into such collections. Let’s create the dogs collection and add a dog name Molly with weight 50kg. Since we have selected mydb we can call it as db and perform operations." }, { "code": null, "e": 5317, "s": 5274, "text": "db.dogs.insert({name: ‘Molly’, weight:50})" }, { "code": null, "e": 5478, "s": 5317, "text": "Viewing dataUsing the pretty method formats the output for a more readable format. As you can see mongo add an id name _id as an index to each of the documents." }, { "code": null, "e": 5691, "s": 5478, "text": "> db.dogs.find(){ \"_id\" : ObjectId(\"59bbce8288b6c364cefd9de6\"), \"name\" : \"Molly\", \"weight\" : 50 }> db.dogs.find().pretty(){ \"_id\" : ObjectId(\"59bbce8288b6c364cefd9de6\"), \"name\" : \"Molly\", \"weight\" : 50}>" }, { "code": null, "e": 5775, "s": 5691, "text": "Updating dataThe command below updates the entry we made and set the name to Tommy." }, { "code": null, "e": 5863, "s": 5775, "text": "> db.dogs.update({_id: ObjectId('59bbce8288b6c364cefd9de6')}, {$set: {name:'Tommy'}})" }, { "code": null, "e": 5910, "s": 5863, "text": "Deleting dataLets delete what we have inserted" }, { "code": null, "e": 6003, "s": 5910, "text": "> db.dogs.remove({_id:ObjectId('59bbce8288b6c364cefd9de6')})WriteResult({ \"nRemoved\" : 1 })>" }, { "code": null, "e": 6082, "s": 6003, "text": "Those are the basic operations of any database, or simply the CRUD operations." } ]
Python Program to Read Height in Centimeters and convert the Height to Feet and Inches
When it is required to read the height in ‘cm’ and convert it into ‘feet’ and ‘inches’, the ‘round’ method can be used. Below is a demonstration of the same − Live Demo in_cm=int(input("Enter the height in centimeters...")) in_inches=0.394*in_cm in_feet=0.0328*in_cm print("The length in inches is ") print(round(in_inches,2)) print("The length in feet is") print(round(in_feet,2)) Enter the height in centimeters...178 The length in inches is 70.13 The length in feet is 5.84 The input is taken by user, as ‘cm’. The input is taken by user, as ‘cm’. It can be converted into inches by multiplying it with 0.394. It can be converted into inches by multiplying it with 0.394. This is assigned to a variable. This is assigned to a variable. It can be converted into feet by multiplying it with 0.0328. It can be converted into feet by multiplying it with 0.0328. This is assigned to a variable. This is assigned to a variable. It is rounded off to nearest two decimal values. It is rounded off to nearest two decimal values. Both these converted values are displayed as output on the console. Both these converted values are displayed as output on the console.
[ { "code": null, "e": 1182, "s": 1062, "text": "When it is required to read the height in ‘cm’ and convert it into ‘feet’ and ‘inches’, the ‘round’ method can be used." }, { "code": null, "e": 1221, "s": 1182, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1232, "s": 1221, "text": " Live Demo" }, { "code": null, "e": 1445, "s": 1232, "text": "in_cm=int(input(\"Enter the height in centimeters...\"))\nin_inches=0.394*in_cm\nin_feet=0.0328*in_cm\nprint(\"The length in inches is \")\nprint(round(in_inches,2))\nprint(\"The length in feet is\")\nprint(round(in_feet,2))" }, { "code": null, "e": 1540, "s": 1445, "text": "Enter the height in centimeters...178\nThe length in inches is\n70.13\nThe length in feet is\n5.84" }, { "code": null, "e": 1577, "s": 1540, "text": "The input is taken by user, as ‘cm’." }, { "code": null, "e": 1614, "s": 1577, "text": "The input is taken by user, as ‘cm’." }, { "code": null, "e": 1676, "s": 1614, "text": "It can be converted into inches by multiplying it with 0.394." }, { "code": null, "e": 1738, "s": 1676, "text": "It can be converted into inches by multiplying it with 0.394." }, { "code": null, "e": 1770, "s": 1738, "text": "This is assigned to a variable." }, { "code": null, "e": 1802, "s": 1770, "text": "This is assigned to a variable." }, { "code": null, "e": 1863, "s": 1802, "text": "It can be converted into feet by multiplying it with 0.0328." }, { "code": null, "e": 1924, "s": 1863, "text": "It can be converted into feet by multiplying it with 0.0328." }, { "code": null, "e": 1956, "s": 1924, "text": "This is assigned to a variable." }, { "code": null, "e": 1988, "s": 1956, "text": "This is assigned to a variable." }, { "code": null, "e": 2037, "s": 1988, "text": "It is rounded off to nearest two decimal values." }, { "code": null, "e": 2086, "s": 2037, "text": "It is rounded off to nearest two decimal values." }, { "code": null, "e": 2154, "s": 2086, "text": "Both these converted values are displayed as output on the console." }, { "code": null, "e": 2222, "s": 2154, "text": "Both these converted values are displayed as output on the console." } ]
Adding Button in Bokeh - GeeksforGeeks
03 Mar, 2021 In this article, we will learn about how to add a button in bokeh. Now, Bokeh provides us with a variety of widgets that can be used for various purposes. One of them is button. The button is one of the widgets of bokeh.models module that helps us in creating a button in our python notebook. Lets us see an example in order to understand the concept better. But before that, if you are using local device for the above implementation, then be sure to have python installed in the device and after that, run this code in the command prompt for the bokeh functionalities to work properly in the code editor. pip install bokeh After the installation is done, let’s move to the code and learn the implementation. Example 1: Adding a button in Bokeh: Approach: In the code below, apart from importing show and button, we are importing another package in our python shell and that is customJS. customJS provides the user to have customized behaiviors in response to change of a particular event . It is a javascript callback that works in bokeh server apps. In the implementation, we will be using js_on_click(handler) which sets up a javascript handler for button clicks. It activates when the button created is clicked and inside which, customJS will be used as a handler and the message will be printed in the console. js_on_click(handler) Code: Python3 # importing show from bokeh.io# to show the buttonfrom bokeh.io import show # importing button and customJS package# from bokeh.modelsfrom bokeh.models import Button, CustomJS # Creating a button variable where# we are specifying the properties of the# button such as label on the button and# the button type(Different color)button = Button(label = "Click on the button", button_type = "danger") # js_on_click sets up a javascript handler# for state changes and also when we # are clicking on the button. a message# is printed on the consolebutton.js_on_click(CustomJS(code = "console.log('button: You have clicked on the button!')")) # showing the above buttonshow(button) Output: Code Explain: Now, in the code, after importing the packages and creating a variable(button) inside which we are specifying different properties of the button, we are using js_on_click handler which is used for button clicks. So, as soon as someone clicks the button, the handler gets triggered, and after that customJS callback activates and prints the message in the console which can be checked using “inspect element” by the right click of the mouse. Now, we can add buttons of varying colors such as warning(yellow), success(yellow), primary(blue) etc. Example 2: Adding multiple buttons in Bokeh. Let us take another example where we will be adding multiple buttons, row-wise and column-wise in our plot. In the code below, we are importing a package from bokeh.layouts module is known as row which helps us to show the buttons in a row-wise manner. Code: Python # importing show from bokeh.iofrom bokeh.io import show # importing Button from bokeh.models# modulefrom bokeh.models import Button # importing row from bokeh.layouts module# so that buttons can be shown side by sidefrom bokeh.layouts import row # Creating a list of buttons with defining different properties# in each of the buttonsbuttons = [Button(label="Button 1", button_type="danger"), Button(label='Button 2', button_type='success', width=200, height=60), Button(label='Button 3', button_type='primary', width=100, height=100)] # Showing all the buttons rowwiseshow(row(buttons)) Output: Code Explain: In the above code, after importing all the necessary packages we are using variable buttons which is an array or list of 3 buttons, each with a different size, color, and label. After that using show(row(buttons)), e is showing all the buttons in ‘row-wise’ manner. Apart from that, we can also show all the buttons in column-wise format. For that, we need to import column package from bokeh.layouts, and instead of show(row(buttons)), we need to write show(column(buttons)) and all the buttons will be printed column-wise. Picked Python-Bokeh Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n03 Mar, 2021" }, { "code": null, "e": 24532, "s": 23925, "text": "In this article, we will learn about how to add a button in bokeh. Now, Bokeh provides us with a variety of widgets that can be used for various purposes. One of them is button. The button is one of the widgets of bokeh.models module that helps us in creating a button in our python notebook. Lets us see an example in order to understand the concept better. But before that, if you are using local device for the above implementation, then be sure to have python installed in the device and after that, run this code in the command prompt for the bokeh functionalities to work properly in the code editor." }, { "code": null, "e": 24550, "s": 24532, "text": "pip install bokeh" }, { "code": null, "e": 24635, "s": 24550, "text": "After the installation is done, let’s move to the code and learn the implementation." }, { "code": null, "e": 24672, "s": 24635, "text": "Example 1: Adding a button in Bokeh:" }, { "code": null, "e": 24682, "s": 24672, "text": "Approach:" }, { "code": null, "e": 25242, "s": 24682, "text": "In the code below, apart from importing show and button, we are importing another package in our python shell and that is customJS. customJS provides the user to have customized behaiviors in response to change of a particular event . It is a javascript callback that works in bokeh server apps. In the implementation, we will be using js_on_click(handler) which sets up a javascript handler for button clicks. It activates when the button created is clicked and inside which, customJS will be used as a handler and the message will be printed in the console." }, { "code": null, "e": 25263, "s": 25242, "text": "js_on_click(handler)" }, { "code": null, "e": 25269, "s": 25263, "text": "Code:" }, { "code": null, "e": 25277, "s": 25269, "text": "Python3" }, { "code": "# importing show from bokeh.io# to show the buttonfrom bokeh.io import show # importing button and customJS package# from bokeh.modelsfrom bokeh.models import Button, CustomJS # Creating a button variable where# we are specifying the properties of the# button such as label on the button and# the button type(Different color)button = Button(label = \"Click on the button\", button_type = \"danger\") # js_on_click sets up a javascript handler# for state changes and also when we # are clicking on the button. a message# is printed on the consolebutton.js_on_click(CustomJS(code = \"console.log('button: You have clicked on the button!')\")) # showing the above buttonshow(button)", "e": 25970, "s": 25277, "text": null }, { "code": null, "e": 25978, "s": 25970, "text": "Output:" }, { "code": null, "e": 25992, "s": 25978, "text": "Code Explain:" }, { "code": null, "e": 26433, "s": 25992, "text": "Now, in the code, after importing the packages and creating a variable(button) inside which we are specifying different properties of the button, we are using js_on_click handler which is used for button clicks. So, as soon as someone clicks the button, the handler gets triggered, and after that customJS callback activates and prints the message in the console which can be checked using “inspect element” by the right click of the mouse." }, { "code": null, "e": 26536, "s": 26433, "text": "Now, we can add buttons of varying colors such as warning(yellow), success(yellow), primary(blue) etc." }, { "code": null, "e": 26581, "s": 26536, "text": "Example 2: Adding multiple buttons in Bokeh." }, { "code": null, "e": 26834, "s": 26581, "text": "Let us take another example where we will be adding multiple buttons, row-wise and column-wise in our plot. In the code below, we are importing a package from bokeh.layouts module is known as row which helps us to show the buttons in a row-wise manner." }, { "code": null, "e": 26840, "s": 26834, "text": "Code:" }, { "code": null, "e": 26847, "s": 26840, "text": "Python" }, { "code": "# importing show from bokeh.iofrom bokeh.io import show # importing Button from bokeh.models# modulefrom bokeh.models import Button # importing row from bokeh.layouts module# so that buttons can be shown side by sidefrom bokeh.layouts import row # Creating a list of buttons with defining different properties# in each of the buttonsbuttons = [Button(label=\"Button 1\", button_type=\"danger\"), Button(label='Button 2', button_type='success', width=200, height=60), Button(label='Button 3', button_type='primary', width=100, height=100)] # Showing all the buttons rowwiseshow(row(buttons))", "e": 27464, "s": 26847, "text": null }, { "code": null, "e": 27472, "s": 27464, "text": "Output:" }, { "code": null, "e": 27486, "s": 27472, "text": "Code Explain:" }, { "code": null, "e": 27752, "s": 27486, "text": "In the above code, after importing all the necessary packages we are using variable buttons which is an array or list of 3 buttons, each with a different size, color, and label. After that using show(row(buttons)), e is showing all the buttons in ‘row-wise’ manner." }, { "code": null, "e": 28011, "s": 27752, "text": "Apart from that, we can also show all the buttons in column-wise format. For that, we need to import column package from bokeh.layouts, and instead of show(row(buttons)), we need to write show(column(buttons)) and all the buttons will be printed column-wise." }, { "code": null, "e": 28018, "s": 28011, "text": "Picked" }, { "code": null, "e": 28031, "s": 28018, "text": "Python-Bokeh" }, { "code": null, "e": 28055, "s": 28031, "text": "Technical Scripter 2020" }, { "code": null, "e": 28062, "s": 28055, "text": "Python" }, { "code": null, "e": 28081, "s": 28062, "text": "Technical Scripter" }, { "code": null, "e": 28179, "s": 28081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28188, "s": 28179, "text": "Comments" }, { "code": null, "e": 28201, "s": 28188, "text": "Old Comments" }, { "code": null, "e": 28233, "s": 28201, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28289, "s": 28233, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28331, "s": 28289, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28373, "s": 28331, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28409, "s": 28373, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28431, "s": 28409, "text": "Defaultdict in Python" }, { "code": null, "e": 28470, "s": 28431, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28497, "s": 28470, "text": "Python Classes and Objects" }, { "code": null, "e": 28528, "s": 28497, "text": "Python | os.path.join() method" } ]
Finding duplicate "words" in a string - JavaScript
We are required to write a JavaScript function that takes in a string and returns a new string with only the words that appeared for more than once in the original string. For example: If the input string is − const str = "big black bug bit a big black dog on his big black nose"; Then the output should be − const output = "big black"; Let’s write the code for this function − const str = "big black bug bit a big black dog on his big black nose"; const findDuplicateWords = str => { const strArr = str.split(" "); const res = []; for(let i = 0; i < strArr.length; i++){ if(strArr.indexOf(strArr[i]) !== strArr.lastIndexOf(strArr[i])){ if(!res.includes(strArr[i])){ res.push(strArr[i]); }; }; }; return res.join(" "); }; console.log(findDuplicateWords(str)); The output in the console: − big black
[ { "code": null, "e": 1234, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string and returns a new string with only the words that appeared for more than once in the original string." }, { "code": null, "e": 1272, "s": 1234, "text": "For example: If the input string is −" }, { "code": null, "e": 1343, "s": 1272, "text": "const str = \"big black bug bit a big black dog on his big black nose\";" }, { "code": null, "e": 1371, "s": 1343, "text": "Then the output should be −" }, { "code": null, "e": 1399, "s": 1371, "text": "const output = \"big black\";" }, { "code": null, "e": 1440, "s": 1399, "text": "Let’s write the code for this function −" }, { "code": null, "e": 1879, "s": 1440, "text": "const str = \"big black bug bit a big black dog on his big black nose\";\nconst findDuplicateWords = str => {\n const strArr = str.split(\" \");\n const res = [];\n for(let i = 0; i < strArr.length; i++){\n if(strArr.indexOf(strArr[i]) !== strArr.lastIndexOf(strArr[i])){\n if(!res.includes(strArr[i])){\n res.push(strArr[i]);\n };\n };\n };\n return res.join(\" \");\n};\nconsole.log(findDuplicateWords(str));" }, { "code": null, "e": 1908, "s": 1879, "text": "The output in the console: −" }, { "code": null, "e": 1918, "s": 1908, "text": "big black" } ]
Subset with sum divisible by m | Practice | GeeksforGeeks
Given a set of n non-negative integers, and a value m, determine if there is a subset of the given set with sum divisible by m. Example 1: Input: n = 4 m = 6 nums[] = {3 1 7 5} Output: 1 Explanation: If we take the subset {7, 5} then sum will be 12 which is divisible by 6. Example 2: Input: n = 3, m = 5 nums[] = {1 2 6} Output: 0 Explanation: All possible subsets of the given set are {1}, {2}, {6}, {1, 2}, {2, 6}, {1, 6} and {1, 2, 6}. There is no subset whose sum is divisible by 5. Your Task: You don't need to read or print anything. Your task is to complete the function DivisibleByM() which takes the given set and m as input parameter and returns 1 if any of the subset(non-empty) sum is divisible by m otherwise returns 0. Expected Time Complexity: O(n*m) Expected Space Complexity: O(n) Constraints: 1 <= elements in set <= 1000 1 <= n, m <= 1000 0 imranwahid1 week ago Easy C++ solution using memoization 0 _luffy_2 months ago int sum =0; for(auto v:nums) sum+=v; bool dp[2][sum+1]; for(int i=0;i<=nums.size();i++) { for(int j=0;j<=sum;j++) { if(j==0) dp[i%2][j] = true; else if(i==0) dp[0][j] = false; else if(nums[i-1] <= j) dp[i%2][j] = dp[1 - i%2][j- nums[i-1]] || dp[1 - i%2][j]; else dp[i%2][j] = dp[1 - i%2][j]; } } for(int i=m;i<=sum;i+=m) if(dp[nums.size()%2][i]) { return 1; } return 0; 0 ayushshaw13 months ago Simple recursive solution in java // { Driver Code Starts//Initial Template for Java import java.util.*;import java.lang.*;import java.io.*;class GFG{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String a = br.readLine().trim(); String[] a1 = a.split(" "); int n = Integer.parseInt(a1[0]); int m = Integer.parseInt(a1[1]); String b = br.readLine().trim(); String[] b1 = b.split(" "); int[] nums = new int[n]; for(int i = 0; i < b1.length; i++) nums[i] = Integer.parseInt(b1[i]); Solution ob = new Solution(); int ans = ob.DivisibleByM(nums, m); System.out.println(ans); } }}// } Driver Code Ends //User function Template for Java class Solution{ int A[]; int mod; boolean ans =false; public int DivisibleByM(int [] nums, int m) { // Code here A=nums; mod=m; Check(0,0,true); if(ans) return(1); else return(0); } public void Check(int prev_sum, int i,boolean empty){ if(i==A.length || ans){ if(prev_sum==0 && !empty) ans=true; return; } else{ if(prev_sum==0 && !empty){ ans=true; return; } else{ Check(prev_sum,i+1,empty); } prev_sum=(prev_sum+A[i])%mod; if(prev_sum==0) { ans=true; return; } Check(prev_sum,i+1,false); } } } 0 aaravarya14 months ago C++ simple recursive solution in 0.0 time bool solve(vector<int> nums, int m, int sum, int end) { if(sum%m == 0 && sum!=0) return true; if(end<0) return false; else return solve(nums, m, sum, end-1) || solve(nums, m , sum+nums[end], end-1); } int DivisibleByM(vector<int>nums, int m){ // Code here int len=nums.size(); if(solve(nums, m, 0, len-1 )) return 1; else return 0; } 0 soumo2k154 months ago int fnc(vector<int>a,int n,int k,int sum,vector<vector<int>>&dp){ if(sum && sum%k==0)return 1; if(n<=0)return 0; if(dp[n][sum]!=-1)return dp[n][]; dp[n][sum] = fnc(a,n-1,k,sum+a[n-1],dp)+fnc(a,n-1,k,sum,dp); return dp[n][sum]; } int DivisibleByM(vector<int>v, int k){ int n=v.size(); vector<vector<int>>dp(n+1,vector<int>(1003,-1)); if (fnc(v,n,k,0,dp))return 1; return 0; } +1 pereiraripson5 months ago man the brute force totally got accepted, i used 3 nested for loops 0 shrish9 months ago shrish USING BITSET (WITHOUT DP SOLN)-> if you don't know bitset please learn it from youtube or errictto's blog soln link int DivisibleByM(vector<int>nums, int m){ bitset<10000>b; b[0] = 1; for(auto a:nums) b|=(b<<a); int="" c="0;" for(int="" i="1;i&lt;10000;i++)" if(i%m="=0" &&="" b[i]="=1)" return="" 1;="" return="" 0;="" }="" <="" code=""> 0 Dhananjay Singh9 months ago Dhananjay Singh class Solution{ public int find(int nums[],int n,int m,int sum,int arr[]){ if((sum%m)==0 && sum!=0)return 1; else if(n==0)return 0; else if(arr[(sum%m)]!=-1)return arr[(sum%m)]; else return arr[(sum%m)]=(find(nums,n-1,m,sum+nums[n-1],arr) | find(nums,n-1,m,sum,arr)); } public int DivisibleByM(int [] nums, int m) { int n= nums.length; int arr[]=new int[m]; Arrays.fill(arr,-1); return find(nums,n,m,0,arr); }} 0 Saubhik Kumar11 months ago Saubhik Kumar O(nlogm) time and O(n) space approach .We can use set to store the mod of prefix sum till ith element, and check if the same mod value was there till jth element where j<i. this="" can="" be="" found="" in="" o(logm)="" using="" set.="" <code="">int DivisibleByM(vector<int>nums, int m){ // Code here vector<int> presums; set<int> st; for(int i=0;i<nums.size();i++) {="" if(i="=0)" presums.push_back(nums[0]%m);="" else="" presums.push_back((presums[i-1]+nums[i])%m);="" }="" for(int="" ch="" :="" presums)="" {="" cout<<ch<<endl;="" if(ch="=0)" return="" 1;="" if(st.count(ch))="" return="" 1;="" st.insert(ch);="" }="" return="" 0;="" }="" <="" code=""> 0 yash garala1 year ago yash garala Simple Solution int DivisibleByM(vector<int>nums, int m){ int n=nums.size(); map<int,int> arr; int ans=0; int sum=0; arr[0]=1; for(int i=0;i<n;i++) {="" sum+="nums[i];" int="" temp="sum%m;" if(arr[temp]="=0)" {="" arr[temp]="1;" }="" else="" {="" arr[temp]+="1;" ans+="arr[temp];" }="" }="" if(ans="=0" )="" {="" return="" 0;="" }="" else="" return="" 1;="" code="" here="" }="" <="" code=""> 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": 366, "s": 238, "text": "Given a set of n non-negative integers, and a value m, determine if there is a subset of the given set with sum divisible by m." }, { "code": null, "e": 377, "s": 366, "text": "Example 1:" }, { "code": null, "e": 515, "s": 377, "text": "Input: \nn = 4 m = 6 \nnums[] = {3 1 7 5}\nOutput:\n1\nExplanation:\nIf we take the subset {7, 5} then sum\nwill be 12 which is divisible by 6.\n" }, { "code": null, "e": 526, "s": 515, "text": "Example 2:" }, { "code": null, "e": 732, "s": 526, "text": "Input:\nn = 3, m = 5\nnums[] = {1 2 6}\nOutput:\n0\nExplanation: \nAll possible subsets of the given set are \n{1}, {2}, {6}, {1, 2}, {2, 6}, {1, 6}\nand {1, 2, 6}. There is no subset whose\nsum is divisible by 5.\n" }, { "code": null, "e": 978, "s": 732, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function DivisibleByM() which takes the given set and m as input parameter and returns 1 if any of the subset(non-empty) sum is divisible by m otherwise returns 0." }, { "code": null, "e": 1043, "s": 978, "text": "Expected Time Complexity: O(n*m)\nExpected Space Complexity: O(n)" }, { "code": null, "e": 1103, "s": 1043, "text": "Constraints:\n1 <= elements in set <= 1000\n1 <= n, m <= 1000" }, { "code": null, "e": 1105, "s": 1103, "text": "0" }, { "code": null, "e": 1126, "s": 1105, "text": "imranwahid1 week ago" }, { "code": null, "e": 1162, "s": 1126, "text": "Easy C++ solution using memoization" }, { "code": null, "e": 1164, "s": 1162, "text": "0" }, { "code": null, "e": 1184, "s": 1164, "text": "_luffy_2 months ago" }, { "code": null, "e": 1822, "s": 1184, "text": "int sum =0;\n\t\t for(auto v:nums)\n\t\t sum+=v;\n\t\t \n\t\t bool dp[2][sum+1];\n\t\t for(int i=0;i<=nums.size();i++)\n\t\t {\n\t\t for(int j=0;j<=sum;j++)\n\t\t {\n\t\t if(j==0)\n\t\t dp[i%2][j] = true;\n\t\t else if(i==0)\n\t\t dp[0][j] = false;\n\t\t else if(nums[i-1] <= j)\n\t\t dp[i%2][j] = dp[1 - i%2][j- nums[i-1]] || dp[1 - i%2][j];\n\t\t else\n\t\t dp[i%2][j] = dp[1 - i%2][j];\n\t\t }\n\t\t }\n\t\t for(int i=m;i<=sum;i+=m)\n\t\t if(dp[nums.size()%2][i])\n\t\t {\n\t\t return 1;\n\t\t }\n\t\t \n\t\t return 0;" }, { "code": null, "e": 1824, "s": 1822, "text": "0" }, { "code": null, "e": 1847, "s": 1824, "text": "ayushshaw13 months ago" }, { "code": null, "e": 1881, "s": 1847, "text": "Simple recursive solution in java" }, { "code": null, "e": 1932, "s": 1881, "text": "// { Driver Code Starts//Initial Template for Java" }, { "code": null, "e": 2767, "s": 1932, "text": "import java.util.*;import java.lang.*;import java.io.*;class GFG{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { String a = br.readLine().trim(); String[] a1 = a.split(\" \"); int n = Integer.parseInt(a1[0]); int m = Integer.parseInt(a1[1]); String b = br.readLine().trim(); String[] b1 = b.split(\" \"); int[] nums = new int[n]; for(int i = 0; i < b1.length; i++) nums[i] = Integer.parseInt(b1[i]); Solution ob = new Solution(); int ans = ob.DivisibleByM(nums, m); System.out.println(ans); } }}// } Driver Code Ends" }, { "code": null, "e": 2801, "s": 2767, "text": "//User function Template for Java" }, { "code": null, "e": 3376, "s": 2801, "text": "class Solution{ int A[]; int mod; boolean ans =false; public int DivisibleByM(int [] nums, int m) { // Code here A=nums; mod=m; Check(0,0,true); if(ans) return(1); else return(0); } public void Check(int prev_sum, int i,boolean empty){ if(i==A.length || ans){ if(prev_sum==0 && !empty) ans=true; return; } else{ if(prev_sum==0 && !empty){ ans=true; return; } else{ Check(prev_sum,i+1,empty);" }, { "code": null, "e": 3562, "s": 3376, "text": " } prev_sum=(prev_sum+A[i])%mod; if(prev_sum==0) { ans=true; return; } Check(prev_sum,i+1,false);" }, { "code": null, "e": 3579, "s": 3562, "text": " } } }" }, { "code": null, "e": 3581, "s": 3579, "text": "0" }, { "code": null, "e": 3604, "s": 3581, "text": "aaravarya14 months ago" }, { "code": null, "e": 3646, "s": 3604, "text": "C++ simple recursive solution in 0.0 time" }, { "code": null, "e": 4086, "s": 3646, "text": " bool solve(vector<int> nums, int m, int sum, int end) { if(sum%m == 0 && sum!=0) return true; if(end<0) return false; else return solve(nums, m, sum, end-1) || solve(nums, m , sum+nums[end], end-1); } int DivisibleByM(vector<int>nums, int m){ // Code here int len=nums.size(); if(solve(nums, m, 0, len-1 )) return 1; else return 0; }" }, { "code": null, "e": 4090, "s": 4088, "text": "0" }, { "code": null, "e": 4112, "s": 4090, "text": "soumo2k154 months ago" }, { "code": null, "e": 4559, "s": 4112, "text": "int fnc(vector<int>a,int n,int k,int sum,vector<vector<int>>&dp){ if(sum && sum%k==0)return 1; if(n<=0)return 0; if(dp[n][sum]!=-1)return dp[n][]; dp[n][sum] = fnc(a,n-1,k,sum+a[n-1],dp)+fnc(a,n-1,k,sum,dp); return dp[n][sum]; } int DivisibleByM(vector<int>v, int k){ int n=v.size(); vector<vector<int>>dp(n+1,vector<int>(1003,-1)); if (fnc(v,n,k,0,dp))return 1; return 0; }" }, { "code": null, "e": 4562, "s": 4559, "text": "+1" }, { "code": null, "e": 4588, "s": 4562, "text": "pereiraripson5 months ago" }, { "code": null, "e": 4656, "s": 4588, "text": "man the brute force totally got accepted, i used 3 nested for loops" }, { "code": null, "e": 4658, "s": 4656, "text": "0" }, { "code": null, "e": 4677, "s": 4658, "text": "shrish9 months ago" }, { "code": null, "e": 4684, "s": 4677, "text": "shrish" }, { "code": null, "e": 4791, "s": 4684, "text": "USING BITSET (WITHOUT DP SOLN)-> if you don't know bitset please learn it from youtube or errictto's blog" }, { "code": null, "e": 4801, "s": 4791, "text": "soln link" }, { "code": null, "e": 5038, "s": 4801, "text": "int DivisibleByM(vector<int>nums, int m){ bitset<10000>b; b[0] = 1; for(auto a:nums) b|=(b<<a); int=\"\" c=\"0;\" for(int=\"\" i=\"1;i&lt;10000;i++)\" if(i%m=\"=0\" &&=\"\" b[i]=\"=1)\" return=\"\" 1;=\"\" return=\"\" 0;=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 5040, "s": 5038, "text": "0" }, { "code": null, "e": 5068, "s": 5040, "text": "Dhananjay Singh9 months ago" }, { "code": null, "e": 5084, "s": 5068, "text": "Dhananjay Singh" }, { "code": null, "e": 5162, "s": 5084, "text": "class Solution{ public int find(int nums[],int n,int m,int sum,int arr[]){" }, { "code": null, "e": 5287, "s": 5162, "text": " if((sum%m)==0 && sum!=0)return 1; else if(n==0)return 0; else if(arr[(sum%m)]!=-1)return arr[(sum%m)];" }, { "code": null, "e": 5442, "s": 5287, "text": " else return arr[(sum%m)]=(find(nums,n-1,m,sum+nums[n-1],arr) | find(nums,n-1,m,sum,arr)); } public int DivisibleByM(int [] nums, int m) {" }, { "code": null, "e": 5527, "s": 5442, "text": " int n= nums.length; int arr[]=new int[m]; Arrays.fill(arr,-1);" }, { "code": null, "e": 5570, "s": 5527, "text": " return find(nums,n,m,0,arr); }}" }, { "code": null, "e": 5572, "s": 5570, "text": "0" }, { "code": null, "e": 5599, "s": 5572, "text": "Saubhik Kumar11 months ago" }, { "code": null, "e": 5613, "s": 5599, "text": "Saubhik Kumar" }, { "code": null, "e": 6281, "s": 5613, "text": "O(nlogm) time and O(n) space approach .We can use set to store the mod of prefix sum till ith element, and check if the same mod value was there till jth element where j<i. this=\"\" can=\"\" be=\"\" found=\"\" in=\"\" o(logm)=\"\" using=\"\" set.=\"\" <code=\"\">int DivisibleByM(vector<int>nums, int m){ // Code here vector<int> presums; set<int> st; for(int i=0;i<nums.size();i++) {=\"\" if(i=\"=0)\" presums.push_back(nums[0]%m);=\"\" else=\"\" presums.push_back((presums[i-1]+nums[i])%m);=\"\" }=\"\" for(int=\"\" ch=\"\" :=\"\" presums)=\"\" {=\"\" cout<<ch<<endl;=\"\" if(ch=\"=0)\" return=\"\" 1;=\"\" if(st.count(ch))=\"\" return=\"\" 1;=\"\" st.insert(ch);=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 6283, "s": 6281, "text": "0" }, { "code": null, "e": 6305, "s": 6283, "text": "yash garala1 year ago" }, { "code": null, "e": 6317, "s": 6305, "text": "yash garala" }, { "code": null, "e": 6728, "s": 6317, "text": "Simple Solution int DivisibleByM(vector<int>nums, int m){ int n=nums.size(); map<int,int> arr; int ans=0; int sum=0; arr[0]=1; for(int i=0;i<n;i++) {=\"\" sum+=\"nums[i];\" int=\"\" temp=\"sum%m;\" if(arr[temp]=\"=0)\" {=\"\" arr[temp]=\"1;\" }=\"\" else=\"\" {=\"\" arr[temp]+=\"1;\" ans+=\"arr[temp];\" }=\"\" }=\"\" if(ans=\"=0\" )=\"\" {=\"\" return=\"\" 0;=\"\" }=\"\" else=\"\" return=\"\" 1;=\"\" code=\"\" here=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 6874, "s": 6728, "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": 6910, "s": 6874, "text": " Login to access your submissions. " }, { "code": null, "e": 6920, "s": 6910, "text": "\nProblem\n" }, { "code": null, "e": 6930, "s": 6920, "text": "\nContest\n" }, { "code": null, "e": 6993, "s": 6930, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7141, "s": 6993, "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": 7349, "s": 7141, "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": 7455, "s": 7349, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to send a SMS using SMSmanager in Dual SIM mobile in Android?
This example demonstrates how do I send in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="4dp" tools:context=".MainActivity"> <EditText android:hint="Enter mobile number" android:id="@+id/editTextNum" android:layout_width="match_parent" android:layout_height="wrap_content"/> <EditText android:hint="Enter your message" android:id="@+id/editTextMsg" android:layout_width="match_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/btnSendMsg" android:onClick="SendSMS" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send Message"/> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.telephony.SmsManager; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button btnSend; EditText editTextNum, editTextMsg; private static final int PERMISSION_REQUEST = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextNum = findViewById(R.id.editTextNum); editTextMsg = findViewById(R.id.editTextMsg); btnSend = findViewById(R.id.btnSendMsg); } public void SendSMS(View view) { int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS); if (permissionCheck == PackageManager.PERMISSION_GRANTED){ MyMessage(); } else { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.SEND_SMS}, PERMISSION_REQUEST); } } private void MyMessage() { String myNumber = editTextNum.getText().toString().trim(); String myMsg = editTextMsg.getText().toString().trim(); if (myNumber.equals("") || myMsg.equals("")){ Toast.makeText(this, "Field cannot be empty", Toast.LENGTH_SHORT).show(); } else { if (TextUtils.isDigitsOnly(myNumber)){ SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(myNumber, null, myMsg, null, null); Toast.makeText(this, "Message Sent", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Please enter the correct number", Toast.LENGTH_SHORT).show(); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_REQUEST) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { MyMessage(); } else { Toast.makeText(this, "You don't have required permission to send a message", Toast.LENGTH_SHORT).show(); } } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.SEND_SMS"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1114, "s": 1062, "text": "This example demonstrates how do I send in android." }, { "code": null, "e": 1243, "s": 1114, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1308, "s": 1243, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2210, "s": 1308, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:hint=\"Enter mobile number\"\n android:id=\"@+id/editTextNum\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"/>\n <EditText\n android:hint=\"Enter your message\"\n android:id=\"@+id/editTextMsg\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"/>\n <Button\n android:id=\"@+id/btnSendMsg\"\n android:onClick=\"SendSMS\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Send Message\"/>\n</LinearLayout>" }, { "code": null, "e": 2267, "s": 2210, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4780, "s": 2267, "text": "import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.core.app.ActivityCompat;\nimport androidx.core.content.ContextCompat;\nimport android.Manifest;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.telephony.SmsManager;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Button btnSend;\n EditText editTextNum, editTextMsg;\n private static final int PERMISSION_REQUEST = 101;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n editTextNum = findViewById(R.id.editTextNum);\n editTextMsg = findViewById(R.id.editTextMsg);\n btnSend = findViewById(R.id.btnSendMsg);\n }\n public void SendSMS(View view) {\n int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS);\n if (permissionCheck == PackageManager.PERMISSION_GRANTED){\n MyMessage();\n } else {\n ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.SEND_SMS},\nPERMISSION_REQUEST);\n }\n }\n private void MyMessage() {\n String myNumber = editTextNum.getText().toString().trim();\n String myMsg = editTextMsg.getText().toString().trim();\n if (myNumber.equals(\"\") || myMsg.equals(\"\")){\n Toast.makeText(this, \"Field cannot be empty\", Toast.LENGTH_SHORT).show();\n } else {\n if (TextUtils.isDigitsOnly(myNumber)){\n SmsManager smsManager = SmsManager.getDefault();\n smsManager.sendTextMessage(myNumber, null, myMsg, null, null);\n Toast.makeText(this, \"Message Sent\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(this, \"Please enter the correct number\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n if (requestCode == PERMISSION_REQUEST) {\n if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n MyMessage();\n } else {\n Toast.makeText(this, \"You don't have required permission to send a message\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n}" }, { "code": null, "e": 4835, "s": 4780, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5573, "s": 4835, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.SEND_SMS\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5928, "s": 5573, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5969, "s": 5928, "text": "Click here to download the project code." } ]
How to create a responsive Image Grid with HTML and CSS?
Following is the code to create a responsive image grid using HTML and CSS − Live Demo <!DOCTYPE html> <html> <style> * { box-sizing: border-box; } h1 { text-align: center; } .outer-grid { display: flex; flex-wrap: wrap; padding: 0 4px; } .inner-grid { flex: 25%; max-width: 25%; padding: 0 4px; } .inner-grid img { margin-top: 8px; width: 100%; padding: 10px; } @media screen and (max-width: 800px) { .inner-grid { flex: 50%; max-width: 50%; } } @media screen and (max-width: 600px) { .inner-grid { flex: 100%; max-width: 100%; } } </style> <body> <h1>Responsive Image Grid Example</h1> <div class="outer-grid"> <div class="inner-grid"> <img src="https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <img src="https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <img src="https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> </div> <div class="inner-grid"> <img src="https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <img src="https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <img src="https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> </div> <div class="inner-grid"> <img src="https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <img src="https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> <img src="https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/> </div> </div> </body> </html> The above code will produce the following output − On resizing the screen the grid will resize from 3 columns to 2 columns and so on −
[ { "code": null, "e": 1139, "s": 1062, "text": "Following is the code to create a responsive image grid using HTML and CSS −" }, { "code": null, "e": 1150, "s": 1139, "text": " Live Demo" }, { "code": null, "e": 2926, "s": 1150, "text": "<!DOCTYPE html>\n<html>\n<style>\n* {\n box-sizing: border-box;\n}\nh1 {\n text-align: center;\n}\n.outer-grid {\n display: flex;\n flex-wrap: wrap;\n padding: 0 4px;\n}\n.inner-grid {\n flex: 25%;\n max-width: 25%;\n padding: 0 4px;\n}\n.inner-grid img {\n margin-top: 8px;\n width: 100%;\n padding: 10px;\n}\n@media screen and (max-width: 800px) {\n .inner-grid {\n flex: 50%;\n max-width: 50%;\n }\n}\n@media screen and (max-width: 600px) {\n .inner-grid {\n flex: 100%;\n max-width: 100%;\n }\n}\n</style>\n<body>\n<h1>Responsive Image Grid Example</h1>\n<div class=\"outer-grid\">\n<div class=\"inner-grid\">\n<img src=\"https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<img src=\"https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<img src=\"https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n</div>\n<div class=\"inner-grid\">\n<img src=\"https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<img src=\"https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<img src=\"https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n</div>\n<div class=\"inner-grid\">\n<img src=\"https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<img src=\"https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n<img src=\"https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\"/>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2977, "s": 2926, "text": "The above code will produce the following output −" }, { "code": null, "e": 3061, "s": 2977, "text": "On resizing the screen the grid will resize from 3 columns to 2 columns and so on −" } ]
spaCy - Doc.ents Property
This doc property is used for the named entities in the document. If the entity recognizer has been applied, this property will return a tuple of named entity span objects. An example of Doc.ents property is as follows − import spacy nlp_model = spacy.load("en_core_web_sm") doc = nlp_model("This is Tutorialspoint.com.") ents = list(doc.ents) ents[0].label When you execute the code, you will see the following output − 383 Here is an another example of Doc.ents property − ents[0].label_ ‘ORG’ Given below is an example of Doc.ents property − ents[0].text 'Tutorialspoint.com' Print Add Notes Bookmark this page
[ { "code": null, "e": 2245, "s": 2072, "text": "This doc property is used for the named entities in the document. If the entity recognizer has been applied, this property will return a tuple of named entity span objects." }, { "code": null, "e": 2293, "s": 2245, "text": "An example of Doc.ents property is as follows −" }, { "code": null, "e": 2430, "s": 2293, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\ndoc = nlp_model(\"This is Tutorialspoint.com.\")\nents = list(doc.ents)\nents[0].label" }, { "code": null, "e": 2493, "s": 2430, "text": "When you execute the code, you will see the following output −" }, { "code": null, "e": 2498, "s": 2493, "text": "383\n" }, { "code": null, "e": 2548, "s": 2498, "text": "Here is an another example of Doc.ents property −" }, { "code": null, "e": 2563, "s": 2548, "text": "ents[0].label_" }, { "code": null, "e": 2570, "s": 2563, "text": "‘ORG’\n" }, { "code": null, "e": 2619, "s": 2570, "text": "Given below is an example of Doc.ents property −" }, { "code": null, "e": 2632, "s": 2619, "text": "ents[0].text" }, { "code": null, "e": 2654, "s": 2632, "text": "'Tutorialspoint.com'\n" }, { "code": null, "e": 2661, "s": 2654, "text": " Print" }, { "code": null, "e": 2672, "s": 2661, "text": " Add Notes" } ]
Aptitude | Arithmetic Aptitude 4 | Question 5 - GeeksforGeeks
28 Jun, 2021 Subhash has 90 currency notes, some of which are Rs. 1000 denomination and rest of Rs. 500 denomination. The total amount is Rs 71,000. How many notes he has in denomination of Rs. 500?(A) 30(B) 32(C) 34(D) 38Answer: (D)Explanation: Let the no. of Rs. 500 note be X Then the no. of Rs. 1000 note = 90 – X ∴ 500X + 1000(90 – X) = 71000 ∴ 500X + 90000 – 1000X = 71000 ∴ 500X = 19000 ∴ X = 38 Quiz of this Question Aptitude Aptitude-Arithmetic Aptitude 4 Arithmetic Aptitude 4 Aptitude Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments | | Question 44 Puzzle | How much money did the man have before entering the bank? Maximum GCD of all subarrays of length at least 2 7 Best Tips to Prepare for Aptitude Test For Campus Placements Puzzle | Splitting a Cake with a Missing Piece in two equal portion Order and Ranking Questions & Answers Aptitude | GATE CS 1998 | Question 77 10 Tips and Tricks to Crack Internships and Placements Geometry and Co-ordinates Seating Arrangement | Aptitude
[ { "code": null, "e": 24348, "s": 24320, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24581, "s": 24348, "text": "Subhash has 90 currency notes, some of which are Rs. 1000 denomination and rest of Rs. 500 denomination. The total amount is Rs 71,000. How many notes he has in denomination of Rs. 500?(A) 30(B) 32(C) 34(D) 38Answer: (D)Explanation:" }, { "code": null, "e": 24738, "s": 24581, "text": "Let the no. of Rs. 500 note be X\nThen the no. of Rs. 1000 note = 90 – X\n∴ 500X + 1000(90 – X) = 71000\n∴ 500X + 90000 – 1000X = 71000\n∴ 500X = 19000\n∴ X = 38" }, { "code": null, "e": 24760, "s": 24738, "text": "Quiz of this Question" }, { "code": null, "e": 24769, "s": 24760, "text": "Aptitude" }, { "code": null, "e": 24800, "s": 24769, "text": "Aptitude-Arithmetic Aptitude 4" }, { "code": null, "e": 24822, "s": 24800, "text": "Arithmetic Aptitude 4" }, { "code": null, "e": 24831, "s": 24822, "text": "Aptitude" }, { "code": null, "e": 24929, "s": 24831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24938, "s": 24929, "text": "Comments" }, { "code": null, "e": 24951, "s": 24938, "text": "Old Comments" }, { "code": null, "e": 24967, "s": 24951, "text": "| | Question 44" }, { "code": null, "e": 25034, "s": 24967, "text": "Puzzle | How much money did the man have before entering the bank?" }, { "code": null, "e": 25084, "s": 25034, "text": "Maximum GCD of all subarrays of length at least 2" }, { "code": null, "e": 25147, "s": 25084, "text": "7 Best Tips to Prepare for Aptitude Test For Campus Placements" }, { "code": null, "e": 25215, "s": 25147, "text": "Puzzle | Splitting a Cake with a Missing Piece in two equal portion" }, { "code": null, "e": 25253, "s": 25215, "text": "Order and Ranking Questions & Answers" }, { "code": null, "e": 25291, "s": 25253, "text": "Aptitude | GATE CS 1998 | Question 77" }, { "code": null, "e": 25346, "s": 25291, "text": "10 Tips and Tricks to Crack Internships and Placements" }, { "code": null, "e": 25372, "s": 25346, "text": "Geometry and Co-ordinates" } ]
RSpec - Subjects
One of RSpec’s strengths is that it provides many ways to write tests, clean tests. When your tests are short and uncluttered, it becomes easier to focus on the expected behavior and not on the details of how the tests are written. RSpec Subjects are yet another shortcut allowing you to write simple straightforward tests. Consider this code − class Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end end describe Person do it 'create a new person with a first and last name' do person = Person.new 'John', 'Smith' expect(person).to have_attributes(first_name: 'John') expect(person).to have_attributes(last_name: 'Smith') end end It’s actually pretty clear as is, but we could use RSpec’s subject feature to reduce the amount of code in the example. We do that by moving the person object instantiation into the describe line. class Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end end describe Person.new 'John', 'Smith' do it { is_expected.to have_attributes(first_name: 'John') } it { is_expected.to have_attributes(last_name: 'Smith') } end When you run this code, you will see this output − .. Finished in 0.003 seconds (files took 0.11201 seconds to load) 2 examples, 0 failures Note, how much simpler the second code sample is. We took the one it block in the first example and replaced it with two it blocks which end up requiring less code and are just as clear. 9 Lectures 37 mins Harshit Srivastava 27 Lectures 7 hours Atul Tiwari Print Add Notes Bookmark this page
[ { "code": null, "e": 2118, "s": 1794, "text": "One of RSpec’s strengths is that it provides many ways to write tests, clean tests. When your tests are short and uncluttered, it becomes easier to focus on the expected behavior and not on the details of how the tests are written. RSpec Subjects are yet another shortcut allowing you to write simple straightforward tests." }, { "code": null, "e": 2139, "s": 2118, "text": "Consider this code −" }, { "code": null, "e": 2576, "s": 2139, "text": "class Person \n attr_reader :first_name, :last_name \n \n def initialize(first_name, last_name) \n @first_name = first_name \n @last_name = last_name \n end \nend \n\ndescribe Person do \n it 'create a new person with a first and last name' do\n person = Person.new 'John', 'Smith'\n \n expect(person).to have_attributes(first_name: 'John') \n expect(person).to have_attributes(last_name: 'Smith') \n end \nend" }, { "code": null, "e": 2773, "s": 2576, "text": "It’s actually pretty clear as is, but we could use RSpec’s subject feature to reduce the amount of code in the example. We do that by moving the person object instantiation into the describe line." }, { "code": null, "e": 3118, "s": 2773, "text": "class Person \n attr_reader :first_name, :last_name \n \n def initialize(first_name, last_name) \n @first_name = first_name \n @last_name = last_name \n end \n\t\nend \n\ndescribe Person.new 'John', 'Smith' do \n it { is_expected.to have_attributes(first_name: 'John') } \n it { is_expected.to have_attributes(last_name: 'Smith') }\nend" }, { "code": null, "e": 3169, "s": 3118, "text": "When you run this code, you will see this output −" }, { "code": null, "e": 3261, "s": 3169, "text": ".. \nFinished in 0.003 seconds (files took 0.11201 seconds to load) \n2 examples, 0 failures\n" }, { "code": null, "e": 3448, "s": 3261, "text": "Note, how much simpler the second code sample is. We took the one it block in the first example and replaced it with two it blocks which end up requiring less code and are just as clear." }, { "code": null, "e": 3479, "s": 3448, "text": "\n 9 Lectures \n 37 mins\n" }, { "code": null, "e": 3499, "s": 3479, "text": " Harshit Srivastava" }, { "code": null, "e": 3532, "s": 3499, "text": "\n 27 Lectures \n 7 hours \n" }, { "code": null, "e": 3545, "s": 3532, "text": " Atul Tiwari" }, { "code": null, "e": 3552, "s": 3545, "text": " Print" }, { "code": null, "e": 3563, "s": 3552, "text": " Add Notes" } ]
How to split a string into elements of a string array in C#?
Set the string you want to split. string str = "Hello World!"; Use the split() method to split the string into separate elements. string[] res = str.Split(' '); The following is the complete code to split a string into elements of a string array in C#. Live Demo using System; class Demo { static void Main() { string str = "Hello World!"; string[] res = str.Split(' '); Console.WriteLine("Separate elements:"); foreach (string words in res) { Console.WriteLine(words); } } } Separate elements: Hello World!
[ { "code": null, "e": 1096, "s": 1062, "text": "Set the string you want to split." }, { "code": null, "e": 1125, "s": 1096, "text": "string str = \"Hello World!\";" }, { "code": null, "e": 1192, "s": 1125, "text": "Use the split() method to split the string into separate elements." }, { "code": null, "e": 1223, "s": 1192, "text": "string[] res = str.Split(' ');" }, { "code": null, "e": 1315, "s": 1223, "text": "The following is the complete code to split a string into elements of a string array in C#." }, { "code": null, "e": 1326, "s": 1315, "text": " Live Demo" }, { "code": null, "e": 1584, "s": 1326, "text": "using System;\nclass Demo {\n static void Main() {\n string str = \"Hello World!\";\n string[] res = str.Split(' ');\n Console.WriteLine(\"Separate elements:\");\n foreach (string words in res) {\n Console.WriteLine(words);\n }\n }\n}" }, { "code": null, "e": 1616, "s": 1584, "text": "Separate elements:\nHello\nWorld!" } ]
How to read data from one file and print to another file in Java?
Java provides I/O Streams to read and write data where a Stream represents an input source or an output destination which could be a file, i/o devise, other programs, etc. In general, a Stream will be an input stream or, an output stream. InputStream − This is used to read data from a source. InputStream − This is used to read data from a source. OutputStream − This is used to write data to a destination. OutputStream − This is used to write data to a destination. Based on the data they handle there are two types of streams − Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images, etc. Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images, etc. Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only. Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only. The following diagram illustrates all the input and output Streams (classes) in Java. Among these, you can read the contents of a file using Scanner, BufferedReader and, FileReader classes. In the same way, you can write data into a file using BufferedWriter, FileOutputStream, FileWriter. Following is a Java program that reads data from a file to a String using the Scanner class and writes it to another file using the FileWriter class. import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class CopyContent { public static void main(String[] args) throws IOException { //Instantiating a file class File file = new File("D:\\sampleData.txt"); //Instantiate an FileInputStream class FileInputStream inputStream = new FileInputStream(file); //Instantiating the Scanner class Scanner sc = new Scanner(inputStream); //StringBuffer to store the contents StringBuffer buffer = new StringBuffer(); //Appending each line to the buffer while(sc.hasNext()) { buffer.append(" "+sc.nextLine()); } System.out.println("Contents of the file: "+buffer); //Creating a File object to hold the destination file File dest = new File("D:\\outputFile.txt"); //Instantiating an FileWriter object FileWriter writer = new FileWriter(dest); //Writing content to the destination writer.write(buffer.toString()); writer.flush(); System.out.println("File copied successfully......."); } } Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more. 40 million readers read 100 million pages every month. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit their details either. No preconditions and no impediments. Simply Easy Learning! File copied successfully.......
[ { "code": null, "e": 1234, "s": 1062, "text": "Java provides I/O Streams to read and write data where a Stream represents an input source or an output destination which could be a file, i/o devise, other programs, etc." }, { "code": null, "e": 1301, "s": 1234, "text": "In general, a Stream will be an input stream or, an output stream." }, { "code": null, "e": 1356, "s": 1301, "text": "InputStream − This is used to read data from a source." }, { "code": null, "e": 1411, "s": 1356, "text": "InputStream − This is used to read data from a source." }, { "code": null, "e": 1471, "s": 1411, "text": "OutputStream − This is used to write data to a destination." }, { "code": null, "e": 1531, "s": 1471, "text": "OutputStream − This is used to write data to a destination." }, { "code": null, "e": 1594, "s": 1531, "text": "Based on the data they handle there are two types of streams −" }, { "code": null, "e": 1769, "s": 1594, "text": "Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images, etc." }, { "code": null, "e": 1944, "s": 1769, "text": "Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images, etc." }, { "code": null, "e": 2052, "s": 1944, "text": "Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only." }, { "code": null, "e": 2160, "s": 2052, "text": "Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only." }, { "code": null, "e": 2246, "s": 2160, "text": "The following diagram illustrates all the input and output Streams (classes) in Java." }, { "code": null, "e": 2350, "s": 2246, "text": "Among these, you can read the contents of a file using Scanner, BufferedReader and, FileReader classes." }, { "code": null, "e": 2450, "s": 2350, "text": "In the same way, you can write data into a file using BufferedWriter, FileOutputStream, FileWriter." }, { "code": null, "e": 2600, "s": 2450, "text": "Following is a Java program that reads data from a file to a String using the Scanner class and writes it to another file using the FileWriter class." }, { "code": null, "e": 3746, "s": 2600, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Scanner;\npublic class CopyContent {\n public static void main(String[] args) throws IOException {\n //Instantiating a file class\n File file = new File(\"D:\\\\sampleData.txt\");\n //Instantiate an FileInputStream class\n FileInputStream inputStream = new FileInputStream(file);\n //Instantiating the Scanner class\n Scanner sc = new Scanner(inputStream);\n //StringBuffer to store the contents\n StringBuffer buffer = new StringBuffer();\n //Appending each line to the buffer\n while(sc.hasNext()) {\n buffer.append(\" \"+sc.nextLine());\n }\n System.out.println(\"Contents of the file: \"+buffer);\n //Creating a File object to hold the destination file\n File dest = new File(\"D:\\\\outputFile.txt\");\n //Instantiating an FileWriter object\n FileWriter writer = new FileWriter(dest);\n //Writing content to the destination\n writer.write(buffer.toString());\n writer.flush();\n System.out.println(\"File copied successfully.......\");\n }\n}" }, { "code": null, "e": 4682, "s": 3746, "text": "Contents of the file: Tutorials Point originated from the idea that there exists a \nclass of readers who respond better to online content and prefer to learn new skills \nat their own pace from the comforts of their drawing rooms. The journey commenced \nwith a single tutorial on HTML in 2006 and elated by the response it generated, \nwe worked our way to adding fresh tutorials to our repository which now proudly \nflaunts a wealth of tutorials and allied articles on topics ranging from programming \nlanguages to web designing to academics and much more. 40 million readers read 100 \nmillion pages every month. Our content and resources are freely available and we prefer \nto keep it that way to encourage our readers acquire as many skills as they would like to. \nWe don’t force our readers to sign up with us or submit their details either. \nNo preconditions and no impediments. Simply Easy Learning!\nFile copied successfully......." } ]
Contains Duplicate III in C++
Suppose we have an array of integers, we have to check whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t. And the absolute difference between i and j is at most k. So if input is like [1,2,3,1], then if k = 3 and t = 0, then return true. To solve this, we will follow these steps − Make a set s, n := size of nums array Make a set s, n := size of nums array for i in range 0 to n – 1x is index of set element starting from nums[i] and aboveif x is not in range of the set and value of x <= nums[i] + t, then return trueif x is not the first elementx := next element as randomif t th element starting from x is >= nums[i], then return trueinsert nums[i] into s, then delete nums[i - k] from s for i in range 0 to n – 1 x is index of set element starting from nums[i] and above x is index of set element starting from nums[i] and above if x is not in range of the set and value of x <= nums[i] + t, then return true if x is not in range of the set and value of x <= nums[i] + t, then return true if x is not the first elementx := next element as randomif t th element starting from x is >= nums[i], then return true if x is not the first element x := next element as random x := next element as random if t th element starting from x is >= nums[i], then return true if t th element starting from x is >= nums[i], then return true insert nums[i] into s, then delete nums[i - k] from s insert nums[i] into s, then delete nums[i - k] from s return false return false Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { multiset <int> s; int n = nums.size(); for(int i = 0; i< n; i++){ multiset <int> :: iterator x = s.lower_bound(nums[i]); if(x != s.end() && *x <= nums[i] + t ) return true; if(x != s.begin()){ x = std::next(x, -1); if(*x + t >= nums[i])return true; } s.insert(nums[i]); if(i >= k){ s.erase(nums[i - k]); } } return false; } }; main(){ Solution ob; vector<int> v = {1,2,3,1}; cout << (ob.containsNearbyAlmostDuplicate(v, 3,0)); } [1,2,3,1] 3 0 1
[ { "code": null, "e": 1385, "s": 1062, "text": "Suppose we have an array of integers, we have to check whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t. And the absolute difference between i and j is at most k. So if input is like [1,2,3,1], then if k = 3 and t = 0, then return true." }, { "code": null, "e": 1429, "s": 1385, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1467, "s": 1429, "text": "Make a set s, n := size of nums array" }, { "code": null, "e": 1505, "s": 1467, "text": "Make a set s, n := size of nums array" }, { "code": null, "e": 1839, "s": 1505, "text": "for i in range 0 to n – 1x is index of set element starting from nums[i] and aboveif x is not in range of the set and value of x <= nums[i] + t, then return trueif x is not the first elementx := next element as randomif t th element starting from x is >= nums[i], then return trueinsert nums[i] into s, then delete nums[i - k] from s" }, { "code": null, "e": 1865, "s": 1839, "text": "for i in range 0 to n – 1" }, { "code": null, "e": 1923, "s": 1865, "text": "x is index of set element starting from nums[i] and above" }, { "code": null, "e": 1981, "s": 1923, "text": "x is index of set element starting from nums[i] and above" }, { "code": null, "e": 2061, "s": 1981, "text": "if x is not in range of the set and value of x <= nums[i] + t, then return true" }, { "code": null, "e": 2141, "s": 2061, "text": "if x is not in range of the set and value of x <= nums[i] + t, then return true" }, { "code": null, "e": 2261, "s": 2141, "text": "if x is not the first elementx := next element as randomif t th element starting from x is >= nums[i], then return true" }, { "code": null, "e": 2291, "s": 2261, "text": "if x is not the first element" }, { "code": null, "e": 2319, "s": 2291, "text": "x := next element as random" }, { "code": null, "e": 2347, "s": 2319, "text": "x := next element as random" }, { "code": null, "e": 2411, "s": 2347, "text": "if t th element starting from x is >= nums[i], then return true" }, { "code": null, "e": 2475, "s": 2411, "text": "if t th element starting from x is >= nums[i], then return true" }, { "code": null, "e": 2529, "s": 2475, "text": "insert nums[i] into s, then delete nums[i - k] from s" }, { "code": null, "e": 2583, "s": 2529, "text": "insert nums[i] into s, then delete nums[i - k] from s" }, { "code": null, "e": 2596, "s": 2583, "text": "return false" }, { "code": null, "e": 2609, "s": 2596, "text": "return false" }, { "code": null, "e": 2681, "s": 2609, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2692, "s": 2681, "text": " Live Demo" }, { "code": null, "e": 3442, "s": 2692, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {\n multiset <int> s;\n int n = nums.size();\n for(int i = 0; i< n; i++){\n multiset <int> :: iterator x = s.lower_bound(nums[i]);\n if(x != s.end() && *x <= nums[i] + t ) return true;\n if(x != s.begin()){\n x = std::next(x, -1);\n if(*x + t >= nums[i])return true;\n }\n s.insert(nums[i]);\n if(i >= k){\n s.erase(nums[i - k]);\n }\n }\n return false;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,2,3,1};\n cout << (ob.containsNearbyAlmostDuplicate(v, 3,0));\n}" }, { "code": null, "e": 3456, "s": 3442, "text": "[1,2,3,1]\n3\n0" }, { "code": null, "e": 3458, "s": 3456, "text": "1" } ]
C# | How to use multiple catch clause - GeeksforGeeks
24 Jan, 2019 The main purpose of the catch block is to handle the exception raised in the try block. This block is only going to execute when the exception raised in the program.In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception. If you use multiple catch blocks for the same type of exception, then it will give you a compile-time error because C# does not allow you to use multiple catch block for the same type of exception. A catch block is always preceded by the try block. In general, the catch block is checked within the order in which they have occurred in the program. If the given type of exception is matched with the first catch block, then first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then compiler search for the next catch block. Syntax: try { // Your code } // 1st catch block catch(Exception_Name) { // Code } // 2nd catch block catch(Exception_Name) { // Code } . . . . Below given are some examples to understand the implementation in a better way: Example 1: In the below example, try block generate two different types of exception i.e DivideByZeroException and IndexOutOfRangeException. Now we use two catch blocks to handle these exceptions that are associated with a single try block. Each catch block caught a different type of exception like catch block 1 is used to catch DivideByZeroException, catch block 2 is used to catch IndexOutOfRangeException. // C# program to illustrate the// use of multiple catch blockusing System; class GFG { // Main Method static void Main() { // Here, number is greater than divisor int[] number = { 8, 17, 24, 5, 25 }; int[] divisor = { 2, 0, 0, 5 }; // --------- try block --------- for (int j = 0; j < number.Length; j++) // Here this block raises two different // types of exception, i.e. DivideByZeroException // and IndexOutOfRangeException try { Console.WriteLine("Number: " + number[j]); Console.WriteLine("Divisor: " + divisor[j]); Console.WriteLine("Quotient: " + number[j] / divisor[j]); } // Catch block 1 // This Catch block is for // handling DivideByZeroException catch (DivideByZeroException) { Console.WriteLine("Not possible to Divide by zero"); } // Catch block 2 // This Catch block is for // handling IndexOutOfRangeException catch (IndexOutOfRangeException) { Console.WriteLine("Index is Out of Range"); } }} Number: 8 Divisor: 2 Quotient: 4 Number: 17 Divisor: 0 Not possible to Divide by zero Number: 24 Divisor: 0 Not possible to Divide by zero Number: 5 Divisor: 5 Quotient: 1 Number: 25 Index is Out of Range Example 2: In the below example, try block raise an exception. So we will use three different type of catch blocks to handle the exception raised by the try block. Catch block 1 will handle IndexOutOfRangeException, catch block 2 will handle FormatException, and catch block 3 will handle OverflowException. // C# program to illustrate the concept// of multiple catch clauseusing System; class GFG { // Main method static void Main() { // This block raises an exception try { byte data = byte.Parse("a"); Console.WriteLine(data); } // Catch block 1 // This block is used to handle // IndexOutOfRangeException type exception catch (IndexOutOfRangeException) { Console.WriteLine("At least provide one Argument!"); } // Catch block 2 // This block is used to handle // FormatException type exception catch (FormatException) { Console.WriteLine("Entered value in not a number!"); } // Catch block 3 // This block is used to handle // OverflowException type exception catch (OverflowException) { Console.WriteLine("Data is out of Range!"); } }} Entered value in not a number! CSharp-Exception-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Introduction to .NET Framework Extension Method in C# C# | Class and Object C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1 Common Language Runtime (CLR) in C# C# | Encapsulation
[ { "code": null, "e": 24309, "s": 24281, "text": "\n24 Jan, 2019" }, { "code": null, "e": 24938, "s": 24309, "text": "The main purpose of the catch block is to handle the exception raised in the try block. This block is only going to execute when the exception raised in the program.In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception. If you use multiple catch blocks for the same type of exception, then it will give you a compile-time error because C# does not allow you to use multiple catch block for the same type of exception. A catch block is always preceded by the try block." }, { "code": null, "e": 25310, "s": 24938, "text": "In general, the catch block is checked within the order in which they have occurred in the program. If the given type of exception is matched with the first catch block, then first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then compiler search for the next catch block." }, { "code": null, "e": 25318, "s": 25310, "text": "Syntax:" }, { "code": null, "e": 25464, "s": 25318, "text": "try {\n\n// Your code \n\n}\n\n// 1st catch block\ncatch(Exception_Name) {\n\n// Code\n\n}\n\n// 2nd catch block\ncatch(Exception_Name) {\n\n// Code\n\n}\n\n.\n.\n.\n.\n" }, { "code": null, "e": 25544, "s": 25464, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25955, "s": 25544, "text": "Example 1: In the below example, try block generate two different types of exception i.e DivideByZeroException and IndexOutOfRangeException. Now we use two catch blocks to handle these exceptions that are associated with a single try block. Each catch block caught a different type of exception like catch block 1 is used to catch DivideByZeroException, catch block 2 is used to catch IndexOutOfRangeException." }, { "code": "// C# program to illustrate the// use of multiple catch blockusing System; class GFG { // Main Method static void Main() { // Here, number is greater than divisor int[] number = { 8, 17, 24, 5, 25 }; int[] divisor = { 2, 0, 0, 5 }; // --------- try block --------- for (int j = 0; j < number.Length; j++) // Here this block raises two different // types of exception, i.e. DivideByZeroException // and IndexOutOfRangeException try { Console.WriteLine(\"Number: \" + number[j]); Console.WriteLine(\"Divisor: \" + divisor[j]); Console.WriteLine(\"Quotient: \" + number[j] / divisor[j]); } // Catch block 1 // This Catch block is for // handling DivideByZeroException catch (DivideByZeroException) { Console.WriteLine(\"Not possible to Divide by zero\"); } // Catch block 2 // This Catch block is for // handling IndexOutOfRangeException catch (IndexOutOfRangeException) { Console.WriteLine(\"Index is Out of Range\"); } }}", "e": 27176, "s": 25955, "text": null }, { "code": null, "e": 27382, "s": 27176, "text": "Number: 8\nDivisor: 2\nQuotient: 4\nNumber: 17\nDivisor: 0\nNot possible to Divide by zero\nNumber: 24\nDivisor: 0\nNot possible to Divide by zero\nNumber: 5\nDivisor: 5\nQuotient: 1\nNumber: 25\nIndex is Out of Range\n" }, { "code": null, "e": 27690, "s": 27382, "text": "Example 2: In the below example, try block raise an exception. So we will use three different type of catch blocks to handle the exception raised by the try block. Catch block 1 will handle IndexOutOfRangeException, catch block 2 will handle FormatException, and catch block 3 will handle OverflowException." }, { "code": "// C# program to illustrate the concept// of multiple catch clauseusing System; class GFG { // Main method static void Main() { // This block raises an exception try { byte data = byte.Parse(\"a\"); Console.WriteLine(data); } // Catch block 1 // This block is used to handle // IndexOutOfRangeException type exception catch (IndexOutOfRangeException) { Console.WriteLine(\"At least provide one Argument!\"); } // Catch block 2 // This block is used to handle // FormatException type exception catch (FormatException) { Console.WriteLine(\"Entered value in not a number!\"); } // Catch block 3 // This block is used to handle // OverflowException type exception catch (OverflowException) { Console.WriteLine(\"Data is out of Range!\"); } }}", "e": 28640, "s": 27690, "text": null }, { "code": null, "e": 28672, "s": 28640, "text": "Entered value in not a number!\n" }, { "code": null, "e": 28698, "s": 28672, "text": "CSharp-Exception-Handling" }, { "code": null, "e": 28701, "s": 28698, "text": "C#" }, { "code": null, "e": 28799, "s": 28701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28808, "s": 28799, "text": "Comments" }, { "code": null, "e": 28821, "s": 28808, "text": "Old Comments" }, { "code": null, "e": 28836, "s": 28821, "text": "C# | Delegates" }, { "code": null, "e": 28876, "s": 28836, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28894, "s": 28876, "text": "C# | Constructors" }, { "code": null, "e": 28925, "s": 28894, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28948, "s": 28925, "text": "Extension Method in C#" }, { "code": null, "e": 28970, "s": 28948, "text": "C# | Class and Object" }, { "code": null, "e": 28992, "s": 28970, "text": "C# | Abstract Classes" }, { "code": null, "e": 29032, "s": 28992, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29068, "s": 29032, "text": "Common Language Runtime (CLR) in C#" } ]
Java Program to swap two arrays Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this Java programming tutorials, I am going to show you how to swap two arrays in Java. Input 1 : Give an integer array from command line. array1 {1,,2,4,5,3,7} Input 2 : Give an another integer array from command line. array2 {5,6,0,8,4,3} Output : array1 : {5,6,0,8,4,3} and array2 : {1,,2,4,5,3,7} package com.onlinetutorialspoint.javaprograms; import java.util.Scanner; public class SwappingTwoArrays { public static void main(String[] args) { Scanner input_size = new Scanner(System.in); System.out.println("Enter the Size of Arrays : "); int size = input_size.nextInt(); int[] array1 = new int[size], array2 = new int[size], buffer = new int[size]; Scanner sc = new Scanner(System.in); System.out.println("Enter the First Array of Elements: "); for (int i = 0; i < size; i++) { array1[i] = sc.nextInt(); } System.out.println("Enter the Second Array of Elements: "); for (int i = 0; i < size; i++) { array2[i] = sc.nextInt(); } System.out.println("Before Swapping"); System.out.println("First Array: "); for (int i = 0; i < size; i++) { System.out.print(array1[i]); } System.out.println("\nSecond Array: "); for (int i = 0; i < size; i++) { System.out.print(array2[i]); } for (int i = 0; i < size; i++) { buffer[i] = array1[i]; array1[i] = array2[i]; array2[i] = buffer[i]; } System.out.println("\nArrays after Swapping"); System.out.println("First Array: "); for (int i = 0; i < size; i++) { System.out.print(array1[i]); } System.out.println("\nSecond Array: "); for (int i = 0; i < size; i++) { System.out.print(array2[i]); } } } Output Enter the Size of Arrays : 5 Enter the First Array of Elements: 1 5 6 9 8 Enter the Second Array of Elements: 5 6 4 2 8 Before Swapping First Array: 15698 Second Array: 56428 Arrays after Swapping First Array: 56428 Second Array: 15698 Happy Learning 🙂 Binary To Decimal Conversion Java Program Binary To Hexadecimal Conversion Java Program Binary Search using Java Java Program to Find the GCD of Two Numbers Java Program to Check a Number is Palindrome or not ? How to Rotate an Array to Left direction based on user input ? Java Program for Reverse Of Number What is Java Arrays and how it works ? Java Program for String Sorting Example Java Program to Print Pattern Triangle Java Program to Print Diamond Pattern Java Program For Binary Addition Java program to find sum of digits Program to display Java Multiplication Table Java program for Triangle Part – 2 Binary To Decimal Conversion Java Program Binary To Hexadecimal Conversion Java Program Binary Search using Java Java Program to Find the GCD of Two Numbers Java Program to Check a Number is Palindrome or not ? How to Rotate an Array to Left direction based on user input ? Java Program for Reverse Of Number What is Java Arrays and how it works ? Java Program for String Sorting Example Java Program to Print Pattern Triangle Java Program to Print Diamond Pattern Java Program For Binary Addition Java program to find sum of digits Program to display Java Multiplication Table Java program for Triangle Part – 2 Naina July 14, 2019 at 8:06 am - Reply How can we swap 133967 in java Naina July 14, 2019 at 8:06 am - Reply How can we swap 133967 in java How can we swap 133967 in java
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 489, "s": 398, "text": "In this Java programming tutorials, I am going to show you how to swap two arrays in Java." }, { "code": null, "e": 562, "s": 489, "text": "Input 1 : Give an integer array from command line. array1 {1,,2,4,5,3,7}" }, { "code": null, "e": 642, "s": 562, "text": "Input 2 : Give an another integer array from command line. array2 {5,6,0,8,4,3}" }, { "code": null, "e": 702, "s": 642, "text": "Output : array1 : {5,6,0,8,4,3} and array2 : {1,,2,4,5,3,7}" }, { "code": null, "e": 2273, "s": 702, "text": "package com.onlinetutorialspoint.javaprograms;\n\nimport java.util.Scanner;\n\npublic class SwappingTwoArrays {\n public static void main(String[] args) {\n Scanner input_size = new Scanner(System.in);\n System.out.println(\"Enter the Size of Arrays : \");\n int size = input_size.nextInt();\n int[] array1 = new int[size], array2 = new int[size], buffer = new int[size];\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the First Array of Elements: \");\n for (int i = 0; i < size; i++) {\n array1[i] = sc.nextInt();\n }\n System.out.println(\"Enter the Second Array of Elements: \");\n for (int i = 0; i < size; i++) {\n array2[i] = sc.nextInt();\n }\n System.out.println(\"Before Swapping\");\n System.out.println(\"First Array: \");\n for (int i = 0; i < size; i++) {\n System.out.print(array1[i]);\n }\n System.out.println(\"\\nSecond Array: \");\n for (int i = 0; i < size; i++) {\n System.out.print(array2[i]);\n }\n for (int i = 0; i < size; i++) {\n buffer[i] = array1[i];\n array1[i] = array2[i];\n array2[i] = buffer[i];\n }\n System.out.println(\"\\nArrays after Swapping\");\n System.out.println(\"First Array: \");\n for (int i = 0; i < size; i++) {\n System.out.print(array1[i]);\n }\n System.out.println(\"\\nSecond Array: \");\n for (int i = 0; i < size; i++) {\n System.out.print(array2[i]);\n }\n }\n}\n" }, { "code": null, "e": 2280, "s": 2273, "text": "Output" }, { "code": null, "e": 2516, "s": 2280, "text": "Enter the Size of Arrays :\n5\nEnter the First Array of Elements:\n1\n5\n6\n9\n8\nEnter the Second Array of Elements:\n5\n6\n4\n2\n8\nBefore Swapping\nFirst Array:\n15698\nSecond Array:\n56428\nArrays after Swapping\nFirst Array:\n56428\nSecond Array:\n15698" }, { "code": null, "e": 2533, "s": 2516, "text": "Happy Learning 🙂" }, { "code": null, "e": 3148, "s": 2533, "text": "\nBinary To Decimal Conversion Java Program\nBinary To Hexadecimal Conversion Java Program\nBinary Search using Java\nJava Program to Find the GCD of Two Numbers\nJava Program to Check a Number is Palindrome or not ?\nHow to Rotate an Array to Left direction based on user input ?\nJava Program for Reverse Of Number\nWhat is Java Arrays and how it works ?\nJava Program for String Sorting Example\nJava Program to Print Pattern Triangle\nJava Program to Print Diamond Pattern\nJava Program For Binary Addition\nJava program to find sum of digits\nProgram to display Java Multiplication Table\nJava program for Triangle Part – 2\n" }, { "code": null, "e": 3190, "s": 3148, "text": "Binary To Decimal Conversion Java Program" }, { "code": null, "e": 3236, "s": 3190, "text": "Binary To Hexadecimal Conversion Java Program" }, { "code": null, "e": 3261, "s": 3236, "text": "Binary Search using Java" }, { "code": null, "e": 3305, "s": 3261, "text": "Java Program to Find the GCD of Two Numbers" }, { "code": null, "e": 3359, "s": 3305, "text": "Java Program to Check a Number is Palindrome or not ?" }, { "code": null, "e": 3422, "s": 3359, "text": "How to Rotate an Array to Left direction based on user input ?" }, { "code": null, "e": 3457, "s": 3422, "text": "Java Program for Reverse Of Number" }, { "code": null, "e": 3496, "s": 3457, "text": "What is Java Arrays and how it works ?" }, { "code": null, "e": 3536, "s": 3496, "text": "Java Program for String Sorting Example" }, { "code": null, "e": 3575, "s": 3536, "text": "Java Program to Print Pattern Triangle" }, { "code": null, "e": 3613, "s": 3575, "text": "Java Program to Print Diamond Pattern" }, { "code": null, "e": 3646, "s": 3613, "text": "Java Program For Binary Addition" }, { "code": null, "e": 3681, "s": 3646, "text": "Java program to find sum of digits" }, { "code": null, "e": 3726, "s": 3681, "text": "Program to display Java Multiplication Table" }, { "code": null, "e": 3761, "s": 3726, "text": "Java program for Triangle Part – 2" }, { "code": null, "e": 3844, "s": 3761, "text": "\n\n\n\n\n\nNaina\nJuly 14, 2019 at 8:06 am - Reply \n\nHow can we swap 133967 in java\n\n\n\n\n" }, { "code": null, "e": 3925, "s": 3844, "text": "\n\n\n\n\nNaina\nJuly 14, 2019 at 8:06 am - Reply \n\nHow can we swap 133967 in java\n\n\n\n" } ]
End-to-End Machine Learning Project: Train and Deploy Models as Web Apps Using Flask and Heroku | by Saket Garodia | Towards Data Science
Business Problem: One of the fields where AI will play a huge role in the future is Medical Science. Doctors and researchers have been trying to use Machine Learning and Deep Learning to learn the occurrence of cancers and other chronic diseases by using millions of data points available through the protein combinations of our DNA and other lifestyle attributes. In the future, we might be able to know our chance of getting cancer a decade or two earlier that can help us avoid it. Fortunately, in my search of finding a good medical science dataset, I came across this Pima Indians Diabetes dataset on Kaggle. It is collected from the National Institute of Diabetes and Digestive and Kidney Disease. This dataset is small with 9 features and 768 observations which is enough to solve the problem of predicting the probability of a person to be a Diabetic. Here’s a brief description of all the features which I’m referring to from the data source itself for you to follow along. Link to the dataset: https://www.kaggle.com/uciml/pima-indians-diabetes-database Feel free to get a feel of the app before reading ( :) ): predict-diabetes-using-ml.herokuapp.com 1: Pregnancies: Number of times pregnant 2: Glucose: Plasma glucose concentration a 2 hours in an oral glucose tolerance test. 3: BloodPressure: Diastolic blood pressure (mm Hg) 4: SkinThickness: Triceps skinfold thickness (mm) 5: Insulin: 2-Hour serum insulin (mu U/ml) 6: BMI: Body mass index (weight in kg/(height in m)2) 7: DiabetesPedigreeFunction: Diabetes pedigree function 8: Age: Age (years) 9: Outcome: Class variable (0 or 1) 268 of 768 are 1, the others are 0 All the variables are either self-known or available in a simple Blood Test and “Outcome” (Diabetic/Not) is what we need to predict. We will explore different features and perform various pre-processing techniques before trying out different machine learning algorithms like logistic Regression, Support Vector Machines, Decision Forest, Gradient Boosting and finally we will also explore neural networks. Once we have the best model, we will save our model using Pickle and use that to develop a diabetes prediction app using the Flask web framework and then deploy it using Heroku. Let’s begin. Grab a coffee!! A brief overview of the structure: Feel free to jump over to step 2 if you don’t want to get an overview of the preparation and modeling part. Step 1: Data Preparation and model building In this step, we will explore the data, do the required pre-processing and try various Machine Learning models like Logistic Regression, SVMs, Random Forest, Gradient Boosting, and the state of the art models like Neural Networks. Step 2: Building the app using Flask and HTML Here, we will fetch the best-performing model from step 1 and build a web app using Flask and HTML. Step 3: Deploying the app using Heroku In the end, we will deploy our working app through Heroku for the world to use our product. You can follow along through my Jupiter notebook that can be accessed at: https://github.com/garodisk/Diabetes-prediction-app-using-ML/blob/main/Diabetes%20prediction%20using%20Machine%20Learning.ipynb #importing reqd librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdf.head() For the feel of the data, let’s print the head: Though a top-level overview of data shows that there are no null values, a deeper analysis shows that a lot of attributes have 0 values which don’t make any sense. How can someone’s BMI/Skin Thickness/Age be 0? Let’s see how many zero values are there for each of the attributes and let’s convert them to null values. We will later handle those null values with imputation techniques. Now, that we have all the zero values converted into the null values, our next step is to impute these null values. At this point, many people just use a simple mean/median imputation that they calculate using the whole column which is not correct. For imputing each of the null values, we will look at the outcome whether it belongs to a diabetic person or not. We will impute using the median of that particular attribute based on what Outcome we will see. If a null value belongs to a diabetic person, we will find the median using only the diabetic records, and similarly if it belongs to a non-diabetic person, we will find the median using the non-diabetic records. Let’s analyze the correlation map and histogram plots for a further feel of the data. We can see that for most of the attributes, the distribution for the diabetic people (the red part) is shifted towards the right when compared with the distribution of the non-diabetic part (blue part). This basically tells us a story that a diabetic person is more likely to be a elder person with a higher BMI, SkinThickness, and glucose levels. Next, we will plot the boxplot for each of these attributes to clearly see the difference in the distribution of each of the attributes for both these outcomes (Diabetic and Non-diabetic). Here’s the distribution of the outcome variable: The data contains 500 non-diabetic people and 268 diabetic people. Now, let's use PCA and t-SNE to visualize the data on a 2-dimensional plane for better intuition. PCA does a decent job of 2-d visualization since the 2 principal components contain about 50% of the overall variance in data. Now, let’s try t-SNE which is even better for visualizing on 2-d since it uses probabilistic distribution and tries to keep similar data points closer to each other on the 2-d plane. It indeed did a great job. We can see that the diabetic people and non-diabetic people are mostly clustered together on the t-SNE plot. Now, before modeling, we must scale the data since all the attributes are on a different scale. Except for the tree algorithms, most of the machine learning algorithms especially those that use Gradient Descent or distance metrics require scaling. The two most discussed scaling methods are Normalization and Standardization. Normalization typically means rescales the values into a range of [0,1]. Standardization typically means rescales data to have a mean of 0 and a standard deviation of 1 (unit variance). Normalization vs. standardization is an eternal question among machine learning newcomers. Normalization is good to use when you know that the distribution of your data does not follow a Gaussian distribution. This can be useful in algorithms that do not assume any distribution of the data like K-Nearest Neighbors and Neural Networks. Standardization, on the other hand, can be helpful in cases where the data follows a Gaussian distribution. However, this does not have to be necessarily true. Also, unlike normalization, standardization does not have a bounding range. So, even if you have outliers in your data, they will not be affected by standardization. There is no hard and fast rule to tell us when to normalize or standardize your data. We can always start by fitting your model to raw, normalized, and standardized data and compare the performance for the best results. Important: It is a good practice to fit the scaler on the training data and then use it to transform the testing data. This would avoid any data leakage during the model testing process. Also, the scaling of target values is generally not required. Now, let’s see the distribution of each of the attributes again to understand which ones follow Gaussian distribution. Only Glucose, BloodPressure and BMI follow a Gaussian distribution where normalization can make sense but since there is no hard and fast rule, we will try 3 things and compare their performance. Use Normalization on all the attributes and check the performance of a Logistic regression model on the test setUse Standardization on all the attributes and check the performance of a Logistic regression model on the test setUse standardization on the attributes that follow a Gaussian distribution and normalization on the rest of the attributes and see the performance Use Normalization on all the attributes and check the performance of a Logistic regression model on the test set Use Standardization on all the attributes and check the performance of a Logistic regression model on the test set Use standardization on the attributes that follow a Gaussian distribution and normalization on the rest of the attributes and see the performance Out of the above 3, normalization had the best accuracy of 0.83 on a test set using a Logistic Regression model. Repeat Note: One other important thing to keep in mind is to fit the StandardScalar only on the training set and then use this to scale the test set to avoid Data Leakage. We will also save the preprocessor for further use in our Machine Learning app. Logistic Regression (Accuracy - 83%): Now, let’s try other Machine Learning algorithms: K-Nearest Neighbors (Accuracy - 87%): Support Vector Machines (Accuracy - 88%-89%): Random Forest(Accuracy - 88%-89%): Gradient Boosting(Accuracy - 87%-88%): The best performing machine learning algorithm on the dataset are SVMs and Random Forest; both have an accuracy between 88% and 89% but SVMs are more simplistic for deployment and will take less time when further data comes in for training. Before moving with SVM, let’s try and see how Neural Network performs on the dataset. On the test set, the neural network just has an 85% accuracy. This can be very much possible because a neural network creates a more complex set of hidden layers but at the same time, it requires more and more examples for a better result. Out data only contains 768 observations for it to perform well. Neural Network (Accuracy - 85%) Now, as a final step, we will save our SVM model for prediction into a .h5 or .bin file using a library like pickle . The next step is to package this model into a web service that, when given the data through a POST request, returns the diabetic prediction probability as a response. For this, we will use the Flask web framework, a commonly used lightweight framework for developing web services in Python. Flask is a web framework that can be used for developing web applications relatively quickly. You can find a walk-through for quick development here. The code below in the app.py file essentially sets up the home page and serves the index.html to the user: #import relevant libraries for flask, html rendering and loading the #ML modelfrom flask import Flask,request, url_for, redirect, render_templateimport pickleimport pandas as pdapp = Flask(__name__)#loading the SVM model and the preprocessormodel = pickle.load(open(“svm_model.pkl”, “rb”))std = pickle.load(open(‘std.pkl’,’rb’))#Index.html will be returned for the input@app.route(‘/’)def hello_world(): return render_template(“index.html”)#predict function, POST method to take in inputs@app.route(‘/predict’,methods=[‘POST’,’GET’])def predict():#take inputs for all the attributes through the HTML form pregnancies = request.form[‘1’] glucose = request.form[‘2’] bloodpressure = request.form[‘3’] skinthickness = request.form[‘4’] insulin = request.form[‘5’] bmi = request.form[‘6’] diabetespedigreefunction = request.form[‘7’] age = request.form[‘8’]#form a dataframe with the inpus and run the preprocessor as used in the training row_df = pd.DataFrame([pd.Series([pregnancies, glucose, bloodpressure, skinthickness, insulin, bmi, diabetespedigreefunction, age])]) row_df = pd.DataFrame(std.transform(row_df)) print(row_df)#predict the probability and return the probability of being a diabetic prediction=model.predict_proba(row_df) output=’{0:.{1}f}’.format(prediction[0][1], 2) output_print = str(float(output)*100)+’%’ if float(output)>0.5: return render_template(‘result.html’,pred=f’You have a chance of having diabetes.\nProbability of you being a diabetic is {output_print}.\nEat clean and exercise regularly’) else: return render_template(‘result.html’,pred=f’Congratulations, you are safe.\n Probability of you being a diabetic is {output_print}’)if __name__ == ‘__main__’: app.run(debug=True) Detailed steps(app.py): Create a new file app.py. Import the flask module, and create a Flask app by instantiating the Flask class. #import relevant libraries for flask, html rendering and loading the ML modelfrom flask import Flask,request, url_for, redirect, render_templateimport pickleimport pandas as pdapp = Flask(__name__) Now, let's import the saved pre-processer element and the model. #loading the SVM model and the preprocessormodel = pickle.load(open(“svm_model.pkl”, “rb”))std = pickle.load(open(‘std.pkl’,’rb’)) Now, let us define the route that will render the index.html webpage (created using HTML). This file has CSS running and background for the look and feels and has relevant fields for the user to type in values for the attributes. #Index.html will be returned for the input@app.route(‘/’)def hello_world(): return render_template(“index.html”) Let’s also define the predict/ route and a function corresponding to it that will accept the different values for the inputs and return the predictions using the SVM model. First, we will capture the data from the user using the request method and store the values in their respective variables. Now, we will preprocess using the scalar pre-processor that we loaded above and use the model to predict the probability that a person is a diabetic Next, we will render the result.html page and display the relevant output based on the prediction #predict function, POST method to take in inputs@app.route(‘/predict’,methods=[‘POST’,’GET’])def predict():#take inputs for all the attributes through the HTML form pregnancies = request.form[‘1’] glucose = request.form[‘2’] bloodpressure = request.form[‘3’] skinthickness = request.form[‘4’] insulin = request.form[‘5’] bmi = request.form[‘6’] diabetespedigreefunction = request.form[‘7’] age = request.form[‘8’]#form a dataframe with the inpus and run the preprocessor as used in the training row_df = pd.DataFrame([pd.Series([pregnancies, glucose, bloodpressure, skinthickness, insulin, bmi, diabetespedigreefunction, age])]) row_df = pd.DataFrame(std.transform(row_df)) print(row_df)#predict the probability and return the probability of being a diabetic prediction=model.predict_proba(row_df) output=’{0:.{1}f}’.format(prediction[0][1], 2) output_print = str(float(output)*100)+’%’ if float(output)>0.5: return render_template(‘result.html’,pred=f’You have a chance of having diabetes.\nProbability of you being a diabetic is {output_print}.\nEat clean and exercise regularly’) else: return render_template(‘result.html’,pred=f’Congratulations, you are safe.\n Probability of you being a diabetic is {output_print}’) Now, let’s put the last piece of code before running the flask app. if __name__ == '__main__': app.run(debug=True) From the terminal, we can run the app using the python environment: Well, it's time to celebrate. Our app is running on the local if you are following the code as well. If not, don’t worry, we will deploy on Heroku for the public as well. http://127.0.0.1:5000/ Heroku is a Platform as a service tool that allows developers to host their serverless code. What this means is that one can develop scripts to serve one or the other for specific purposes. The Heroku platform is itself hosted on AWS (Amazon Web Services), which is an infrastructure as a service tool. We will use Heroku for hosting because they have a good free tier for non-commercial apps. There are various ways to deploy an app. One of the most common ways is building a docker and then deploying the docker into the Heroku platform. Here, since the data and the model are public, we will instead just use Github and then deploy the Github repository in Heroku. Let’s first create the required folder structure for the app. diabetes(root) |____templates |___index.html #main html page to enter the data |___result.html #Page returned after pressing submit |____static |____css #code for the look and feel of the web app |_____js |____app.py #main file with flask and prediction code |_____svm_model.pkl #model |_____std.pkl #preprocessor |_____requirements.txt #Library list with versions |_____Procfile templates: index.html contains the HTML code to bring in the web form where users can enter the values of different attributes. result.html contains the code for the prediction page.static: static contains the CSS that has the code for the look and feel of the HTML pagesapp.py is the main file as explained in the previous sectionsvm_model and std.pkl are the model and preprocessor respectively that will be used to make a prediction in the new datarequirements.txt contains the details of all the libraries and their versions that are used templates: index.html contains the HTML code to bring in the web form where users can enter the values of different attributes. result.html contains the code for the prediction page. static: static contains the CSS that has the code for the look and feel of the HTML pages app.py is the main file as explained in the previous section svm_model and std.pkl are the model and preprocessor respectively that will be used to make a prediction in the new data requirements.txt contains the details of all the libraries and their versions that are used Flask==1.1.1gunicorn==19.9.0itsdangerous==1.1.0Jinja2==2.10.1MarkupSafe==1.1.1Werkzeug==0.15.5numpy>=1.9.2scipy>=0.15.1scikit-learn>=0.18matplotlib>=1.4.3pandas>=0.19 6. Procfile: This contains the command to get the run the application on the server. web: gunicorn app:app The first app above is the name of the python file that contains our application (app.py) and code. The second is the name of the route as shown again below. #predict function, POST method to take in inputs@app.route(‘/predict’,methods=[‘POST’,’GET’])def predict():#take inputs for all the attributes through the HTML form pregnancies = request.form[‘1’] glucose = request.form[‘2’] bloodpressure = request.form[‘3’] skinthickness = request.form[‘4’] insulin = request.form[‘5’] bmi = request.form[‘6’] diabetespedigreefunction = request.form[‘7’] age = request.form[‘8’] Gunicorn: Web applications that process incoming HTTP requests concurrently make much more efficient use of dyno resources than web applications that only process one request at a time. Because of this, we recommend using web servers that support concurrent request processing whenever developing and running production services. Now that we have everything in place, our next step is to commit the project to a new Github repository. I just uploaded the diabetes root folder with all the files in the structure described above in a new Github repository. We just need to create a Heroku account, create a new app, connect to Github and deploy our newly created repository. Congratulations, we were able to deploy our machine learning app. Now, let’s visit the web app link and check the probability of being a diabetic using different attribute values. Feel free to play around with the web app. Here’s the link: To follow my code, here’s the link to my Github repository: https://github.com/garodisk/Diabetes-prediction-app-using-ML You can connect with me on Linkedin: https://www.linkedin.com/in/saket-garodia/ Here are some of my other blogs: Recommendation System (using Spark): https://towardsdatascience.com/building-a-recommendation-engine-to-recommend-books-in-spark-f09334d47d67 Simulation https://towardsdatascience.com/gambling-with-a-statisticians-brain-ae4e0b854ca2 Market Basket Analysis medium.com Recommendation Systems for movies medium.com Credit Default Analysis
[ { "code": null, "e": 1032, "s": 172, "text": "Business Problem: One of the fields where AI will play a huge role in the future is Medical Science. Doctors and researchers have been trying to use Machine Learning and Deep Learning to learn the occurrence of cancers and other chronic diseases by using millions of data points available through the protein combinations of our DNA and other lifestyle attributes. In the future, we might be able to know our chance of getting cancer a decade or two earlier that can help us avoid it. Fortunately, in my search of finding a good medical science dataset, I came across this Pima Indians Diabetes dataset on Kaggle. It is collected from the National Institute of Diabetes and Digestive and Kidney Disease. This dataset is small with 9 features and 768 observations which is enough to solve the problem of predicting the probability of a person to be a Diabetic." }, { "code": null, "e": 1155, "s": 1032, "text": "Here’s a brief description of all the features which I’m referring to from the data source itself for you to follow along." }, { "code": null, "e": 1236, "s": 1155, "text": "Link to the dataset: https://www.kaggle.com/uciml/pima-indians-diabetes-database" }, { "code": null, "e": 1294, "s": 1236, "text": "Feel free to get a feel of the app before reading ( :) ):" }, { "code": null, "e": 1334, "s": 1294, "text": "predict-diabetes-using-ml.herokuapp.com" }, { "code": null, "e": 1375, "s": 1334, "text": "1: Pregnancies: Number of times pregnant" }, { "code": null, "e": 1461, "s": 1375, "text": "2: Glucose: Plasma glucose concentration a 2 hours in an oral glucose tolerance test." }, { "code": null, "e": 1512, "s": 1461, "text": "3: BloodPressure: Diastolic blood pressure (mm Hg)" }, { "code": null, "e": 1562, "s": 1512, "text": "4: SkinThickness: Triceps skinfold thickness (mm)" }, { "code": null, "e": 1605, "s": 1562, "text": "5: Insulin: 2-Hour serum insulin (mu U/ml)" }, { "code": null, "e": 1659, "s": 1605, "text": "6: BMI: Body mass index (weight in kg/(height in m)2)" }, { "code": null, "e": 1715, "s": 1659, "text": "7: DiabetesPedigreeFunction: Diabetes pedigree function" }, { "code": null, "e": 1735, "s": 1715, "text": "8: Age: Age (years)" }, { "code": null, "e": 1806, "s": 1735, "text": "9: Outcome: Class variable (0 or 1) 268 of 768 are 1, the others are 0" }, { "code": null, "e": 1939, "s": 1806, "text": "All the variables are either self-known or available in a simple Blood Test and “Outcome” (Diabetic/Not) is what we need to predict." }, { "code": null, "e": 2390, "s": 1939, "text": "We will explore different features and perform various pre-processing techniques before trying out different machine learning algorithms like logistic Regression, Support Vector Machines, Decision Forest, Gradient Boosting and finally we will also explore neural networks. Once we have the best model, we will save our model using Pickle and use that to develop a diabetes prediction app using the Flask web framework and then deploy it using Heroku." }, { "code": null, "e": 2419, "s": 2390, "text": "Let’s begin. Grab a coffee!!" }, { "code": null, "e": 2562, "s": 2419, "text": "A brief overview of the structure: Feel free to jump over to step 2 if you don’t want to get an overview of the preparation and modeling part." }, { "code": null, "e": 2606, "s": 2562, "text": "Step 1: Data Preparation and model building" }, { "code": null, "e": 2837, "s": 2606, "text": "In this step, we will explore the data, do the required pre-processing and try various Machine Learning models like Logistic Regression, SVMs, Random Forest, Gradient Boosting, and the state of the art models like Neural Networks." }, { "code": null, "e": 2883, "s": 2837, "text": "Step 2: Building the app using Flask and HTML" }, { "code": null, "e": 2983, "s": 2883, "text": "Here, we will fetch the best-performing model from step 1 and build a web app using Flask and HTML." }, { "code": null, "e": 3022, "s": 2983, "text": "Step 3: Deploying the app using Heroku" }, { "code": null, "e": 3114, "s": 3022, "text": "In the end, we will deploy our working app through Heroku for the world to use our product." }, { "code": null, "e": 3316, "s": 3114, "text": "You can follow along through my Jupiter notebook that can be accessed at: https://github.com/garodisk/Diabetes-prediction-app-using-ML/blob/main/Diabetes%20prediction%20using%20Machine%20Learning.ipynb" }, { "code": null, "e": 3440, "s": 3316, "text": "#importing reqd librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdf.head()" }, { "code": null, "e": 3488, "s": 3440, "text": "For the feel of the data, let’s print the head:" }, { "code": null, "e": 3699, "s": 3488, "text": "Though a top-level overview of data shows that there are no null values, a deeper analysis shows that a lot of attributes have 0 values which don’t make any sense. How can someone’s BMI/Skin Thickness/Age be 0?" }, { "code": null, "e": 3873, "s": 3699, "text": "Let’s see how many zero values are there for each of the attributes and let’s convert them to null values. We will later handle those null values with imputation techniques." }, { "code": null, "e": 4122, "s": 3873, "text": "Now, that we have all the zero values converted into the null values, our next step is to impute these null values. At this point, many people just use a simple mean/median imputation that they calculate using the whole column which is not correct." }, { "code": null, "e": 4545, "s": 4122, "text": "For imputing each of the null values, we will look at the outcome whether it belongs to a diabetic person or not. We will impute using the median of that particular attribute based on what Outcome we will see. If a null value belongs to a diabetic person, we will find the median using only the diabetic records, and similarly if it belongs to a non-diabetic person, we will find the median using the non-diabetic records." }, { "code": null, "e": 4631, "s": 4545, "text": "Let’s analyze the correlation map and histogram plots for a further feel of the data." }, { "code": null, "e": 4979, "s": 4631, "text": "We can see that for most of the attributes, the distribution for the diabetic people (the red part) is shifted towards the right when compared with the distribution of the non-diabetic part (blue part). This basically tells us a story that a diabetic person is more likely to be a elder person with a higher BMI, SkinThickness, and glucose levels." }, { "code": null, "e": 5168, "s": 4979, "text": "Next, we will plot the boxplot for each of these attributes to clearly see the difference in the distribution of each of the attributes for both these outcomes (Diabetic and Non-diabetic)." }, { "code": null, "e": 5217, "s": 5168, "text": "Here’s the distribution of the outcome variable:" }, { "code": null, "e": 5284, "s": 5217, "text": "The data contains 500 non-diabetic people and 268 diabetic people." }, { "code": null, "e": 5382, "s": 5284, "text": "Now, let's use PCA and t-SNE to visualize the data on a 2-dimensional plane for better intuition." }, { "code": null, "e": 5692, "s": 5382, "text": "PCA does a decent job of 2-d visualization since the 2 principal components contain about 50% of the overall variance in data. Now, let’s try t-SNE which is even better for visualizing on 2-d since it uses probabilistic distribution and tries to keep similar data points closer to each other on the 2-d plane." }, { "code": null, "e": 5828, "s": 5692, "text": "It indeed did a great job. We can see that the diabetic people and non-diabetic people are mostly clustered together on the t-SNE plot." }, { "code": null, "e": 6076, "s": 5828, "text": "Now, before modeling, we must scale the data since all the attributes are on a different scale. Except for the tree algorithms, most of the machine learning algorithms especially those that use Gradient Descent or distance metrics require scaling." }, { "code": null, "e": 6340, "s": 6076, "text": "The two most discussed scaling methods are Normalization and Standardization. Normalization typically means rescales the values into a range of [0,1]. Standardization typically means rescales data to have a mean of 0 and a standard deviation of 1 (unit variance)." }, { "code": null, "e": 6431, "s": 6340, "text": "Normalization vs. standardization is an eternal question among machine learning newcomers." }, { "code": null, "e": 6677, "s": 6431, "text": "Normalization is good to use when you know that the distribution of your data does not follow a Gaussian distribution. This can be useful in algorithms that do not assume any distribution of the data like K-Nearest Neighbors and Neural Networks." }, { "code": null, "e": 7003, "s": 6677, "text": "Standardization, on the other hand, can be helpful in cases where the data follows a Gaussian distribution. However, this does not have to be necessarily true. Also, unlike normalization, standardization does not have a bounding range. So, even if you have outliers in your data, they will not be affected by standardization." }, { "code": null, "e": 7223, "s": 7003, "text": "There is no hard and fast rule to tell us when to normalize or standardize your data. We can always start by fitting your model to raw, normalized, and standardized data and compare the performance for the best results." }, { "code": null, "e": 7472, "s": 7223, "text": "Important: It is a good practice to fit the scaler on the training data and then use it to transform the testing data. This would avoid any data leakage during the model testing process. Also, the scaling of target values is generally not required." }, { "code": null, "e": 7591, "s": 7472, "text": "Now, let’s see the distribution of each of the attributes again to understand which ones follow Gaussian distribution." }, { "code": null, "e": 7787, "s": 7591, "text": "Only Glucose, BloodPressure and BMI follow a Gaussian distribution where normalization can make sense but since there is no hard and fast rule, we will try 3 things and compare their performance." }, { "code": null, "e": 8159, "s": 7787, "text": "Use Normalization on all the attributes and check the performance of a Logistic regression model on the test setUse Standardization on all the attributes and check the performance of a Logistic regression model on the test setUse standardization on the attributes that follow a Gaussian distribution and normalization on the rest of the attributes and see the performance" }, { "code": null, "e": 8272, "s": 8159, "text": "Use Normalization on all the attributes and check the performance of a Logistic regression model on the test set" }, { "code": null, "e": 8387, "s": 8272, "text": "Use Standardization on all the attributes and check the performance of a Logistic regression model on the test set" }, { "code": null, "e": 8533, "s": 8387, "text": "Use standardization on the attributes that follow a Gaussian distribution and normalization on the rest of the attributes and see the performance" }, { "code": null, "e": 8646, "s": 8533, "text": "Out of the above 3, normalization had the best accuracy of 0.83 on a test set using a Logistic Regression model." }, { "code": null, "e": 8898, "s": 8646, "text": "Repeat Note: One other important thing to keep in mind is to fit the StandardScalar only on the training set and then use this to scale the test set to avoid Data Leakage. We will also save the preprocessor for further use in our Machine Learning app." }, { "code": null, "e": 8936, "s": 8898, "text": "Logistic Regression (Accuracy - 83%):" }, { "code": null, "e": 8986, "s": 8936, "text": "Now, let’s try other Machine Learning algorithms:" }, { "code": null, "e": 9024, "s": 8986, "text": "K-Nearest Neighbors (Accuracy - 87%):" }, { "code": null, "e": 9070, "s": 9024, "text": "Support Vector Machines (Accuracy - 88%-89%):" }, { "code": null, "e": 9105, "s": 9070, "text": "Random Forest(Accuracy - 88%-89%):" }, { "code": null, "e": 9144, "s": 9105, "text": "Gradient Boosting(Accuracy - 87%-88%):" }, { "code": null, "e": 9471, "s": 9144, "text": "The best performing machine learning algorithm on the dataset are SVMs and Random Forest; both have an accuracy between 88% and 89% but SVMs are more simplistic for deployment and will take less time when further data comes in for training. Before moving with SVM, let’s try and see how Neural Network performs on the dataset." }, { "code": null, "e": 9775, "s": 9471, "text": "On the test set, the neural network just has an 85% accuracy. This can be very much possible because a neural network creates a more complex set of hidden layers but at the same time, it requires more and more examples for a better result. Out data only contains 768 observations for it to perform well." }, { "code": null, "e": 9807, "s": 9775, "text": "Neural Network (Accuracy - 85%)" }, { "code": null, "e": 9925, "s": 9807, "text": "Now, as a final step, we will save our SVM model for prediction into a .h5 or .bin file using a library like pickle ." }, { "code": null, "e": 10092, "s": 9925, "text": "The next step is to package this model into a web service that, when given the data through a POST request, returns the diabetic prediction probability as a response." }, { "code": null, "e": 10216, "s": 10092, "text": "For this, we will use the Flask web framework, a commonly used lightweight framework for developing web services in Python." }, { "code": null, "e": 10366, "s": 10216, "text": "Flask is a web framework that can be used for developing web applications relatively quickly. You can find a walk-through for quick development here." }, { "code": null, "e": 10473, "s": 10366, "text": "The code below in the app.py file essentially sets up the home page and serves the index.html to the user:" }, { "code": null, "e": 12183, "s": 10473, "text": "#import relevant libraries for flask, html rendering and loading the #ML modelfrom flask import Flask,request, url_for, redirect, render_templateimport pickleimport pandas as pdapp = Flask(__name__)#loading the SVM model and the preprocessormodel = pickle.load(open(“svm_model.pkl”, “rb”))std = pickle.load(open(‘std.pkl’,’rb’))#Index.html will be returned for the input@app.route(‘/’)def hello_world(): return render_template(“index.html”)#predict function, POST method to take in inputs@app.route(‘/predict’,methods=[‘POST’,’GET’])def predict():#take inputs for all the attributes through the HTML form pregnancies = request.form[‘1’] glucose = request.form[‘2’] bloodpressure = request.form[‘3’] skinthickness = request.form[‘4’] insulin = request.form[‘5’] bmi = request.form[‘6’] diabetespedigreefunction = request.form[‘7’] age = request.form[‘8’]#form a dataframe with the inpus and run the preprocessor as used in the training row_df = pd.DataFrame([pd.Series([pregnancies, glucose, bloodpressure, skinthickness, insulin, bmi, diabetespedigreefunction, age])]) row_df = pd.DataFrame(std.transform(row_df)) print(row_df)#predict the probability and return the probability of being a diabetic prediction=model.predict_proba(row_df) output=’{0:.{1}f}’.format(prediction[0][1], 2) output_print = str(float(output)*100)+’%’ if float(output)>0.5: return render_template(‘result.html’,pred=f’You have a chance of having diabetes.\\nProbability of you being a diabetic is {output_print}.\\nEat clean and exercise regularly’) else: return render_template(‘result.html’,pred=f’Congratulations, you are safe.\\n Probability of you being a diabetic is {output_print}’)if __name__ == ‘__main__’: app.run(debug=True)" }, { "code": null, "e": 12207, "s": 12183, "text": "Detailed steps(app.py):" }, { "code": null, "e": 12233, "s": 12207, "text": "Create a new file app.py." }, { "code": null, "e": 12315, "s": 12233, "text": "Import the flask module, and create a Flask app by instantiating the Flask class." }, { "code": null, "e": 12513, "s": 12315, "text": "#import relevant libraries for flask, html rendering and loading the ML modelfrom flask import Flask,request, url_for, redirect, render_templateimport pickleimport pandas as pdapp = Flask(__name__)" }, { "code": null, "e": 12578, "s": 12513, "text": "Now, let's import the saved pre-processer element and the model." }, { "code": null, "e": 12709, "s": 12578, "text": "#loading the SVM model and the preprocessormodel = pickle.load(open(“svm_model.pkl”, “rb”))std = pickle.load(open(‘std.pkl’,’rb’))" }, { "code": null, "e": 12939, "s": 12709, "text": "Now, let us define the route that will render the index.html webpage (created using HTML). This file has CSS running and background for the look and feels and has relevant fields for the user to type in values for the attributes." }, { "code": null, "e": 13052, "s": 12939, "text": "#Index.html will be returned for the input@app.route(‘/’)def hello_world(): return render_template(“index.html”)" }, { "code": null, "e": 13225, "s": 13052, "text": "Let’s also define the predict/ route and a function corresponding to it that will accept the different values for the inputs and return the predictions using the SVM model." }, { "code": null, "e": 13348, "s": 13225, "text": "First, we will capture the data from the user using the request method and store the values in their respective variables." }, { "code": null, "e": 13497, "s": 13348, "text": "Now, we will preprocess using the scalar pre-processor that we loaded above and use the model to predict the probability that a person is a diabetic" }, { "code": null, "e": 13595, "s": 13497, "text": "Next, we will render the result.html page and display the relevant output based on the prediction" }, { "code": null, "e": 14819, "s": 13595, "text": "#predict function, POST method to take in inputs@app.route(‘/predict’,methods=[‘POST’,’GET’])def predict():#take inputs for all the attributes through the HTML form pregnancies = request.form[‘1’] glucose = request.form[‘2’] bloodpressure = request.form[‘3’] skinthickness = request.form[‘4’] insulin = request.form[‘5’] bmi = request.form[‘6’] diabetespedigreefunction = request.form[‘7’] age = request.form[‘8’]#form a dataframe with the inpus and run the preprocessor as used in the training row_df = pd.DataFrame([pd.Series([pregnancies, glucose, bloodpressure, skinthickness, insulin, bmi, diabetespedigreefunction, age])]) row_df = pd.DataFrame(std.transform(row_df)) print(row_df)#predict the probability and return the probability of being a diabetic prediction=model.predict_proba(row_df) output=’{0:.{1}f}’.format(prediction[0][1], 2) output_print = str(float(output)*100)+’%’ if float(output)>0.5: return render_template(‘result.html’,pred=f’You have a chance of having diabetes.\\nProbability of you being a diabetic is {output_print}.\\nEat clean and exercise regularly’) else: return render_template(‘result.html’,pred=f’Congratulations, you are safe.\\n Probability of you being a diabetic is {output_print}’)" }, { "code": null, "e": 14887, "s": 14819, "text": "Now, let’s put the last piece of code before running the flask app." }, { "code": null, "e": 14937, "s": 14887, "text": "if __name__ == '__main__': app.run(debug=True)" }, { "code": null, "e": 15005, "s": 14937, "text": "From the terminal, we can run the app using the python environment:" }, { "code": null, "e": 15199, "s": 15005, "text": "Well, it's time to celebrate. Our app is running on the local if you are following the code as well. If not, don’t worry, we will deploy on Heroku for the public as well. http://127.0.0.1:5000/" }, { "code": null, "e": 15502, "s": 15199, "text": "Heroku is a Platform as a service tool that allows developers to host their serverless code. What this means is that one can develop scripts to serve one or the other for specific purposes. The Heroku platform is itself hosted on AWS (Amazon Web Services), which is an infrastructure as a service tool." }, { "code": null, "e": 15593, "s": 15502, "text": "We will use Heroku for hosting because they have a good free tier for non-commercial apps." }, { "code": null, "e": 15867, "s": 15593, "text": "There are various ways to deploy an app. One of the most common ways is building a docker and then deploying the docker into the Heroku platform. Here, since the data and the model are public, we will instead just use Github and then deploy the Github repository in Heroku." }, { "code": null, "e": 15929, "s": 15867, "text": "Let’s first create the required folder structure for the app." }, { "code": null, "e": 16342, "s": 15929, "text": "diabetes(root) |____templates |___index.html #main html page to enter the data |___result.html #Page returned after pressing submit |____static |____css #code for the look and feel of the web app |_____js |____app.py #main file with flask and prediction code |_____svm_model.pkl #model |_____std.pkl #preprocessor |_____requirements.txt #Library list with versions |_____Procfile" }, { "code": null, "e": 16885, "s": 16342, "text": "templates: index.html contains the HTML code to bring in the web form where users can enter the values of different attributes. result.html contains the code for the prediction page.static: static contains the CSS that has the code for the look and feel of the HTML pagesapp.py is the main file as explained in the previous sectionsvm_model and std.pkl are the model and preprocessor respectively that will be used to make a prediction in the new datarequirements.txt contains the details of all the libraries and their versions that are used" }, { "code": null, "e": 17068, "s": 16885, "text": "templates: index.html contains the HTML code to bring in the web form where users can enter the values of different attributes. result.html contains the code for the prediction page." }, { "code": null, "e": 17158, "s": 17068, "text": "static: static contains the CSS that has the code for the look and feel of the HTML pages" }, { "code": null, "e": 17219, "s": 17158, "text": "app.py is the main file as explained in the previous section" }, { "code": null, "e": 17340, "s": 17219, "text": "svm_model and std.pkl are the model and preprocessor respectively that will be used to make a prediction in the new data" }, { "code": null, "e": 17432, "s": 17340, "text": "requirements.txt contains the details of all the libraries and their versions that are used" }, { "code": null, "e": 17599, "s": 17432, "text": "Flask==1.1.1gunicorn==19.9.0itsdangerous==1.1.0Jinja2==2.10.1MarkupSafe==1.1.1Werkzeug==0.15.5numpy>=1.9.2scipy>=0.15.1scikit-learn>=0.18matplotlib>=1.4.3pandas>=0.19" }, { "code": null, "e": 17684, "s": 17599, "text": "6. Procfile: This contains the command to get the run the application on the server." }, { "code": null, "e": 17706, "s": 17684, "text": "web: gunicorn app:app" }, { "code": null, "e": 17864, "s": 17706, "text": "The first app above is the name of the python file that contains our application (app.py) and code. The second is the name of the route as shown again below." }, { "code": null, "e": 18278, "s": 17864, "text": "#predict function, POST method to take in inputs@app.route(‘/predict’,methods=[‘POST’,’GET’])def predict():#take inputs for all the attributes through the HTML form pregnancies = request.form[‘1’] glucose = request.form[‘2’] bloodpressure = request.form[‘3’] skinthickness = request.form[‘4’] insulin = request.form[‘5’] bmi = request.form[‘6’] diabetespedigreefunction = request.form[‘7’] age = request.form[‘8’]" }, { "code": null, "e": 18608, "s": 18278, "text": "Gunicorn: Web applications that process incoming HTTP requests concurrently make much more efficient use of dyno resources than web applications that only process one request at a time. Because of this, we recommend using web servers that support concurrent request processing whenever developing and running production services." }, { "code": null, "e": 18713, "s": 18608, "text": "Now that we have everything in place, our next step is to commit the project to a new Github repository." }, { "code": null, "e": 18834, "s": 18713, "text": "I just uploaded the diabetes root folder with all the files in the structure described above in a new Github repository." }, { "code": null, "e": 18952, "s": 18834, "text": "We just need to create a Heroku account, create a new app, connect to Github and deploy our newly created repository." }, { "code": null, "e": 19132, "s": 18952, "text": "Congratulations, we were able to deploy our machine learning app. Now, let’s visit the web app link and check the probability of being a diabetic using different attribute values." }, { "code": null, "e": 19192, "s": 19132, "text": "Feel free to play around with the web app. Here’s the link:" }, { "code": null, "e": 19313, "s": 19192, "text": "To follow my code, here’s the link to my Github repository: https://github.com/garodisk/Diabetes-prediction-app-using-ML" }, { "code": null, "e": 19393, "s": 19313, "text": "You can connect with me on Linkedin: https://www.linkedin.com/in/saket-garodia/" }, { "code": null, "e": 19426, "s": 19393, "text": "Here are some of my other blogs:" }, { "code": null, "e": 19568, "s": 19426, "text": "Recommendation System (using Spark): https://towardsdatascience.com/building-a-recommendation-engine-to-recommend-books-in-spark-f09334d47d67" }, { "code": null, "e": 19579, "s": 19568, "text": "Simulation" }, { "code": null, "e": 19659, "s": 19579, "text": "https://towardsdatascience.com/gambling-with-a-statisticians-brain-ae4e0b854ca2" }, { "code": null, "e": 19682, "s": 19659, "text": "Market Basket Analysis" }, { "code": null, "e": 19693, "s": 19682, "text": "medium.com" }, { "code": null, "e": 19727, "s": 19693, "text": "Recommendation Systems for movies" }, { "code": null, "e": 19738, "s": 19727, "text": "medium.com" } ]
What is Column Space? — Example, Intuition & Visualization | by Aerin Kim | Towards Data Science
You might already know this, but for some quick background — when we see mathematical expressions like X ∈ R2, X ∈ R5 or X ∈ R100, what do they mean? When you see these expressions, they are easy to understand if you visualize X as a column vector with n components. We use R because its components are the Real numbers. Then, R2 is represented by 2 numbers (coordinates), the good old x-y plane. In the same way, the three components of a vector in R3 is a point in 3-D space. One of the reasons why we’re fond of Linear Algebra is that the extension to n-dimensions is straightforward. For example, if we want to define a vector in R7, all you need are seven real numbers (i.e. [4, 1, 8, 5, 9, 5, 6]), even though it is hard to visualize 7-D space. Let’s say you wrote a vector with 100 random numbers. Then your vector belongs to R100. Space is short for subspace. A subspace is a subset that is “closed” under addition and scalar multiplication, which is basically closed under linear combinations. These two operations keep the output within the subspace always. Definition of Subspace:A subspace of a vector space is a subset that satisfies the requirements for a vector space -- Linear combinations stay in the subspace.(i) If any two vectors x and y are in the subspace, x + y is in the subspace as well.(ii) If we multiply any vector x in the subspace by any scalar c, cx is in the subspace as well. Understanding the concept by only reading the definition doesn’t really work for me. In order to solidify our understanding, let’s try to answer this question: The first quadrant of the x-y plane: Is it a subspace? Let’s check if the rule (i) holds. If we add any two vectors a (a1>0, a2>0) and b (b1>0, b2>0) in the first quadrant, a + b will be in the subspace. Ok, so far so good. How about the rule (ii)? Let’s pick any scalar c = -3 and the vector x = [2, 4] in the first quadrant. Now, cx = [-6, -12] is in the third quadrant, not the first. The first quadrant is not a subspace. If we include the third quadrant along with the first, scalar multiplication is all right. Every multiple cx will stay in this subset. However, now the rule (i) is violated, since adding [3, 5]+[-9, -1] will result in [-6, 4], which is not in either quadrant. Hence, the smallest subspace containing the first quadrant is the whole R2 space. A column space (or range) of matrix X is the space that is spanned by X’s columns. Likewise, a row space is spanned by X’s rows. In the above picture, [0,1] and [1,0] spans the whole plane (R2). However, vectors don’t need to be orthogonal to each other to span the plane. As long as they are two non-parallel vectors, their linear combinations will fill (“SPAN”) the whole plane. Column space of X = Span of the columns of X = Set of all possible linear combinations of the columns of X Multiplying the matrix X by any vector θ gives a combination of the columns. Hence, the vector Xθ is in the column space. In Eq.(a), there are 2 unknowns [θ1, θ2] but 3 equations. When we have more equations than unknowns, usually there is no solution. Notice that the number of equations determines the dimension of the column vectors. (If we have 10 equations, instead of 3, then we’ll be solving a 10-dimensional problem.) Eq.(a) can be written as eq.(b). The right-hand side y can be any combinations of the columns of X. [3,6,9] is just one example among many possible vectors.If you choose θ1 = 1, θ2 = 0, then y will be the X1 vector itself.Likewise, for θ1 = 0, θ2= 1, y will be the same as X2. However, notice, if y lies off the plane C(X), then it is not the combination of the two columns. In that case, Xθ = y has no solution. The spanned plane C(X) is not just a subset of R3. It is a subspace. It consists of every combination of the columns and satisfies the rule (i) and (ii). Xθ = y can be solved only when y lies in the plane that is spanned by the two column vectors, the combination of the columns of X. Then we say y is in the column space. Few things to note: 1. What is a good example for X, y and [θ1, θ2]? Linear regression. (Let’s predict the housing price.) X is a feature matrix or input variables (# of bedrooms, square feet, location, etc). The number of rows in X is the number of training examples. y is a target variable (the housing price). θ is the coefficient that we are trying to fit. Therefore, “y lies in the column space” means the error of the linear regression is zero, which is never the case in real life. 2. Why do [2,0,9] and [1,5,3] span the plane? They are 3-D vectors. Because they are 2 vectors 😜. Just because they are 3-D vectors, they don’t span the 3-D plane, you need 3 vectors to span 3-D space. Two 2-D vectors [1,0] and [4,1] will span the plane.Two 7-D vectors [2,0,9,0,1,4,2] and [7,7,0,1,8,4,8] will still span the plane. 3. Any n by n matrix that is non-singular will have R^n as its columns space. If we allow singular matrices, or rectangular matrices of any shape, then C(X) will be somewhere between the zero space and R^n. Finally, the “Machine Learning” part begins. Before continue reading, make sure you are familiar with the concept of “orthogonality”. medium.com When y lies off the plane (= when y is not in the column space of X), then Xθ = y has no solution. Because the system is inconsistent. However, in real life, we still need to find a solution — the best approximation of θ. So we use linear regression. 99.99999% of the time, there is no way the data points y will lie exactly on the spanned plane C(X). Therefore, we will be approximating the plane that is the closest to where y data points lie. 1 is solvable when y1, y2, y3 are in the ratio 1:5:3. When y1, y2, y3 are not in the ratio 1:5:3, we can still “solve” (it’s rather “fit”) Xθ = y by minimizing the least square error. When there is an exact solution, the minimum error will be absolute zero. However, most likely y won’t be exactly proportional to X, and the graph of (Error)2 will be a parabola. The minimum error will be at where the derivative of (Error)2 is zero. If you look at the derived θ in step 4, it matches with “the normal equation” that we derived in the previous post. Taking the derivative of (Error2) to find a minimum is a calculus technique. However, orthogonality of the dot product X and (y - Xθ) is a geometric interpretation. Geometry confirms Calculus! When we learn linear regression, we learn in an analytical way; however, there is a geometric interpretation as well. I think this is a beautiful connection between the two concepts, which solidifies understanding. Let’s project y onto a subspace (plane), instead of just onto a line. Going back to eq.(a), X is a 3 by 2 matrix and θ is 1 by 2 matrix (no longer a scalar). Think of X as a design matrix for which the number of samples is 3, the number of features is 2. The number of samples (3 in this example, or any m) usually will be much greater than the number of features (2, or any n). So we expect that there will be no exact solution. In other words, y won’t be a combination of columns of X. y will be outside of the column space C(X). Error = ‖ y - Xθ ‖This is the distance between y to the point Xθ which lies in the columns space of X. Searching for the least square solution (θ) that minimizes the error is the same as LOCATING the point Xθ as close as possible in the column space than any other point in the column space. All vectors perpendicular to the column space lie in the left null space. Thus the error vector y - Xθ is in the null space of Xθ. If you like my post, could you please clap? It gives me motivation to write more. :)
[ { "code": null, "e": 321, "s": 171, "text": "You might already know this, but for some quick background — when we see mathematical expressions like X ∈ R2, X ∈ R5 or X ∈ R100, what do they mean?" }, { "code": null, "e": 492, "s": 321, "text": "When you see these expressions, they are easy to understand if you visualize X as a column vector with n components. We use R because its components are the Real numbers." }, { "code": null, "e": 649, "s": 492, "text": "Then, R2 is represented by 2 numbers (coordinates), the good old x-y plane. In the same way, the three components of a vector in R3 is a point in 3-D space." }, { "code": null, "e": 922, "s": 649, "text": "One of the reasons why we’re fond of Linear Algebra is that the extension to n-dimensions is straightforward. For example, if we want to define a vector in R7, all you need are seven real numbers (i.e. [4, 1, 8, 5, 9, 5, 6]), even though it is hard to visualize 7-D space." }, { "code": null, "e": 1010, "s": 922, "text": "Let’s say you wrote a vector with 100 random numbers. Then your vector belongs to R100." }, { "code": null, "e": 1239, "s": 1010, "text": "Space is short for subspace. A subspace is a subset that is “closed” under addition and scalar multiplication, which is basically closed under linear combinations. These two operations keep the output within the subspace always." }, { "code": null, "e": 1580, "s": 1239, "text": "Definition of Subspace:A subspace of a vector space is a subset that satisfies the requirements for a vector space -- Linear combinations stay in the subspace.(i) If any two vectors x and y are in the subspace, x + y is in the subspace as well.(ii) If we multiply any vector x in the subspace by any scalar c, cx is in the subspace as well." }, { "code": null, "e": 1740, "s": 1580, "text": "Understanding the concept by only reading the definition doesn’t really work for me. In order to solidify our understanding, let’s try to answer this question:" }, { "code": null, "e": 1795, "s": 1740, "text": "The first quadrant of the x-y plane: Is it a subspace?" }, { "code": null, "e": 2166, "s": 1795, "text": "Let’s check if the rule (i) holds. If we add any two vectors a (a1>0, a2>0) and b (b1>0, b2>0) in the first quadrant, a + b will be in the subspace. Ok, so far so good. How about the rule (ii)? Let’s pick any scalar c = -3 and the vector x = [2, 4] in the first quadrant. Now, cx = [-6, -12] is in the third quadrant, not the first. The first quadrant is not a subspace." }, { "code": null, "e": 2508, "s": 2166, "text": "If we include the third quadrant along with the first, scalar multiplication is all right. Every multiple cx will stay in this subset. However, now the rule (i) is violated, since adding [3, 5]+[-9, -1] will result in [-6, 4], which is not in either quadrant. Hence, the smallest subspace containing the first quadrant is the whole R2 space." }, { "code": null, "e": 2637, "s": 2508, "text": "A column space (or range) of matrix X is the space that is spanned by X’s columns. Likewise, a row space is spanned by X’s rows." }, { "code": null, "e": 2889, "s": 2637, "text": "In the above picture, [0,1] and [1,0] spans the whole plane (R2). However, vectors don’t need to be orthogonal to each other to span the plane. As long as they are two non-parallel vectors, their linear combinations will fill (“SPAN”) the whole plane." }, { "code": null, "e": 2996, "s": 2889, "text": "Column space of X = Span of the columns of X = Set of all possible linear combinations of the columns of X" }, { "code": null, "e": 3118, "s": 2996, "text": "Multiplying the matrix X by any vector θ gives a combination of the columns. Hence, the vector Xθ is in the column space." }, { "code": null, "e": 3249, "s": 3118, "text": "In Eq.(a), there are 2 unknowns [θ1, θ2] but 3 equations. When we have more equations than unknowns, usually there is no solution." }, { "code": null, "e": 3422, "s": 3249, "text": "Notice that the number of equations determines the dimension of the column vectors. (If we have 10 equations, instead of 3, then we’ll be solving a 10-dimensional problem.)" }, { "code": null, "e": 3455, "s": 3422, "text": "Eq.(a) can be written as eq.(b)." }, { "code": null, "e": 3699, "s": 3455, "text": "The right-hand side y can be any combinations of the columns of X. [3,6,9] is just one example among many possible vectors.If you choose θ1 = 1, θ2 = 0, then y will be the X1 vector itself.Likewise, for θ1 = 0, θ2= 1, y will be the same as X2." }, { "code": null, "e": 3835, "s": 3699, "text": "However, notice, if y lies off the plane C(X), then it is not the combination of the two columns. In that case, Xθ = y has no solution." }, { "code": null, "e": 3989, "s": 3835, "text": "The spanned plane C(X) is not just a subset of R3. It is a subspace. It consists of every combination of the columns and satisfies the rule (i) and (ii)." }, { "code": null, "e": 4158, "s": 3989, "text": "Xθ = y can be solved only when y lies in the plane that is spanned by the two column vectors, the combination of the columns of X. Then we say y is in the column space." }, { "code": null, "e": 4178, "s": 4158, "text": "Few things to note:" }, { "code": null, "e": 4227, "s": 4178, "text": "1. What is a good example for X, y and [θ1, θ2]?" }, { "code": null, "e": 4281, "s": 4227, "text": "Linear regression. (Let’s predict the housing price.)" }, { "code": null, "e": 4519, "s": 4281, "text": "X is a feature matrix or input variables (# of bedrooms, square feet, location, etc). The number of rows in X is the number of training examples. y is a target variable (the housing price). θ is the coefficient that we are trying to fit." }, { "code": null, "e": 4647, "s": 4519, "text": "Therefore, “y lies in the column space” means the error of the linear regression is zero, which is never the case in real life." }, { "code": null, "e": 4715, "s": 4647, "text": "2. Why do [2,0,9] and [1,5,3] span the plane? They are 3-D vectors." }, { "code": null, "e": 4849, "s": 4715, "text": "Because they are 2 vectors 😜. Just because they are 3-D vectors, they don’t span the 3-D plane, you need 3 vectors to span 3-D space." }, { "code": null, "e": 4980, "s": 4849, "text": "Two 2-D vectors [1,0] and [4,1] will span the plane.Two 7-D vectors [2,0,9,0,1,4,2] and [7,7,0,1,8,4,8] will still span the plane." }, { "code": null, "e": 5187, "s": 4980, "text": "3. Any n by n matrix that is non-singular will have R^n as its columns space. If we allow singular matrices, or rectangular matrices of any shape, then C(X) will be somewhere between the zero space and R^n." }, { "code": null, "e": 5321, "s": 5187, "text": "Finally, the “Machine Learning” part begins. Before continue reading, make sure you are familiar with the concept of “orthogonality”." }, { "code": null, "e": 5332, "s": 5321, "text": "medium.com" }, { "code": null, "e": 5467, "s": 5332, "text": "When y lies off the plane (= when y is not in the column space of X), then Xθ = y has no solution. Because the system is inconsistent." }, { "code": null, "e": 5778, "s": 5467, "text": "However, in real life, we still need to find a solution — the best approximation of θ. So we use linear regression. 99.99999% of the time, there is no way the data points y will lie exactly on the spanned plane C(X). Therefore, we will be approximating the plane that is the closest to where y data points lie." }, { "code": null, "e": 5832, "s": 5778, "text": "1 is solvable when y1, y2, y3 are in the ratio 1:5:3." }, { "code": null, "e": 5962, "s": 5832, "text": "When y1, y2, y3 are not in the ratio 1:5:3, we can still “solve” (it’s rather “fit”) Xθ = y by minimizing the least square error." }, { "code": null, "e": 6141, "s": 5962, "text": "When there is an exact solution, the minimum error will be absolute zero. However, most likely y won’t be exactly proportional to X, and the graph of (Error)2 will be a parabola." }, { "code": null, "e": 6212, "s": 6141, "text": "The minimum error will be at where the derivative of (Error)2 is zero." }, { "code": null, "e": 6328, "s": 6212, "text": "If you look at the derived θ in step 4, it matches with “the normal equation” that we derived in the previous post." }, { "code": null, "e": 6493, "s": 6328, "text": "Taking the derivative of (Error2) to find a minimum is a calculus technique. However, orthogonality of the dot product X and (y - Xθ) is a geometric interpretation." }, { "code": null, "e": 6521, "s": 6493, "text": "Geometry confirms Calculus!" }, { "code": null, "e": 6736, "s": 6521, "text": "When we learn linear regression, we learn in an analytical way; however, there is a geometric interpretation as well. I think this is a beautiful connection between the two concepts, which solidifies understanding." }, { "code": null, "e": 6806, "s": 6736, "text": "Let’s project y onto a subspace (plane), instead of just onto a line." }, { "code": null, "e": 6991, "s": 6806, "text": "Going back to eq.(a), X is a 3 by 2 matrix and θ is 1 by 2 matrix (no longer a scalar). Think of X as a design matrix for which the number of samples is 3, the number of features is 2." }, { "code": null, "e": 7268, "s": 6991, "text": "The number of samples (3 in this example, or any m) usually will be much greater than the number of features (2, or any n). So we expect that there will be no exact solution. In other words, y won’t be a combination of columns of X. y will be outside of the column space C(X)." }, { "code": null, "e": 7371, "s": 7268, "text": "Error = ‖ y - Xθ ‖This is the distance between y to the point Xθ which lies in the columns space of X." }, { "code": null, "e": 7560, "s": 7371, "text": "Searching for the least square solution (θ) that minimizes the error is the same as LOCATING the point Xθ as close as possible in the column space than any other point in the column space." }, { "code": null, "e": 7691, "s": 7560, "text": "All vectors perpendicular to the column space lie in the left null space. Thus the error vector y - Xθ is in the null space of Xθ." } ]
RxJava - Environment Setup
RxJava is a library for Java, so the very first requirement is to have JDK installed in your machine. First of all, open the console and execute a java command based on the operating system you are working on. Let's verify the output for all the operating systems − java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link https://www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example. Append Java compiler location to the System Path. Verify Java installation using the command java -version as explained above. Download the latest version of RxJava jar file from RxJava @ MVNRepository and its dependency Reactive Streams @ MVNRepository . At the time of writing this tutorial, we have downloaded rxjava-2.2.4.jar, reactive-streams-1.0.2.jar and copied it into C:\>RxJava folder. Set the RX_JAVA environment variable to point to the base directory location where RxJava jar is stored on your machine. Let’s assuming we've stored rxjava-2.2.4.jar and reactive-streams-1.0.2.jar in the RxJava folder. Windows Set the environment variable RX_JAVA to C:\RxJava Linux export RX_JAVA = /usr/local/RxJava Mac export RX_JAVA = /Library/RxJava Set the CLASSPATH environment variable to point to the RxJava jar location. Windows Set the environment variable CLASSPATH to %CLASSPATH%;%RX_JAVA%\rxjava-2.2.4.jar;%RX_JAVA%\reactive-streams-1.0.2.jar;.; Linux export CLASSPATH = $CLASSPATH:$RX_JAVA/rxjava-2.2.4.jar:reactive-streams-1.0.2.jar:. Mac export CLASSPATH = $CLASSPATH:$RX_JAVA/rxjava-2.2.4.jar:reactive-streams-1.0.2.jar:. Create a class TestRx.java as shown below − import io.reactivex.Flowable; public class TestRx { public static void main(String[] args) { Flowable.just("Hello World!").subscribe(System.out::println); } } Compile the classes using javac compiler as follows − C:\RxJava>javac Tester.java Verify the output. Hello World! Print Add Notes Bookmark this page
[ { "code": null, "e": 2503, "s": 2401, "text": "RxJava is a library for Java, so the very first requirement is to have JDK installed in your machine." }, { "code": null, "e": 2611, "s": 2503, "text": "First of all, open the console and execute a java command based on the operating system you are working on." }, { "code": null, "e": 2667, "s": 2611, "text": "Let's verify the output for all the operating systems −" }, { "code": null, "e": 2692, "s": 2667, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 2742, "s": 2692, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 2767, "s": 2742, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 2817, "s": 2767, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 2842, "s": 2817, "text": "java version \"1.8.0_101\"" }, { "code": null, "e": 2892, "s": 2842, "text": "Java(TM) SE Runtime Environment (build 1.8.0_101)" }, { "code": null, "e": 3119, "s": 2892, "text": "If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link https://www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial." }, { "code": null, "e": 3252, "s": 3119, "text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example." }, { "code": null, "e": 3302, "s": 3252, "text": "Append Java compiler location to the System Path." }, { "code": null, "e": 3379, "s": 3302, "text": "Verify Java installation using the command java -version as explained above." }, { "code": null, "e": 3648, "s": 3379, "text": "Download the latest version of RxJava jar file from RxJava @ MVNRepository\nand its dependency Reactive Streams @ MVNRepository\n. At the time of writing this tutorial, we have downloaded rxjava-2.2.4.jar, reactive-streams-1.0.2.jar and copied it into C:\\>RxJava folder." }, { "code": null, "e": 3867, "s": 3648, "text": "Set the RX_JAVA environment variable to point to the base directory location where RxJava jar is stored on your machine. Let’s assuming we've stored rxjava-2.2.4.jar and reactive-streams-1.0.2.jar in the RxJava folder." }, { "code": null, "e": 3875, "s": 3867, "text": "Windows" }, { "code": null, "e": 3925, "s": 3875, "text": "Set the environment variable RX_JAVA to C:\\RxJava" }, { "code": null, "e": 3931, "s": 3925, "text": "Linux" }, { "code": null, "e": 3966, "s": 3931, "text": "export RX_JAVA = /usr/local/RxJava" }, { "code": null, "e": 3970, "s": 3966, "text": "Mac" }, { "code": null, "e": 4003, "s": 3970, "text": "export RX_JAVA = /Library/RxJava" }, { "code": null, "e": 4079, "s": 4003, "text": "Set the CLASSPATH environment variable to point to the RxJava jar location." }, { "code": null, "e": 4087, "s": 4079, "text": "Windows" }, { "code": null, "e": 4208, "s": 4087, "text": "Set the environment variable CLASSPATH to %CLASSPATH%;%RX_JAVA%\\rxjava-2.2.4.jar;%RX_JAVA%\\reactive-streams-1.0.2.jar;.;" }, { "code": null, "e": 4214, "s": 4208, "text": "Linux" }, { "code": null, "e": 4299, "s": 4214, "text": "export CLASSPATH = $CLASSPATH:$RX_JAVA/rxjava-2.2.4.jar:reactive-streams-1.0.2.jar:." }, { "code": null, "e": 4303, "s": 4299, "text": "Mac" }, { "code": null, "e": 4388, "s": 4303, "text": "export CLASSPATH = $CLASSPATH:$RX_JAVA/rxjava-2.2.4.jar:reactive-streams-1.0.2.jar:." }, { "code": null, "e": 4432, "s": 4388, "text": "Create a class TestRx.java as shown below −" }, { "code": null, "e": 4603, "s": 4432, "text": "import io.reactivex.Flowable;\npublic class TestRx {\n public static void main(String[] args) {\n Flowable.just(\"Hello World!\").subscribe(System.out::println);\n }\n}" }, { "code": null, "e": 4657, "s": 4603, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 4686, "s": 4657, "text": "C:\\RxJava>javac Tester.java\n" }, { "code": null, "e": 4705, "s": 4686, "text": "Verify the output." }, { "code": null, "e": 4719, "s": 4705, "text": "Hello World!\n" }, { "code": null, "e": 4726, "s": 4719, "text": " Print" }, { "code": null, "e": 4737, "s": 4726, "text": " Add Notes" } ]
Return Statement vs Exit() in Main() using C++
If you are a programmer, you write the code; If you write the code, you use the function; if you use the function, you use return and exit statements in every function. So In this article, we will discuss what a return statement and exit statement are and their differences. In C++, return is a statement that returns the control of the flow of execution to the function which is calling. Exit statement terminates the program at the point it is used. int main() This is where the execution of the program begins. The program is executed from the main() function, and since we have int in place of the return type, it has to return some integer value. We can say this integer represents the program's status, where 0 means the program executes successfully. A non-zero value means there is an execution error in the code. A return statement always returns the control of flow to the function which is calling. Return uses exit code which is int value, to return to the calling function. Using the return statement in the main function means exiting the program with a status code; for example, return 0 means returning status code 0 to the operating system. Let us look at a C++ program using the return statement. #include <iostream> using namespace std; class Test { public: //To activate Constructor Test() { cout<<"Hey this is Return Constructor \n"; } //To activate Destructor ~Test() { cout<<"Hey this is return Destructor"; } }; int main() { //Creating object of Test class Test object; //Using return in main return 0; } Hey this is Return Constructor Hey this is return Destructor Looking at the above program, we can say that return calls the constructor and destructor of a class object. Calling the destructor is essential to release the allocated memory. Exit () statement terminates the program at the point it is used. When the exit keyword is used in the main function, it will exit the program without calling the destructor for locally scoped objects. Any created object will not be destroyed and will not release memory; it will just terminate the program. #include <iostream> using namespace std; class Test { public: //To activate Constructor Test() { cout<<"Hey this is exit Constructor \n"; } //To activate Destructor ~Test() { cout<<"Hey this is exit Destructor"; } }; int main() { //Creating object of Test class Test object; //Using exit() in main exit(0); } Hey this is exit Constructor Looking at the program's output, we can conclude that using the exit keyword in our program means it will not call a destructor to destroy allocated memory and the locally scoped objects. In this article, we understand the differences between return statements and exit statements. We can conclude from the differences that using them makes a lot of difference in our program. Using exit over return requires precautions. However, they don't impact much on one page of code and impact a lot when developing software. We hope you find this article helpful.
[ { "code": null, "e": 1337, "s": 1062, "text": "If you are a programmer, you write the code; If you write the code, you use the function; if you use the function, you use return and exit statements in every function. So In this article, we will discuss what a return statement and exit statement are and their differences." }, { "code": null, "e": 1345, "s": 1337, "text": "In C++," }, { "code": null, "e": 1451, "s": 1345, "text": "return is a statement that returns the control of the flow of execution to the function which is calling." }, { "code": null, "e": 1514, "s": 1451, "text": "Exit statement terminates the program at the point it is used." }, { "code": null, "e": 1525, "s": 1514, "text": "int main()" }, { "code": null, "e": 1884, "s": 1525, "text": "This is where the execution of the program begins. The program is executed from the main() function, and since we have int in place of the return type, it has to return some integer value. We can say this integer represents the program's status, where 0 means the program executes successfully. A non-zero value means there is an execution error in the code." }, { "code": null, "e": 2277, "s": 1884, "text": "A return statement always returns the control of flow to the function which is calling. Return uses exit code which is int value, to return to the calling function. Using the return statement in the main function means exiting the program with a status code; for example, return 0 means returning status code 0 to the operating system. Let us look at a C++ program using the return statement." }, { "code": null, "e": 2638, "s": 2277, "text": "#include <iostream>\nusing namespace std;\nclass Test {\n public:\n //To activate Constructor\n Test() {\n cout<<\"Hey this is Return Constructor \\n\";\n }\n\n //To activate Destructor\n ~Test() {\n cout<<\"Hey this is return Destructor\";\n }\n};\nint main() {\n //Creating object of Test class\n Test object;\n\n //Using return in main\n return 0;\n}" }, { "code": null, "e": 2699, "s": 2638, "text": "Hey this is Return Constructor\nHey this is return Destructor" }, { "code": null, "e": 2877, "s": 2699, "text": "Looking at the above program, we can say that return calls the constructor and destructor of a class object. Calling the destructor is essential to release the allocated memory." }, { "code": null, "e": 3185, "s": 2877, "text": "Exit () statement terminates the program at the point it is used. When the exit keyword is used in the main function, it will exit the program without calling the destructor for locally scoped objects. Any created object will not be destroyed and will not release memory; it will just terminate the program." }, { "code": null, "e": 3541, "s": 3185, "text": "#include <iostream>\nusing namespace std;\nclass Test {\n public:\n //To activate Constructor\n Test() {\n cout<<\"Hey this is exit Constructor \\n\";\n }\n\n //To activate Destructor\n ~Test() {\n cout<<\"Hey this is exit Destructor\";\n }\n};\nint main() {\n //Creating object of Test class\n Test object;\n\n //Using exit() in main\n exit(0);\n}" }, { "code": null, "e": 3570, "s": 3541, "text": "Hey this is exit Constructor" }, { "code": null, "e": 3758, "s": 3570, "text": "Looking at the program's output, we can conclude that using the exit keyword in our program means it will not call a destructor to destroy allocated memory and the locally scoped objects." }, { "code": null, "e": 4126, "s": 3758, "text": "In this article, we understand the differences between return statements and exit statements. We can conclude from the differences that using them makes a lot of difference in our program. Using exit over return requires precautions. However, they don't impact much on one page of code and impact a lot when developing software. We hope you find this article helpful." } ]
ASP.NET Core - Identity Migrations
In this chapter, we will discuss the Identity migration. In ASP.NET Core MVC, authentication and identity features are configured in the Startup.cs file. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<FirstAppDemoDbContext>option. UseSqlServer(Configuration["database:connection"])); services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>(); } Anytime you make a change to one of your entity classes or you make a change to your DBContext derived class, chances are you will have to create a new migration script to apply to the database and bring the schema in sync with what is in your code. This is the case in our application because we now derive our FirstAppDemoDbContext class from the IdentityDbContext class, and it contains its own DbSets, and it will also create a schema to store all the information about the entities that it manages. using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; namespace FirstAppDemo.Models { public class FirstAppDemoDbContext : IdentityDbContext<User> { public DbSet<Employee> Employees { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source = (localdb)\\MSSQLLocalDB; Initial Catalog = FirstAppDemo;Integrated Security = True; Connect Timeout = 30;Encrypt = False; TrustServerCertificate = True;ApplicationIntent = ReadWrite; MultiSubnetFailover = False"); } } } Let us now open the command prompt and make sure we are in the location where the project.json file exists for our project. We can also get the Entity Framework commands by typing dnx ef. Our project.json file has a section that maps this “ef” keyword with the EntityFramework.Commands. "commands": { "web": "Microsoft.AspNet.Server.Kestrel", "ef": "EntityFramework.Commands" } We can add a migration from here. We also need to provide a name to the migration. Let us use v2 for version 2 and press enter. When the migration is complete, you will have a v2 file in your migrations folder. We now want to apply that migration to our database by running the “dnx ef database update” command. The Entity Framework will see there is a migration that needs to be applied and it will execute that migration. If you come into the SQL Server Object Explorer, you will see the Employee table that we created earlier. You will also see some additional tables that have to store users, claims, roles, and some mapping tables that map users to specific roles. All these tables are related to the entities that the Identity framework provides. Let us take a quick look at the users table. You can now see that the columns in the AspNetUsers table include columns to store all those properties that we saw on the Identity User which we inherited from, and its fields like UserName and PasswordHash. So, you have been using some of the built-in Identity services because they also contain an ability to create a user and validate a user's password. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2615, "s": 2461, "text": "In this chapter, we will discuss the Identity migration. In ASP.NET Core MVC, authentication and identity features are configured in the Startup.cs file." }, { "code": null, "e": 2983, "s": 2615, "text": "public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext<FirstAppDemoDbContext>option.\n UseSqlServer(Configuration[\"database:connection\"])); \n \n services.AddIdentity<User, IdentityRole>() \n .AddEntityFrameworkStores<FirstAppDemoDbContext>(); \n}" }, { "code": null, "e": 3233, "s": 2983, "text": "Anytime you make a change to one of your entity classes or you make a change to your DBContext derived class, chances are you will have to create a new migration script to apply to the database and bring the schema in sync with what is in your code." }, { "code": null, "e": 3487, "s": 3233, "text": "This is the case in our application because we now derive our FirstAppDemoDbContext class from the IdentityDbContext class, and it contains its own DbSets, and it will also create a schema to store all the information about the entities that it manages." }, { "code": null, "e": 4150, "s": 3487, "text": "using Microsoft.AspNet.Identity.EntityFramework; \nusing Microsoft.Data.Entity; \n\nnamespace FirstAppDemo.Models { \n public class FirstAppDemoDbContext : IdentityDbContext<User> { \n public DbSet<Employee> Employees { get; set; } \n \n protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { \n optionsBuilder.UseSqlServer(\"Data Source = (localdb)\\\\MSSQLLocalDB;\n Initial Catalog = FirstAppDemo;Integrated Security = True;\n Connect Timeout = 30;Encrypt = False;\n TrustServerCertificate = True;ApplicationIntent = ReadWrite;\n MultiSubnetFailover = False\"); \n }\n } \n} " }, { "code": null, "e": 4274, "s": 4150, "text": "Let us now open the command prompt and make sure we are in the location where the project.json file exists for our project." }, { "code": null, "e": 4338, "s": 4274, "text": "We can also get the Entity Framework commands by typing dnx ef." }, { "code": null, "e": 4437, "s": 4338, "text": "Our project.json file has a section that maps this “ef” keyword with the EntityFramework.Commands." }, { "code": null, "e": 4538, "s": 4437, "text": "\"commands\": { \n \"web\": \"Microsoft.AspNet.Server.Kestrel\", \n \"ef\": \"EntityFramework.Commands\" \n} " }, { "code": null, "e": 4666, "s": 4538, "text": "We can add a migration from here. We also need to provide a name to the migration. Let us use v2 for version 2 and press enter." }, { "code": null, "e": 4749, "s": 4666, "text": "When the migration is complete, you will have a v2 file in your migrations folder." }, { "code": null, "e": 4850, "s": 4749, "text": "We now want to apply that migration to our database by running the “dnx ef database update” command." }, { "code": null, "e": 4962, "s": 4850, "text": "The Entity Framework will see there is a migration that needs to be applied and it will execute that migration." }, { "code": null, "e": 5208, "s": 4962, "text": "If you come into the SQL Server Object Explorer, you will see the Employee table that we created earlier. You will also see some additional tables that have to store users, claims, roles, and some mapping tables that map users to specific roles." }, { "code": null, "e": 5291, "s": 5208, "text": "All these tables are related to the entities that the Identity framework provides." }, { "code": null, "e": 5336, "s": 5291, "text": "Let us take a quick look at the users table." }, { "code": null, "e": 5694, "s": 5336, "text": "You can now see that the columns in the AspNetUsers table include columns to store all those properties that we saw on the Identity User which we inherited from, and its fields like UserName and PasswordHash. So, you have been using some of the built-in Identity services because they also contain an ability to create a user and validate a user's password." }, { "code": null, "e": 5729, "s": 5694, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5743, "s": 5729, "text": " Anadi Sharma" }, { "code": null, "e": 5778, "s": 5743, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5801, "s": 5778, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5835, "s": 5801, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 5855, "s": 5835, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5890, "s": 5855, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5907, "s": 5890, "text": " University Code" }, { "code": null, "e": 5942, "s": 5907, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5959, "s": 5942, "text": " University Code" }, { "code": null, "e": 5993, "s": 5959, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 6008, "s": 5993, "text": " Bhrugen Patel" }, { "code": null, "e": 6015, "s": 6008, "text": " Print" }, { "code": null, "e": 6026, "s": 6015, "text": " Add Notes" } ]
Parallax scrolling effect using CSS. - GeeksforGeeks
16 Mar, 2021 ParallaxParallax is a 3d effect used in various websites to make webpages attractive. In this effect, as we scroll, the background of the webpages moves at a different speed than the foreground making it look brilliant to the eyes. Examples:These websites show the parallax effect brilliantly- Firewatchgame Gardenstudio alquimiawrg This effect is a great visual but an easy method to implement with the help of CSS.First, let us understand what is happening in the given examples.The effect is created because the image in the background is kept fixed with no movement but other images are moving. This simple technique makes this effect look brilliant.Now let us see the implementation of this effect using CSS-Explanation1. background-attachmentThis property is used to determine whether a background image is fixed or scroll with the page. Syntax : background-attachment: scroll/fixed/local; 2. background-positionThis property determines the starting position of the background image. Syntax : background-position: value; 3. background-repeatThis property determines whether a background image will repeat or not and if repeated , how will it be repeated. Syntax : background-repeat: repeat/repeat-x/repeat-y/no-repeat; repeat – The background image will be repeated both vertically and horizontally.repeat-x – The background image will be repeated only horizontally.repeat-y – The background image will be repeated only vertically.no-repeat – The background-image will not be repeated.4. background-sizeThis property determines the size of the background image. Syntax : background-size: auto/length/cover/contain/; auto – Default value.length – Sets the width and height of the background image.percentage – Sets the width and height of the background image in percent of the container element.cover – Scale the background image to be as large as possible so that the background area is completely covered by the background image.contain – Scale the image to the largest size such that both its width and its height can fit inside the content area. <html><head><style>.parallax { background-image: url("http://s1.picswalls.com/wallpapers/2015/09/20/2015-wallpaper_111525594_269.jpg"); min-height: 500px; background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover;}</style></head><body><p>This is a Parallax</p><div class="parallax"></div><div style="height:1000px;font-size:60px;"><center>Hi</center></div></body></html> Output: Note that This parallax effect does not always work with mobiles and tablets, so you need to turn off the effect using media queries. This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ? Node.js fs.readFileSync() Method File uploading in React.js How to Open URL in New Tab using JavaScript ?
[ { "code": null, "e": 24553, "s": 24525, "text": "\n16 Mar, 2021" }, { "code": null, "e": 24785, "s": 24553, "text": "ParallaxParallax is a 3d effect used in various websites to make webpages attractive. In this effect, as we scroll, the background of the webpages moves at a different speed than the foreground making it look brilliant to the eyes." }, { "code": null, "e": 24847, "s": 24785, "text": "Examples:These websites show the parallax effect brilliantly-" }, { "code": null, "e": 24861, "s": 24847, "text": "Firewatchgame" }, { "code": null, "e": 24874, "s": 24861, "text": "Gardenstudio" }, { "code": null, "e": 24886, "s": 24874, "text": "alquimiawrg" }, { "code": null, "e": 25397, "s": 24886, "text": "This effect is a great visual but an easy method to implement with the help of CSS.First, let us understand what is happening in the given examples.The effect is created because the image in the background is kept fixed with no movement but other images are moving. This simple technique makes this effect look brilliant.Now let us see the implementation of this effect using CSS-Explanation1. background-attachmentThis property is used to determine whether a background image is fixed or scroll with the page." }, { "code": null, "e": 25449, "s": 25397, "text": "Syntax : background-attachment: scroll/fixed/local;" }, { "code": null, "e": 25543, "s": 25449, "text": "2. background-positionThis property determines the starting position of the background image." }, { "code": null, "e": 25580, "s": 25543, "text": "Syntax : background-position: value;" }, { "code": null, "e": 25714, "s": 25580, "text": "3. background-repeatThis property determines whether a background image will repeat or not and if repeated , how will it be repeated." }, { "code": null, "e": 25778, "s": 25714, "text": "Syntax : background-repeat: repeat/repeat-x/repeat-y/no-repeat;" }, { "code": null, "e": 26121, "s": 25778, "text": "repeat – The background image will be repeated both vertically and horizontally.repeat-x – The background image will be repeated only horizontally.repeat-y – The background image will be repeated only vertically.no-repeat – The background-image will not be repeated.4. background-sizeThis property determines the size of the background image." }, { "code": null, "e": 26175, "s": 26121, "text": "Syntax : background-size: auto/length/cover/contain/;" }, { "code": null, "e": 26609, "s": 26175, "text": "auto – Default value.length – Sets the width and height of the background image.percentage – Sets the width and height of the background image in percent of the container element.cover – Scale the background image to be as large as possible so that the background area is completely covered by the background image.contain – Scale the image to the largest size such that both its width and its height can fit inside the content area." }, { "code": "<html><head><style>.parallax { background-image: url(\"http://s1.picswalls.com/wallpapers/2015/09/20/2015-wallpaper_111525594_269.jpg\"); min-height: 500px; background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover;}</style></head><body><p>This is a Parallax</p><div class=\"parallax\"></div><div style=\"height:1000px;font-size:60px;\"><center>Hi</center></div></body></html>", "e": 27053, "s": 26609, "text": null }, { "code": null, "e": 27061, "s": 27053, "text": "Output:" }, { "code": null, "e": 27195, "s": 27061, "text": "Note that This parallax effect does not always work with mobiles and tablets, so you need to turn off the effect using media queries." }, { "code": null, "e": 27495, "s": 27195, "text": "This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27620, "s": 27495, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27637, "s": 27620, "text": "Web Technologies" }, { "code": null, "e": 27735, "s": 27637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27744, "s": 27735, "text": "Comments" }, { "code": null, "e": 27757, "s": 27744, "text": "Old Comments" }, { "code": null, "e": 27813, "s": 27757, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27856, "s": 27813, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27917, "s": 27856, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27962, "s": 27917, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28034, "s": 27962, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28092, "s": 28034, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28152, "s": 28092, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28185, "s": 28152, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 28212, "s": 28185, "text": "File uploading in React.js" } ]
How to draw a circle in JavaScript?
Following is the code to draw a circle in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .circleCanvas { border: 3px solid #110101; } </style> </head> <body> <h1>Draw a circle in JavaScript</h1> <canvas class="circleCanvas" width="400" height="200"></canvas><br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to create a circle in the above canvas element</h3> <script> let canvasEle = document.querySelector(".circleCanvas"); let BtnEle = document.querySelector(".Btn"); BtnEle.addEventListener("click", () => { var circle = canvasEle.getContext("2d"); circle.beginPath(); circle.arc(180, 100, 90, 0, 2 * Math.PI); circle.stroke(); }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1117, "s": 1062, "text": "Following is the code to draw a circle in JavaScript −" }, { "code": null, "e": 1128, "s": 1117, "text": " Live Demo" }, { "code": null, "e": 2029, "s": 1128, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .circleCanvas {\n border: 3px solid #110101;\n }\n</style>\n</head>\n<body>\n<h1>Draw a circle in JavaScript</h1>\n<canvas class=\"circleCanvas\" width=\"400\" height=\"200\"></canvas><br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to create a circle in the above canvas element</h3>\n<script>\n let canvasEle = document.querySelector(\".circleCanvas\");\n let BtnEle = document.querySelector(\".Btn\");\n BtnEle.addEventListener(\"click\", () => {\n var circle = canvasEle.getContext(\"2d\");\n circle.beginPath();\n circle.arc(180, 100, 90, 0, 2 * Math.PI);\n circle.stroke();\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2080, "s": 2029, "text": "The above code will produce the following output −" }, { "code": null, "e": 2118, "s": 2080, "text": "On clicking the ‘CLICK HERE’ button −" } ]
All the Pandas merge() you should know for combining datasets | by B. Chen | Towards Data Science
Pandas provides various built-in functions for easily combining datasets. Among them, merge() is a high-performance in-memory operation very similar to relational databases like SQL. You can use merge() any time when you want to do database-like join operations. In this article, we’ll be going through some examples of combining datasets using Pandas merge() function. We will cover the following common usages and should help you get started with data combinations. The simplest call without any key columnSpecifying key columns using onMerging using left_on and right_onVarious forms of joins: inner, left, right and outerUsing validate to avoid invalid records The simplest call without any key column Specifying key columns using on Merging using left_on and right_on Various forms of joins: inner, left, right and outer Using validate to avoid invalid records Please check out Notebook for the source code. When you use merge(), the simplest call must have two arguments: the left DataFrame and the right DataFrame. For example, to combine df_customer and df_info: df_customer = pd.DataFrame({ 'id': [1, 2, 3, 4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_info = pd.DataFrame({ 'id': [2, 3, 4, 5], 'age': [31, 20, 40, 70], 'sex': ['F', 'M', 'M', 'F']})pd.merge(df_customer, df_info) By default, the function will combine data on common columns (It is the column id in our example) and produces only the result that matches in both left and right DataFrames. The following is an equivalent statement if you prefer to call merge from the left DataFrame. df_customer.merge(df_info) You can specify the common columns for merging. To do so, pass an additional argument on as the name of the common column, here 'id' in our example, to merge() function: pd.merge(df_customer, df_info, on='id') If you use on , you have to make sure the column you specify must be present in both left and right DataFrames. To combine data on multiple common columns, you can pass a list toon: pd.merge(df_customer, df_order, on=['id', 'name']) It might happen that the column on which you want to merge the DataFrames have different names. For such merges, you will have to specify the left_on as the left DataFrame name and right_on as the right DataFrame name, for example: pd.merge( df_customer, df_info_2, left_on='id', right_on='customer_id') The result will contain both id and customer_id columns. They are 4 types of joins available to Pandas merge() function. The logic behind these joins is very much the same that you have in SQL when you join tables. You can perform a type of join by specifying the how argument with the following values: inner: the default join type in Pandas merge() function and it produces records that have matching values in both DataFrames left: produces all records from the left DataFrame and the matched records from the right DataFrame right: produces all records from the right DataFrame and the matched records from the left DataFrame outer: produces all records when there is a match in either left or right DataFrame And below is how the Venn Diagram looks like for our test dataset df_customer = pd.DataFrame({ 'id': [1,2,3,4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_info = pd.DataFrame({ 'id': [2,3,4,5], 'age': [31,20,40,70], 'sex': ['F', 'M', 'M', 'F']})pd.merge(df_customer, df_info, on='id', how=?) By default, Pandas merge() is performing the inner join and it produces only the set of records that match in both DataFrame. pd.merge(df_customer, df_info, on='id') And below is the equivalent SQL query: SELECT * from customerINNER JOIN infoON customer.id = info.id To explicitly specify the inner join, you can set the argument how='inner' pd.merge(df_customer, df_info, how='inner', on='id') The left join produces all records from the left DataFrame, and the matched records from the right DataFrame. If there is no match, the left side will contain NaN. You can set the argument how='left' to do left join: pd.merge(df_customer, df_info, how='left', on='id') And below is the equivalent SQL query: SELECT * from customerLEFT OUTER JOIN infoON customer.id = info.id The right join produces all records from the right DataFrame, and the matched records from the left DataFrame. If there is no match, the right side will contain NaN. You can set the argument how='right' to do right join: pd.merge(df_customer, df_info, how='right', on='id') And below is the equivalent SQL query: SELECT * from customerRIGHT OUTER JOIN infoON customer.id = info.id The outer join produces all records when there is a match in either left or right DataFrame. NaN will be filled for no match on either sides. You can set the argument how='outer' to do outer join: pd.merge(df_customer, df_info, how='outer', on='id') And below is the equivalent SQL query: SELECT * from customerFULL OUTER JOIN infoON customer.id = info.id The result of merge() might have an increased number of rows if the merge keys are not unique. For example df_customer = pd.DataFrame({ 'id': [1,2,3,4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_order_2 = pd.DataFrame({ 'id': [2, 2, 4, 4], 'product': ['A', 'B' ,'A', 'C'], 'quantity': [31, 21, 20,40], 'date': pd.date_range('2019-02-24', periods=4, freq='D')}) Both df_customer and df_order_2 have 4 records. But, you will get a result with 6 records when running the following merge statement: pd.merge(df_customer, df_order_2, how='left', on='id') Here are the reasons: the how='left' will produce all records from df_customer, and the matched records from df_order_2. In addition, the id in df_order_2 is not unique and all the matching records will be combined and returned. This is an example of one-to-many merge. It is a valid scenario in our example, in which a customer can have multiple orders. However, one-to-many might be invalid in some other cases, for example, there are two records with the id value 2 in df_info df_customer = pd.DataFrame({ 'id': [1, 2, 3, 4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_info = pd.DataFrame({ 'id': [2, 2, 3, 4, 5], 'age': [31, 21, 20, 40, 70], 'sex': ['F', 'F', 'M', 'M', 'F']}) And the merge result will be ended up with 2 different records for the same customer Jenny: pd.merge(df_customer, df_info, how='left', on='id') This is certainly wrong because the same customer cannot have different information. To avoid this problem, we can set the argument validate to '1:1' , so it checks if merges keys are unique in both left and right DataFrames. It will raise a MergeError if the validation fails, for example: pd.merge(df_customer, df_info, how='left', on='id', validate='1:1') The argument validate takes one of the following values, so you can use it to validate different merge outputs. one_to_one or 1:1 : check if merge keys are unique in both left and right datasets. one_to_many or 1:m: check if merge keys are unique in left dataset. many_to_one or m:1: check if merge keys are unique in right dataset. many_to_many or m:m: allowed, but does not result in checks. Pandas merge() function is a simple, powerful, and high-performance in-memory operation very similar to relational databases like SQL. I hope this article will help you to save time in combining datasets. I recommend you to check out the documentation for the merge() API and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. Pandas resample() tricks you should know for manipulating time-series data How to do a Custom Sort on Pandas DataFrame When to use Pandas transform() function Pandas concat() tricks you should know Difference between apply() and transform() in Pandas Using Pandas method chaining to improve code readability Working with datetime in Pandas DataFrame Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More tutorials can be found on my Github
[ { "code": null, "e": 435, "s": 172, "text": "Pandas provides various built-in functions for easily combining datasets. Among them, merge() is a high-performance in-memory operation very similar to relational databases like SQL. You can use merge() any time when you want to do database-like join operations." }, { "code": null, "e": 640, "s": 435, "text": "In this article, we’ll be going through some examples of combining datasets using Pandas merge() function. We will cover the following common usages and should help you get started with data combinations." }, { "code": null, "e": 837, "s": 640, "text": "The simplest call without any key columnSpecifying key columns using onMerging using left_on and right_onVarious forms of joins: inner, left, right and outerUsing validate to avoid invalid records" }, { "code": null, "e": 878, "s": 837, "text": "The simplest call without any key column" }, { "code": null, "e": 910, "s": 878, "text": "Specifying key columns using on" }, { "code": null, "e": 945, "s": 910, "text": "Merging using left_on and right_on" }, { "code": null, "e": 998, "s": 945, "text": "Various forms of joins: inner, left, right and outer" }, { "code": null, "e": 1038, "s": 998, "text": "Using validate to avoid invalid records" }, { "code": null, "e": 1085, "s": 1038, "text": "Please check out Notebook for the source code." }, { "code": null, "e": 1243, "s": 1085, "text": "When you use merge(), the simplest call must have two arguments: the left DataFrame and the right DataFrame. For example, to combine df_customer and df_info:" }, { "code": null, "e": 1480, "s": 1243, "text": "df_customer = pd.DataFrame({ 'id': [1, 2, 3, 4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_info = pd.DataFrame({ 'id': [2, 3, 4, 5], 'age': [31, 20, 40, 70], 'sex': ['F', 'M', 'M', 'F']})pd.merge(df_customer, df_info)" }, { "code": null, "e": 1655, "s": 1480, "text": "By default, the function will combine data on common columns (It is the column id in our example) and produces only the result that matches in both left and right DataFrames." }, { "code": null, "e": 1749, "s": 1655, "text": "The following is an equivalent statement if you prefer to call merge from the left DataFrame." }, { "code": null, "e": 1777, "s": 1749, "text": "df_customer.merge(df_info) " }, { "code": null, "e": 1947, "s": 1777, "text": "You can specify the common columns for merging. To do so, pass an additional argument on as the name of the common column, here 'id' in our example, to merge() function:" }, { "code": null, "e": 1987, "s": 1947, "text": "pd.merge(df_customer, df_info, on='id')" }, { "code": null, "e": 2099, "s": 1987, "text": "If you use on , you have to make sure the column you specify must be present in both left and right DataFrames." }, { "code": null, "e": 2169, "s": 2099, "text": "To combine data on multiple common columns, you can pass a list toon:" }, { "code": null, "e": 2220, "s": 2169, "text": "pd.merge(df_customer, df_order, on=['id', 'name'])" }, { "code": null, "e": 2452, "s": 2220, "text": "It might happen that the column on which you want to merge the DataFrames have different names. For such merges, you will have to specify the left_on as the left DataFrame name and right_on as the right DataFrame name, for example:" }, { "code": null, "e": 2531, "s": 2452, "text": "pd.merge( df_customer, df_info_2, left_on='id', right_on='customer_id')" }, { "code": null, "e": 2588, "s": 2531, "text": "The result will contain both id and customer_id columns." }, { "code": null, "e": 2835, "s": 2588, "text": "They are 4 types of joins available to Pandas merge() function. The logic behind these joins is very much the same that you have in SQL when you join tables. You can perform a type of join by specifying the how argument with the following values:" }, { "code": null, "e": 2960, "s": 2835, "text": "inner: the default join type in Pandas merge() function and it produces records that have matching values in both DataFrames" }, { "code": null, "e": 3060, "s": 2960, "text": "left: produces all records from the left DataFrame and the matched records from the right DataFrame" }, { "code": null, "e": 3161, "s": 3060, "text": "right: produces all records from the right DataFrame and the matched records from the left DataFrame" }, { "code": null, "e": 3245, "s": 3161, "text": "outer: produces all records when there is a match in either left or right DataFrame" }, { "code": null, "e": 3311, "s": 3245, "text": "And below is how the Venn Diagram looks like for our test dataset" }, { "code": null, "e": 3555, "s": 3311, "text": "df_customer = pd.DataFrame({ 'id': [1,2,3,4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_info = pd.DataFrame({ 'id': [2,3,4,5], 'age': [31,20,40,70], 'sex': ['F', 'M', 'M', 'F']})pd.merge(df_customer, df_info, on='id', how=?)" }, { "code": null, "e": 3681, "s": 3555, "text": "By default, Pandas merge() is performing the inner join and it produces only the set of records that match in both DataFrame." }, { "code": null, "e": 3721, "s": 3681, "text": "pd.merge(df_customer, df_info, on='id')" }, { "code": null, "e": 3760, "s": 3721, "text": "And below is the equivalent SQL query:" }, { "code": null, "e": 3822, "s": 3760, "text": "SELECT * from customerINNER JOIN infoON customer.id = info.id" }, { "code": null, "e": 3897, "s": 3822, "text": "To explicitly specify the inner join, you can set the argument how='inner'" }, { "code": null, "e": 3950, "s": 3897, "text": "pd.merge(df_customer, df_info, how='inner', on='id')" }, { "code": null, "e": 4167, "s": 3950, "text": "The left join produces all records from the left DataFrame, and the matched records from the right DataFrame. If there is no match, the left side will contain NaN. You can set the argument how='left' to do left join:" }, { "code": null, "e": 4219, "s": 4167, "text": "pd.merge(df_customer, df_info, how='left', on='id')" }, { "code": null, "e": 4258, "s": 4219, "text": "And below is the equivalent SQL query:" }, { "code": null, "e": 4325, "s": 4258, "text": "SELECT * from customerLEFT OUTER JOIN infoON customer.id = info.id" }, { "code": null, "e": 4546, "s": 4325, "text": "The right join produces all records from the right DataFrame, and the matched records from the left DataFrame. If there is no match, the right side will contain NaN. You can set the argument how='right' to do right join:" }, { "code": null, "e": 4599, "s": 4546, "text": "pd.merge(df_customer, df_info, how='right', on='id')" }, { "code": null, "e": 4638, "s": 4599, "text": "And below is the equivalent SQL query:" }, { "code": null, "e": 4706, "s": 4638, "text": "SELECT * from customerRIGHT OUTER JOIN infoON customer.id = info.id" }, { "code": null, "e": 4903, "s": 4706, "text": "The outer join produces all records when there is a match in either left or right DataFrame. NaN will be filled for no match on either sides. You can set the argument how='outer' to do outer join:" }, { "code": null, "e": 4956, "s": 4903, "text": "pd.merge(df_customer, df_info, how='outer', on='id')" }, { "code": null, "e": 4995, "s": 4956, "text": "And below is the equivalent SQL query:" }, { "code": null, "e": 5062, "s": 4995, "text": "SELECT * from customerFULL OUTER JOIN infoON customer.id = info.id" }, { "code": null, "e": 5169, "s": 5062, "text": "The result of merge() might have an increased number of rows if the merge keys are not unique. For example" }, { "code": null, "e": 5445, "s": 5169, "text": "df_customer = pd.DataFrame({ 'id': [1,2,3,4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_order_2 = pd.DataFrame({ 'id': [2, 2, 4, 4], 'product': ['A', 'B' ,'A', 'C'], 'quantity': [31, 21, 20,40], 'date': pd.date_range('2019-02-24', periods=4, freq='D')})" }, { "code": null, "e": 5579, "s": 5445, "text": "Both df_customer and df_order_2 have 4 records. But, you will get a result with 6 records when running the following merge statement:" }, { "code": null, "e": 5634, "s": 5579, "text": "pd.merge(df_customer, df_order_2, how='left', on='id')" }, { "code": null, "e": 5656, "s": 5634, "text": "Here are the reasons:" }, { "code": null, "e": 5755, "s": 5656, "text": "the how='left' will produce all records from df_customer, and the matched records from df_order_2." }, { "code": null, "e": 5863, "s": 5755, "text": "In addition, the id in df_order_2 is not unique and all the matching records will be combined and returned." }, { "code": null, "e": 6114, "s": 5863, "text": "This is an example of one-to-many merge. It is a valid scenario in our example, in which a customer can have multiple orders. However, one-to-many might be invalid in some other cases, for example, there are two records with the id value 2 in df_info" }, { "code": null, "e": 6333, "s": 6114, "text": "df_customer = pd.DataFrame({ 'id': [1, 2, 3, 4], 'name': ['Tom', 'Jenny', 'James', 'Dan'],})df_info = pd.DataFrame({ 'id': [2, 2, 3, 4, 5], 'age': [31, 21, 20, 40, 70], 'sex': ['F', 'F', 'M', 'M', 'F']})" }, { "code": null, "e": 6425, "s": 6333, "text": "And the merge result will be ended up with 2 different records for the same customer Jenny:" }, { "code": null, "e": 6477, "s": 6425, "text": "pd.merge(df_customer, df_info, how='left', on='id')" }, { "code": null, "e": 6768, "s": 6477, "text": "This is certainly wrong because the same customer cannot have different information. To avoid this problem, we can set the argument validate to '1:1' , so it checks if merges keys are unique in both left and right DataFrames. It will raise a MergeError if the validation fails, for example:" }, { "code": null, "e": 6836, "s": 6768, "text": "pd.merge(df_customer, df_info, how='left', on='id', validate='1:1')" }, { "code": null, "e": 6948, "s": 6836, "text": "The argument validate takes one of the following values, so you can use it to validate different merge outputs." }, { "code": null, "e": 7032, "s": 6948, "text": "one_to_one or 1:1 : check if merge keys are unique in both left and right datasets." }, { "code": null, "e": 7100, "s": 7032, "text": "one_to_many or 1:m: check if merge keys are unique in left dataset." }, { "code": null, "e": 7169, "s": 7100, "text": "many_to_one or m:1: check if merge keys are unique in right dataset." }, { "code": null, "e": 7230, "s": 7169, "text": "many_to_many or m:m: allowed, but does not result in checks." }, { "code": null, "e": 7365, "s": 7230, "text": "Pandas merge() function is a simple, powerful, and high-performance in-memory operation very similar to relational databases like SQL." }, { "code": null, "e": 7545, "s": 7365, "text": "I hope this article will help you to save time in combining datasets. I recommend you to check out the documentation for the merge() API and to know about other things you can do." }, { "code": null, "e": 7697, "s": 7545, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 7772, "s": 7697, "text": "Pandas resample() tricks you should know for manipulating time-series data" }, { "code": null, "e": 7816, "s": 7772, "text": "How to do a Custom Sort on Pandas DataFrame" }, { "code": null, "e": 7856, "s": 7816, "text": "When to use Pandas transform() function" }, { "code": null, "e": 7895, "s": 7856, "text": "Pandas concat() tricks you should know" }, { "code": null, "e": 7948, "s": 7895, "text": "Difference between apply() and transform() in Pandas" }, { "code": null, "e": 8005, "s": 7948, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 8047, "s": 8005, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 8088, "s": 8047, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 8158, "s": 8088, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" } ]
MariaDB - Like Clause
The WHERE clause provides a way to retrieve data when an operation uses an exact match. In situations requiring multiple results with shared characteristics, the LIKE clause accommodates broad pattern matching. A LIKE clause tests for a pattern match, returning a true or false. The patterns used for comparison accept the following wildcard characters: “%”, which matches numbers of characters (0 or more); and “_”, which matches a single character. The “_” wildcard character only matches characters within its set, meaning it will ignore latin characters when using another set. The matches are case-insensitive by default requiring additional settings for case sensitivity. A NOT LIKE clause allows for testing the opposite condition, much like the not operator. If the statement expression or pattern evaluate to NULL, the result is NULL. Review the general LIKE clause syntax given below − SELECT field, field2,... FROM table_name, table_name2,... WHERE field LIKE condition Employ a LIKE clause either at the command prompt or within a PHP script. At the command prompt, simply use a standard command − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from products_tbl WHERE product_manufacturer LIKE 'XYZ%'; +-------------+----------------+----------------------+ | ID_number | Nomenclature | product_manufacturer | +-------------+----------------+----------------------+ | 12345 | Orbitron 4000 | XYZ Corp | +-------------+----------------+----------------------+ | 12346 | Orbitron 3000 | XYZ Corp | +-------------+----------------+----------------------+ | 12347 | Orbitron 1000 | XYZ Corp | +-------------+----------------+----------------------+ Use the mysql_query() function in statements employing the LIKE clause <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'SELECT product_id, product_name, product_manufacturer, ship_date FROM products_tbl WHERE product_manufacturer LIKE "xyz%"'; mysql_select_db('PRODUCTS'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Product ID:{$row['product_id']} <br> ". "Name: {$row['product_name']} <br> ". "Manufacturer: {$row['product_manufacturer']} <br> ". "Ship Date: {$row['ship_date']} <br> ". "--------------------------------<br>"; } echo "Fetched data successfully\n"; mysql_close($conn); ?> On successful data retrieval, you will see the following output − Product ID: 12345 Nomenclature: Orbitron 4000 Manufacturer: XYZ Corp Ship Date: 01/01/17 ---------------------------------------------- Product ID: 12346 Nomenclature: Orbitron 3000 Manufacturer: XYZ Corp Ship Date: 01/02/17 ---------------------------------------------- Product ID: 12347 Nomenclature: Orbitron 1000 Manufacturer: XYZ Corp Ship Date: 01/02/17 ---------------------------------------------- mysql> Fetched data successfully Print Add Notes Bookmark this page
[ { "code": null, "e": 2573, "s": 2362, "text": "The WHERE clause provides a way to retrieve data when an operation uses an exact match. In situations requiring multiple results with shared characteristics, the LIKE clause accommodates broad pattern matching." }, { "code": null, "e": 3040, "s": 2573, "text": "A LIKE clause tests for a pattern match, returning a true or false. The patterns used for comparison accept the following wildcard characters: “%”, which matches numbers of characters (0 or more); and “_”, which matches a single character. The “_” wildcard character only matches characters within its set, meaning it will ignore latin characters when using another set. The matches are case-insensitive by default requiring additional settings for case sensitivity." }, { "code": null, "e": 3129, "s": 3040, "text": "A NOT LIKE clause allows for testing the opposite condition, much like the not operator." }, { "code": null, "e": 3206, "s": 3129, "text": "If the statement expression or pattern evaluate to NULL, the result is NULL." }, { "code": null, "e": 3258, "s": 3206, "text": "Review the general LIKE clause syntax given below −" }, { "code": null, "e": 3344, "s": 3258, "text": "SELECT field, field2,... FROM table_name, table_name2,...\nWHERE field LIKE condition\n" }, { "code": null, "e": 3418, "s": 3344, "text": "Employ a LIKE clause either at the command prompt or within a PHP script." }, { "code": null, "e": 3473, "s": 3418, "text": "At the command prompt, simply use a standard command −" }, { "code": null, "e": 4155, "s": 3473, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from products_tbl\n WHERE product_manufacturer LIKE 'XYZ%';\n+-------------+----------------+----------------------+\n| ID_number | Nomenclature | product_manufacturer |\n+-------------+----------------+----------------------+\n| 12345 | Orbitron 4000 | XYZ Corp |\n+-------------+----------------+----------------------+\n| 12346 | Orbitron 3000 | XYZ Corp |\n+-------------+----------------+----------------------+\n| 12347 | Orbitron 1000 | XYZ Corp |\n+-------------+----------------+----------------------+\n" }, { "code": null, "e": 4226, "s": 4155, "text": "Use the mysql_query() function in statements employing the LIKE clause" }, { "code": null, "e": 5136, "s": 4226, "text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n\n $sql = 'SELECT product_id, product_name, product_manufacturer, ship_date\n FROM products_tbl WHERE product_manufacturer LIKE \"xyz%\"';\n \n mysql_select_db('PRODUCTS');\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not get data: ' . mysql_error());\n }\n\n while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {\n echo \"Product ID:{$row['product_id']} <br> \".\n \"Name: {$row['product_name']} <br> \".\n \"Manufacturer: {$row['product_manufacturer']} <br> \".\n \"Ship Date: {$row['ship_date']} <br> \".\n \"--------------------------------<br>\";\n }\n \n echo \"Fetched data successfully\\n\";\n mysql_close($conn);\n?>" }, { "code": null, "e": 5202, "s": 5136, "text": "On successful data retrieval, you will see the following output −" }, { "code": null, "e": 5644, "s": 5202, "text": "Product ID: 12345\nNomenclature: Orbitron 4000\nManufacturer: XYZ Corp\nShip Date: 01/01/17\n----------------------------------------------\nProduct ID: 12346\nNomenclature: Orbitron 3000\nManufacturer: XYZ Corp\nShip Date: 01/02/17\n----------------------------------------------\nProduct ID: 12347\nNomenclature: Orbitron 1000\nManufacturer: XYZ Corp\nShip Date: 01/02/17\n----------------------------------------------\nmysql> Fetched data successfully\n" }, { "code": null, "e": 5651, "s": 5644, "text": " Print" }, { "code": null, "e": 5662, "s": 5651, "text": " Add Notes" } ]
Apache Pig - MIN()
The MIN() function of Pig Latin is used to get the minimum (lowest) value (numeric or chararray) for a certain column in a single-column bag. While calculating the minimum value, the MIN() function ignores the NULL values. Note − To get the global minimum value, we need to perform a Group All operation, and calculate the minimum value using the MIN() function. To get the global minimum value, we need to perform a Group All operation, and calculate the minimum value using the MIN() function. To get the minimum value of a group, we need to group it using the Group By operator and proceed with the minimum function. To get the minimum value of a group, we need to group it using the Group By operator and proceed with the minimum function. Given below is the syntax of the MIN() function. grunt> MIN(expression) Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below. student_details.txt 001,Rajiv,Reddy,21,9848022337,Hyderabad,89 002,siddarth,Battacharya,22,9848022338,Kolkata,78 003,Rajesh,Khanna,22,9848022339,Delhi,90 004,Preethi,Agarwal,21,9848022330,Pune,93 005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 006,Archana,Mishra,23,9848022335,Chennai,87 007,Komal,Nayak,24,9848022334,trivendram,83 008,Bharathi,Nambiayar,24,9848022333,Chennai,72 And we have loaded this file into Pig with the relation named student_details as shown below. grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',') as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int); We can use the built-in function MIN() (case sensitive) to calculate the minimum value from a set of given numerical values. Let us group the relation student_details using the Group All operator, and store the result in the relation named student_group_all as shown below grunt> student_group_all = Group student_details All; It will produce a relation as shown below. grunt> Dump student_group_all; (all,{(8,Bharathi,Nambiayar,24,9848022333,Chennai,72), (7,Komal,Nayak,24,9848022 334,trivendram,83), (6,Archana,Mishra,23,9848022335,Chennai,87), (5,Trupthi,Mohan thy,23,9848022336,Bhuwaneshwar,75), (4,Preethi,Agarwal,21,9848022330,Pune,93), (3 ,Rajesh,Khanna,22,9848022339,Delhi,90), (2,siddarth,Battacharya,22,9848022338,Ko lkata,78), (1,Rajiv,Reddy,21,9848022337,Hyderabad,89)}) Let us now calculate the global minimum of GPA, i.e., minimum among the GPA values of all the students using the MIN() function as shown below. grunt> student_gpa_min = foreach student_group_all Generate (student_details.firstname, student_details.gpa), MIN(student_details.gpa); Verify the relation student_gpa_min using the DUMP operator as shown below. grunt> Dump student_gpa_min; It will produce the following output, displaying the contents of the relation student_gpa_min. (({(Bharathi),(Komal),(Archana),(Trupthi),(Preethi),(Rajesh),(siddarth),(Rajiv) } , { (72) , (83) , (87) , (75) , (93) , (90) , (78) , (89) }) ,72) 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2907, "s": 2684, "text": "The MIN() function of Pig Latin is used to get the minimum (lowest) value (numeric or chararray) for a certain column in a single-column bag. While calculating the minimum value, the MIN() function ignores the NULL values." }, { "code": null, "e": 2914, "s": 2907, "text": "Note −" }, { "code": null, "e": 3047, "s": 2914, "text": "To get the global minimum value, we need to perform a Group All operation, and calculate the minimum value using the MIN() function." }, { "code": null, "e": 3180, "s": 3047, "text": "To get the global minimum value, we need to perform a Group All operation, and calculate the minimum value using the MIN() function." }, { "code": null, "e": 3304, "s": 3180, "text": "To get the minimum value of a group, we need to group it using the Group By operator and proceed with the minimum function." }, { "code": null, "e": 3428, "s": 3304, "text": "To get the minimum value of a group, we need to group it using the Group By operator and proceed with the minimum function." }, { "code": null, "e": 3477, "s": 3428, "text": "Given below is the syntax of the MIN() function." }, { "code": null, "e": 3501, "s": 3477, "text": "grunt> MIN(expression)\n" }, { "code": null, "e": 3603, "s": 3501, "text": "Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below." }, { "code": null, "e": 3623, "s": 3603, "text": "student_details.txt" }, { "code": null, "e": 3994, "s": 3623, "text": "001,Rajiv,Reddy,21,9848022337,Hyderabad,89 \n002,siddarth,Battacharya,22,9848022338,Kolkata,78 \n003,Rajesh,Khanna,22,9848022339,Delhi,90 \n004,Preethi,Agarwal,21,9848022330,Pune,93 \n005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 \n006,Archana,Mishra,23,9848022335,Chennai,87 \n007,Komal,Nayak,24,9848022334,trivendram,83 \n008,Bharathi,Nambiayar,24,9848022333,Chennai,72\n" }, { "code": null, "e": 4088, "s": 3994, "text": "And we have loaded this file into Pig with the relation named student_details as shown below." }, { "code": null, "e": 4301, "s": 4088, "text": "grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')\n as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int);" }, { "code": null, "e": 4574, "s": 4301, "text": "We can use the built-in function MIN() (case sensitive) to calculate the minimum value from a set of given numerical values. Let us group the relation student_details using the Group All operator, and store the result in the relation named student_group_all as shown below" }, { "code": null, "e": 4628, "s": 4574, "text": "grunt> student_group_all = Group student_details All;" }, { "code": null, "e": 4671, "s": 4628, "text": "It will produce a relation as shown below." }, { "code": null, "e": 5088, "s": 4671, "text": "grunt> Dump student_group_all;\n \n(all,{(8,Bharathi,Nambiayar,24,9848022333,Chennai,72),\n(7,Komal,Nayak,24,9848022 334,trivendram,83),\n(6,Archana,Mishra,23,9848022335,Chennai,87),\n(5,Trupthi,Mohan thy,23,9848022336,Bhuwaneshwar,75),\n(4,Preethi,Agarwal,21,9848022330,Pune,93),\n(3 ,Rajesh,Khanna,22,9848022339,Delhi,90),\n(2,siddarth,Battacharya,22,9848022338,Ko lkata,78),\n(1,Rajiv,Reddy,21,9848022337,Hyderabad,89)})\n" }, { "code": null, "e": 5232, "s": 5088, "text": "Let us now calculate the global minimum of GPA, i.e., minimum among the GPA values of all the students using the MIN() function as shown below." }, { "code": null, "e": 5372, "s": 5232, "text": "grunt> student_gpa_min = foreach student_group_all Generate\n (student_details.firstname, student_details.gpa), MIN(student_details.gpa);" }, { "code": null, "e": 5448, "s": 5372, "text": "Verify the relation student_gpa_min using the DUMP operator as shown below." }, { "code": null, "e": 5477, "s": 5448, "text": "grunt> Dump student_gpa_min;" }, { "code": null, "e": 5572, "s": 5477, "text": "It will produce the following output, displaying the contents of the relation student_gpa_min." }, { "code": null, "e": 5763, "s": 5572, "text": "(({(Bharathi),(Komal),(Archana),(Trupthi),(Preethi),(Rajesh),(siddarth),(Rajiv) } , \n { (72) , (83) , (87) , (75) , (93) , (90) , (78) , (89) }) ,72)\n" }, { "code": null, "e": 5798, "s": 5763, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5817, "s": 5798, "text": " Arnab Chakraborty" }, { "code": null, "e": 5852, "s": 5817, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5873, "s": 5852, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5906, "s": 5873, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5919, "s": 5906, "text": " Nilay Mehta" }, { "code": null, "e": 5954, "s": 5919, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5972, "s": 5954, "text": " Bigdata Engineer" }, { "code": null, "e": 6005, "s": 5972, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6023, "s": 6005, "text": " Bigdata Engineer" }, { "code": null, "e": 6056, "s": 6023, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 6074, "s": 6056, "text": " Bigdata Engineer" }, { "code": null, "e": 6081, "s": 6074, "text": " Print" }, { "code": null, "e": 6092, "s": 6081, "text": " Add Notes" } ]
How to insert only a single column into a MySQL table with Java?
Use INSERT INTO statement in the Java-MySQL connection code to insert a column. Let us first create a table − mysql> create table DemoTable -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.54 sec) Here is the Java code to insert only a single column into a MySQL table. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertOneColumnDemo { public static void main(String[] args) { Connection con = null; PreparedStatement ps = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/web?" + "useSSL=false", "root", "123456"); String query = "insert into DemoTable(Name) values(?) "; ps = con.prepareStatement(query); ps.setString(1, "Robert"); ps.executeUpdate(); System.out.println("Record is inserted successfully......"); } catch (Exception e) { e.printStackTrace(); } } } This will produce the following output − Now let us check the records inserted in the table using select statement − mysql> select * from DemoTable; This will produce the following output − +--------+ | Name | +--------+ | Robert | +--------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "Use INSERT INTO statement in the Java-MySQL connection code to insert a column." }, { "code": null, "e": 1172, "s": 1142, "text": "Let us first create a table −" }, { "code": null, "e": 1279, "s": 1172, "text": "mysql> create table DemoTable\n -> (\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1352, "s": 1279, "text": "Here is the Java code to insert only a single column into a MySQL table." }, { "code": null, "e": 2041, "s": 1352, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class InsertOneColumnDemo {\n public static void main(String[] args) {\n Connection con = null;\n PreparedStatement ps = null;\n try {\n con = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/web?\" + \"useSSL=false\", \"root\", \"123456\");\n String query = \"insert into DemoTable(Name) values(?) \";\n ps = con.prepareStatement(query);\n ps.setString(1, \"Robert\");\n ps.executeUpdate();\n System.out.println(\"Record is inserted successfully......\");\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2082, "s": 2041, "text": "This will produce the following output −" }, { "code": null, "e": 2158, "s": 2082, "text": "Now let us check the records inserted in the table using select statement −" }, { "code": null, "e": 2190, "s": 2158, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 2231, "s": 2190, "text": "This will produce the following output −" }, { "code": null, "e": 2310, "s": 2231, "text": "+--------+\n| Name |\n+--------+\n| Robert |\n+--------+\n1 row in set (0.00 sec)" } ]
Find the other number when LCM and HCF given - GeeksforGeeks
04 Mar, 2021 Given a number A and L.C.M and H.C.F. The task is to determine the other number B.Examples: Input: A = 10, Lcm = 10, Hcf = 50. Output: B = 50 Input: A = 5, Lcm = 25, Hcf = 4. Output: B = 20 Formula:- A * B = LCM * HCF B = (LCM * HCF)/AExample : A = 15, B = 12 HCF = 3, LCM = 60 We can see that 3 * 60 = 15 * 12.How does this formula work? Since HCF divides both the numbers, let. A = HCF * x B = HCF * yNote that x and y are not common factors, so LCM must include HCF, x and y. So we can conclude. LCM = HCF * x * ySo LCM * HCF = HCF * x * y * HCF which is equal to A * B Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find other number from given// HCF and LCM#include <bits/stdc++.h>using namespace std; // Function that will calculates// the zeroes at the endint otherNumber(int A, int Lcm, int Hcf){ return (Lcm * Hcf) / A;} // Driver codeint main(){ int A = 8, Lcm = 8, Hcf = 1; // Calling function. int result = otherNumber(A, Lcm, Hcf); cout << "B = " << result; return 0;} // Java program to find other number from given// HCF and LCMclass GFG{ // Function that will calculates// the zeroes at the endstatic int otherNumber(int A, int Lcm, int Hcf){ return (Lcm * Hcf) / A;} // Driver codepublic static void main(String args[]){ int A = 8, Lcm = 8, Hcf = 1; // Calling function. int result = otherNumber(A, Lcm, Hcf); System.out.println("B = "+ result); }} # Python 3 program to find other# number from given HCF and LCM # Function that will calculates# the zeroes at the enddef otherNumber(a, Lcm, Hcf): return (Lcm * Hcf) // A # Driver codeA = 8; Lcm = 8; Hcf = 1 # Calling functionresult = otherNumber(A, Lcm, Hcf)print("B =", result) # This code is contributed# by Shrikant13 // C# program to find other number// from given HCF and LCMusing System; class GFG{ // Function that will calculates// the zeroes at the endstatic int otherNumber(int A, int Lcm, int Hcf){ return (Lcm * Hcf) / A;} // Driver codestatic public void Main(String []args){ int A = 8, Lcm = 8, Hcf = 1; // Calling function. int result = otherNumber(A, Lcm, Hcf); Console.WriteLine("B = " + result);}} // This code is contributed by Arnab Kundu <?php// PHP program to find other number// from given HCF and LCM // Function that will calculates// the zeroes at the endfunction otherNumber($A, $Lcm, $Hcf){ return ($Lcm * $Hcf) / $A;} // Driver code$A = 8; $Lcm = 8; $Hcf = 1; // Calling function.$result = otherNumber($A, $Lcm, $Hcf); echo "B = " . $result; // This code is contributed// by Akanksha Rai <script> // Javascript program to find other number from given// HCF and LCM // Function that will calculates// the zeroes at the endfunction otherNumber(A, Lcm, Hcf){ return (Lcm * Hcf) / A;} // Driver code let A = 8, Lcm = 8, Hcf = 1; // Calling function. let result = otherNumber(A, Lcm, Hcf); document.write("B = " + result); // This code is contributed by Mayank Tyagi </script> B = 1 Kirti_Mangal andrew1234 Akanksha_Rai shrikanth13 mayanktyagi1709 GCD-LCM Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Fizz Buzz Implementation Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 24327, "s": 24299, "text": "\n04 Mar, 2021" }, { "code": null, "e": 24421, "s": 24327, "text": "Given a number A and L.C.M and H.C.F. The task is to determine the other number B.Examples: " }, { "code": null, "e": 24520, "s": 24421, "text": "Input: A = 10, Lcm = 10, Hcf = 50.\nOutput: B = 50\n\nInput: A = 5, Lcm = 25, Hcf = 4.\nOutput: B = 20" }, { "code": null, "e": 24534, "s": 24522, "text": "Formula:- " }, { "code": null, "e": 24907, "s": 24534, "text": "A * B = LCM * HCF B = (LCM * HCF)/AExample : A = 15, B = 12 HCF = 3, LCM = 60 We can see that 3 * 60 = 15 * 12.How does this formula work? Since HCF divides both the numbers, let. A = HCF * x B = HCF * yNote that x and y are not common factors, so LCM must include HCF, x and y. So we can conclude. LCM = HCF * x * ySo LCM * HCF = HCF * x * y * HCF which is equal to A * B" }, { "code": null, "e": 24960, "s": 24907, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 24964, "s": 24960, "text": "C++" }, { "code": null, "e": 24969, "s": 24964, "text": "Java" }, { "code": null, "e": 24977, "s": 24969, "text": "Python3" }, { "code": null, "e": 24980, "s": 24977, "text": "C#" }, { "code": null, "e": 24984, "s": 24980, "text": "PHP" }, { "code": null, "e": 24995, "s": 24984, "text": "Javascript" }, { "code": "// CPP program to find other number from given// HCF and LCM#include <bits/stdc++.h>using namespace std; // Function that will calculates// the zeroes at the endint otherNumber(int A, int Lcm, int Hcf){ return (Lcm * Hcf) / A;} // Driver codeint main(){ int A = 8, Lcm = 8, Hcf = 1; // Calling function. int result = otherNumber(A, Lcm, Hcf); cout << \"B = \" << result; return 0;}", "e": 25396, "s": 24995, "text": null }, { "code": "// Java program to find other number from given// HCF and LCMclass GFG{ // Function that will calculates// the zeroes at the endstatic int otherNumber(int A, int Lcm, int Hcf){ return (Lcm * Hcf) / A;} // Driver codepublic static void main(String args[]){ int A = 8, Lcm = 8, Hcf = 1; // Calling function. int result = otherNumber(A, Lcm, Hcf); System.out.println(\"B = \"+ result); }}", "e": 25797, "s": 25396, "text": null }, { "code": "# Python 3 program to find other# number from given HCF and LCM # Function that will calculates# the zeroes at the enddef otherNumber(a, Lcm, Hcf): return (Lcm * Hcf) // A # Driver codeA = 8; Lcm = 8; Hcf = 1 # Calling functionresult = otherNumber(A, Lcm, Hcf)print(\"B =\", result) # This code is contributed# by Shrikant13", "e": 26123, "s": 25797, "text": null }, { "code": "// C# program to find other number// from given HCF and LCMusing System; class GFG{ // Function that will calculates// the zeroes at the endstatic int otherNumber(int A, int Lcm, int Hcf){ return (Lcm * Hcf) / A;} // Driver codestatic public void Main(String []args){ int A = 8, Lcm = 8, Hcf = 1; // Calling function. int result = otherNumber(A, Lcm, Hcf); Console.WriteLine(\"B = \" + result);}} // This code is contributed by Arnab Kundu", "e": 26607, "s": 26123, "text": null }, { "code": "<?php// PHP program to find other number// from given HCF and LCM // Function that will calculates// the zeroes at the endfunction otherNumber($A, $Lcm, $Hcf){ return ($Lcm * $Hcf) / $A;} // Driver code$A = 8; $Lcm = 8; $Hcf = 1; // Calling function.$result = otherNumber($A, $Lcm, $Hcf); echo \"B = \" . $result; // This code is contributed// by Akanksha Rai", "e": 26968, "s": 26607, "text": null }, { "code": "<script> // Javascript program to find other number from given// HCF and LCM // Function that will calculates// the zeroes at the endfunction otherNumber(A, Lcm, Hcf){ return (Lcm * Hcf) / A;} // Driver code let A = 8, Lcm = 8, Hcf = 1; // Calling function. let result = otherNumber(A, Lcm, Hcf); document.write(\"B = \" + result); // This code is contributed by Mayank Tyagi </script>", "e": 27374, "s": 26968, "text": null }, { "code": null, "e": 27380, "s": 27374, "text": "B = 1" }, { "code": null, "e": 27395, "s": 27382, "text": "Kirti_Mangal" }, { "code": null, "e": 27406, "s": 27395, "text": "andrew1234" }, { "code": null, "e": 27419, "s": 27406, "text": "Akanksha_Rai" }, { "code": null, "e": 27431, "s": 27419, "text": "shrikanth13" }, { "code": null, "e": 27447, "s": 27431, "text": "mayanktyagi1709" }, { "code": null, "e": 27455, "s": 27447, "text": "GCD-LCM" }, { "code": null, "e": 27468, "s": 27455, "text": "Mathematical" }, { "code": null, "e": 27487, "s": 27468, "text": "School Programming" }, { "code": null, "e": 27500, "s": 27487, "text": "Mathematical" }, { "code": null, "e": 27598, "s": 27500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27607, "s": 27598, "text": "Comments" }, { "code": null, "e": 27620, "s": 27607, "text": "Old Comments" }, { "code": null, "e": 27665, "s": 27620, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 27697, "s": 27665, "text": "Check if a number is Palindrome" }, { "code": null, "e": 27741, "s": 27697, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 27775, "s": 27741, "text": "Program to add two binary strings" }, { "code": null, "e": 27800, "s": 27775, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 27818, "s": 27800, "text": "Python Dictionary" }, { "code": null, "e": 27834, "s": 27818, "text": "Arrays in C/C++" }, { "code": null, "e": 27859, "s": 27834, "text": "Reverse a string in Java" }, { "code": null, "e": 27878, "s": 27859, "text": "Inheritance in C++" } ]
How to put a Toplevel window in front of the main window in Tkinter?
The Tkinter Toplevel window creates an additional window apart from the main window. We can add widgets and components to the newly created top-level window. It supports all the properties of the parent or main window. Sometimes the Toplevel window is also referred to as the child window. To put the child window in front of the parent window, we can use the wm_transient() method. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") win.title("Parent Window") # Create a Toplevel window top=Toplevel(win) top.geometry('600x250') top.title("Child Window") # Place the toplevel window at the top top.wm_transient(win) win.mainloop() If we run the above code, it will display a Toplevel window in front of the main window.
[ { "code": null, "e": 1281, "s": 1062, "text": "The Tkinter Toplevel window creates an additional window apart from the main window. We can add widgets and components to the newly created top-level window. It supports all the properties of the parent or main window." }, { "code": null, "e": 1445, "s": 1281, "text": "Sometimes the Toplevel window is also referred to as the child window. To put the child window in front of the parent window, we can use the wm_transient() method." }, { "code": null, "e": 1836, "s": 1445, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\nwin.title(\"Parent Window\")\n\n# Create a Toplevel window\ntop=Toplevel(win)\ntop.geometry('600x250')\ntop.title(\"Child Window\")\n\n# Place the toplevel window at the top\ntop.wm_transient(win)\n\nwin.mainloop()" }, { "code": null, "e": 1925, "s": 1836, "text": "If we run the above code, it will display a Toplevel window in front of the main window." } ]
Pandas Tricks for Imputing Missing Data | by Sadrach Pierre, Ph.D. | Towards Data Science
One of the biggest challenges data scientists face is dealing with missing data. In this post, we will discuss how to impute missing numerical and categorical values using Pandas. Let’s get started! For our purposes, we will be working with the Wine Magazine Dataset, which can be found here. To start, let’s read the data into a Pandas data frame: import pandas as pd df = pd.read_csv("winemag-data-130k-v2.csv") Next, let’s print the first five rows of data using the ‘.head()’ method: print(df.head()) Since we are interested in imputing missing values, it would be useful to see the distribution in missing values across columns. We can display missing value information with the ‘.info()’ method. This displays the number of non-null values in each column: print(df.info()) We can also use the ‘.isnull()’ and ‘.sum()’ methods to calculate the number of missing values in each column: print(df.isnull().sum()) We see that the resulting Pandas series shows the missing values for each of the columns in our data. The ‘price’ column contains 8996 missing values. We can replace these missing values using the ‘.fillna()’ method. For example, let’s fill in the missing values with the mean price: df['price'].fillna(df['price'].mean(), inplace = True)print(df.isnull().sum()) We see that the ‘price’ column no longer has missing values. Now, suppose we wanted to make a more accurate imputation. A good guess would be to replace missing values in the price column with the mean prices within the countries the missing values belong. For example, if we consider missing wine prices for Italian wine, we can replace these missing values with the mean price of Italian wine. To proceed, let’s look at the distribution in ‘country’ values. We can use the ‘Counter’ method from the collections module to do so: from collections import Counterprint(Counter(df['country'])) Let’s take a look at wine made in the ‘US’. We can define a data frame containing only ‘US’ wines: df_US = df[df['country']=='US'] Now, let’s print the number of missing values: print(df_US.isnull().sum()) We see that there are 239 missing ‘price’ values in the ‘US’ wines data. To fill in the missing values with the mean corresponding to the prices in the US we do the following: df_US['price'].fillna(df_US['price'].mean(), inplace = True) Now suppose we wanted to do this for the missing price values in each country. First, let’s impute missing country values: df['country'].fillna(df['country'].mode()[0], inplace = True) Next, within a for-loop we can define country-specific data frames: for i in list(set(df['country'])): df_country = df[df['country']== country] Next, we can fill the missing values in these country-specific data frames with their respective mean prices: for i in list(set(df['country'])): df_country = df[df['country']== country] df_country['price'].fillna(df_country['price'].mean(),inplace = True) We then append the result to a list we’ll call “frames” frames = []for i in list(set(df['country'])): df_country = df[df['country']== country] df_country['price'].fillna(df_country['price'].mean(),inplace = True) frames.append(df_country) Finally, we concatenate the resulting list of data frames: frames = []for i in list(set(df['country'])): df_country = df[df['country']== i] df_country['price'].fillna(df_country['price'].mean(),inplace = True) frames.append(df_country) final_df = pd.concat(frames) Now, if we print the number of missing price values before imputation we get: print(df.isnull().sum()) And after imputation: print(final_df.isnull().sum()) We see all but one of the missing values have been imputed. This corresponds to wines in Egypt which has no price data. We can fix this by checking the length of the data frame within the for loop and only imputing with the country-specific mean if the length is greater than one. If the length is equal to 1 we impute with the mean across all countries: frames = []for i in list(set(df['country'])): df_country = df[df['country']== i] if len(df_country) > 1: df_country['price'].fillna(df_country['price'].mean(),inplace = True) else: df_country['price'].fillna(df['price'].mean(),inplace = True) frames.append(df_country) final_df = pd.concat(frames) Printing the result we see that all of the values have been imputed for the ‘price’ column: print(final_df.isnull().sum()) We can define a function that generalizes this logic. Our function will take variables corresponding to a numerical column and categorical column: def impute_numerical(categorical_column, numerical_column): frames = [] for i in list(set(df[categorical_column])): df_category = df[df[categorical_column]== i] if len(df_category) > 1: df_category[numerical_column].fillna(df_category[numerical_column].mean(),inplace = True) else: df_category[numerical_column].fillna(df[numerical_column].mean(),inplace = True) frames.append(df_category) final_df = pd.concat(frames) return final_df We perform imputation using our function by executing the following: impute_price = impute_numerical('country', 'price')print(impute_price.isnull().sum()) Let’s also verify that the shapes of the original and imputed data frames match print("Original Shape: ", df.shape)print("Imputed Shape: ", impute_price.shape) Similarly, we can define a function that imputes categorical values. This function will take two variables corresponding columns with categorical values. def impute_categorical(categorical_column1, categorical_column2): cat_frames = [] for i in list(set(df[categorical_column1])): df_category = df[df[categorical_column1]== i] if len(df_category) > 1: df_category[categorical_column2].fillna(df_category[categorical_column2].mode()[0],inplace = True) else: df_category[categorical_column2].fillna(df[categorical_column2].mode()[0],inplace = True) cat_frames.append(df_category) cat_df = pd.concat(cat_frames) return cat_df We can impute missing ‘taster_name’ values with the mode in each respective country: impute_taster = impute_categorical('country', 'taster_name')print(impute_taster.isnull().sum()) We see that the ‘taster_name’ column now has zero missing values. Again, let’s verify that the shape matches with the original data frame: print("Original Shape: ", df.shape)print("Imputed Shape: ", impute_taster.shape) I’ll stop here but feel free to play around with the data and code yourself. To summarize, in this post we discussed how to handle missing values using the Pandas library. First, we discussed how to impute missing numerical values with the mean value across the data. We then looked at how to make category-specific numerical imputations. Finally, we showed how to impute missing categorical values with the mode corresponding to another categorical column. I hope you found this post useful/interesting. The code in this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 226, "s": 46, "text": "One of the biggest challenges data scientists face is dealing with missing data. In this post, we will discuss how to impute missing numerical and categorical values using Pandas." }, { "code": null, "e": 245, "s": 226, "text": "Let’s get started!" }, { "code": null, "e": 339, "s": 245, "text": "For our purposes, we will be working with the Wine Magazine Dataset, which can be found here." }, { "code": null, "e": 395, "s": 339, "text": "To start, let’s read the data into a Pandas data frame:" }, { "code": null, "e": 460, "s": 395, "text": "import pandas as pd df = pd.read_csv(\"winemag-data-130k-v2.csv\")" }, { "code": null, "e": 534, "s": 460, "text": "Next, let’s print the first five rows of data using the ‘.head()’ method:" }, { "code": null, "e": 551, "s": 534, "text": "print(df.head())" }, { "code": null, "e": 680, "s": 551, "text": "Since we are interested in imputing missing values, it would be useful to see the distribution in missing values across columns." }, { "code": null, "e": 808, "s": 680, "text": "We can display missing value information with the ‘.info()’ method. This displays the number of non-null values in each column:" }, { "code": null, "e": 825, "s": 808, "text": "print(df.info())" }, { "code": null, "e": 936, "s": 825, "text": "We can also use the ‘.isnull()’ and ‘.sum()’ methods to calculate the number of missing values in each column:" }, { "code": null, "e": 961, "s": 936, "text": "print(df.isnull().sum())" }, { "code": null, "e": 1245, "s": 961, "text": "We see that the resulting Pandas series shows the missing values for each of the columns in our data. The ‘price’ column contains 8996 missing values. We can replace these missing values using the ‘.fillna()’ method. For example, let’s fill in the missing values with the mean price:" }, { "code": null, "e": 1324, "s": 1245, "text": "df['price'].fillna(df['price'].mean(), inplace = True)print(df.isnull().sum())" }, { "code": null, "e": 1854, "s": 1324, "text": "We see that the ‘price’ column no longer has missing values. Now, suppose we wanted to make a more accurate imputation. A good guess would be to replace missing values in the price column with the mean prices within the countries the missing values belong. For example, if we consider missing wine prices for Italian wine, we can replace these missing values with the mean price of Italian wine. To proceed, let’s look at the distribution in ‘country’ values. We can use the ‘Counter’ method from the collections module to do so:" }, { "code": null, "e": 1915, "s": 1854, "text": "from collections import Counterprint(Counter(df['country']))" }, { "code": null, "e": 2014, "s": 1915, "text": "Let’s take a look at wine made in the ‘US’. We can define a data frame containing only ‘US’ wines:" }, { "code": null, "e": 2046, "s": 2014, "text": "df_US = df[df['country']=='US']" }, { "code": null, "e": 2093, "s": 2046, "text": "Now, let’s print the number of missing values:" }, { "code": null, "e": 2121, "s": 2093, "text": "print(df_US.isnull().sum())" }, { "code": null, "e": 2297, "s": 2121, "text": "We see that there are 239 missing ‘price’ values in the ‘US’ wines data. To fill in the missing values with the mean corresponding to the prices in the US we do the following:" }, { "code": null, "e": 2358, "s": 2297, "text": "df_US['price'].fillna(df_US['price'].mean(), inplace = True)" }, { "code": null, "e": 2481, "s": 2358, "text": "Now suppose we wanted to do this for the missing price values in each country. First, let’s impute missing country values:" }, { "code": null, "e": 2543, "s": 2481, "text": "df['country'].fillna(df['country'].mode()[0], inplace = True)" }, { "code": null, "e": 2611, "s": 2543, "text": "Next, within a for-loop we can define country-specific data frames:" }, { "code": null, "e": 2690, "s": 2611, "text": "for i in list(set(df['country'])): df_country = df[df['country']== country]" }, { "code": null, "e": 2800, "s": 2690, "text": "Next, we can fill the missing values in these country-specific data frames with their respective mean prices:" }, { "code": null, "e": 2952, "s": 2800, "text": "for i in list(set(df['country'])): df_country = df[df['country']== country] df_country['price'].fillna(df_country['price'].mean(),inplace = True)" }, { "code": null, "e": 3008, "s": 2952, "text": "We then append the result to a list we’ll call “frames”" }, { "code": null, "e": 3200, "s": 3008, "text": "frames = []for i in list(set(df['country'])): df_country = df[df['country']== country] df_country['price'].fillna(df_country['price'].mean(),inplace = True) frames.append(df_country)" }, { "code": null, "e": 3259, "s": 3200, "text": "Finally, we concatenate the resulting list of data frames:" }, { "code": null, "e": 3477, "s": 3259, "text": "frames = []for i in list(set(df['country'])): df_country = df[df['country']== i] df_country['price'].fillna(df_country['price'].mean(),inplace = True) frames.append(df_country) final_df = pd.concat(frames)" }, { "code": null, "e": 3555, "s": 3477, "text": "Now, if we print the number of missing price values before imputation we get:" }, { "code": null, "e": 3584, "s": 3555, "text": "print(df.isnull().sum()) " }, { "code": null, "e": 3606, "s": 3584, "text": "And after imputation:" }, { "code": null, "e": 3637, "s": 3606, "text": "print(final_df.isnull().sum())" }, { "code": null, "e": 3992, "s": 3637, "text": "We see all but one of the missing values have been imputed. This corresponds to wines in Egypt which has no price data. We can fix this by checking the length of the data frame within the for loop and only imputing with the country-specific mean if the length is greater than one. If the length is equal to 1 we impute with the mean across all countries:" }, { "code": null, "e": 4335, "s": 3992, "text": "frames = []for i in list(set(df['country'])): df_country = df[df['country']== i] if len(df_country) > 1: df_country['price'].fillna(df_country['price'].mean(),inplace = True) else: df_country['price'].fillna(df['price'].mean(),inplace = True) frames.append(df_country) final_df = pd.concat(frames)" }, { "code": null, "e": 4427, "s": 4335, "text": "Printing the result we see that all of the values have been imputed for the ‘price’ column:" }, { "code": null, "e": 4458, "s": 4427, "text": "print(final_df.isnull().sum())" }, { "code": null, "e": 4605, "s": 4458, "text": "We can define a function that generalizes this logic. Our function will take variables corresponding to a numerical column and categorical column:" }, { "code": null, "e": 5122, "s": 4605, "text": "def impute_numerical(categorical_column, numerical_column): frames = [] for i in list(set(df[categorical_column])): df_category = df[df[categorical_column]== i] if len(df_category) > 1: df_category[numerical_column].fillna(df_category[numerical_column].mean(),inplace = True) else: df_category[numerical_column].fillna(df[numerical_column].mean(),inplace = True) frames.append(df_category) final_df = pd.concat(frames) return final_df" }, { "code": null, "e": 5191, "s": 5122, "text": "We perform imputation using our function by executing the following:" }, { "code": null, "e": 5278, "s": 5191, "text": "impute_price = impute_numerical('country', 'price')print(impute_price.isnull().sum())" }, { "code": null, "e": 5358, "s": 5278, "text": "Let’s also verify that the shapes of the original and imputed data frames match" }, { "code": null, "e": 5438, "s": 5358, "text": "print(\"Original Shape: \", df.shape)print(\"Imputed Shape: \", impute_price.shape)" }, { "code": null, "e": 5592, "s": 5438, "text": "Similarly, we can define a function that imputes categorical values. This function will take two variables corresponding columns with categorical values." }, { "code": null, "e": 6143, "s": 5592, "text": "def impute_categorical(categorical_column1, categorical_column2): cat_frames = [] for i in list(set(df[categorical_column1])): df_category = df[df[categorical_column1]== i] if len(df_category) > 1: df_category[categorical_column2].fillna(df_category[categorical_column2].mode()[0],inplace = True) else: df_category[categorical_column2].fillna(df[categorical_column2].mode()[0],inplace = True) cat_frames.append(df_category) cat_df = pd.concat(cat_frames) return cat_df" }, { "code": null, "e": 6228, "s": 6143, "text": "We can impute missing ‘taster_name’ values with the mode in each respective country:" }, { "code": null, "e": 6324, "s": 6228, "text": "impute_taster = impute_categorical('country', 'taster_name')print(impute_taster.isnull().sum())" }, { "code": null, "e": 6463, "s": 6324, "text": "We see that the ‘taster_name’ column now has zero missing values. Again, let’s verify that the shape matches with the original data frame:" }, { "code": null, "e": 6544, "s": 6463, "text": "print(\"Original Shape: \", df.shape)print(\"Imputed Shape: \", impute_taster.shape)" }, { "code": null, "e": 6621, "s": 6544, "text": "I’ll stop here but feel free to play around with the data and code yourself." } ]
C++ Functions (Sum of numbers) | Set 1 | Practice | GeeksforGeeks
Given three numbers A, B, C you have to write a function named calcSum() which takes these 3 numbers as arguments and returns their sum. Input: The input line contains T, which denotes the number of testcases. Then T test cases follow. Each test case consists of a single line which contains three space separated integers A, B, and C. Output: Corresponding to each testcase, output sum of A, B and C in a new line. User Task: Since this is a functional problem you don't have to worry about input, you just have to complete the function calcSum(). Constraints: 1 <= T <= 105 1 <= A <= 102 1 <= B <= 102 1 <= C <= 102 Example: Input: 3 1 2 3 5 6 7 2 5 3 Output: 6 18 10 Explanation: Testcase 1: Sum of the given 1,2 and 3 is 6. 0 rohitpandey484Premium1 week ago What is the issue of this logic like if we will use int x=a+b+c; int y=a+b+c; int z=a+b+c; return calSum(x,y,z) -1 0niharika22 months ago return a+b+c; 0 bhargabeesahoo2000Premium2 months ago int calcSum(int a,int b,int c){ int sum; sum=a+b+c; return sum; } -1 helloutkarsh983 months ago int calcSum(int a, int b, int c) { return (a+b+c);} 0 tushargarg98683 months ago // { Driver Code Starts#include <iostream>using namespace std; int calcSum(int a,int b,int c); int main() {int t;cin>>t;while(t--){ int a,b,c; cin>>a>>b>>c; int sum = calcSum(a,b,c); cout<<sum<<"\n";}return 0;}// } Driver Code Ends /* Write your function here */ /* The function should be named calcSum and accepts three parameters of integer type and returns the sum of the three integers */ int calcSum(int a, int b, int c) { // Your code here int s=0; s=a+b+c; return s;} -2 gauravbhakuni093 months ago #include<iostream> using namespace std; int main(){ -2 20ce020064 months ago int calcSum(int a, int b, int c) { return a+b+c; // Your code here} -1 looser6 months ago int calcSum(int a, int b, int c) { return a+b+c; // Your code here } -2 kumarabhaydaan6 months ago #include <iostream> using namespace std; int main() { int a,b,d,c,x,e,y,z; cout<<" enter any three digit number :"; cin>>x; cout<<" enter any three digit number :"; cin>>y; cout<<" enter any three digit number :"; cin>>z; a=x%10; b=x/10; c=b%10; d=b/10; e=a+c+d; cout<<"\n the sum of the three digits is: "<<e; a=y%10; b=y/10; c=b%10; d=b/10; e=a+c+d; cout<<"\n the sum of the three digits is: "<<e; a=z%10; b=z/10; c=b%10; d=b/10; e=a+c+d; cout<<" \n the sum of the three digits is: "<<e; return 0; } -4 tushartxts7 months ago 1 2 3 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": 363, "s": 226, "text": "Given three numbers A, B, C you have to write a function named calcSum() which takes these 3 numbers as arguments and returns their sum." }, { "code": null, "e": 563, "s": 363, "text": "Input: \nThe input line contains T, which denotes the number of testcases. Then T test cases follow. Each test case consists of a single line which contains three space separated integers A, B, and C." }, { "code": null, "e": 643, "s": 563, "text": "Output:\nCorresponding to each testcase, output sum of A, B and C in a new line." }, { "code": null, "e": 776, "s": 643, "text": "User Task:\nSince this is a functional problem you don't have to worry about input, you just have to complete the function calcSum()." }, { "code": null, "e": 845, "s": 776, "text": "Constraints:\n1 <= T <= 105\n1 <= A <= 102\n1 <= B <= 102\n1 <= C <= 102" }, { "code": null, "e": 881, "s": 845, "text": "Example:\nInput:\n3\n1 2 3\n5 6 7\n2 5 3" }, { "code": null, "e": 897, "s": 881, "text": "Output:\n6\n18\n10" }, { "code": null, "e": 955, "s": 897, "text": "Explanation:\nTestcase 1: Sum of the given 1,2 and 3 is 6." }, { "code": null, "e": 957, "s": 955, "text": "0" }, { "code": null, "e": 989, "s": 957, "text": "rohitpandey484Premium1 week ago" }, { "code": null, "e": 1027, "s": 989, "text": "What is the issue of this logic like " }, { "code": null, "e": 1043, "s": 1027, "text": "if we will use " }, { "code": null, "e": 1056, "s": 1043, "text": "int x=a+b+c;" }, { "code": null, "e": 1069, "s": 1056, "text": "int y=a+b+c;" }, { "code": null, "e": 1082, "s": 1069, "text": "int z=a+b+c;" }, { "code": null, "e": 1103, "s": 1082, "text": "return calSum(x,y,z)" }, { "code": null, "e": 1106, "s": 1103, "text": "-1" }, { "code": null, "e": 1129, "s": 1106, "text": "0niharika22 months ago" }, { "code": null, "e": 1143, "s": 1129, "text": "return a+b+c;" }, { "code": null, "e": 1145, "s": 1143, "text": "0" }, { "code": null, "e": 1183, "s": 1145, "text": "bhargabeesahoo2000Premium2 months ago" }, { "code": null, "e": 1253, "s": 1183, "text": "int calcSum(int a,int b,int c){ int sum; sum=a+b+c; return sum;" }, { "code": null, "e": 1255, "s": 1253, "text": "}" }, { "code": null, "e": 1258, "s": 1255, "text": "-1" }, { "code": null, "e": 1285, "s": 1258, "text": "helloutkarsh983 months ago" }, { "code": null, "e": 1342, "s": 1285, "text": "int calcSum(int a, int b, int c) { return (a+b+c);}" }, { "code": null, "e": 1344, "s": 1342, "text": "0" }, { "code": null, "e": 1371, "s": 1344, "text": "tushargarg98683 months ago" }, { "code": null, "e": 1434, "s": 1371, "text": "// { Driver Code Starts#include <iostream>using namespace std;" }, { "code": null, "e": 1466, "s": 1434, "text": "int calcSum(int a,int b,int c);" }, { "code": null, "e": 1615, "s": 1466, "text": "int main() {int t;cin>>t;while(t--){ int a,b,c; cin>>a>>b>>c; int sum = calcSum(a,b,c); cout<<sum<<\"\\n\";}return 0;}// } Driver Code Ends" }, { "code": null, "e": 1647, "s": 1615, "text": "/* Write your function here */" }, { "code": null, "e": 1876, "s": 1647, "text": "/* The function should be named calcSum and accepts three parameters of integer type and returns the sum of the three integers */ int calcSum(int a, int b, int c) { // Your code here int s=0; s=a+b+c; return s;}" }, { "code": null, "e": 1879, "s": 1876, "text": "-2" }, { "code": null, "e": 1907, "s": 1879, "text": "gauravbhakuni093 months ago" }, { "code": null, "e": 1926, "s": 1907, "text": "#include<iostream>" }, { "code": null, "e": 1947, "s": 1926, "text": "using namespace std;" }, { "code": null, "e": 1959, "s": 1947, "text": "int main(){" }, { "code": null, "e": 1964, "s": 1961, "text": "-2" }, { "code": null, "e": 1986, "s": 1964, "text": "20ce020064 months ago" }, { "code": null, "e": 2061, "s": 1986, "text": "int calcSum(int a, int b, int c) { return a+b+c; // Your code here}" }, { "code": null, "e": 2064, "s": 2061, "text": "-1" }, { "code": null, "e": 2083, "s": 2064, "text": "looser6 months ago" }, { "code": null, "e": 2162, "s": 2083, "text": "int calcSum(int a, int b, int c) \n{\n return a+b+c;\n // Your code here\n}" }, { "code": null, "e": 2165, "s": 2162, "text": "-2" }, { "code": null, "e": 2192, "s": 2165, "text": "kumarabhaydaan6 months ago" }, { "code": null, "e": 2212, "s": 2192, "text": "#include <iostream>" }, { "code": null, "e": 2233, "s": 2212, "text": "using namespace std;" }, { "code": null, "e": 2244, "s": 2233, "text": "int main()" }, { "code": null, "e": 2270, "s": 2244, "text": "{ int a,b,d,c,x,e,y,z;" }, { "code": null, "e": 2320, "s": 2274, "text": " cout<<\" enter any three digit number :\";" }, { "code": null, "e": 2333, "s": 2320, "text": " cin>>x;" }, { "code": null, "e": 2379, "s": 2333, "text": " cout<<\" enter any three digit number :\";" }, { "code": null, "e": 2392, "s": 2379, "text": " cin>>y;" }, { "code": null, "e": 2438, "s": 2392, "text": " cout<<\" enter any three digit number :\";" }, { "code": null, "e": 2451, "s": 2438, "text": " cin>>z;" }, { "code": null, "e": 2464, "s": 2451, "text": " a=x%10;" }, { "code": null, "e": 2477, "s": 2464, "text": " b=x/10;" }, { "code": null, "e": 2490, "s": 2477, "text": " c=b%10;" }, { "code": null, "e": 2503, "s": 2490, "text": " d=b/10;" }, { "code": null, "e": 2518, "s": 2503, "text": " e=a+c+d;" }, { "code": null, "e": 2569, "s": 2518, "text": " cout<<\"\\n the sum of the three digits is: \"<<e;" }, { "code": null, "e": 2580, "s": 2569, "text": " a=y%10;" }, { "code": null, "e": 2593, "s": 2580, "text": " b=y/10;" }, { "code": null, "e": 2606, "s": 2593, "text": " c=b%10;" }, { "code": null, "e": 2619, "s": 2606, "text": " d=b/10;" }, { "code": null, "e": 2634, "s": 2619, "text": " e=a+c+d;" }, { "code": null, "e": 2684, "s": 2634, "text": " cout<<\"\\n the sum of the three digits is: \"<<e;" }, { "code": null, "e": 2695, "s": 2684, "text": " a=z%10;" }, { "code": null, "e": 2708, "s": 2695, "text": " b=z/10;" }, { "code": null, "e": 2721, "s": 2708, "text": " c=b%10;" }, { "code": null, "e": 2734, "s": 2721, "text": " d=b/10;" }, { "code": null, "e": 2749, "s": 2734, "text": " e=a+c+d;" }, { "code": null, "e": 2800, "s": 2749, "text": " cout<<\" \\n the sum of the three digits is: \"<<e;" }, { "code": null, "e": 2815, "s": 2800, "text": " return 0;" }, { "code": null, "e": 2819, "s": 2817, "text": "}" }, { "code": null, "e": 2822, "s": 2819, "text": "-4" }, { "code": null, "e": 2845, "s": 2822, "text": "tushartxts7 months ago" }, { "code": null, "e": 2847, "s": 2845, "text": "1" }, { "code": null, "e": 2849, "s": 2847, "text": "2" }, { "code": null, "e": 2851, "s": 2849, "text": "3" }, { "code": null, "e": 2997, "s": 2851, "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": 3033, "s": 2997, "text": " Login to access your submissions. " }, { "code": null, "e": 3043, "s": 3033, "text": "\nProblem\n" }, { "code": null, "e": 3053, "s": 3043, "text": "\nContest\n" }, { "code": null, "e": 3116, "s": 3053, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3264, "s": 3116, "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": 3472, "s": 3264, "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": 3578, "s": 3472, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
XML - Syntax
In this chapter, we will discuss the simple syntax rules to write an XML document. Following is a complete XML document − <?xml version = "1.0"?> <contact-info> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </contact-info> You can notice there are two kinds of information in the above example − Markup, like <contact-info> Markup, like <contact-info> The text, or the character data, Tutorials Point and (040) 123-4567. The text, or the character data, Tutorials Point and (040) 123-4567. The following diagram depicts the syntax rules to write different types of markup and text in an XML document. Let us see each component of the above diagram in detail. The XML document can optionally have an XML declaration. It is written as follows − <?xml version = "1.0" encoding = "UTF-8"?> Where version is the XML version and encoding specifies the character encoding used in the document. The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written in lower-case. The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written in lower-case. If document contains XML declaration, then it strictly needs to be the first statement of the XML document. If document contains XML declaration, then it strictly needs to be the first statement of the XML document. The XML declaration strictly needs be the first statement in the XML document. The XML declaration strictly needs be the first statement in the XML document. An HTTP protocol can override the value of encoding that you put in the XML declaration. An HTTP protocol can override the value of encoding that you put in the XML declaration. An XML file is structured by several XML-elements, also called XML-nodes or XML-tags. The names of XML-elements are enclosed in triangular brackets < > as shown below − <element> Element Syntax − Each XML-element needs to be closed either with start or with end elements as shown below − <element>....</element> or in simple-cases, just this way − <element/> Nesting of Elements − An XML-element can contain multiple XML-elements as its children, but the children elements must not overlap. i.e., an end tag of an element must have the same name as that of the most recent unmatched start tag. The Following example shows incorrect nested tags − <?xml version = "1.0"?> <contact-info> <company>TutorialsPoint </contact-info> </company> The Following example shows correct nested tags − <?xml version = "1.0"?> <contact-info> <company>TutorialsPoint</company> <contact-info> Root Element − An XML document can have only one root element. For example, following is not a correct XML document, because both the x and y elements occur at the top level without a root element − <x>...</x> <y>...</y> The Following example shows a correctly formed XML document − <root> <x>...</x> <y>...</y> </root> Case Sensitivity − The names of XML-elements are case-sensitive. That means the name of the start and the end elements need to be exactly in the same case. For example, <contact-info> is different from <Contact-Info> An attribute specifies a single property for the element, using a name/value pair. An XML-element can have one or more attributes. For example − <a href = "http://www.tutorialspoint.com/">Tutorialspoint!</a> Here href is the attribute name and http://www.tutorialspoint.com/ is attribute value. Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered two different XML attributes. Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered two different XML attributes. Same attribute cannot have two values in a syntax. The following example shows incorrect syntax because the attribute b is specified twice − Same attribute cannot have two values in a syntax. The following example shows incorrect syntax because the attribute b is specified twice <a b = "x" c = "y" b = "z">....</a> Attribute names are defined without quotation marks, whereas attribute values must always appear in quotation marks. Following example demonstrates incorrect xml syntax − Attribute names are defined without quotation marks, whereas attribute values must always appear in quotation marks. Following example demonstrates incorrect xml syntax <a b = x>....</a> In the above syntax, the attribute value is not defined in quotation marks. References usually allow you to add or include additional text or markup in an XML document. References always begin with the symbol "&" which is a reserved character and end with the symbol ";". XML has two types of references − Entity References − An entity reference contains a name between the start and the end delimiters. For example &amp; where amp is name. The name refers to a predefined string of text and/or markup. Entity References − An entity reference contains a name between the start and the end delimiters. For example &amp; where amp is name. The name refers to a predefined string of text and/or markup. Character References − These contain references, such as &#65;, contains a hash mark (“#”) followed by a number. The number always refers to the Unicode code of a character. In this case, 65 refers to alphabet "A". Character References − These contain references, such as &#65;, contains a hash mark (“#”) followed by a number. The number always refers to the Unicode code of a character. In this case, 65 refers to alphabet "A". The names of XML-elements and XML-attributes are case-sensitive, which means the name of start and end elements need to be written in the same case. To avoid character encoding problems, all XML files should be saved as Unicode UTF-8 or UTF-16 files. Whitespace characters like blanks, tabs and line-breaks between XML-elements and between the XML-attributes will be ignored. Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly. To use them, some replacement-entities are used, which are listed below − 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2083, "s": 1961, "text": "In this chapter, we will discuss the simple syntax rules to write an XML document. Following is a complete XML document −" }, { "code": null, "e": 2237, "s": 2083, "text": "<?xml version = \"1.0\"?>\n<contact-info>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n</contact-info>" }, { "code": null, "e": 2310, "s": 2237, "text": "You can notice there are two kinds of information in the above example −" }, { "code": null, "e": 2338, "s": 2310, "text": "Markup, like <contact-info>" }, { "code": null, "e": 2366, "s": 2338, "text": "Markup, like <contact-info>" }, { "code": null, "e": 2435, "s": 2366, "text": "The text, or the character data, Tutorials Point and (040) 123-4567." }, { "code": null, "e": 2504, "s": 2435, "text": "The text, or the character data, Tutorials Point and (040) 123-4567." }, { "code": null, "e": 2615, "s": 2504, "text": "The following diagram depicts the syntax rules to write different types of markup and text in an XML document." }, { "code": null, "e": 2673, "s": 2615, "text": "Let us see each component of the above diagram in detail." }, { "code": null, "e": 2757, "s": 2673, "text": "The XML document can optionally have an XML declaration. It is written as follows −" }, { "code": null, "e": 2800, "s": 2757, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" }, { "code": null, "e": 2901, "s": 2800, "text": "Where version is the XML version and encoding specifies the character encoding used in the document." }, { "code": null, "e": 3006, "s": 2901, "text": "The XML declaration is case sensitive and must begin with \"<?xml>\" where \"xml\" is written in lower-case." }, { "code": null, "e": 3111, "s": 3006, "text": "The XML declaration is case sensitive and must begin with \"<?xml>\" where \"xml\" is written in lower-case." }, { "code": null, "e": 3219, "s": 3111, "text": "If document contains XML declaration, then it strictly needs to be the first statement of the XML document." }, { "code": null, "e": 3327, "s": 3219, "text": "If document contains XML declaration, then it strictly needs to be the first statement of the XML document." }, { "code": null, "e": 3406, "s": 3327, "text": "The XML declaration strictly needs be the first statement in the XML document." }, { "code": null, "e": 3485, "s": 3406, "text": "The XML declaration strictly needs be the first statement in the XML document." }, { "code": null, "e": 3574, "s": 3485, "text": "An HTTP protocol can override the value of encoding that you put in the XML declaration." }, { "code": null, "e": 3663, "s": 3574, "text": "An HTTP protocol can override the value of encoding that you put in the XML declaration." }, { "code": null, "e": 3832, "s": 3663, "text": "An XML file is structured by several XML-elements, also called XML-nodes or XML-tags.\nThe names of XML-elements are enclosed in triangular brackets < > as shown below −" }, { "code": null, "e": 3842, "s": 3832, "text": "<element>" }, { "code": null, "e": 3951, "s": 3842, "text": "Element Syntax − Each XML-element needs to be closed either with start or with end elements as shown below −" }, { "code": null, "e": 3975, "s": 3951, "text": "<element>....</element>" }, { "code": null, "e": 4011, "s": 3975, "text": "or in simple-cases, just this way −" }, { "code": null, "e": 4022, "s": 4011, "text": "<element/>" }, { "code": null, "e": 4257, "s": 4022, "text": "Nesting of Elements − An XML-element can contain multiple XML-elements as its children, but the children elements must not overlap. i.e., an end tag of an element must have the same name as that of the most recent unmatched start tag." }, { "code": null, "e": 4309, "s": 4257, "text": "The Following example shows incorrect nested tags −" }, { "code": null, "e": 4399, "s": 4309, "text": "<?xml version = \"1.0\"?>\n<contact-info>\n<company>TutorialsPoint\n</contact-info>\n</company>" }, { "code": null, "e": 4449, "s": 4399, "text": "The Following example shows correct nested tags −" }, { "code": null, "e": 4540, "s": 4449, "text": "<?xml version = \"1.0\"?>\n<contact-info>\n <company>TutorialsPoint</company>\n<contact-info>" }, { "code": null, "e": 4739, "s": 4540, "text": "Root Element − An XML document can have only one root element. For example, following is not a correct XML document, because both the x and y elements occur at the top level without a root element −" }, { "code": null, "e": 4761, "s": 4739, "text": "<x>...</x>\n<y>...</y>" }, { "code": null, "e": 4823, "s": 4761, "text": "The Following example shows a correctly formed XML document −" }, { "code": null, "e": 4866, "s": 4823, "text": "<root>\n <x>...</x>\n <y>...</y>\n</root>" }, { "code": null, "e": 5022, "s": 4866, "text": "Case Sensitivity − The names of XML-elements are case-sensitive. That means the name of the start and the end elements need to be exactly in the same case." }, { "code": null, "e": 5083, "s": 5022, "text": "For example, <contact-info> is different from <Contact-Info>" }, { "code": null, "e": 5228, "s": 5083, "text": "An attribute specifies a single property for the element, using a name/value pair. An XML-element can have one or more attributes. For example −" }, { "code": null, "e": 5292, "s": 5228, "text": "<a href = \"http://www.tutorialspoint.com/\">Tutorialspoint!</a>\n" }, { "code": null, "e": 5379, "s": 5292, "text": "Here href is the attribute name and http://www.tutorialspoint.com/ is attribute value." }, { "code": null, "e": 5504, "s": 5379, "text": "Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered two different XML attributes." }, { "code": null, "e": 5629, "s": 5504, "text": "Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered two different XML attributes." }, { "code": null, "e": 5770, "s": 5629, "text": "Same attribute cannot have two values in a syntax. The following example shows incorrect syntax because the attribute b is specified twice −" }, { "code": null, "e": 5909, "s": 5770, "text": "Same attribute cannot have two values in a syntax. The following example shows incorrect syntax because the attribute b is specified twice" }, { "code": null, "e": 5945, "s": 5909, "text": "<a b = \"x\" c = \"y\" b = \"z\">....</a>" }, { "code": null, "e": 6116, "s": 5945, "text": "Attribute names are defined without quotation marks, whereas attribute values must always appear in quotation marks. Following example demonstrates incorrect xml syntax −" }, { "code": null, "e": 6285, "s": 6116, "text": "Attribute names are defined without quotation marks, whereas attribute values must always appear in quotation marks. Following example demonstrates incorrect xml syntax" }, { "code": null, "e": 6303, "s": 6285, "text": "<a b = x>....</a>" }, { "code": null, "e": 6379, "s": 6303, "text": "In the above syntax, the attribute value is not defined in quotation marks." }, { "code": null, "e": 6609, "s": 6379, "text": "References usually allow you to add or include additional text or markup in an XML document. References always begin with the symbol \"&\" which is a reserved character and end with the symbol \";\". XML has two types of references −" }, { "code": null, "e": 6806, "s": 6609, "text": "Entity References − An entity reference contains a name between the start and the end delimiters. For example &amp; where amp is name. The name refers to a predefined string of text and/or markup." }, { "code": null, "e": 7003, "s": 6806, "text": "Entity References − An entity reference contains a name between the start and the end delimiters. For example &amp; where amp is name. The name refers to a predefined string of text and/or markup." }, { "code": null, "e": 7218, "s": 7003, "text": "Character References − These contain references, such as &#65;, contains a hash mark (“#”) followed by a number. The number always refers to the Unicode code of a character. In this case, 65 refers to alphabet \"A\"." }, { "code": null, "e": 7433, "s": 7218, "text": "Character References − These contain references, such as &#65;, contains a hash mark (“#”) followed by a number. The number always refers to the Unicode code of a character. In this case, 65 refers to alphabet \"A\"." }, { "code": null, "e": 7684, "s": 7433, "text": "The names of XML-elements and XML-attributes are case-sensitive, which means the name of start and end elements need to be written in the same case. To avoid character encoding problems, all XML files should be saved as Unicode UTF-8 or UTF-16 files." }, { "code": null, "e": 7809, "s": 7684, "text": "Whitespace characters like blanks, tabs and line-breaks between XML-elements and between the XML-attributes will be ignored." }, { "code": null, "e": 7975, "s": 7809, "text": "Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly. To use them, some replacement-entities are used, which are listed below −" }, { "code": null, "e": 8008, "s": 7975, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 8025, "s": 8008, "text": " Frahaan Hussain" }, { "code": null, "e": 8058, "s": 8025, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 8068, "s": 8058, "text": " YouAccel" }, { "code": null, "e": 8101, "s": 8068, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 8118, "s": 8101, "text": " Jordan Stanchev" }, { "code": null, "e": 8151, "s": 8118, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8165, "s": 8151, "text": " Simon Sez IT" }, { "code": null, "e": 8172, "s": 8165, "text": " Print" }, { "code": null, "e": 8183, "s": 8172, "text": " Add Notes" } ]
Fortran - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable should have a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. A name in Fortran must follow the following rules − It cannot be longer than 31 characters. It cannot be longer than 31 characters. It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_). It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_). First character of a name must be a letter. First character of a name must be a letter. Names are case-insensitive. Names are case-insensitive. Based on the basic types explained in previous chapter, following are the variable types − Integer It can hold only integer values. Real It stores the floating point numbers. Complex It is used for storing complex numbers. Logical It stores logical Boolean values. Character It stores characters or strings. Variables are declared at the beginning of a program (or subprogram) in a type declaration statement. Syntax for variable declaration is as follows − type-specifier :: variable_name integer :: total real :: average complex :: cx logical :: done character(len = 80) :: message ! a string of 80 characters Later you can assign values to these variables, like, total = 20000 average = 1666.67 done = .true. message = “A big Hello from Tutorials Point” cx = (3.0, 5.0) ! cx = 3.0 + 5.0i You can also use the intrinsic function cmplx, to assign values to a complex variable − cx = cmplx (1.0/2.0, -7.0) ! cx = 0.5 – 7.0i cx = cmplx (x, y) ! cx = x + yi The following example demonstrates variable declaration, assignment and display on screen − program variableTesting implicit none ! declaring variables integer :: total real :: average complex :: cx logical :: done character(len=80) :: message ! a string of 80 characters !assigning values total = 20000 average = 1666.67 done = .true. message = "A big Hello from Tutorials Point" cx = (3.0, 5.0) ! cx = 3.0 + 5.0i Print *, total Print *, average Print *, cx Print *, done Print *, message end program variableTesting When the above code is compiled and executed, it produces the following result − 20000 1666.67004 (3.00000000, 5.00000000 ) T A big Hello from Tutorials Point Print Add Notes Bookmark this page
[ { "code": null, "e": 2465, "s": 2146, "text": "A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable should have a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable." }, { "code": null, "e": 2606, "s": 2465, "text": "The name of a variable can be composed of letters, digits, and the underscore character. A name in Fortran must follow the following rules −" }, { "code": null, "e": 2646, "s": 2606, "text": "It cannot be longer than 31 characters." }, { "code": null, "e": 2686, "s": 2646, "text": "It cannot be longer than 31 characters." }, { "code": null, "e": 2811, "s": 2686, "text": "It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_)." }, { "code": null, "e": 2936, "s": 2811, "text": "It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_)." }, { "code": null, "e": 2980, "s": 2936, "text": "First character of a name must be a letter." }, { "code": null, "e": 3024, "s": 2980, "text": "First character of a name must be a letter." }, { "code": null, "e": 3052, "s": 3024, "text": "Names are case-insensitive." }, { "code": null, "e": 3080, "s": 3052, "text": "Names are case-insensitive." }, { "code": null, "e": 3171, "s": 3080, "text": "Based on the basic types explained in previous chapter, following are the variable types −" }, { "code": null, "e": 3179, "s": 3171, "text": "Integer" }, { "code": null, "e": 3212, "s": 3179, "text": "It can hold only integer values." }, { "code": null, "e": 3217, "s": 3212, "text": "Real" }, { "code": null, "e": 3255, "s": 3217, "text": "It stores the floating point numbers." }, { "code": null, "e": 3263, "s": 3255, "text": "Complex" }, { "code": null, "e": 3303, "s": 3263, "text": "It is used for storing complex numbers." }, { "code": null, "e": 3311, "s": 3303, "text": "Logical" }, { "code": null, "e": 3345, "s": 3311, "text": "It stores logical Boolean values." }, { "code": null, "e": 3355, "s": 3345, "text": "Character" }, { "code": null, "e": 3388, "s": 3355, "text": "It stores characters or strings." }, { "code": null, "e": 3490, "s": 3388, "text": "Variables are declared at the beginning of a program (or subprogram) in a type declaration statement." }, { "code": null, "e": 3538, "s": 3490, "text": "Syntax for variable declaration is as follows −" }, { "code": null, "e": 3571, "s": 3538, "text": "type-specifier :: variable_name\n" }, { "code": null, "e": 3700, "s": 3571, "text": "integer :: total \t\nreal :: average \ncomplex :: cx \nlogical :: done \ncharacter(len = 80) :: message ! a string of 80 characters" }, { "code": null, "e": 3754, "s": 3700, "text": "Later you can assign values to these variables, like," }, { "code": null, "e": 3889, "s": 3754, "text": "total = 20000 \naverage = 1666.67 \ndone = .true. \nmessage = “A big Hello from Tutorials Point” \ncx = (3.0, 5.0) ! cx = 3.0 + 5.0i\n" }, { "code": null, "e": 3977, "s": 3889, "text": "You can also use the intrinsic function cmplx, to assign values to a complex variable −" }, { "code": null, "e": 4056, "s": 3977, "text": "cx = cmplx (1.0/2.0, -7.0) ! cx = 0.5 – 7.0i \ncx = cmplx (x, y) ! cx = x + yi\n" }, { "code": null, "e": 4148, "s": 4056, "text": "The following example demonstrates variable declaration, assignment and display on screen −" }, { "code": null, "e": 4654, "s": 4148, "text": "program variableTesting\nimplicit none\n\n ! declaring variables\n integer :: total \n real :: average \n complex :: cx \n logical :: done \n character(len=80) :: message ! a string of 80 characters\n \n !assigning values\n total = 20000 \n average = 1666.67 \n done = .true. \n message = \"A big Hello from Tutorials Point\" \n cx = (3.0, 5.0) ! cx = 3.0 + 5.0i\n\n Print *, total\n Print *, average\n Print *, cx\n Print *, done\n Print *, message\n \nend program variableTesting" }, { "code": null, "e": 4735, "s": 4654, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4827, "s": 4735, "text": "20000\n1666.67004 \n(3.00000000, 5.00000000 )\nT\nA big Hello from Tutorials Point \n" }, { "code": null, "e": 4834, "s": 4827, "text": " Print" }, { "code": null, "e": 4845, "s": 4834, "text": " Add Notes" } ]
Python 3 - break statement
The break statement is used for premature termination of the current loop. After abandoning the loop, execution at the next statement is resumed, just like the traditional break statement in C. The most common use of break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and starts executing the next line of the code after the block. The syntax for a break statement in Python is as follows − break #!/usr/bin/python3 for letter in 'Python': # First Example if letter == 'h': break print ('Current Letter :', letter) var = 10 # Second Example while var > 0: print ('Current variable value :', var) var = var -1 if var == 5: break print ("Good bye!") When the above code is executed, it produces the following result − Current Letter : P Current Letter : y Current Letter : t Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye! The following program demonstrates use of the break in a for loop iterating over a list. User inputs a number, which is searched in the list. If it is found, then the loop terminates with the 'found' message. #!/usr/bin/python3 no = int(input('any number: ')) numbers = [11,33,55,39,55,75,37,21,23,41,13] for num in numbers: if num == no: print ('number found in list') break else: print ('number not found in list') The above program will produce the following output − any number: 33 number found in list any number: 5 number not found in list 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": 2534, "s": 2340, "text": "The break statement is used for premature termination of the current loop. After abandoning the loop, execution at the next statement is resumed, just like the traditional break statement in C." }, { "code": null, "e": 2705, "s": 2534, "text": "The most common use of break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops." }, { "code": null, "e": 2862, "s": 2705, "text": "If you are using nested loops, the break statement stops the execution of the innermost loop and starts executing the next line of the code after the block." }, { "code": null, "e": 2921, "s": 2862, "text": "The syntax for a break statement in Python is as follows −" }, { "code": null, "e": 2928, "s": 2921, "text": "break\n" }, { "code": null, "e": 3248, "s": 2928, "text": "#!/usr/bin/python3\n\nfor letter in 'Python': # First Example\n if letter == 'h':\n break\n print ('Current Letter :', letter)\n \nvar = 10 # Second Example\nwhile var > 0: \n print ('Current variable value :', var)\n var = var -1\n if var == 5:\n break\n\nprint (\"Good bye!\")" }, { "code": null, "e": 3316, "s": 3248, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3520, "s": 3316, "text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nCurrent variable value : 10\nCurrent variable value : 9\nCurrent variable value : 8\nCurrent variable value : 7\nCurrent variable value : 6\nGood bye!\n" }, { "code": null, "e": 3729, "s": 3520, "text": "The following program demonstrates use of the break in a for loop iterating over a list. User inputs a number, which is searched in the list. If it is found, then the loop terminates with the 'found' message." }, { "code": null, "e": 3957, "s": 3729, "text": "#!/usr/bin/python3\n\nno = int(input('any number: '))\nnumbers = [11,33,55,39,55,75,37,21,23,41,13]\n\nfor num in numbers:\n if num == no:\n print ('number found in list')\n break\nelse:\n print ('number not found in list')" }, { "code": null, "e": 4011, "s": 3957, "text": "The above program will produce the following output −" }, { "code": null, "e": 4088, "s": 4011, "text": "any number: 33\nnumber found in list\n\nany number: 5\nnumber not found in list\n" }, { "code": null, "e": 4125, "s": 4088, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4141, "s": 4125, "text": " Malhar Lathkar" }, { "code": null, "e": 4174, "s": 4141, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4193, "s": 4174, "text": " Arnab Chakraborty" }, { "code": null, "e": 4228, "s": 4193, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4250, "s": 4228, "text": " In28Minutes Official" }, { "code": null, "e": 4284, "s": 4250, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4312, "s": 4284, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4347, "s": 4312, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4361, "s": 4347, "text": " Lets Kode It" }, { "code": null, "e": 4394, "s": 4361, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4411, "s": 4394, "text": " Abhilash Nelson" }, { "code": null, "e": 4418, "s": 4411, "text": " Print" }, { "code": null, "e": 4429, "s": 4418, "text": " Add Notes" } ]
Creating VGG from Scratch using Tensorflow | by Arjun Sarkar | Towards Data Science
LeNet-5 was one of the oldest convolutional neural network architectures, designed by Yann LeCun in 1998, which was used to recognize handwritten digits. It used 5x5 filters, average pooling, and no padding. But by modern standards, this was a very small neural network and had only 60 thousand parameters. Nowadays, we see networks that have a range of 10 million to a few billion parameters. The next big Convolutional neural network that revolutionized the use of a convolutional network was AlexNet which had approximately 60 million parameters. The first layer of AlexNet uses 96 filters with kernel size 11x11, with strides of 4. The next layer uses 3x3 filters, and so on. Also, AlexNet uses Max Pooling and padding, which were not used in LeNet-5. AlexNet was very similar to LeNet-5, but it was much bigger. Also, AlexNet uses the ReLU activation function, while LeNet-5 mainly used the Sigmoid activation. What these networks had in common is that, as we go deeper into the network, the size of the tensor kept on decreasing, while the number of channels kept on increasing. Also, another trend that is still used nowadays while creating neural network architectures is the use of Convolutional layers (one or multiple) followed by some Pooling layers, and in the end, some fully connected layers. The next big convolutional neural network was the VGG network. The remarkable thing about VGG was that, instead of having so many hyperparameters, the authors used a much simpler network, where the focus was on using convolutional layers with small sizes of 3x3 filters, with a stride of 1 and using the ‘same’ padding, and make all the MaxPooling layers 2x2 with a stride of 2. VGG greatly simplified the previously made neural network architectures. VGG paper link — https://arxiv.org/abs/1409.1556 VGG 16 architecture and implementation using Tensorflow: Figure 2 shows all the VGG architectures. The architecture of VGG 16 is highlighted in red. A simpler version of the architecture is presented in Figure 1. VGG network uses Max Pooling and ReLU activation function. All the hidden layers use ReLU activation and the last Dense layer uses Softmax activation. MaxPooling is performed over a 2x2 pixel window with a stride of 2. VGG 16 has 5 convolutional blocks and 3 fully connected layers. Each block consists of 2 or more Convolutional layers and a Max Pool layer. Algorithm: import all the necessary layersWrite code for the convolutional blocksWrite code for the Dense layersBuild the model import all the necessary layers Write code for the convolutional blocks Write code for the Dense layers Build the model Importing the libraries: # import necessary layersfrom tensorflow.keras.layers import Input, Conv2Dfrom tensorflow.keras.layers import MaxPool2D, Flatten, Densefrom tensorflow.keras import Model Input: # input input = Input(shape =(224,224,3)) Input is a 224x224 RGB image, so 3 channels. Conv Block 1: It has two Conv layers with 64 filters each, followed by Max Pooling. # 1st Conv Blockx = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(input)x = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x) Conv Block 2: It has two Conv layers with 128 filters followed by Max Pooling. # 2nd Conv Blockx = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x) Conv Block 3: It has three Conv layers with 256 filters followed by Max Pooling. # 3rd Conv block x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x) x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x) x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x) x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x) Conv Block 4 and 5: Both Conv blocks 4 and 5 have 3 Conv layers with 512 filters followed by Max Pooling. # 4th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 5th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x) Dense layers: There are 3 fully connected layers, the first two layers with 4096 hidden units and ReLU activation and the last output layer with 1000 hidden units and Softmax activation. # Fully connected layers x = Flatten()(x) x = Dense(units = 4096, activation ='relu')(x) x = Dense(units = 4096, activation ='relu')(x) output = Dense(units = 1000, activation ='softmax')(x) Creating the Model: # creating the modelmodel = Model (inputs=input, outputs =output)model.summary() Output: Plotting the Model: # plotting the modelfrom tensorflow.python.keras.utils.vis_utils import model_to_dotfrom IPython.display import SVGimport pydotimport graphvizSVG(model_to_dot(model, show_shapes=True, show_layer_names=True, rankdir='TB',expand_nested=False, dpi=60, subgraph=False).create(prog='dot',format='svg')) Output Snippet: # import necessary layers from tensorflow.keras.layers import Input, Conv2D from tensorflow.keras.layers import MaxPool2D, Flatten, Dense from tensorflow.keras import Model# inputinput = Input(shape =(224,224,3))# 1st Conv Blockx = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(input)x = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 2nd Conv Blockx = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 3rd Conv blockx = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 4th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 5th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# Fully connected layersx = Flatten()(x)x = Dense(units = 4096, activation ='relu')(x)x = Dense(units = 4096, activation ='relu')(x)output = Dense(units = 1000, activation ='softmax')(x)# creating the modelmodel = Model (inputs=input, outputs =output)model.summary() Conclusion: The VGG network is a very simple Convolutional Neural Network, and due to its simplicity is very easy to implement using Tensorflow. It has only Conv2D, MaxPooling, and Dense layers. VGG 16 has a total of 138 million trainable parameters. VGG was the deepest CNN model architecture during its publication with a maximum of 19 weight layers. It achieved state-of-the-art performance in the ImageNet challenge and showed that deeper networks are beneficial for better classification accuracy. References: Karen Simonyan and Andrew Zisserman, Very Deep Convolutional Networks for Large-Scale Image Recognition, arXiv:1409.1556v6 [cs.CV], 2015. Karen Simonyan and Andrew Zisserman, Very Deep Convolutional Networks for Large-Scale Image Recognition, arXiv:1409.1556v6 [cs.CV], 2015.
[ { "code": null, "e": 1480, "s": 172, "text": "LeNet-5 was one of the oldest convolutional neural network architectures, designed by Yann LeCun in 1998, which was used to recognize handwritten digits. It used 5x5 filters, average pooling, and no padding. But by modern standards, this was a very small neural network and had only 60 thousand parameters. Nowadays, we see networks that have a range of 10 million to a few billion parameters. The next big Convolutional neural network that revolutionized the use of a convolutional network was AlexNet which had approximately 60 million parameters. The first layer of AlexNet uses 96 filters with kernel size 11x11, with strides of 4. The next layer uses 3x3 filters, and so on. Also, AlexNet uses Max Pooling and padding, which were not used in LeNet-5. AlexNet was very similar to LeNet-5, but it was much bigger. Also, AlexNet uses the ReLU activation function, while LeNet-5 mainly used the Sigmoid activation. What these networks had in common is that, as we go deeper into the network, the size of the tensor kept on decreasing, while the number of channels kept on increasing. Also, another trend that is still used nowadays while creating neural network architectures is the use of Convolutional layers (one or multiple) followed by some Pooling layers, and in the end, some fully connected layers." }, { "code": null, "e": 1932, "s": 1480, "text": "The next big convolutional neural network was the VGG network. The remarkable thing about VGG was that, instead of having so many hyperparameters, the authors used a much simpler network, where the focus was on using convolutional layers with small sizes of 3x3 filters, with a stride of 1 and using the ‘same’ padding, and make all the MaxPooling layers 2x2 with a stride of 2. VGG greatly simplified the previously made neural network architectures." }, { "code": null, "e": 1981, "s": 1932, "text": "VGG paper link — https://arxiv.org/abs/1409.1556" }, { "code": null, "e": 2038, "s": 1981, "text": "VGG 16 architecture and implementation using Tensorflow:" }, { "code": null, "e": 2194, "s": 2038, "text": "Figure 2 shows all the VGG architectures. The architecture of VGG 16 is highlighted in red. A simpler version of the architecture is presented in Figure 1." }, { "code": null, "e": 2413, "s": 2194, "text": "VGG network uses Max Pooling and ReLU activation function. All the hidden layers use ReLU activation and the last Dense layer uses Softmax activation. MaxPooling is performed over a 2x2 pixel window with a stride of 2." }, { "code": null, "e": 2553, "s": 2413, "text": "VGG 16 has 5 convolutional blocks and 3 fully connected layers. Each block consists of 2 or more Convolutional layers and a Max Pool layer." }, { "code": null, "e": 2564, "s": 2553, "text": "Algorithm:" }, { "code": null, "e": 2681, "s": 2564, "text": "import all the necessary layersWrite code for the convolutional blocksWrite code for the Dense layersBuild the model" }, { "code": null, "e": 2713, "s": 2681, "text": "import all the necessary layers" }, { "code": null, "e": 2753, "s": 2713, "text": "Write code for the convolutional blocks" }, { "code": null, "e": 2785, "s": 2753, "text": "Write code for the Dense layers" }, { "code": null, "e": 2801, "s": 2785, "text": "Build the model" }, { "code": null, "e": 2826, "s": 2801, "text": "Importing the libraries:" }, { "code": null, "e": 2996, "s": 2826, "text": "# import necessary layersfrom tensorflow.keras.layers import Input, Conv2Dfrom tensorflow.keras.layers import MaxPool2D, Flatten, Densefrom tensorflow.keras import Model" }, { "code": null, "e": 3003, "s": 2996, "text": "Input:" }, { "code": null, "e": 3046, "s": 3003, "text": "# input input = Input(shape =(224,224,3))" }, { "code": null, "e": 3091, "s": 3046, "text": "Input is a 224x224 RGB image, so 3 channels." }, { "code": null, "e": 3105, "s": 3091, "text": "Conv Block 1:" }, { "code": null, "e": 3175, "s": 3105, "text": "It has two Conv layers with 64 filters each, followed by Max Pooling." }, { "code": null, "e": 3413, "s": 3175, "text": "# 1st Conv Blockx = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(input)x = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)" }, { "code": null, "e": 3427, "s": 3413, "text": "Conv Block 2:" }, { "code": null, "e": 3492, "s": 3427, "text": "It has two Conv layers with 128 filters followed by Max Pooling." }, { "code": null, "e": 3728, "s": 3492, "text": "# 2nd Conv Blockx = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)" }, { "code": null, "e": 3742, "s": 3728, "text": "Conv Block 3:" }, { "code": null, "e": 3809, "s": 3742, "text": "It has three Conv layers with 256 filters followed by Max Pooling." }, { "code": null, "e": 4130, "s": 3809, "text": "# 3rd Conv block x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x) x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x) x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x) x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)" }, { "code": null, "e": 4150, "s": 4130, "text": "Conv Block 4 and 5:" }, { "code": null, "e": 4236, "s": 4150, "text": "Both Conv blocks 4 and 5 have 3 Conv layers with 512 filters followed by Max Pooling." }, { "code": null, "e": 4867, "s": 4236, "text": "# 4th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 5th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)" }, { "code": null, "e": 4881, "s": 4867, "text": "Dense layers:" }, { "code": null, "e": 5054, "s": 4881, "text": "There are 3 fully connected layers, the first two layers with 4096 hidden units and ReLU activation and the last output layer with 1000 hidden units and Softmax activation." }, { "code": null, "e": 5246, "s": 5054, "text": "# Fully connected layers x = Flatten()(x) x = Dense(units = 4096, activation ='relu')(x) x = Dense(units = 4096, activation ='relu')(x) output = Dense(units = 1000, activation ='softmax')(x)" }, { "code": null, "e": 5266, "s": 5246, "text": "Creating the Model:" }, { "code": null, "e": 5347, "s": 5266, "text": "# creating the modelmodel = Model (inputs=input, outputs =output)model.summary()" }, { "code": null, "e": 5355, "s": 5347, "text": "Output:" }, { "code": null, "e": 5375, "s": 5355, "text": "Plotting the Model:" }, { "code": null, "e": 5673, "s": 5375, "text": "# plotting the modelfrom tensorflow.python.keras.utils.vis_utils import model_to_dotfrom IPython.display import SVGimport pydotimport graphvizSVG(model_to_dot(model, show_shapes=True, show_layer_names=True, rankdir='TB',expand_nested=False, dpi=60, subgraph=False).create(prog='dot',format='svg'))" }, { "code": null, "e": 5689, "s": 5673, "text": "Output Snippet:" }, { "code": null, "e": 7586, "s": 5689, "text": "# import necessary layers from tensorflow.keras.layers import Input, Conv2D from tensorflow.keras.layers import MaxPool2D, Flatten, Dense from tensorflow.keras import Model# inputinput = Input(shape =(224,224,3))# 1st Conv Blockx = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(input)x = Conv2D (filters =64, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 2nd Conv Blockx = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =128, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 3rd Conv blockx = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =256, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 4th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# 5th Conv blockx = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = Conv2D (filters =512, kernel_size =3, padding ='same', activation='relu')(x)x = MaxPool2D(pool_size =2, strides =2, padding ='same')(x)# Fully connected layersx = Flatten()(x)x = Dense(units = 4096, activation ='relu')(x)x = Dense(units = 4096, activation ='relu')(x)output = Dense(units = 1000, activation ='softmax')(x)# creating the modelmodel = Model (inputs=input, outputs =output)model.summary()" }, { "code": null, "e": 7598, "s": 7586, "text": "Conclusion:" }, { "code": null, "e": 7837, "s": 7598, "text": "The VGG network is a very simple Convolutional Neural Network, and due to its simplicity is very easy to implement using Tensorflow. It has only Conv2D, MaxPooling, and Dense layers. VGG 16 has a total of 138 million trainable parameters." }, { "code": null, "e": 8089, "s": 7837, "text": "VGG was the deepest CNN model architecture during its publication with a maximum of 19 weight layers. It achieved state-of-the-art performance in the ImageNet challenge and showed that deeper networks are beneficial for better classification accuracy." }, { "code": null, "e": 8101, "s": 8089, "text": "References:" }, { "code": null, "e": 8239, "s": 8101, "text": "Karen Simonyan and Andrew Zisserman, Very Deep Convolutional Networks for Large-Scale Image Recognition, arXiv:1409.1556v6 [cs.CV], 2015." } ]
Find duplicates in O(n) time and O(1) extra space | Set 1 - GeeksforGeeks
08 Apr, 2022 Given an array of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. Example: Input : n = 7 and array[] = {1, 2, 3, 6, 3, 6, 1} Output: 1, 3, 6 Explanation: The numbers 1 , 3 and 6 appears more than once in the array. Input : n = 5 and array[] = {1, 2, 3, 4 ,3} Output: 3 Explanation: The number 3 appears more than once in the array. This problem is an extended version of the following problem. Find the two repeating elements in a given array Method 1 and Method 2 of the above link are not applicable as the question says O(n) time complexity and O(1) constant space. Also, Method 3 and Method 4 cannot be applied here because there can be more than 2 repeating elements in this problem. Method 5 can be extended to work for this problem. Below is the solution that is similar to Method 5. Solution 1: Approach:The elements in the array is from 0 to n-1 and all of them are positive. So to find out the duplicate elements, a HashMap is required, but the question is to solve the problem in constant space. There is a catch, the array is of length n and the elements are from 0 to n-1 (n elements). The array can be used as a HashMap. Problem in the below approach. This approach only works for arrays having at most 2 duplicate elements i.e It will not work if the array contains more than 2 duplicates of an element. For example: {1, 6, 3, 1, 3, 6, 6} it will give output as : 1 3 6 6. Note: The above program doesn’t handle 0 cases (If 0 is present in array). The program can be easily modified to handle that also. It is not handled to keep the code simple. (Program can be modified to handle 0 cases by adding plus One(+1) to all the values. also subtracting One from the answer and by writing { arr [abs(arr[i]) – 1] } in code) In other approach below, the discussed solution prints repeating elements only once. Approach: The basic idea is to use a HashMap to solve the problem. But there is a catch, the numbers in the array are from 0 to n-1, and the input array has length n. So, the input array can be used as a HashMap. While Traversing the array, if an element ‘a’ is encountered then increase the value of a%n‘th element by n. The frequency can be retrieved by dividing the a % n’th element by n. Algorithm: Traverse the given array from start to end.For every element in the array increment the arr[i]%n‘th element by n.Now traverse the array again and print all those indexes i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that indexThis approach works because all elements are in the range from 0 to n-1 and arr[i] would be greater than n only if a value “i” has appeared more than once. Traverse the given array from start to end.For every element in the array increment the arr[i]%n‘th element by n.Now traverse the array again and print all those indexes i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that indexThis approach works because all elements are in the range from 0 to n-1 and arr[i] would be greater than n only if a value “i” has appeared more than once. Traverse the given array from start to end. For every element in the array increment the arr[i]%n‘th element by n. Now traverse the array again and print all those indexes i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that index This approach works because all elements are in the range from 0 to n-1 and arr[i] would be greater than n only if a value “i” has appeared more than once. Implementation: C++ C Java Python C# Javascript // C++ code to find// duplicates in O(n) time#include <bits/stdc++.h>using namespace std; int main(){ int numRay[] = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; int arr_size = sizeof(numRay) / sizeof(numRay[0]); // count the frequency for (int i = 0; i < arr_size; i++) { numRay[numRay[i] % arr_size] = numRay[numRay[i] % arr_size] + arr_size; } cout << "The repeating elements are : " << endl; for (int i = 0; i < arr_size; i++) { if (numRay[i] >= arr_size * 2) { cout << i << " " << endl; } } return 0;} // This code is contributed by aditya kumar (adityakumar129) // C++ code to find// duplicates in O(n) time #include <stdio.h> int main(){ int numRay[] = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; int arr_size = sizeof(numRay) / sizeof(numRay[0]); // count the frequency for (int i = 0; i < arr_size; i++) { numRay[numRay[i] % arr_size] = numRay[numRay[i] % arr_size] + arr_size; } printf("The repeating elements are : \n"); for (int i = 0; i < arr_size; i++) { if (numRay[i] >= arr_size * 2) { printf("%d \n", i ); } } return 0;}// This code is contributed by aditya kumar (adityakumar129) // JAVA code to find// duplicates in O(n) time class Leet442 { public static void main(String args[]) { int numRay[] = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; for (int i = 0; i < numRay.length; i++) { numRay[numRay[i] % numRay.length] = numRay[numRay[i] % numRay.length] + numRay.length; } System.out.println("The repeating elements are : "); for (int i = 0; i < numRay.length; i++) { if (numRay[i] >= numRay.length * 2) { System.out.println(i + " "); } } }} # Python3 code to find duplicates in O(n) timenumRay = [0, 4, 3, 2, 7, 8, 2, 3, 1]arr_size = len(numRay)for i in range(arr_size): x = numRay[i] % arr_size numRay[x] = numRay[x] + arr_size print("The repeating elements are : ")for i in range(arr_size): if (numRay[i] >= arr_size*2): print(i, " ") # This code is contributed by 29AjayKumar // C# code to find// duplicates in O(n) timeusing System;class Leet442{ public static void Main(String []args) { int []numRay = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; for (int i = 0; i < numRay.Length; i++) { numRay[numRay[i] % numRay.Length] = numRay[numRay[i] % numRay.Length] + numRay.Length; } Console.WriteLine("The repeating elements are : "); for (int i = 0; i < numRay.Length; i++) { if (numRay[i] >= numRay.Length * 2) { Console.WriteLine(i + " "); } } }} // This code is contributed by shivanisinghss2110 <script> // Javascript code to find // duplicates in O(n) time let numRay = [ 0, 4, 3, 2, 7, 8, 2, 3, 1 ]; let arr_size = numRay.length; // count the frequency for (let i = 0; i < arr_size; i++) { numRay[numRay[i] % arr_size] = numRay[numRay[i] % arr_size] + arr_size; } document.write("The repeating elements are : " + "</br>"); for (let i = 0; i < arr_size; i++) { if (numRay[i] >= arr_size * 2) { document.write(i + " " + "</br>"); } } // This code is contributed by mukesh07.</script> Output: The repeating elements are : 2 3 Complexity Analysis: Time Complexity: O(n). Only two traversals are needed. So the time complexity is O(n). Auxiliary Space: O(1). No extra space is needed, so the space complexity is constant. Sriharsha Sammeta Sam007 Akanksha_Rai kenbrooker Rajput-Ji princiraj1992 29AjayKumar andrew1234 ApurvaKhatri khyati_ shivanisinghss2110 surbhityagi15 mukesh07 rathod009 adityakumar129 Amazon Paytm Qualcomm Zoho Arrays Paytm Zoho Amazon Qualcomm Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Python | Using 2D arrays/lists the right way Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Maximum and minimum of an array using minimum number of comparisons Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 24869, "s": 24841, "text": "\n08 Apr, 2022" }, { "code": null, "e": 25068, "s": 24869, "text": "Given an array of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space." }, { "code": null, "e": 25078, "s": 25068, "text": "Example: " }, { "code": null, "e": 25338, "s": 25078, "text": "Input : n = 7 and array[] = {1, 2, 3, 6, 3, 6, 1}\nOutput: 1, 3, 6\n\nExplanation: The numbers 1 , 3 and 6 appears more\nthan once in the array.\n\nInput : n = 5 and array[] = {1, 2, 3, 4 ,3}\nOutput: 3\n\nExplanation: The number 3 appears more than once\nin the array." }, { "code": null, "e": 25797, "s": 25338, "text": "This problem is an extended version of the following problem. Find the two repeating elements in a given array Method 1 and Method 2 of the above link are not applicable as the question says O(n) time complexity and O(1) constant space. Also, Method 3 and Method 4 cannot be applied here because there can be more than 2 repeating elements in this problem. Method 5 can be extended to work for this problem. Below is the solution that is similar to Method 5." }, { "code": null, "e": 25809, "s": 25797, "text": "Solution 1:" }, { "code": null, "e": 26394, "s": 25809, "text": "Approach:The elements in the array is from 0 to n-1 and all of them are positive. So to find out the duplicate elements, a HashMap is required, but the question is to solve the problem in constant space. There is a catch, the array is of length n and the elements are from 0 to n-1 (n elements). The array can be used as a HashMap. Problem in the below approach. This approach only works for arrays having at most 2 duplicate elements i.e It will not work if the array contains more than 2 duplicates of an element. For example: {1, 6, 3, 1, 3, 6, 6} it will give output as : 1 3 6 6." }, { "code": null, "e": 26740, "s": 26394, "text": "Note: The above program doesn’t handle 0 cases (If 0 is present in array). The program can be easily modified to handle that also. It is not handled to keep the code simple. (Program can be modified to handle 0 cases by adding plus One(+1) to all the values. also subtracting One from the answer and by writing { arr [abs(arr[i]) – 1] } in code)" }, { "code": null, "e": 26825, "s": 26740, "text": "In other approach below, the discussed solution prints repeating elements only once." }, { "code": null, "e": 27217, "s": 26825, "text": "Approach: The basic idea is to use a HashMap to solve the problem. But there is a catch, the numbers in the array are from 0 to n-1, and the input array has length n. So, the input array can be used as a HashMap. While Traversing the array, if an element ‘a’ is encountered then increase the value of a%n‘th element by n. The frequency can be retrieved by dividing the a % n’th element by n." }, { "code": null, "e": 27657, "s": 27217, "text": "Algorithm: Traverse the given array from start to end.For every element in the array increment the arr[i]%n‘th element by n.Now traverse the array again and print all those indexes i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that indexThis approach works because all elements are in the range from 0 to n-1 and arr[i] would be greater than n only if a value “i” has appeared more than once." }, { "code": null, "e": 28086, "s": 27657, "text": "Traverse the given array from start to end.For every element in the array increment the arr[i]%n‘th element by n.Now traverse the array again and print all those indexes i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that indexThis approach works because all elements are in the range from 0 to n-1 and arr[i] would be greater than n only if a value “i” has appeared more than once." }, { "code": null, "e": 28130, "s": 28086, "text": "Traverse the given array from start to end." }, { "code": null, "e": 28201, "s": 28130, "text": "For every element in the array increment the arr[i]%n‘th element by n." }, { "code": null, "e": 28362, "s": 28201, "text": "Now traverse the array again and print all those indexes i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that index" }, { "code": null, "e": 28518, "s": 28362, "text": "This approach works because all elements are in the range from 0 to n-1 and arr[i] would be greater than n only if a value “i” has appeared more than once." }, { "code": null, "e": 28535, "s": 28518, "text": "Implementation: " }, { "code": null, "e": 28539, "s": 28535, "text": "C++" }, { "code": null, "e": 28541, "s": 28539, "text": "C" }, { "code": null, "e": 28546, "s": 28541, "text": "Java" }, { "code": null, "e": 28553, "s": 28546, "text": "Python" }, { "code": null, "e": 28556, "s": 28553, "text": "C#" }, { "code": null, "e": 28567, "s": 28556, "text": "Javascript" }, { "code": "// C++ code to find// duplicates in O(n) time#include <bits/stdc++.h>using namespace std; int main(){ int numRay[] = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; int arr_size = sizeof(numRay) / sizeof(numRay[0]); // count the frequency for (int i = 0; i < arr_size; i++) { numRay[numRay[i] % arr_size] = numRay[numRay[i] % arr_size] + arr_size; } cout << \"The repeating elements are : \" << endl; for (int i = 0; i < arr_size; i++) { if (numRay[i] >= arr_size * 2) { cout << i << \" \" << endl; } } return 0;} // This code is contributed by aditya kumar (adityakumar129)", "e": 29191, "s": 28567, "text": null }, { "code": "// C++ code to find// duplicates in O(n) time #include <stdio.h> int main(){ int numRay[] = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; int arr_size = sizeof(numRay) / sizeof(numRay[0]); // count the frequency for (int i = 0; i < arr_size; i++) { numRay[numRay[i] % arr_size] = numRay[numRay[i] % arr_size] + arr_size; } printf(\"The repeating elements are : \\n\"); for (int i = 0; i < arr_size; i++) { if (numRay[i] >= arr_size * 2) { printf(\"%d \\n\", i ); } } return 0;}// This code is contributed by aditya kumar (adityakumar129)", "e": 29786, "s": 29191, "text": null }, { "code": "// JAVA code to find// duplicates in O(n) time class Leet442 { public static void main(String args[]) { int numRay[] = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; for (int i = 0; i < numRay.length; i++) { numRay[numRay[i] % numRay.length] = numRay[numRay[i] % numRay.length] + numRay.length; } System.out.println(\"The repeating elements are : \"); for (int i = 0; i < numRay.length; i++) { if (numRay[i] >= numRay.length * 2) { System.out.println(i + \" \"); } } }}", "e": 30369, "s": 29786, "text": null }, { "code": "# Python3 code to find duplicates in O(n) timenumRay = [0, 4, 3, 2, 7, 8, 2, 3, 1]arr_size = len(numRay)for i in range(arr_size): x = numRay[i] % arr_size numRay[x] = numRay[x] + arr_size print(\"The repeating elements are : \")for i in range(arr_size): if (numRay[i] >= arr_size*2): print(i, \" \") # This code is contributed by 29AjayKumar", "e": 30724, "s": 30369, "text": null }, { "code": "// C# code to find// duplicates in O(n) timeusing System;class Leet442{ public static void Main(String []args) { int []numRay = { 0, 4, 3, 2, 7, 8, 2, 3, 1 }; for (int i = 0; i < numRay.Length; i++) { numRay[numRay[i] % numRay.Length] = numRay[numRay[i] % numRay.Length] + numRay.Length; } Console.WriteLine(\"The repeating elements are : \"); for (int i = 0; i < numRay.Length; i++) { if (numRay[i] >= numRay.Length * 2) { Console.WriteLine(i + \" \"); } } }} // This code is contributed by shivanisinghss2110", "e": 31386, "s": 30724, "text": null }, { "code": "<script> // Javascript code to find // duplicates in O(n) time let numRay = [ 0, 4, 3, 2, 7, 8, 2, 3, 1 ]; let arr_size = numRay.length; // count the frequency for (let i = 0; i < arr_size; i++) { numRay[numRay[i] % arr_size] = numRay[numRay[i] % arr_size] + arr_size; } document.write(\"The repeating elements are : \" + \"</br>\"); for (let i = 0; i < arr_size; i++) { if (numRay[i] >= arr_size * 2) { document.write(i + \" \" + \"</br>\"); } } // This code is contributed by mukesh07.</script>", "e": 31956, "s": 31386, "text": null }, { "code": null, "e": 31965, "s": 31956, "text": "Output: " }, { "code": null, "e": 32000, "s": 31965, "text": "The repeating elements are : \n2 \n3" }, { "code": null, "e": 32022, "s": 32000, "text": "Complexity Analysis: " }, { "code": null, "e": 32109, "s": 32022, "text": "Time Complexity: O(n). Only two traversals are needed. So the time complexity is O(n)." }, { "code": null, "e": 32195, "s": 32109, "text": "Auxiliary Space: O(1). No extra space is needed, so the space complexity is constant." }, { "code": null, "e": 32213, "s": 32195, "text": "Sriharsha Sammeta" }, { "code": null, "e": 32220, "s": 32213, "text": "Sam007" }, { "code": null, "e": 32233, "s": 32220, "text": "Akanksha_Rai" }, { "code": null, "e": 32244, "s": 32233, "text": "kenbrooker" }, { "code": null, "e": 32254, "s": 32244, "text": "Rajput-Ji" }, { "code": null, "e": 32268, "s": 32254, "text": "princiraj1992" }, { "code": null, "e": 32280, "s": 32268, "text": "29AjayKumar" }, { "code": null, "e": 32291, "s": 32280, "text": "andrew1234" }, { "code": null, "e": 32304, "s": 32291, "text": "ApurvaKhatri" }, { "code": null, "e": 32312, "s": 32304, "text": "khyati_" }, { "code": null, "e": 32331, "s": 32312, "text": "shivanisinghss2110" }, { "code": null, "e": 32345, "s": 32331, "text": "surbhityagi15" }, { "code": null, "e": 32354, "s": 32345, "text": "mukesh07" }, { "code": null, "e": 32364, "s": 32354, "text": "rathod009" }, { "code": null, "e": 32379, "s": 32364, "text": "adityakumar129" }, { "code": null, "e": 32386, "s": 32379, "text": "Amazon" }, { "code": null, "e": 32392, "s": 32386, "text": "Paytm" }, { "code": null, "e": 32401, "s": 32392, "text": "Qualcomm" }, { "code": null, "e": 32406, "s": 32401, "text": "Zoho" }, { "code": null, "e": 32413, "s": 32406, "text": "Arrays" }, { "code": null, "e": 32419, "s": 32413, "text": "Paytm" }, { "code": null, "e": 32424, "s": 32419, "text": "Zoho" }, { "code": null, "e": 32431, "s": 32424, "text": "Amazon" }, { "code": null, "e": 32440, "s": 32431, "text": "Qualcomm" }, { "code": null, "e": 32447, "s": 32440, "text": "Arrays" }, { "code": null, "e": 32545, "s": 32447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32554, "s": 32545, "text": "Comments" }, { "code": null, "e": 32567, "s": 32554, "text": "Old Comments" }, { "code": null, "e": 32615, "s": 32567, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32659, "s": 32615, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32682, "s": 32659, "text": "Introduction to Arrays" }, { "code": null, "e": 32714, "s": 32682, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32728, "s": 32714, "text": "Linear Search" }, { "code": null, "e": 32749, "s": 32728, "text": "Linked List vs Array" }, { "code": null, "e": 32794, "s": 32749, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 32879, "s": 32794, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 32947, "s": 32879, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
Good Grams: How to Find Predictive N-Grams for your Problem | by Nicolas Bertagnolli | Towards Data Science
Nowadays NLP feels like it’s just about applying BERT and getting state of the art results on your problem. Often times, I find that grabbing a few good informative words can help too. Usually, I’ll have an expert come to me and say these five words are really predictive for this class. Then I’ll use those words as features, and voila! You get some performance improvements or a little bit more interpretability. But what do you do if you don’t have a domain expert? One easy thing I like to try is to train a simple linear model on the TF-IDF features and take the top n words or n-grams : ). In this blog post we’ll: Train a simple model using SciKit-Learn and get the most informative n-gram featuresThen run some performance comparisons on models with different numbers of features. Train a simple model using SciKit-Learn and get the most informative n-gram features Then run some performance comparisons on models with different numbers of features. By the end of this tutorial hopefully, you’ll have a fun new tool for uncovering good features for text classification. Let’s get started. Use a linear classifier on SciKit-Learn’s TfidfVectorizer then sort the features by their weight and take the top n. You can also use the TfidfVectorizer to extract only a subset of n-grams for your model by using the vocabulary parameter. One very successful way to classify text is to look for predictive words, or short phrases, that are relevant to the problem. In the context of say movie review sentiment, we could look for the words “good”, “excellent”, “great”, or “perfect” to find good reviews and “bad”, “boring”, or “awful” to find bad reviews. As subject matter experts in good and bad movie reviews, it was easy for us to come up with these features. More often than not, I am not a subject matter expert and it’s hard for me to determine what good predictive words or phrases might be. When this happens, and I have labeled data, there is a quick way to find descriptive words and phrases. Just train a linear model and sort the weights! SciKit-Learn makes it very easy to train a linear model and extract the associated weights. Let’s look at training a model on the IMDB sentiment dataset. df = pd.read_csv("IMDB_Dataset.csv")df["split"] = np.random.choice(["train", "val", "test"], df.shape[0], [.7, .15, .15])x_train = df[df["split"] == "train"]y_train = x_train["sentiment"]x_val = df[df["split"] == "val"]y_val = x_val["sentiment"]classifier = svm.LinearSVC(C=1.0, class_weight="balanced")tf_idf = Pipeline([ ('tfidf', TfidfVectorizer()), ("classifier", classifier) ])tf_idf.fit(x_train["review"], y_train) This model only takes a few seconds to train but gets a pretty decent F-score of .88 only using unigrams. With this new model, we can find the most predictive features by simply grabbing the coefficient names from the TF-IDF Transformer and the coefficient values from our SVM. coefs = tf_idf.named_steps["classifier"].coef_if type(coefs) == csr_matrix: coefs.toarray().tolist()[0]else: coefs.tolist()feature_names = tf_idf.named_steps["tfidf"].get_feature_names()coefs_and_features = list(zip(coefs[0], feature_names))# Most positive featuressorted(coefs_and_features, key=lambda x: x[0], reverse=True)# Most negative featuressorted(coefs_and_features, key=lambda x: x[0])# Most predictive overallsorted(coefs_and_features, key=lambda x: abs(x[0]), reverse=True) We can grab the weights our model gives to each feature by accessing the “classifier” named step in our pipeline. When creating a pipeline we name each step in the process so that we can access them with this named_steps function. Most SciKit-Learn models have a .coef_ parameter which will return the coefficients of the model that we can use to find what is most predictive. I do a little type checking around sparse matrices for convenience because these types of lexical features can be very very sparse. The feature names are stored in the tfidf step of our pipeline we access it the same way as the classifier but call the get_feature_names function instead. Our top ten positive words are: [(3.482397353551051, 'excellent'), (3.069350528649819, 'great'), (2.515865496104781, 'loved'), (2.470404287610431, 'best'), (2.4634974085860115, 'amazing'), (2.421134741115058, 'enjoyable'), (2.2237089115789166, 'perfect'), (2.196802503474607, 'fun'), (2.1811330282241426, 'today'), (2.1407707555282363, 'highly')] and our top ten negative words are: [(-5.115103657971178, 'worst'), (-4.486712890495122, 'awful'), (-3.676776745907702, 'terrible'), (-3.5051277582046536, 'bad'), (-3.4949920792779157, 'waste'), (-3.309000819824398, 'boring'), (-3.2772982524056973, 'poor'), (-2.9054813685114307, 'dull'), (-2.7129398526527253, 'nothing'), (-2.710497534821449, 'fails')] Now that we’ve discovered some “good” features we can build even simpler models, or use these as features in other problems in a similar domain. Let’s build some simple rules that will return 1 if any of these predictive words are present in a review and 0 otherwise. Then retrain the model with only those 20 features and see how we do. To do this I created a simple SciKit-Learn transformer which converts a list of n-grams to regex rules which NLTK’s tokenizer can search for. It’s not super fast (That’s an understatement it’s really slow. You should use the vocabulary parameter in the TfidfVectorizer instead, more to come.) but it’s easy to read and gets the job done. There are three main parts of this code. Line 11 converts a tuple representing an n-gram so something like (“good”, “movie”) into a regex r”<good><movie>” which NLTK can use to search the text for that specific n-gram. It’s basically just a list comprehension stepping through all the n-grams with a foldl concatenating the words into a regex. Lines 13–26 perform the transformation by stopping through every sentence, or review in this case, in our input and applying each regex to that sentence. If the regex finds something it places a one in a list at the position corresponding to the n-gram that fired. This will produce a vector with 1’s and 0’s representing which n-grams are present in which sentences. Lines 28–29 allow us to get the relevant feature names as we did before. It’s just convenient. With this new handy-dandy transformer, we can retrain our model using just those top ten best, and bottom ten worst words. n_grams = [('excellent',), ('great',), ('perfect',), ('best',), ('brilliant',), ('surprised',), ('hilarious',), ('loved',), ('today',), ('superb',), ('worst',), ('awful',), ('waste',), ('poor',), ('boring',), ('bad',), ('disappointment',), ('poorly',), ('horrible',), ('bored',)]classifier = svm.LinearSVC(C=1.0, class_weight="balanced")rules = Pipeline([ ('rules', RuleTransformer(n_grams)), ("classifier", classifier) ])rules.fit(x_train["review"], y_train) These 20 features decrease our F1 by about .13 which may seem like a lot, but we are only using .03% of the original 65,247 words. That’s pretty neat! These 20 features encode a majority of the information in our data and we could use them as features in other pipelines! I built that rule vectorizer above but we can get the same results by using the TfidfVectorizer and passing in a vocabulary parameter. The original SciKit-Learn vectorizer takes a parameter called vocabulary which accepts a dictionary mapping individual words, or n-grams separated by spaces, to integers. So to get the same effect we could have run: top_feats = sorted(coefs_and_features, key=lambda x: abs(x[0]), reverse=True)[:20]vocab = {x[1]: i for i, x in enumerate(top_feats)}TfidfVectorizer(vocabulary=vocab) Here we get the sorted list of features, then we create a map from feature name to integer index and pass it to the vectorizer. If you’re curious about what the map looks like it’s something like this: {"great": 0, "poor": 1, "very poor": 2, "very poor performance": 3} N-grams are represented by adding a space between the words. If we use the above code instead of our RuleTransformer we’ll get the same results in a fraction of the time. Those 20 words seem to be pretty powerful. They can get us .79 F1 right out of the gate, but maybe 20 wasn’t the right number of features. We can find out by running our classifier on more and more of the top features and plotting the F1. This shows us that the model starts to converge to the best TF-IDF unigram performance after about 13k of the most predictive words. So we can get the same performance with only 20% of our original feature set! Going forward using these 13k features is a more principled number and we still get a massive reduction in the number of original features. If we are looking at purely lexical features, specific words, and their counts, then this can be a nice way of uncovering useful words and phrases. Language is much more complicated than simply the words you use. It’s important to look at all kinds of information when designing real systems. Use BERT, use syntactic features like how the sentence parses. There is so much more to language than just the raw words, but hopefully, this little trick can help you find some good words when you’re stuck.
[ { "code": null, "e": 768, "s": 172, "text": "Nowadays NLP feels like it’s just about applying BERT and getting state of the art results on your problem. Often times, I find that grabbing a few good informative words can help too. Usually, I’ll have an expert come to me and say these five words are really predictive for this class. Then I’ll use those words as features, and voila! You get some performance improvements or a little bit more interpretability. But what do you do if you don’t have a domain expert? One easy thing I like to try is to train a simple linear model on the TF-IDF features and take the top n words or n-grams : )." }, { "code": null, "e": 793, "s": 768, "text": "In this blog post we’ll:" }, { "code": null, "e": 961, "s": 793, "text": "Train a simple model using SciKit-Learn and get the most informative n-gram featuresThen run some performance comparisons on models with different numbers of features." }, { "code": null, "e": 1046, "s": 961, "text": "Train a simple model using SciKit-Learn and get the most informative n-gram features" }, { "code": null, "e": 1130, "s": 1046, "text": "Then run some performance comparisons on models with different numbers of features." }, { "code": null, "e": 1269, "s": 1130, "text": "By the end of this tutorial hopefully, you’ll have a fun new tool for uncovering good features for text classification. Let’s get started." }, { "code": null, "e": 1509, "s": 1269, "text": "Use a linear classifier on SciKit-Learn’s TfidfVectorizer then sort the features by their weight and take the top n. You can also use the TfidfVectorizer to extract only a subset of n-grams for your model by using the vocabulary parameter." }, { "code": null, "e": 1934, "s": 1509, "text": "One very successful way to classify text is to look for predictive words, or short phrases, that are relevant to the problem. In the context of say movie review sentiment, we could look for the words “good”, “excellent”, “great”, or “perfect” to find good reviews and “bad”, “boring”, or “awful” to find bad reviews. As subject matter experts in good and bad movie reviews, it was easy for us to come up with these features." }, { "code": null, "e": 2222, "s": 1934, "text": "More often than not, I am not a subject matter expert and it’s hard for me to determine what good predictive words or phrases might be. When this happens, and I have labeled data, there is a quick way to find descriptive words and phrases. Just train a linear model and sort the weights!" }, { "code": null, "e": 2376, "s": 2222, "text": "SciKit-Learn makes it very easy to train a linear model and extract the associated weights. Let’s look at training a model on the IMDB sentiment dataset." }, { "code": null, "e": 2805, "s": 2376, "text": "df = pd.read_csv(\"IMDB_Dataset.csv\")df[\"split\"] = np.random.choice([\"train\", \"val\", \"test\"], df.shape[0], [.7, .15, .15])x_train = df[df[\"split\"] == \"train\"]y_train = x_train[\"sentiment\"]x_val = df[df[\"split\"] == \"val\"]y_val = x_val[\"sentiment\"]classifier = svm.LinearSVC(C=1.0, class_weight=\"balanced\")tf_idf = Pipeline([ ('tfidf', TfidfVectorizer()), (\"classifier\", classifier) ])tf_idf.fit(x_train[\"review\"], y_train)" }, { "code": null, "e": 2911, "s": 2805, "text": "This model only takes a few seconds to train but gets a pretty decent F-score of .88 only using unigrams." }, { "code": null, "e": 3083, "s": 2911, "text": "With this new model, we can find the most predictive features by simply grabbing the coefficient names from the TF-IDF Transformer and the coefficient values from our SVM." }, { "code": null, "e": 3575, "s": 3083, "text": "coefs = tf_idf.named_steps[\"classifier\"].coef_if type(coefs) == csr_matrix: coefs.toarray().tolist()[0]else: coefs.tolist()feature_names = tf_idf.named_steps[\"tfidf\"].get_feature_names()coefs_and_features = list(zip(coefs[0], feature_names))# Most positive featuressorted(coefs_and_features, key=lambda x: x[0], reverse=True)# Most negative featuressorted(coefs_and_features, key=lambda x: x[0])# Most predictive overallsorted(coefs_and_features, key=lambda x: abs(x[0]), reverse=True)" }, { "code": null, "e": 4240, "s": 3575, "text": "We can grab the weights our model gives to each feature by accessing the “classifier” named step in our pipeline. When creating a pipeline we name each step in the process so that we can access them with this named_steps function. Most SciKit-Learn models have a .coef_ parameter which will return the coefficients of the model that we can use to find what is most predictive. I do a little type checking around sparse matrices for convenience because these types of lexical features can be very very sparse. The feature names are stored in the tfidf step of our pipeline we access it the same way as the classifier but call the get_feature_names function instead." }, { "code": null, "e": 4272, "s": 4240, "text": "Our top ten positive words are:" }, { "code": null, "e": 4587, "s": 4272, "text": "[(3.482397353551051, 'excellent'), (3.069350528649819, 'great'), (2.515865496104781, 'loved'), (2.470404287610431, 'best'), (2.4634974085860115, 'amazing'), (2.421134741115058, 'enjoyable'), (2.2237089115789166, 'perfect'), (2.196802503474607, 'fun'), (2.1811330282241426, 'today'), (2.1407707555282363, 'highly')]" }, { "code": null, "e": 4623, "s": 4587, "text": "and our top ten negative words are:" }, { "code": null, "e": 4941, "s": 4623, "text": "[(-5.115103657971178, 'worst'), (-4.486712890495122, 'awful'), (-3.676776745907702, 'terrible'), (-3.5051277582046536, 'bad'), (-3.4949920792779157, 'waste'), (-3.309000819824398, 'boring'), (-3.2772982524056973, 'poor'), (-2.9054813685114307, 'dull'), (-2.7129398526527253, 'nothing'), (-2.710497534821449, 'fails')]" }, { "code": null, "e": 5279, "s": 4941, "text": "Now that we’ve discovered some “good” features we can build even simpler models, or use these as features in other problems in a similar domain. Let’s build some simple rules that will return 1 if any of these predictive words are present in a review and 0 otherwise. Then retrain the model with only those 20 features and see how we do." }, { "code": null, "e": 5617, "s": 5279, "text": "To do this I created a simple SciKit-Learn transformer which converts a list of n-grams to regex rules which NLTK’s tokenizer can search for. It’s not super fast (That’s an understatement it’s really slow. You should use the vocabulary parameter in the TfidfVectorizer instead, more to come.) but it’s easy to read and gets the job done." }, { "code": null, "e": 5658, "s": 5617, "text": "There are three main parts of this code." }, { "code": null, "e": 5961, "s": 5658, "text": "Line 11 converts a tuple representing an n-gram so something like (“good”, “movie”) into a regex r”<good><movie>” which NLTK can use to search the text for that specific n-gram. It’s basically just a list comprehension stepping through all the n-grams with a foldl concatenating the words into a regex." }, { "code": null, "e": 6329, "s": 5961, "text": "Lines 13–26 perform the transformation by stopping through every sentence, or review in this case, in our input and applying each regex to that sentence. If the regex finds something it places a one in a list at the position corresponding to the n-gram that fired. This will produce a vector with 1’s and 0’s representing which n-grams are present in which sentences." }, { "code": null, "e": 6424, "s": 6329, "text": "Lines 28–29 allow us to get the relevant feature names as we did before. It’s just convenient." }, { "code": null, "e": 6547, "s": 6424, "text": "With this new handy-dandy transformer, we can retrain our model using just those top ten best, and bottom ten worst words." }, { "code": null, "e": 7075, "s": 6547, "text": "n_grams = [('excellent',), ('great',), ('perfect',), ('best',), ('brilliant',), ('surprised',), ('hilarious',), ('loved',), ('today',), ('superb',), ('worst',), ('awful',), ('waste',), ('poor',), ('boring',), ('bad',), ('disappointment',), ('poorly',), ('horrible',), ('bored',)]classifier = svm.LinearSVC(C=1.0, class_weight=\"balanced\")rules = Pipeline([ ('rules', RuleTransformer(n_grams)), (\"classifier\", classifier) ])rules.fit(x_train[\"review\"], y_train)" }, { "code": null, "e": 7347, "s": 7075, "text": "These 20 features decrease our F1 by about .13 which may seem like a lot, but we are only using .03% of the original 65,247 words. That’s pretty neat! These 20 features encode a majority of the information in our data and we could use them as features in other pipelines!" }, { "code": null, "e": 7698, "s": 7347, "text": "I built that rule vectorizer above but we can get the same results by using the TfidfVectorizer and passing in a vocabulary parameter. The original SciKit-Learn vectorizer takes a parameter called vocabulary which accepts a dictionary mapping individual words, or n-grams separated by spaces, to integers. So to get the same effect we could have run:" }, { "code": null, "e": 7900, "s": 7698, "text": "top_feats = sorted(coefs_and_features, key=lambda x: abs(x[0]), reverse=True)[:20]vocab = {x[1]: i for i, x in enumerate(top_feats)}TfidfVectorizer(vocabulary=vocab)" }, { "code": null, "e": 8102, "s": 7900, "text": "Here we get the sorted list of features, then we create a map from feature name to integer index and pass it to the vectorizer. If you’re curious about what the map looks like it’s something like this:" }, { "code": null, "e": 8170, "s": 8102, "text": "{\"great\": 0, \"poor\": 1, \"very poor\": 2, \"very poor performance\": 3}" }, { "code": null, "e": 8341, "s": 8170, "text": "N-grams are represented by adding a space between the words. If we use the above code instead of our RuleTransformer we’ll get the same results in a fraction of the time." }, { "code": null, "e": 8580, "s": 8341, "text": "Those 20 words seem to be pretty powerful. They can get us .79 F1 right out of the gate, but maybe 20 wasn’t the right number of features. We can find out by running our classifier on more and more of the top features and plotting the F1." }, { "code": null, "e": 8931, "s": 8580, "text": "This shows us that the model starts to converge to the best TF-IDF unigram performance after about 13k of the most predictive words. So we can get the same performance with only 20% of our original feature set! Going forward using these 13k features is a more principled number and we still get a massive reduction in the number of original features." } ]
How to combine columns by excluding missing values in R?
If we have a data set that contains missing values at alternate places for each column then we might want to combine the columns by excluding those missing values, this will reduce the data set and the analysis is likely to become easier. For this purpose, we can use na.exclude function along with apply function as shown in the below given examples. Following snippet creates a sample data frame − x1<-rep(c(NA,2,10),times=c(5,10,5)) x2<-rep(c(1,3,5,NA),times=c(5,5,5,5)) x3<-rep(c(10,NA,3),times=c(5,10,5)) df1<-data.frame(x1,x2,x3) df1 The following dataframe is created − x1 x2 x3 1 NA 1 10 2 NA 1 10 3 NA 1 10 4 NA 1 10 5 NA 1 10 6 2 3 NA 7 2 3 NA 8 2 3 NA 9 2 3 NA 10 2 3 NA 11 2 5 NA 12 2 5 NA 13 2 5 NA 14 2 5 NA 15 2 5 NA 16 10 NA 3 17 10 NA 3 18 10 NA 3 19 10 NA 3 20 10 NA 3 To exclude NA’s from df1 and combine the columns, add the following code to the above snippet − x1<-rep(c(NA,2,10),times=c(5,10,5)) x2<-rep(c(1,3,5,NA),times=c(5,5,5,5)) x3<-rep(c(10,NA,3),times=c(5,10,5)) df1<-data.frame(x1,x2,x3) t(apply(df1,1,na.exclude)) If you execute all the above given snippets as a single program, it generates the following output − [,1][,2] [1,] 1 10 [2,] 1 10 [3,] 1 10 [4,] 1 10 [5,] 1 10 [6,] 2 3 [7,] 2 3 [8,] 2 3 [9,] 2 3 [10,] 2 3 [11,] 2 5 [12,] 2 5 [13,] 2 5 [14,] 2 5 [15,] 2 5 [16,] 10 3 [17,] 10 3 [18,] 10 3 [19,] 10 3 [20,] 10 3 Following snippet creates a sample data frame − y1<-rep(c(NA,rnorm(5)),times=c(5,2,3,3,3,4)) y2<-rep(c(rnorm(2),NA),times=c(10,5,5)) y3<-rep(c(rnorm(1),NA,rnorm(1)),times=c(5,10,5)) df2<-data.frame(y1,y2,y3) df2 The following dataframe is created − y1 y2 y3 1 NA 0.1152603 -0.9838989 2 NA 0.1152603 -0.9838989 3 NA 0.1152603 -0.9838989 4 NA 0.1152603 -0.9838989 5 NA 0.1152603 -0.9838989 6 -0.74142593 0.1152603 NA 7 -0.74142593 0.1152603 NA 8 -1.88274271 0.1152603 NA 9 -1.88274271 0.1152603 NA 10 -1.88274271 0.1152603 NA 11 -0.09684216 -1.2886519 NA 12 -0.09684216 -1.2886519 NA 13 -0.09684216 -1.2886519 NA 14 -0.08528031 -1.2886519 NA 15 -0.08528031 -1.2886519 NA 16 -0.08528031 NA 0.1967864 17 -0.80126932 NA 0.1967864 18 -0.80126932 NA 0.1967864 19 -0.80126932 NA 0.1967864 20 -0.80126932 NA 0.1967864 To exclude NA’s from df2 and combine the columns, add the following code to the above snippet − y1<-rep(c(NA,rnorm(5)),times=c(5,2,3,3,3,4)) y2<-rep(c(rnorm(2),NA),times=c(10,5,5)) y3<-rep(c(rnorm(1),NA,rnorm(1)),times=c(5,10,5)) df2<-data.frame(y1,y2,y3) t(apply(df2,1,na.exclude)) If you execute all the above given snippets as a single program, it generates the following output − [,1] [,2] [1,] 0.11526026 -0.9838989 [2,] 0.11526026 -0.9838989 [3,] 0.11526026 -0.9838989 [4,] 0.11526026 -0.9838989 [5,] 0.11526026 -0.9838989 [6,] -0.74142593 0.1152603 [7,] -0.74142593 0.1152603 [8,] -1.88274271 0.1152603 [9,] -1.88274271 0.1152603 [10,] -1.88274271 0.1152603 [11,] -0.09684216 -1.2886519 [12,] -0.09684216 -1.2886519 [13,] -0.09684216 -1.2886519 [14,] -0.08528031 -1.2886519 [15,] -0.08528031 -1.2886519 [16,] -0.08528031 0.1967864 [17,] -0.80126932 0.1967864 [18,] -0.80126932 0.1967864 [19,] -0.80126932 0.1967864 [20,] -0.80126932 0.1967864
[ { "code": null, "e": 1301, "s": 1062, "text": "If we have a data set that contains missing values at alternate places for each column then we might want to combine the columns by excluding those missing values, this will reduce the data set and the analysis is likely to become easier." }, { "code": null, "e": 1414, "s": 1301, "text": "For this purpose, we can use na.exclude function along with apply function as shown in the below given examples." }, { "code": null, "e": 1462, "s": 1414, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1602, "s": 1462, "text": "x1<-rep(c(NA,2,10),times=c(5,10,5))\nx2<-rep(c(1,3,5,NA),times=c(5,5,5,5))\nx3<-rep(c(10,NA,3),times=c(5,10,5))\ndf1<-data.frame(x1,x2,x3)\ndf1" }, { "code": null, "e": 1639, "s": 1602, "text": "The following dataframe is created −" }, { "code": null, "e": 1892, "s": 1639, "text": " x1 x2 x3\n1 NA 1 10\n2 NA 1 10\n3 NA 1 10\n4 NA 1 10\n5 NA 1 10\n6 2 3 NA\n7 2 3 NA\n8 2 3 NA\n9 2 3 NA\n10 2 3 NA\n11 2 5 NA\n12 2 5 NA\n13 2 5 NA\n14 2 5 NA\n15 2 5 NA\n16 10 NA 3\n17 10 NA 3\n18 10 NA 3\n19 10 NA 3\n20 10 NA 3" }, { "code": null, "e": 1988, "s": 1892, "text": "To exclude NA’s from df1 and combine the columns, add the following code to the above snippet −" }, { "code": null, "e": 2151, "s": 1988, "text": "x1<-rep(c(NA,2,10),times=c(5,10,5))\nx2<-rep(c(1,3,5,NA),times=c(5,5,5,5))\nx3<-rep(c(10,NA,3),times=c(5,10,5))\ndf1<-data.frame(x1,x2,x3)\nt(apply(df1,1,na.exclude))" }, { "code": null, "e": 2252, "s": 2151, "text": "If you execute all the above given snippets as a single program, it generates the following output −" }, { "code": null, "e": 2547, "s": 2252, "text": " [,1][,2]\n[1,] 1 10\n[2,] 1 10\n[3,] 1 10\n[4,] 1 10\n[5,] 1 10\n[6,] 2 3\n[7,] 2 3\n[8,] 2 3\n[9,] 2 3\n[10,] 2 3\n[11,] 2 5\n[12,] 2 5\n[13,] 2 5\n[14,] 2 5\n[15,] 2 5\n[16,] 10 3\n[17,] 10 3\n[18,] 10 3\n[19,] 10 3\n[20,] 10 3" }, { "code": null, "e": 2595, "s": 2547, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 2759, "s": 2595, "text": "y1<-rep(c(NA,rnorm(5)),times=c(5,2,3,3,3,4))\ny2<-rep(c(rnorm(2),NA),times=c(10,5,5))\ny3<-rep(c(rnorm(1),NA,rnorm(1)),times=c(5,10,5))\ndf2<-data.frame(y1,y2,y3)\ndf2" }, { "code": null, "e": 2796, "s": 2759, "text": "The following dataframe is created −" }, { "code": null, "e": 3518, "s": 2796, "text": " y1 y2 y3\n1 NA 0.1152603 -0.9838989\n2 NA 0.1152603 -0.9838989\n3 NA 0.1152603 -0.9838989\n4 NA 0.1152603 -0.9838989\n5 NA 0.1152603 -0.9838989\n6 -0.74142593 0.1152603 NA\n7 -0.74142593 0.1152603 NA\n8 -1.88274271 0.1152603 NA\n9 -1.88274271 0.1152603 NA\n10 -1.88274271 0.1152603 NA\n11 -0.09684216 -1.2886519 NA\n12 -0.09684216 -1.2886519 NA\n13 -0.09684216 -1.2886519 NA\n14 -0.08528031 -1.2886519 NA\n15 -0.08528031 -1.2886519 NA\n16 -0.08528031 NA 0.1967864\n17 -0.80126932 NA 0.1967864\n18 -0.80126932 NA 0.1967864\n19 -0.80126932 NA 0.1967864\n20 -0.80126932 NA 0.1967864" }, { "code": null, "e": 3614, "s": 3518, "text": "To exclude NA’s from df2 and combine the columns, add the following code to the above snippet −" }, { "code": null, "e": 3801, "s": 3614, "text": "y1<-rep(c(NA,rnorm(5)),times=c(5,2,3,3,3,4))\ny2<-rep(c(rnorm(2),NA),times=c(10,5,5))\ny3<-rep(c(rnorm(1),NA,rnorm(1)),times=c(5,10,5))\ndf2<-data.frame(y1,y2,y3)\nt(apply(df2,1,na.exclude))" }, { "code": null, "e": 3902, "s": 3801, "text": "If you execute all the above given snippets as a single program, it generates the following output −" }, { "code": null, "e": 4528, "s": 3902, "text": " [,1] [,2]\n[1,] 0.11526026 -0.9838989\n[2,] 0.11526026 -0.9838989\n[3,] 0.11526026 -0.9838989\n[4,] 0.11526026 -0.9838989\n[5,] 0.11526026 -0.9838989\n[6,] -0.74142593 0.1152603\n[7,] -0.74142593 0.1152603\n[8,] -1.88274271 0.1152603\n[9,] -1.88274271 0.1152603\n[10,] -1.88274271 0.1152603\n[11,] -0.09684216 -1.2886519\n[12,] -0.09684216 -1.2886519\n[13,] -0.09684216 -1.2886519\n[14,] -0.08528031 -1.2886519\n[15,] -0.08528031 -1.2886519\n[16,] -0.08528031 0.1967864\n[17,] -0.80126932 0.1967864\n[18,] -0.80126932 0.1967864\n[19,] -0.80126932 0.1967864\n[20,] -0.80126932 0.1967864" } ]
Apache Camel - Introduction
Consider a situation where a large online grocery store in your town such as the Bigbasket in India invites you to design an IT solution for them. The stable and scalable solution will help them overcome the software maintenance problems they are facing today. This online store has been running its business for the last decade. The store accepts online orders for different categories of products from their customers and distributes those to the respective suppliers. For example, suppose you order some soaps, oil and milk; these three items will be distributed to the three respective suppliers. The three suppliers will then send their supplies to a common distribution point from where the entire order will be fulfilled by the delivery center. Now, let us look at the problem they are facing today. When this store started its business, it was accepting orders in a comma-separated plain text file. Over a period of time, the store switched to message-driven order placement. Later, some software developer suggested an XML based order placement. Eventually, the store even adapted a web service interface. Now, here comes the real problem. The orders now come in different formats. Obviously, every time the company upgraded the order acceptance format, it did not want to break the previously deployed interface so as not to cause confusions in the customer’s mind. At the same time, as the business kept on growing, the store periodically added new suppliers to its repertoire. Each such supplier had its own protocol for accepting orders. Once again, we face the integration issue; our application architecture must be scalable to accommodate new suppliers with their unique order placement mechanism. The entire situation is shown in the following figure − Now, let us see how Apache Camel can come to your rescue to provide an elegant, maintainable, scalable solution architecture for the described scenario. Before we proceed with the solution, we need to make a small assumption. For all the discussions in this tutorial, we will assume that the online orders are placed in XML format. A typical format for the order file that we will be using throughout our discussions is shown here − <?xml version = "1.0" encoding = "UTF-8"?> <OrderID Order = "001"> <order product = "soaps"> <items> <item> <Brand>Cinthol</Brand> <Type>Original</Type> <Quantity>4</Quantity> <Price>25</Price> </item> <item> <Brand>Cinthol</Brand> <Type>Lime</Type> <Quantity>6</Quantity> <Price>30</Price> </item> </items> </order> <order product = "Oil"> <items> <item> <Brand>Saffola</Brand> <Type>Gold</Type> <Quantity>2</Quantity> <Price>649</Price> </item> <item> <Brand>Fortune</Brand> <Type>Sunlite</Type> <Quantity>1</Quantity> <Price>525</Price> </item> </items> </order> <order product = "Milk"> <items> <item> <Product>Milk</Product> <Brand>Amul</Brand> <Type>Pure</Type> <Quantity>2</Quantity> <Price>60</Price> </item> </items> </order> </OrderID> We will be using the above XML template to illustrate the Camel examples in this tutorial. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2678, "s": 1871, "text": "Consider a situation where a large online grocery store in your town such as the Bigbasket in India invites you to design an IT solution for them. The stable and scalable solution will help them overcome the software maintenance problems they are facing today. This online store has been running its business for the last decade. The store accepts online orders for different categories of products from their customers and distributes those to the respective suppliers. For example, suppose you order some soaps, oil and milk; these three items will be distributed to the three respective suppliers. The three suppliers will then send their supplies to a common distribution point from where the entire order will be fulfilled by the delivery center. Now, let us look at the problem they are facing today." }, { "code": null, "e": 3247, "s": 2678, "text": "When this store started its business, it was accepting orders in a comma-separated plain text file. Over a period of time, the store switched to message-driven order placement. Later, some software developer suggested an XML based order placement. Eventually, the store even adapted a web service interface. Now, here comes the real problem. The orders now come in different formats. Obviously, every time the company upgraded the order acceptance format, it did not want to break the previously deployed interface so as not to cause confusions in the customer’s mind." }, { "code": null, "e": 3585, "s": 3247, "text": "At the same time, as the business kept on growing, the store periodically added new suppliers to its repertoire. Each such supplier had its own protocol for accepting orders. Once again, we face the integration issue; our application architecture must be scalable to accommodate new suppliers with their unique order placement mechanism." }, { "code": null, "e": 3641, "s": 3585, "text": "The entire situation is shown in the following figure −" }, { "code": null, "e": 3794, "s": 3641, "text": "Now, let us see how Apache Camel can come to your rescue to provide an elegant, maintainable, scalable solution architecture for the described scenario." }, { "code": null, "e": 4074, "s": 3794, "text": "Before we proceed with the solution, we need to make a small assumption. For all the discussions in this tutorial, we will assume that the online orders are placed in XML format. A typical format for the order file that we will be using throughout our discussions is shown here −" }, { "code": null, "e": 5224, "s": 4074, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<OrderID Order = \"001\">\n <order product = \"soaps\">\n <items>\n <item>\n <Brand>Cinthol</Brand>\n <Type>Original</Type>\n <Quantity>4</Quantity>\n <Price>25</Price>\n </item>\n <item>\n <Brand>Cinthol</Brand>\n <Type>Lime</Type>\n <Quantity>6</Quantity>\n <Price>30</Price>\n </item>\n </items>\n </order>\n \n <order product = \"Oil\">\n <items>\n <item>\n <Brand>Saffola</Brand>\n <Type>Gold</Type>\n <Quantity>2</Quantity>\n <Price>649</Price>\n </item>\n <item>\n <Brand>Fortune</Brand>\n <Type>Sunlite</Type>\n <Quantity>1</Quantity>\n <Price>525</Price>\n </item>\n </items>\n </order>\n \n <order product = \"Milk\">\n <items>\n <item>\n <Product>Milk</Product>\n <Brand>Amul</Brand>\n <Type>Pure</Type>\n <Quantity>2</Quantity>\n <Price>60</Price>\n </item>\n </items>\n </order>\n</OrderID>" }, { "code": null, "e": 5315, "s": 5224, "text": "We will be using the above XML template to illustrate the Camel examples in this tutorial." }, { "code": null, "e": 5350, "s": 5315, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5369, "s": 5350, "text": " Arnab Chakraborty" }, { "code": null, "e": 5404, "s": 5369, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5425, "s": 5404, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5458, "s": 5425, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5471, "s": 5458, "text": " Nilay Mehta" }, { "code": null, "e": 5506, "s": 5471, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5524, "s": 5506, "text": " Bigdata Engineer" }, { "code": null, "e": 5557, "s": 5524, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 5575, "s": 5557, "text": " Bigdata Engineer" }, { "code": null, "e": 5608, "s": 5575, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 5626, "s": 5608, "text": " Bigdata Engineer" }, { "code": null, "e": 5633, "s": 5626, "text": " Print" }, { "code": null, "e": 5644, "s": 5633, "text": " Add Notes" } ]
Python 3 - List count() Method
The count() method returns count of how many times obj occurs in list. Following is the syntax for count() method − list.count(obj) obj − This is the object to be counted in the list. This method returns count of how many times obj occurs in list. The following example shows the usage of count() method. #!/usr/bin/python3 aList = [123, 'xyz', 'zara', 'abc', 123]; print ("Count for 123 : ", aList.count(123)) print ("Count for zara : ", aList.count('zara')) When we run above program, it produces the following result − Count for 123 : 2 Count for zara : 1 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": 2411, "s": 2340, "text": "The count() method returns count of how many times obj occurs in list." }, { "code": null, "e": 2456, "s": 2411, "text": "Following is the syntax for count() method −" }, { "code": null, "e": 2473, "s": 2456, "text": "list.count(obj)\n" }, { "code": null, "e": 2525, "s": 2473, "text": "obj − This is the object to be counted in the list." }, { "code": null, "e": 2589, "s": 2525, "text": "This method returns count of how many times obj occurs in list." }, { "code": null, "e": 2646, "s": 2589, "text": "The following example shows the usage of count() method." }, { "code": null, "e": 2803, "s": 2646, "text": "#!/usr/bin/python3\n\naList = [123, 'xyz', 'zara', 'abc', 123];\n\nprint (\"Count for 123 : \", aList.count(123))\nprint (\"Count for zara : \", aList.count('zara'))" }, { "code": null, "e": 2865, "s": 2803, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 2905, "s": 2865, "text": "Count for 123 : 2\nCount for zara : 1\n" }, { "code": null, "e": 2942, "s": 2905, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2958, "s": 2942, "text": " Malhar Lathkar" }, { "code": null, "e": 2991, "s": 2958, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3010, "s": 2991, "text": " Arnab Chakraborty" }, { "code": null, "e": 3045, "s": 3010, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3067, "s": 3045, "text": " In28Minutes Official" }, { "code": null, "e": 3101, "s": 3067, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3129, "s": 3101, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3164, "s": 3129, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3178, "s": 3164, "text": " Lets Kode It" }, { "code": null, "e": 3211, "s": 3178, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3228, "s": 3211, "text": " Abhilash Nelson" }, { "code": null, "e": 3235, "s": 3228, "text": " Print" }, { "code": null, "e": 3246, "s": 3235, "text": " Add Notes" } ]
How to get the length, size, and shape of a series in Pandas?
There are several ways to get the number of elements present in a pandas Series object. And the class pandas series constructor provides you several attributes and methods to determine the features of the Series object. In the following example, we will learn about the size and shape attributes of the pandas Series object. The size attribute will return an integer value representing the count of the total elements present in a Series object, which works similarly to the python length function. The shape attribute will return a tuple with two elements in it, those two elements are integer values representing the rows and columns count of a pandas data structure object. Here the pandas Series is a one-Dimensional pandas data structure object with labeled indices, hence the output for the shape attribute will return you a tuple with a single integer element representing the rows count of a pandas Series object. # importing pandas packages import pandas as pd # creating pandas Series object series = pd.Series(list('ABCDEFGH')) print(series) # to get length of the series print('Length of series:',len(series)) print('Size of the Series:', series.size) print('The shape of series:',series.shape) Here we have created a simple series object with string data, and the data is A, B, C, D, E, F, G, H, with the index values 0, 1, 2 to 7. By using the python length function we can get the length of the Series object, as well as size and shape attributes will return the count of elements and dimension of the series. 0 A 1 B 2 C 3 D 4 E 5 F 6 G 7 H dtype: object Length of series: 8 Size of the Series: 8 The shape of series: (8,) The integer and Alphabet columns are the representation of the series object output and the data type of this series is an object data type. And we can see the output of length function, size attribute, and shape attribute in the above output block. # importing pandas packages import pandas as pd # creating pandas Series object series = pd.Series({'B':'black', 'W':'white', 'R':'red', 'G':'green'}) print(series) # to get length of the series print('Length of series:',len(series)) print('Size of the Series:', series.size) print('The shape of series:',series.shape) The series object was created by using a dictionary with keys and value pairs, in this example we verified the length, size and shape of the series object by using pandas series attributes. B black W white R red G green dtype: object Length of series: 4 Size of the Series: 4 The shape of series: (4,) The length, size and shape of our series object can be seen in the above output block.
[ { "code": null, "e": 1282, "s": 1062, "text": "There are several ways to get the number of elements present in a pandas Series object. And the class pandas series constructor provides you several attributes and methods to determine the features of the Series object." }, { "code": null, "e": 1561, "s": 1282, "text": "In the following example, we will learn about the size and shape attributes of the pandas Series object. The size attribute will return an integer value representing the count of the total elements present in a Series object, which works similarly to the python length function." }, { "code": null, "e": 1984, "s": 1561, "text": "The shape attribute will return a tuple with two elements in it, those two elements are integer values representing the rows and columns count of a pandas data structure object. Here the pandas Series is a one-Dimensional pandas data structure object with labeled indices, hence the output for the shape attribute will return you a tuple with a single integer element representing the rows count of a pandas Series object." }, { "code": null, "e": 2273, "s": 1984, "text": "# importing pandas packages\nimport pandas as pd\n\n# creating pandas Series object\nseries = pd.Series(list('ABCDEFGH'))\nprint(series)\n\n# to get length of the series\nprint('Length of series:',len(series))\n\nprint('Size of the Series:', series.size)\n\nprint('The shape of series:',series.shape)" }, { "code": null, "e": 2411, "s": 2273, "text": "Here we have created a simple series object with string data, and the data is A, B, C, D, E, F, G, H, with the index values 0, 1, 2 to 7." }, { "code": null, "e": 2591, "s": 2411, "text": "By using the python length function we can get the length of the Series object, as well as size and shape attributes will return the count of elements and dimension of the series." }, { "code": null, "e": 2722, "s": 2591, "text": "0 A\n1 B\n2 C\n3 D\n4 E\n5 F\n6 G\n7 H\ndtype: object\n\nLength of series: 8\nSize of the Series: 8\nThe shape of series: (8,)" }, { "code": null, "e": 2972, "s": 2722, "text": "The integer and Alphabet columns are the representation of the series object output and the data type of this series is an object data type. And we can see the output of length function, size attribute, and shape attribute in the above output block." }, { "code": null, "e": 3295, "s": 2972, "text": "# importing pandas packages\nimport pandas as pd\n\n# creating pandas Series object\nseries = pd.Series({'B':'black', 'W':'white', 'R':'red', 'G':'green'})\nprint(series)\n\n# to get length of the series\nprint('Length of series:',len(series))\n\nprint('Size of the Series:', series.size)\n\nprint('The shape of series:',series.shape)" }, { "code": null, "e": 3485, "s": 3295, "text": "The series object was created by using a dictionary with keys and value pairs, in this example we verified the length, size and shape of the series object by using pandas series attributes." }, { "code": null, "e": 3607, "s": 3485, "text": "B black\nW white\nR red\nG green\ndtype: object\nLength of series: 4\nSize of the Series: 4\nThe shape of series: (4,)" }, { "code": null, "e": 3694, "s": 3607, "text": "The length, size and shape of our series object can be seen in the above output block." } ]
glob – Filename pattern matching - GeeksforGeeks
08 Dec, 2020 Glob module searches all path names looking for files matching a specified pattern according to the rules dictated by the Unix shell. Results so obtained are returned in arbitrary order. Some requirements need traversal through a list of files at some location, mostly having a specific pattern. Python’s glob module has several functions that can help in listing files that match a given pattern under a specified folder. Pattern matching is done using os.scandir() and fnmatch.fnmatch() functions, and not by actually invoking a sub-shell. Unlike fnmatch.fnmatch(), glob treats filenames beginning with a dot (.) as special cases. For tilde and shell variable expansion, os.path.expanduser() and os.path.expandvars() functions are used. Follow standard Unix path expansion rules. Special characters supported : two different wild-cards- *, ? and character ranges expressed in []. The pattern rules are applied to segments of the filename (stopping at the path separator, /). Paths in the pattern can be relative or absolute. It is useful in any situation where your program needs to look for a list of files on the file system with names matching a pattern. If you need a list of filenames that have a certain extension, prefix, or any common string in the middle, use glob instead of writing code to scan the directory contents yourself. glob(pathname, *, recursive=False)- It returns list of path names that match pathname given, which must be a string containing a path specification. List can be empty too. iglob(pathname, *, recursive=False)- This method creates a Python generator object which is used to list files under a given directory. Also returns an iterator that yields the same values as glob() without actually storing them all simultaneously. escape(pathname)- It allows escaping the given character sequence. You can find it handy for locating files with certain characters in their file names and matching an arbitrary literal string that may have special characters in it. Given below is the implementation to help you understand how this module can be put to practice: Example 1: Python3 import glob # search .py files# in the current working directoryfor py in glob.glob("*.py"): print(py) Output : Example 2: Program to depict wildcard characters and ranges If recursive is true, the pattern “**” will match any files and zero or more directories, subdirectories and symbolic links to directories. Using the “**” pattern in large directory trees may consume an inordinate amount of time. Python3 import glob # Using character ranges []print('Finding file using character ranges [] :- ')print(glob.glob('./[0-9].*')) # Using wildcard character *print('\n Finding file using wildcard character * :- ')print(glob.glob('*.gif')) # Using wildcard character ?print('\n Finding file using wildcard character ? :- ')print(glob.glob('?.gif')) # Using recursive attributeprint('\n Finding files using recursive attribute :- ')print(glob.glob('**/*.txt', recursive=True)) Output : Example 3: Python3 import glob gen = glob.iglob("*.py")# returns class type of gentype(gen) for py in gen: print(py) Output : Example 4: Python3 import glob char_seq = "-_#" for spcl_char in char_seq: esc_set = "*" + glob.escape(spcl_char) + "*" + ".py" for py in (glob.glob(esc_set)): print(py) Output : python-modules Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n08 Dec, 2020" }, { "code": null, "e": 24350, "s": 23925, "text": "Glob module searches all path names looking for files matching a specified pattern according to the rules dictated by the Unix shell. Results so obtained are returned in arbitrary order. Some requirements need traversal through a list of files at some location, mostly having a specific pattern. Python’s glob module has several functions that can help in listing files that match a given pattern under a specified folder. " }, { "code": null, "e": 24666, "s": 24350, "text": "Pattern matching is done using os.scandir() and fnmatch.fnmatch() functions, and not by actually invoking a sub-shell. Unlike fnmatch.fnmatch(), glob treats filenames beginning with a dot (.) as special cases. For tilde and shell variable expansion, os.path.expanduser() and os.path.expandvars() functions are used." }, { "code": null, "e": 24709, "s": 24666, "text": "Follow standard Unix path expansion rules." }, { "code": null, "e": 24811, "s": 24709, "text": "Special characters supported : two different wild-cards- *, ? and character ranges expressed in []." }, { "code": null, "e": 24906, "s": 24811, "text": "The pattern rules are applied to segments of the filename (stopping at the path separator, /)." }, { "code": null, "e": 24956, "s": 24906, "text": "Paths in the pattern can be relative or absolute." }, { "code": null, "e": 25089, "s": 24956, "text": "It is useful in any situation where your program needs to look for a list of files on the file system with names matching a pattern." }, { "code": null, "e": 25270, "s": 25089, "text": "If you need a list of filenames that have a certain extension, prefix, or any common string in the middle, use glob instead of writing code to scan the directory contents yourself." }, { "code": null, "e": 25442, "s": 25270, "text": "glob(pathname, *, recursive=False)- It returns list of path names that match pathname given, which must be a string containing a path specification. List can be empty too." }, { "code": null, "e": 25691, "s": 25442, "text": "iglob(pathname, *, recursive=False)- This method creates a Python generator object which is used to list files under a given directory. Also returns an iterator that yields the same values as glob() without actually storing them all simultaneously." }, { "code": null, "e": 25924, "s": 25691, "text": "escape(pathname)- It allows escaping the given character sequence. You can find it handy for locating files with certain characters in their file names and matching an arbitrary literal string that may have special characters in it." }, { "code": null, "e": 26021, "s": 25924, "text": "Given below is the implementation to help you understand how this module can be put to practice:" }, { "code": null, "e": 26032, "s": 26021, "text": "Example 1:" }, { "code": null, "e": 26040, "s": 26032, "text": "Python3" }, { "code": "import glob # search .py files# in the current working directoryfor py in glob.glob(\"*.py\"): print(py)", "e": 26147, "s": 26040, "text": null }, { "code": null, "e": 26156, "s": 26147, "text": "Output :" }, { "code": null, "e": 26216, "s": 26156, "text": "Example 2: Program to depict wildcard characters and ranges" }, { "code": null, "e": 26447, "s": 26216, "text": "If recursive is true, the pattern “**” will match any files and zero or more directories, subdirectories and symbolic links to directories. Using the “**” pattern in large directory trees may consume an inordinate amount of time. " }, { "code": null, "e": 26455, "s": 26447, "text": "Python3" }, { "code": "import glob # Using character ranges []print('Finding file using character ranges [] :- ')print(glob.glob('./[0-9].*')) # Using wildcard character *print('\\n Finding file using wildcard character * :- ')print(glob.glob('*.gif')) # Using wildcard character ?print('\\n Finding file using wildcard character ? :- ')print(glob.glob('?.gif')) # Using recursive attributeprint('\\n Finding files using recursive attribute :- ')print(glob.glob('**/*.txt', recursive=True))", "e": 26924, "s": 26455, "text": null }, { "code": null, "e": 26933, "s": 26924, "text": "Output :" }, { "code": null, "e": 26944, "s": 26933, "text": "Example 3:" }, { "code": null, "e": 26952, "s": 26944, "text": "Python3" }, { "code": "import glob gen = glob.iglob(\"*.py\")# returns class type of gentype(gen) for py in gen: print(py)", "e": 27055, "s": 26952, "text": null }, { "code": null, "e": 27064, "s": 27055, "text": "Output :" }, { "code": null, "e": 27075, "s": 27064, "text": "Example 4:" }, { "code": null, "e": 27083, "s": 27075, "text": "Python3" }, { "code": "import glob char_seq = \"-_#\" for spcl_char in char_seq: esc_set = \"*\" + glob.escape(spcl_char) + \"*\" + \".py\" for py in (glob.glob(esc_set)): print(py)", "e": 27255, "s": 27083, "text": null }, { "code": null, "e": 27264, "s": 27255, "text": "Output :" }, { "code": null, "e": 27279, "s": 27264, "text": "python-modules" }, { "code": null, "e": 27303, "s": 27279, "text": "Technical Scripter 2020" }, { "code": null, "e": 27310, "s": 27303, "text": "Python" }, { "code": null, "e": 27329, "s": 27310, "text": "Technical Scripter" }, { "code": null, "e": 27427, "s": 27329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27436, "s": 27427, "text": "Comments" }, { "code": null, "e": 27449, "s": 27436, "text": "Old Comments" }, { "code": null, "e": 27481, "s": 27449, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27537, "s": 27481, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27579, "s": 27537, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27621, "s": 27579, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27657, "s": 27621, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27696, "s": 27657, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27718, "s": 27696, "text": "Defaultdict in Python" }, { "code": null, "e": 27749, "s": 27718, "text": "Python | os.path.join() method" }, { "code": null, "e": 27776, "s": 27749, "text": "Python Classes and Objects" } ]
Print uncommon elements from two sorted arrays - GeeksforGeeks
10 Feb, 2022 Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements are present in both arrays. Input : arr1[] = {10, 20, 30} arr2[] = {40, 50} Output : 10 20 30 40 50 The idea is based on merge process of merge sort. We traverse both arrays and skip common elements. C++ Java Python3 C# PHP Javascript // C++ program to find uncommon elements of// two sorted arrays#include <bits/stdc++.h>using namespace std; void printUncommon(int arr1[], int arr2[], int n1, int n2){ int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { cout << arr1[i] << " "; i++; k++; } else if (arr2[j] < arr1[i]) { cout << arr2[j] << " "; k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { cout << arr1[i] << " "; i++; k++; } while (j < n2) { cout << arr2[j] << " "; j++; k++; }} // Driver codeint main(){ int arr1[] = {10, 20, 30}; int arr2[] = {20, 25, 30, 40, 50}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); printUncommon(arr1, arr2, n1, n2); return 0;} // Java program to find uncommon elements// of two sorted arraysimport java.io.*; class GFG { static void printUncommon(int arr1[], int arr2[], int n1, int n2) { int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { System.out.print(arr1[i] + " "); i++; k++; } else if (arr2[j] < arr1[i]) { System.out.print(arr2[j] + " "); k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { System.out.print(arr1[i] + " "); i++; k++; } while (j < n2) { System.out.print(arr2[j] + " "); j++; k++; } } // Driver code public static void main(String[] args) { int arr1[] = { 10, 20, 30 }; int arr2[] = { 20, 25, 30, 40, 50 }; int n1 = arr1.length; int n2 = arr2.length; printUncommon(arr1, arr2, n1, n2); }} // This code is contributed by vt_m # Python 3 program to find uncommon# elements of two sorted arrays def printUncommon(arr1, arr2, n1, n2) : i = 0 j = 0 k = 0 while (i < n1 and j < n2) : # If not common, print smaller if (arr1[i] < arr2[j]) : print( arr1[i] , end= " ") i = i + 1 k = k + 1 elif (arr2[j] < arr1[i]) : print( arr2[j] , end= " ") k = k + 1 j = j + 1 # Skip common element else : i = i + 1 j = j + 1 # printing remaining elements while (i < n1) : print( arr1[i] , end= " ") i = i + 1 k = k + 1 while (j < n2) : print( arr2[j] , end= " ") j = j + 1 k = k + 1 # Driver codearr1 = [10, 20, 30]arr2 = [20, 25, 30, 40, 50] n1 = len(arr1)n2 = len(arr2) printUncommon(arr1, arr2, n1, n2) # This code is contributed# by Nikita Tiwari. // C# program to find uncommon elements// of two sorted arraysusing System;class GFG { static void printUncommon(int []arr1, int []arr2, int n1, int n2) { int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { Console.Write(arr1[i] + " "); i++; k++; } else if (arr2[j] < arr1[i]) { Console.Write(arr2[j] + " "); k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { Console.Write(arr1[i] + " "); i++; k++; } while (j < n2) { Console.Write(arr2[j] + " "); j++; k++; } } // Driver Code public static void Main() { int []arr1 = {10, 20, 30}; int []arr2 = {20, 25, 30, 40, 50}; int n1 = arr1.Length; int n2 = arr2.Length; printUncommon(arr1, arr2, n1, n2); }} // This code is contributed by Sam007 <?php// PHP program to find uncommon// elements of two sorted arrays function printUncommon($arr1, $arr2, $n1, $n2){ $i = 0; $j = 0; $k = 0; while ($i < $n1 && $j < $n2) { // If not common, print smaller if ($arr1[$i] < $arr2[$j]) { echo $arr1[$i] . " "; $i++; $k++; } else if ($arr2[$j] < $arr1[$i]) { echo $arr2[$j] . " "; $k++; $j++; } // Skip common element else { $i++; $j++; } } // printing remaining elements while ($i < $n1) { echo $arr1[$i] . " "; $i++; $k++; } while ($j < $n2) { echo $arr2[$j] . " "; $j++; $k++; }} // Driver code$arr1 = array(10, 20, 30);$arr2 = array(20, 25, 30, 40, 50); $n1 = sizeof($arr1) ;$n2 = sizeof($arr2) ; printUncommon($arr1, $arr2, $n1, $n2); // This code is contributed by Anuj_67?> <script>// JavaScript program to find uncommon elements// of two sorted arrays function printUncommon(arr1, arr2, n1, n2) { let i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { document.write(arr1[i] + " "); i++; k++; } else if (arr2[j] < arr1[i]) { document.write(arr2[j] + " "); k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { document.write(arr1[i] + " "); i++; k++; } while (j < n2) { document.write(arr2[j] + " "); j++; k++; } } // Driver Code let arr1 = [ 10, 20, 30 ]; let arr2 = [ 20, 25, 30, 40, 50 ]; let n1 = arr1.length; let n2 = arr2.length; printUncommon(arr1, arr2, n1, n2); // This code is contributed by susmitakundugoaldanga.</script> 10 25 40 50 Sam007 vt_m susmitakundugoaldanga ankita_saini surinderdawra388 two-pointer-algorithm Arrays Searching two-pointer-algorithm Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Binary Search Median of two sorted arrays of different sizes Most frequent element in an array Find the index of an array element in Java Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 24429, "s": 24401, "text": "\n10 Feb, 2022" }, { "code": null, "e": 24604, "s": 24429, "text": "Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : " }, { "code": null, "e": 24855, "s": 24604, "text": "Input : arr1[] = {10, 20, 30}\n arr2[] = {20, 25, 30, 40, 50}\nOutput : 10 25 40 50\nWe do not print 20 and 30 as these\nelements are present in both arrays.\n\nInput : arr1[] = {10, 20, 30}\n arr2[] = {40, 50}\nOutput : 10 20 30 40 50\n " }, { "code": null, "e": 24958, "s": 24857, "text": "The idea is based on merge process of merge sort. We traverse both arrays and skip common elements. " }, { "code": null, "e": 24962, "s": 24958, "text": "C++" }, { "code": null, "e": 24967, "s": 24962, "text": "Java" }, { "code": null, "e": 24975, "s": 24967, "text": "Python3" }, { "code": null, "e": 24978, "s": 24975, "text": "C#" }, { "code": null, "e": 24982, "s": 24978, "text": "PHP" }, { "code": null, "e": 24993, "s": 24982, "text": "Javascript" }, { "code": "// C++ program to find uncommon elements of// two sorted arrays#include <bits/stdc++.h>using namespace std; void printUncommon(int arr1[], int arr2[], int n1, int n2){ int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { cout << arr1[i] << \" \"; i++; k++; } else if (arr2[j] < arr1[i]) { cout << arr2[j] << \" \"; k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { cout << arr1[i] << \" \"; i++; k++; } while (j < n2) { cout << arr2[j] << \" \"; j++; k++; }} // Driver codeint main(){ int arr1[] = {10, 20, 30}; int arr2[] = {20, 25, 30, 40, 50}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); printUncommon(arr1, arr2, n1, n2); return 0;}", "e": 26031, "s": 24993, "text": null }, { "code": "// Java program to find uncommon elements// of two sorted arraysimport java.io.*; class GFG { static void printUncommon(int arr1[], int arr2[], int n1, int n2) { int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { System.out.print(arr1[i] + \" \"); i++; k++; } else if (arr2[j] < arr1[i]) { System.out.print(arr2[j] + \" \"); k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { System.out.print(arr1[i] + \" \"); i++; k++; } while (j < n2) { System.out.print(arr2[j] + \" \"); j++; k++; } } // Driver code public static void main(String[] args) { int arr1[] = { 10, 20, 30 }; int arr2[] = { 20, 25, 30, 40, 50 }; int n1 = arr1.length; int n2 = arr2.length; printUncommon(arr1, arr2, n1, n2); }} // This code is contributed by vt_m", "e": 27281, "s": 26031, "text": null }, { "code": "# Python 3 program to find uncommon# elements of two sorted arrays def printUncommon(arr1, arr2, n1, n2) : i = 0 j = 0 k = 0 while (i < n1 and j < n2) : # If not common, print smaller if (arr1[i] < arr2[j]) : print( arr1[i] , end= \" \") i = i + 1 k = k + 1 elif (arr2[j] < arr1[i]) : print( arr2[j] , end= \" \") k = k + 1 j = j + 1 # Skip common element else : i = i + 1 j = j + 1 # printing remaining elements while (i < n1) : print( arr1[i] , end= \" \") i = i + 1 k = k + 1 while (j < n2) : print( arr2[j] , end= \" \") j = j + 1 k = k + 1 # Driver codearr1 = [10, 20, 30]arr2 = [20, 25, 30, 40, 50] n1 = len(arr1)n2 = len(arr2) printUncommon(arr1, arr2, n1, n2) # This code is contributed# by Nikita Tiwari.", "e": 28209, "s": 27281, "text": null }, { "code": "// C# program to find uncommon elements// of two sorted arraysusing System;class GFG { static void printUncommon(int []arr1, int []arr2, int n1, int n2) { int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { Console.Write(arr1[i] + \" \"); i++; k++; } else if (arr2[j] < arr1[i]) { Console.Write(arr2[j] + \" \"); k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { Console.Write(arr1[i] + \" \"); i++; k++; } while (j < n2) { Console.Write(arr2[j] + \" \"); j++; k++; } } // Driver Code public static void Main() { int []arr1 = {10, 20, 30}; int []arr2 = {20, 25, 30, 40, 50}; int n1 = arr1.Length; int n2 = arr2.Length; printUncommon(arr1, arr2, n1, n2); }} // This code is contributed by Sam007", "e": 29526, "s": 28209, "text": null }, { "code": "<?php// PHP program to find uncommon// elements of two sorted arrays function printUncommon($arr1, $arr2, $n1, $n2){ $i = 0; $j = 0; $k = 0; while ($i < $n1 && $j < $n2) { // If not common, print smaller if ($arr1[$i] < $arr2[$j]) { echo $arr1[$i] . \" \"; $i++; $k++; } else if ($arr2[$j] < $arr1[$i]) { echo $arr2[$j] . \" \"; $k++; $j++; } // Skip common element else { $i++; $j++; } } // printing remaining elements while ($i < $n1) { echo $arr1[$i] . \" \"; $i++; $k++; } while ($j < $n2) { echo $arr2[$j] . \" \"; $j++; $k++; }} // Driver code$arr1 = array(10, 20, 30);$arr2 = array(20, 25, 30, 40, 50); $n1 = sizeof($arr1) ;$n2 = sizeof($arr2) ; printUncommon($arr1, $arr2, $n1, $n2); // This code is contributed by Anuj_67?>", "e": 30522, "s": 29526, "text": null }, { "code": "<script>// JavaScript program to find uncommon elements// of two sorted arrays function printUncommon(arr1, arr2, n1, n2) { let i = 0, j = 0, k = 0; while (i < n1 && j < n2) { // If not common, print smaller if (arr1[i] < arr2[j]) { document.write(arr1[i] + \" \"); i++; k++; } else if (arr2[j] < arr1[i]) { document.write(arr2[j] + \" \"); k++; j++; } // Skip common element else { i++; j++; } } // printing remaining elements while (i < n1) { document.write(arr1[i] + \" \"); i++; k++; } while (j < n2) { document.write(arr2[j] + \" \"); j++; k++; } } // Driver Code let arr1 = [ 10, 20, 30 ]; let arr2 = [ 20, 25, 30, 40, 50 ]; let n1 = arr1.length; let n2 = arr2.length; printUncommon(arr1, arr2, n1, n2); // This code is contributed by susmitakundugoaldanga.</script>", "e": 31714, "s": 30522, "text": null }, { "code": null, "e": 31726, "s": 31714, "text": "10 25 40 50" }, { "code": null, "e": 31735, "s": 31728, "text": "Sam007" }, { "code": null, "e": 31740, "s": 31735, "text": "vt_m" }, { "code": null, "e": 31762, "s": 31740, "text": "susmitakundugoaldanga" }, { "code": null, "e": 31775, "s": 31762, "text": "ankita_saini" }, { "code": null, "e": 31792, "s": 31775, "text": "surinderdawra388" }, { "code": null, "e": 31814, "s": 31792, "text": "two-pointer-algorithm" }, { "code": null, "e": 31821, "s": 31814, "text": "Arrays" }, { "code": null, "e": 31831, "s": 31821, "text": "Searching" }, { "code": null, "e": 31853, "s": 31831, "text": "two-pointer-algorithm" }, { "code": null, "e": 31860, "s": 31853, "text": "Arrays" }, { "code": null, "e": 31870, "s": 31860, "text": "Searching" }, { "code": null, "e": 31968, "s": 31870, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31977, "s": 31968, "text": "Comments" }, { "code": null, "e": 31990, "s": 31977, "text": "Old Comments" }, { "code": null, "e": 32011, "s": 31990, "text": "Next Greater Element" }, { "code": null, "e": 32036, "s": 32011, "text": "Window Sliding Technique" }, { "code": null, "e": 32063, "s": 32036, "text": "Count pairs with given sum" }, { "code": null, "e": 32112, "s": 32063, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32150, "s": 32112, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32164, "s": 32150, "text": "Binary Search" }, { "code": null, "e": 32211, "s": 32164, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 32245, "s": 32211, "text": "Most frequent element in an array" }, { "code": null, "e": 32288, "s": 32245, "text": "Find the index of an array element in Java" } ]
Logistic Regression in Python - Testing
We need to test the above created classifier before we put it into production use. If the testing reveals that the model does not meet the desired accuracy, we will have to go back in the above process, select another set of features (data fields), build the model again, and test it. This will be an iterative step until the classifier meets your requirement of desired accuracy. So let us test our classifier. To test the classifier, we use the test data generated in the earlier stage. We call the predict method on the created object and pass the X array of the test data as shown in the following command − In [24]: predicted_y = classifier.predict(X_test) This generates a single dimensional array for the entire training data set giving the prediction for each row in the X array. You can examine this array by using the following command − In [25]: predicted_y The following is the output upon the execution the above two commands − Out[25]: array([0, 0, 0, ..., 0, 0, 0]) The output indicates that the first and last three customers are not the potential candidates for the Term Deposit. You can examine the entire array to sort out the potential customers. To do so, use the following Python code snippet − In [26]: for x in range(len(predicted_y)): if (predicted_y[x] == 1): print(x, end="\t") The output of running the above code is shown below − The output shows the indexes of all rows who are probable candidates for subscribing to TD. You can now give this output to the bank’s marketing team who would pick up the contact details for each customer in the selected row and proceed with their job. Before we put this model into production, we need to verify the accuracy of prediction. To test the accuracy of the model, use the score method on the classifier as shown below − In [27]: print('Accuracy: {:.2f}'.format(classifier.score(X_test, Y_test))) The screen output of running this command is shown below − Accuracy: 0.90 It shows that the accuracy of our model is 90% which is considered very good in most of the applications. Thus, no further tuning is required. Now, our customer is ready to run the next campaign, get the list of potential customers and chase them for opening the TD with a probable high rate of success. 15 Lectures 1 hours Ajay 53 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2145, "s": 1733, "text": "We need to test the above created classifier before we put it into production use. If the testing reveals that the model does not meet the desired accuracy, we will have to go back in the above process, select another set of features (data fields), build the model again, and test it. This will be an iterative step until the classifier meets your requirement of desired accuracy. So let us test our classifier." }, { "code": null, "e": 2345, "s": 2145, "text": "To test the classifier, we use the test data generated in the earlier stage. We call the predict method on the created object and pass the X array of the test data as shown in the following command −" }, { "code": null, "e": 2396, "s": 2345, "text": "In [24]: predicted_y = classifier.predict(X_test)\n" }, { "code": null, "e": 2582, "s": 2396, "text": "This generates a single dimensional array for the entire training data set giving the prediction for each row in the X array. You can examine this array by using the following command −" }, { "code": null, "e": 2604, "s": 2582, "text": "In [25]: predicted_y\n" }, { "code": null, "e": 2676, "s": 2604, "text": "The following is the output upon the execution the above two commands −" }, { "code": null, "e": 2717, "s": 2676, "text": "Out[25]: array([0, 0, 0, ..., 0, 0, 0])\n" }, { "code": null, "e": 2953, "s": 2717, "text": "The output indicates that the first and last three customers are not the potential candidates for the Term Deposit. You can examine the entire array to sort out the potential customers. To do so, use the following Python code snippet −" }, { "code": null, "e": 3051, "s": 2953, "text": "In [26]: for x in range(len(predicted_y)):\n if (predicted_y[x] == 1):\n print(x, end=\"\\t\")\n" }, { "code": null, "e": 3105, "s": 3051, "text": "The output of running the above code is shown below −" }, { "code": null, "e": 3359, "s": 3105, "text": "The output shows the indexes of all rows who are probable candidates for subscribing to TD. You can now give this output to the bank’s marketing team who would pick up the contact details for each customer in the selected row and proceed with their job." }, { "code": null, "e": 3447, "s": 3359, "text": "Before we put this model into production, we need to verify the accuracy of prediction." }, { "code": null, "e": 3538, "s": 3447, "text": "To test the accuracy of the model, use the score method on the classifier as shown below −" }, { "code": null, "e": 3615, "s": 3538, "text": "In [27]: print('Accuracy: {:.2f}'.format(classifier.score(X_test, Y_test)))\n" }, { "code": null, "e": 3674, "s": 3615, "text": "The screen output of running this command is shown below −" }, { "code": null, "e": 3690, "s": 3674, "text": "Accuracy: 0.90\n" }, { "code": null, "e": 3994, "s": 3690, "text": "It shows that the accuracy of our model is 90% which is considered very good in most of the applications. Thus, no further tuning is required. Now, our customer is ready to run the next campaign, get the list of potential customers and chase them for opening the TD with a probable high rate of success." }, { "code": null, "e": 4027, "s": 3994, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 4033, "s": 4027, "text": " Ajay" }, { "code": null, "e": 4066, "s": 4033, "text": "\n 53 Lectures \n 6 hours \n" }, { "code": null, "e": 4088, "s": 4066, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4121, "s": 4088, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 4143, "s": 4121, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4150, "s": 4143, "text": " Print" }, { "code": null, "e": 4161, "s": 4150, "text": " Add Notes" } ]
MySQL - SHOW ERRORS Statement
The MySQL SHOW ERRORS Statement is used to retrieve the information about the error occurred during the execution of the previous MySQL statement in the current session. Following is the syntax of the SHOW ERRORS Statement − SHOW ERRORS [LIMIT [offset,] row_count] SHOW COUNT(*) ERRORS Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below − mysql> CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255) NOT NULL, Last_Name VARCHAR(255) NOT NULL, Date_Of_Birth date, Place_Of_Birth VARCHAR(15), Country VARCHAR(15), PRIMARY KEY (ID) ); Query OK, 0 rows affected (3.88 sec) Now, we will insert some records in MyPlayers table using INSERT statements − mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); Query OK, 1 row affected (0.57 sec) mysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); Query OK, 1 row affected (0.37 sec) If verify the contents of the MyPlayers table, you can observe the created records as − mysql> select * from MyPlayers; +----+------------+------------+---------------+----------------+-------------+ | ID | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country | +----+------------+------------+---------------+----------------+-------------+ | 1 | Shikhar | Dhawan | 1981-12-05 | Delhi | India | | 2 | Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica | +----+------------+------------+---------------+----------------+-------------+ 2 rows in set (0.07 sec) Now, let us try to insert more rows with repeated ID value, wrong table name and wrong number of values − mysql> insert into MyPlayers values(2, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); ERROR 1062 (23000): Duplicate entry '2' for key 'myplayers.PRIMARY' Following query retrieves the state and message of the above generated error − mysql> SHOW ERRORS; +-------+------+-------------------------------------------------+ | Level | Code | Message | +-------+------+-------------------------------------------------+ | Error | 1136 | Column count doesn't match value count at row 1 | +-------+------+-------------------------------------------------+ 1 row in set (0.00 sec) Following are two more insert statements that generates errors − mysql> insert into WrongTable values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); ERROR 1146 (42S02): Table 'demo.wrongtable' doesn't exist mysql> SHOW ERRORS; +-------+------+---------------------------------------+ | Level | Code | Message | +-------+------+---------------------------------------+ | Error | 1146 | Table 'demo.wrongtable' doesn't exist | +-------+------+---------------------------------------+ 1 row in set (0.00 sec) mysql> insert into MyPlayers values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); ERROR 1136 (21S01): Column count doesn't match value count at row 1 mysql> SHOW ERRORS; +-------+------+-------------------------------------------------+ | Level | Code | Message | +-------+------+-------------------------------------------------+ | Error | 1136 | Column count doesn't match value count at row 1 | +-------+------+-------------------------------------------------+ 1 row in set (0.00 sec) You can limit the number of errors to an offset using the LIMIT clause − mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Long Name For Country'); ERROR 1406 (22001): Data too long for column 'Country' at row 1 mysql> SHOW ERRORS LIMIT 0; Empty set (0.00 sec) mysql> SHOW ERRORS LIMIT 1; +-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ | Level | Code | Message | +-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ | Error | 1064 | You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LINIT 0' at line 1 | +-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) You can count the number of errors you can use the COUNT(*) or the @@error_count; variable. Following query tries to insert a record in the above created MyPlayers table. mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Long Name For Country'); ERROR 1406 (22001): Data too long for column 'Country' at row 1 You can get the number of errors generated by the above statement using the SHOW ERRORS query as follows − mysql> SHOW COUNT(*) ERRORS; +-----------------------+ | @@session.error_count | +-----------------------+ | 1 | +-----------------------+ 1 row in set (0.00 sec) We can also use the error_count variable for the same purpose as − mysql> SELECT @@error_count; +---------------+ | @@error_count | +---------------+ | 1 | +---------------+ 1 row in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2503, "s": 2333, "text": "The MySQL SHOW ERRORS Statement is used to retrieve the information about the error occurred during the execution of the previous MySQL statement in the current session." }, { "code": null, "e": 2558, "s": 2503, "text": "Following is the syntax of the SHOW ERRORS Statement −" }, { "code": null, "e": 2620, "s": 2558, "text": "SHOW ERRORS [LIMIT [offset,] row_count]\nSHOW COUNT(*) ERRORS\n" }, { "code": null, "e": 2720, "s": 2620, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 2973, "s": 2720, "text": "mysql> CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255) NOT NULL,\n Last_Name VARCHAR(255) NOT NULL,\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(15),\n Country VARCHAR(15),\n PRIMARY KEY (ID)\n);\nQuery OK, 0 rows affected (3.88 sec)" }, { "code": null, "e": 3051, "s": 2973, "text": "Now, we will insert some records in MyPlayers table using INSERT statements −" }, { "code": null, "e": 3331, "s": 3051, "text": "mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\nQuery OK, 1 row affected (0.57 sec)\n\nmysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\nQuery OK, 1 row affected (0.37 sec)" }, { "code": null, "e": 3419, "s": 3331, "text": "If verify the contents of the MyPlayers table, you can observe the created records as −" }, { "code": null, "e": 3957, "s": 3419, "text": "mysql> select * from MyPlayers;\n+----+------------+------------+---------------+----------------+-------------+ \n| ID | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country |\n+----+------------+------------+---------------+----------------+-------------+\n| 1 | Shikhar | Dhawan | 1981-12-05 | Delhi | India |\n| 2 | Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica |\n+----+------------+------------+---------------+----------------+-------------+\n2 rows in set (0.07 sec)" }, { "code": null, "e": 4063, "s": 3957, "text": "Now, let us try to insert more rows with repeated ID value, wrong table name and wrong number of values −" }, { "code": null, "e": 4229, "s": 4063, "text": "mysql> insert into MyPlayers values(2, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\nERROR 1062 (23000): Duplicate entry '2' for key 'myplayers.PRIMARY'" }, { "code": null, "e": 4308, "s": 4229, "text": "Following query retrieves the state and message of the above generated error −" }, { "code": null, "e": 4687, "s": 4308, "text": "mysql> SHOW ERRORS;\n+-------+------+-------------------------------------------------+\n| Level | Code | Message |\n+-------+------+-------------------------------------------------+\n| Error | 1136 | Column count doesn't match value count at row 1 |\n+-------+------+-------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4752, "s": 4687, "text": "Following are two more insert statements that generates errors −" }, { "code": null, "e": 5788, "s": 4752, "text": "mysql> insert into WrongTable values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\nERROR 1146 (42S02): Table 'demo.wrongtable' doesn't exist\nmysql> SHOW ERRORS;\n+-------+------+---------------------------------------+\n| Level | Code | Message |\n+-------+------+---------------------------------------+\n| Error | 1146 | Table 'demo.wrongtable' doesn't exist |\n+-------+------+---------------------------------------+\n1 row in set (0.00 sec)\n\nmysql> insert into MyPlayers values('Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\nERROR 1136 (21S01): Column count doesn't match value count at row 1\n\nmysql> SHOW ERRORS;\n+-------+------+-------------------------------------------------+\n| Level | Code | Message |\n+-------+------+-------------------------------------------------+\n| Error | 1136 | Column count doesn't match value count at row 1 |\n+-------+------+-------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 5861, "s": 5788, "text": "You can limit the number of errors to an offset using the LIMIT clause −" }, { "code": null, "e": 7011, "s": 5861, "text": "mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Long Name For Country');\nERROR 1406 (22001): Data too long for column 'Country' at row 1\nmysql> SHOW ERRORS LIMIT 0;\nEmpty set (0.00 sec)\n\nmysql> SHOW ERRORS LIMIT 1;\n+-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Level | Code | Message |\n+-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Error | 1064 | You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LINIT 0' at line 1 |\n+-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 7103, "s": 7011, "text": "You can count the number of errors you can use the COUNT(*) or the @@error_count; variable." }, { "code": null, "e": 7182, "s": 7103, "text": "Following query tries to insert a record in the above created MyPlayers table." }, { "code": null, "e": 7365, "s": 7182, "text": "mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Long Name For Country');\nERROR 1406 (22001): Data too long for column 'Country' at row 1" }, { "code": null, "e": 7472, "s": 7365, "text": "You can get the number of errors generated by the above statement using the SHOW ERRORS query as follows −" }, { "code": null, "e": 7655, "s": 7472, "text": "mysql> SHOW COUNT(*) ERRORS;\n+-----------------------+\n| @@session.error_count |\n+-----------------------+\n| 1 |\n+-----------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 7722, "s": 7655, "text": "We can also use the error_count variable for the same purpose as −" }, { "code": null, "e": 7865, "s": 7722, "text": "mysql> SELECT @@error_count;\n+---------------+\n| @@error_count |\n+---------------+\n| 1 |\n+---------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 7898, "s": 7865, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 7926, "s": 7898, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7961, "s": 7926, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7978, "s": 7961, "text": " Frahaan Hussain" }, { "code": null, "e": 8012, "s": 7978, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8047, "s": 8012, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 8081, "s": 8047, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 8109, "s": 8081, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8142, "s": 8109, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8162, "s": 8142, "text": " Harshit Srivastava" }, { "code": null, "e": 8195, "s": 8162, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 8213, "s": 8195, "text": " Trevoir Williams" }, { "code": null, "e": 8220, "s": 8213, "text": " Print" }, { "code": null, "e": 8231, "s": 8220, "text": " Add Notes" } ]
What is unsigned in MySQL?
Unsigned allows us to enter positive value; you cannot give any negative number. Let us create a table to understand unsigned in MySQL. To create a table, we will use the CREATE command. Let us create a table − mysql> CREATE table UnsignedDemo -> ( -> id int unsigned -> ); Query OK, 0 rows affected (0.61 sec) After that I will insert only positive values. Let us insert some records − mysql> INSERT into UnsignedDemo values(124); Query OK, 1 row affected (0.09 sec) mysql> INSERT into UnsignedDemo values(78967); Query OK, 1 row affected (0.14 sec) I am displaying all the records with the help of SELECT command − mysql> SELECT * from UnsignedDemo; The following is the output +-------+ | id | +-------+ | 124 | | 78967 | +-------+ 2 rows in set (0.00 sec) Now, we will try to insert only negative values. But while doing this, we will get the following error, since the column ‘id’ is unsigned − mysql> INSERT into UnsignedDemo values(-124); ERROR 1264 (22003): Out of range value for column 'id' at row 1
[ { "code": null, "e": 1249, "s": 1062, "text": "Unsigned allows us to enter positive value; you cannot give any negative number. Let us create\na table to understand unsigned in MySQL. To create a table, we will use the CREATE command." }, { "code": null, "e": 1273, "s": 1249, "text": "Let us create a table −" }, { "code": null, "e": 1373, "s": 1273, "text": "mysql> CREATE table UnsignedDemo\n-> (\n-> id int unsigned\n-> );\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1449, "s": 1373, "text": "After that I will insert only positive values. Let us insert some records −" }, { "code": null, "e": 1614, "s": 1449, "text": "mysql> INSERT into UnsignedDemo values(124);\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> INSERT into UnsignedDemo values(78967);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1680, "s": 1614, "text": "I am displaying all the records with the help of SELECT command −" }, { "code": null, "e": 1716, "s": 1680, "text": "mysql> SELECT * from UnsignedDemo;\n" }, { "code": null, "e": 1744, "s": 1716, "text": "The following is the output" }, { "code": null, "e": 1829, "s": 1744, "text": "+-------+\n| id |\n+-------+\n| 124 |\n| 78967 |\n+-------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 1969, "s": 1829, "text": "Now, we will try to insert only negative values. But while doing this, we will get the following\nerror, since the column ‘id’ is unsigned −" }, { "code": null, "e": 2079, "s": 1969, "text": "mysql> INSERT into UnsignedDemo values(-124);\nERROR 1264 (22003): Out of range value for column 'id' at row 1" } ]
How to align Image in HTML? - GeeksforGeeks
21 Jul, 2021 Image alignment is used to move the image at different locations (top, bottom, right, left, middle) in our web pages. We use <img> align attribute to align the image. It is an inline element. Syntax: <img align=”left|right|middle|top|bottom”> Attribute Values: left: It is used for the alignment of image to the left. right: It is used for the alignment of image to the right. middle: It is used for the alignment of image to the middle. top: It is used for the alignment of image to the top. bottom: It is used for the alignment of image to the bottom. To align the image to the left use attribute value as “left”. Syntax: <img align=”left”> Example : HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Left Alignment of Image</title> </head> <body> <h1>GeeksforGeeks</h1> <h3>Welcome to GeeksforGeeks</h3> <h4>Left Alignment of Image</h4> <!-- Keep align attribute value as left --> <img align="left" src="https://media.geeksforgeeks.org/wp- content/uploads/20190506164011/logo3.png" alt=""> </body> </html> Output: To align the image to the right use attribute value as “right”. Syntax: <img align=”right”> Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Right Alignment of Image</title> </head> <body> <h1>GeeksforGeeks</h1> <h3>Welcome to GeeksforGeeks</h3> <h4>Right Alignment of Image</h4> <!-- Keep align attribute value as right --> <img align="right" src="https://media.geeksforgeeks.org/wp- content/uploads/20190506164011/logo3.png" alt=""> </body> </html> Output: To align the image to the right use attribute value as “middle”. Syntax: <img align=”middle”> Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Alignment</title> </head> <body> <h1>GeeksforGeeks</h1> <h3>Welcome to GeeksforGeeks</h3> <h4>Middle Alignment of Image</h4> <!-- Keep align attribute value as "middle" --> <h4>GeeksforGeeks <img align="middle" src="https://media.geeksforgeeks.org/wp- content/uploads/20190506164011/logo3.png" alt="">GeeksforGeeks</h4> </body> </html> Output: To align the image to the right use attribute value as “top”. Syntax: <img align=”top”> Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Alignment</title> </head> <body> <h1>GeeksforGeeks</h1> <h3>Welcome to GeeksforGeeks</h3> <h4>Top Alignment of Image</h4> <!-- Keep align attribute value as "top" --> <h4>GeeksforGeeks <img align="top" src="https://media.geeksforgeeks.org/wp- content/uploads/20190506164011/logo3.png" alt="">GeeksforGeeks</h4> </body> </html> Output: To align the image to the right use attribute value as “bottom”. Syntax: <img align=”bottom”> Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Alignment</title> </head> <body> <h1>GeeksforGeeks</h1> <h3>Welcome to GeeksforGeeks</h3> <h4>Bottom Alignment of Image</h4> <!-- Keep align attribute value as "bottom" --> <h4>GeeksforGeeks <img align="bottom" src="https://media.geeksforgeeks.org/wp- content/uploads/20190506164011/logo3.png" alt="">GeeksforGeeks</h4> </body> </html> Output: Browser Support: anikaseth98 Picked class 7 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience (Off-Campus) 2022 How to Read Text Files with Pandas? Must Do Coding Questions for Product Based Companies TCS NQT Coding Sheet Inshackle - Tool for Instagram Hacks in Kali Linux Libraries in Python Cloud Deployment Models What is a Storage Device? Definition, Types, Examples Generations of Computers - Computer Fundamentals
[ { "code": null, "e": 24135, "s": 24104, "text": " \n21 Jul, 2021\n" }, { "code": null, "e": 24327, "s": 24135, "text": "Image alignment is used to move the image at different locations (top, bottom, right, left, middle) in our web pages. We use <img> align attribute to align the image. It is an inline element." }, { "code": null, "e": 24336, "s": 24327, "text": "Syntax: " }, { "code": null, "e": 24379, "s": 24336, "text": "<img align=”left|right|middle|top|bottom”>" }, { "code": null, "e": 24397, "s": 24379, "text": "Attribute Values:" }, { "code": null, "e": 24454, "s": 24397, "text": "left: It is used for the alignment of image to the left." }, { "code": null, "e": 24513, "s": 24454, "text": "right: It is used for the alignment of image to the right." }, { "code": null, "e": 24574, "s": 24513, "text": "middle: It is used for the alignment of image to the middle." }, { "code": null, "e": 24629, "s": 24574, "text": "top: It is used for the alignment of image to the top." }, { "code": null, "e": 24690, "s": 24629, "text": "bottom: It is used for the alignment of image to the bottom." }, { "code": null, "e": 24752, "s": 24690, "text": "To align the image to the left use attribute value as “left”." }, { "code": null, "e": 24760, "s": 24752, "text": "Syntax:" }, { "code": null, "e": 24779, "s": 24760, "text": "<img align=”left”>" }, { "code": null, "e": 24790, "s": 24779, "text": "Example : " }, { "code": null, "e": 24795, "s": 24790, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Left Alignment of Image</title>\n</head>\n<body>\n <h1>GeeksforGeeks</h1>\n <h3>Welcome to GeeksforGeeks</h3>\n <h4>Left Alignment of Image</h4>\n <!-- Keep align attribute value as left -->\n <img align=\"left\" src=\"https://media.geeksforgeeks.org/wp-\n content/uploads/20190506164011/logo3.png\" alt=\"\">\n</body>\n</html>\n\n\n\n\n\n", "e": 25382, "s": 24805, "text": null }, { "code": null, "e": 25393, "s": 25382, "text": " Output: " }, { "code": null, "e": 25457, "s": 25393, "text": "To align the image to the right use attribute value as “right”." }, { "code": null, "e": 25467, "s": 25457, "text": " Syntax: " }, { "code": null, "e": 25488, "s": 25467, "text": "<img align=”right”> " }, { "code": null, "e": 25499, "s": 25488, "text": "Example: " }, { "code": null, "e": 25504, "s": 25499, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Right Alignment of Image</title>\n</head>\n<body>\n <h1>GeeksforGeeks</h1>\n <h3>Welcome to GeeksforGeeks</h3>\n <h4>Right Alignment of Image</h4>\n <!-- Keep align attribute value as right -->\n <img align=\"right\" src=\"https://media.geeksforgeeks.org/wp-\n content/uploads/20190506164011/logo3.png\" alt=\"\">\n</body>\n</html>\n\n\n\n\n\n", "e": 26096, "s": 25514, "text": null }, { "code": null, "e": 26106, "s": 26096, "text": " Output:" }, { "code": null, "e": 26171, "s": 26106, "text": "To align the image to the right use attribute value as “middle”." }, { "code": null, "e": 26181, "s": 26171, "text": " Syntax: " }, { "code": null, "e": 26202, "s": 26181, "text": "<img align=”middle”>" }, { "code": null, "e": 26213, "s": 26202, "text": " Example: " }, { "code": null, "e": 26218, "s": 26213, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n \n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Image Alignment</title>\n \n</head>\n \n<body>\n <h1>GeeksforGeeks</h1>\n <h3>Welcome to GeeksforGeeks</h3>\n <h4>Middle Alignment of Image</h4>\n <!-- Keep align attribute value as \"middle\" -->\n <h4>GeeksforGeeks <img align=\"middle\" src=\"https://media.geeksforgeeks.org/wp-\n content/uploads/20190506164011/logo3.png\" alt=\"\">GeeksforGeeks</h4>\n</body>\n \n</html>\n\n\n\n\n\n", "e": 26826, "s": 26228, "text": null }, { "code": null, "e": 26836, "s": 26826, "text": " Output:" }, { "code": null, "e": 26898, "s": 26836, "text": "To align the image to the right use attribute value as “top”." }, { "code": null, "e": 26908, "s": 26898, "text": " Syntax: " }, { "code": null, "e": 26926, "s": 26908, "text": "<img align=”top”>" }, { "code": null, "e": 26936, "s": 26926, "text": "Example: " }, { "code": null, "e": 26941, "s": 26936, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n \n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Image Alignment</title>\n \n</head>\n \n<body>\n <h1>GeeksforGeeks</h1>\n <h3>Welcome to GeeksforGeeks</h3>\n <h4>Top Alignment of Image</h4>\n <!-- Keep align attribute value as \"top\" -->\n <h4>GeeksforGeeks <img align=\"top\" src=\"https://media.geeksforgeeks.org/wp-\n content/uploads/20190506164011/logo3.png\" alt=\"\">GeeksforGeeks</h4>\n</body>\n \n</html>\n\n\n\n\n\n", "e": 27540, "s": 26951, "text": null }, { "code": null, "e": 27551, "s": 27540, "text": " Output: " }, { "code": null, "e": 27617, "s": 27551, "text": " To align the image to the right use attribute value as “bottom”." }, { "code": null, "e": 27627, "s": 27617, "text": " Syntax: " }, { "code": null, "e": 27648, "s": 27627, "text": "<img align=”bottom”>" }, { "code": null, "e": 27659, "s": 27648, "text": " Example: " }, { "code": null, "e": 27664, "s": 27659, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n \n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Image Alignment</title>\n \n</head>\n \n<body>\n <h1>GeeksforGeeks</h1>\n <h3>Welcome to GeeksforGeeks</h3>\n <h4>Bottom Alignment of Image</h4>\n <!-- Keep align attribute value as \"bottom\" -->\n <h4>GeeksforGeeks <img align=\"bottom\" src=\"https://media.geeksforgeeks.org/wp-\n content/uploads/20190506164011/logo3.png\" alt=\"\">GeeksforGeeks</h4>\n \n</body>\n \n</html>\n\n\n\n\n\n", "e": 28274, "s": 27674, "text": null }, { "code": null, "e": 28284, "s": 28274, "text": " Output:" }, { "code": null, "e": 28302, "s": 28284, "text": " Browser Support:" }, { "code": null, "e": 28316, "s": 28304, "text": "anikaseth98" }, { "code": null, "e": 28325, "s": 28316, "text": "\nPicked\n" }, { "code": null, "e": 28335, "s": 28325, "text": "\nclass 7\n" }, { "code": null, "e": 28353, "s": 28335, "text": "\nSchool Learning\n" }, { "code": null, "e": 28374, "s": 28353, "text": "\nSchool Programming\n" }, { "code": null, "e": 28579, "s": 28374, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28625, "s": 28579, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 28661, "s": 28625, "text": "How to Read Text Files with Pandas?" }, { "code": null, "e": 28714, "s": 28661, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 28735, "s": 28714, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 28786, "s": 28735, "text": "Inshackle - Tool for Instagram Hacks in Kali Linux" }, { "code": null, "e": 28806, "s": 28786, "text": "Libraries in Python" }, { "code": null, "e": 28830, "s": 28806, "text": "Cloud Deployment Models" }, { "code": null, "e": 28884, "s": 28830, "text": "What is a Storage Device? Definition, Types, Examples" } ]
A Math Lover’s Guide to Hidden Markov Models | by Sachin Date | Towards Data Science
A Hidden Markov Model can be used to study phenomena in which only a portion of the phenomenon can be directly observed while the rest of it cannot be directly observed, although its effect can be felt on what is observed. The effect of the unobserved portion can only be estimated. We represent such phenomena using a mixture of two random processes. One of the two processes is a ‘visible process’. It is used to represent the observable portion of the phenomenon. The visible process is modeled using a suitable regression model such as ARIMA, the Integer Poisson model, or the ever popular Linear Model. The portion that cannot be observed is represented by a ‘hidden process’ which is modeled using a Markov process model. If you are new to Markov processes, please read the following article and then come back here to continue reading: towardsdatascience.com Let’s illustrate how a Hidden Markov Model can be used to represent a real world data set. The following graphic shows the monthly unemployment rate in the United States: The above graph shows large scale regions of positive and negative growth. We hypothesize that there is some hidden process at play that is unbeknownst to the observer, flip-flopping between two ‘regimes’ and the current regime in effect is influencing the observed trend in the inflation rate. While modeling the above data set, we will consider a regression model that is a mixture of the following two random variables: The observable random variable y_t, which would be used to represent the observable pattern in unemployment rate. At each time step t, y_t is simply the observed value of the unemployment rate at t. A hidden random variable s_t which is assumed to change its state or regime, and each time the regime changes, it affects the observed pattern of employment. In other words, a change in value of s_t impacts the mean and variance of y_t. This is the primary idea behind Hidden Markov Models. We’ll see how to precisely express this relationship between y_t and s_t. For now, let’s assume that s_t switches between two regimes 1 and 2. The important question is: why are we calling s_t a ‘hidden’ random variable? We call s_t hidden because we do not know exactly when it changes its regime. If we knew which regime was in effect at each time step, we would have simply made s_t a regression variable and we would have regressed y_t on s_t! For the unemployment data set, we will assume that s_t obeys a 2-state Markov process having the following state transition diagram: The Markov chain shown above has two states, or regimes numbered as 1 and 2. There are four kinds of state transitions possible between the two states: State 1 to state 1: This transition happens with probability p_11. Thus p_11= P(s_t=1|s_(t-1)=1). This is read as the probability that the system is in regime 1 at time t, given that it was in regime 1 at the previous time step (t-1). State 1 to State 2 with transition probability:p_12= P(s_t=2|s_(t-1)=1). State 2 to State 1 with transition probability:p_21=P(s_t=1|s_(t-1)=2). State 2 to State 2 with transition probability:p_22= P(s_t=2|s_(t-1)=2). Since the Markov process needs to be in some state at each time step, it follows that: p11 + p12 = 1, and, p21 + p22 = 1 The state transition matrix P lets us express all transition probabilities in a compact matrix form as follows: P contains the probabilities of transition to the next state which are conditional upon what is the current state. The state probability vector π_t contains the unconditional probability of being in a certain state at time t. For our 2-step Markov random variable s_t, the state probability distribution π_t, (a.k.a. δ_t) is given by the following 2-element vector: It can be shown that if we start with some prior (initial) probability distribution for s_t as π_0, then π_t can be computed by simply matrix multiplying P with itself t number of times and multiplying π_0 by the matrix product P^t: We have thus completed the formulation of the Markov distributed random variable s_t. Recollect that we are assuming s_t to be the hidden variable. Let’s pause for a second and remind ourselves of two important things that we do not know: We do not know the exact time steps at which s_t makes the transition from one state to another. We also do not know the transition probabilities P or the state probability distribution π_t. Therefore, what we have done so far is to hypothesize that there exists a two-regime Markov process characterized by the random variable s_t, and s_t is influencing the observed unemployment rate which is characterized by the random variable y_t. For a second, let’s assume that there is no hidden Markov process influencing the unemployment rate y_t. And with that assumption, let us construct the following regression model for the unemployment rate y_t: We are saying that at any time t, the observed unemployment rate y_t is the sum of the modeled mean μ_cap_t and the residual error ε_t. The modeled mean μ_cap_t is the regression model’s prediction of unemployment rate at time t. The residual error ε_t is simply the predicted rate subtracted from the observed rate. We’ll use the terms modeled mean and predicted mean interchangeably. We will further assume that we have used a really good regression model to calculate the modeled mean μ_cap_t. And therefore, the residual error ε_t can be assumed to be homoskedastic i.e. its variance does not vary with the mean, and furthermore, ε_t is normally distributed around a zero mean and some variance σ2. In notation form, ε_t is an N(0, σ2) distributed random variable. Let us now return to μ_cap_t. Since μ_cap_t is the predicted value of the regression model, μ_cap_t is actually the output of some regression function η(.) such that: μ_cap_t = η(.) Different choices of η(.) will yield different families of regression models. For example, if η(.) = 0, we get the white noise model: y_t = ε_t. If η(.) is the constant mean y_bar of all observations i.e.: y_bar=(y_1+y2+...+y_n)/n, we get a mean model: y_t = y_bar. A more interesting model might rely upon a set of ‘m+1’ number of regression coefficients β_cap=[β_cap_0, β_cap_1, β_cap_2, ..., β_cap_m] that ‘link’ the dependent variable y to a matrix of regression variables X of size [n X (m+1)] as illustrated below: In the above figure, the first column of ones in X acts as the placeholder for the fitted intercept of regression β_cap_0. The ‘cap’ symbol signifies that it is the fitted value of the coefficient after training the model. And x_t is one row of X at time t. If the link function η(x_t, β_cap) is linear, one gets the Linear model.If the link function is exponential, one gets the Poisson, NLS etc. regression models and so on. Let’s take a closer look at the Linear Model, characterized by the following set of equations: At the risk of making the residual errors ε_ t correlated, one is also allowed to introduce lagged values of y_t in x_t, as follows: In case you are wondering, no, the above model is not an Auto-Regressive model in the ARMA sense of that term. Later, we will look at how a ‘real’ AR(1) model looks like. Our model specification isn’t complete unless we also specify the probability (density) function of y_t. In the above model, we will assume y_t to be normally distributed with mean μ_cap_t, and constant variance σ2: The above equation is to be read as follows: The probability (density) of the unemployment rate being y_t at time t, conditioned upon the regression variables vector x_t and the fitted coefficients vector β_cap is normally distributed with a constant variance σ2 and a conditional mean μ_cap_t given given by the equation below: This completes the formulation of the visible process for y_t. Now let’s ‘mix’ the hidden Markov process and the visible process into a single Hidden Markov Model. The key to understanding Hidden Markov Models lies in understanding how the modeled mean and variance of the visible process are influenced by the hidden Markov process. We will introduce below two ways in which the Markov variable s_t influences μ_cap_t and σ2. Suppose we define our regression model as follows: In the above equation, we are saying that the predicted mean of the model changes depending on which state the underlying Markov process variable s_t is in at time t. As before, the predicted mean μ_cap_t_s_t can be expressed as the output of some link function η(.), i.e. μ_cap_t_s_t = η(.). For this model, we define η(.) as follows: The above equation is a special simple case of the dot product x_t·β_cap, where there are no regression variables involved. So x_t is a matrix of size [1 X 1] containing the number 1 which as we have seen earlier, is the placeholder for the intercept of regression β_0. β_cap is also a [1 x 1] matrix containing only the intercept of regression β_0_s_t. The dot product of the two is the scalar value β_0_s_t which is the value that the intercept takes under the Markov regime s_t at time t. If we assume that the Markov process operates over the set of k states [1,2,3,...j,...,k], it is easier to express the above equation as follows: And the regression model’s equation becomes the following: In the above equation, y_t is the observed value, μ_cap_t_j is the predicted mean when the Markov process is in state j, and ε_t is the residual error of regression. In our unemployment rate data set, we have assumed that s_t toggles between two regimes 1 and 2, which gives us the following specification for μ_cap_t_j: This in turn gives rise to a mixture process for y_t that switches between two means μ_s_1 and μ_s_2 as follows: The corresponding two conditional probability densities of y_t are as follows: But each observed y_t ought to have only one probability density associated with it. We will calculate this single density using the Law of Total Probability which states that if event A can take place pair-wise jointly with either event A1, or event A2, or event A3, and so on, then the unconditional probability of A can be expressed as follows: Here’s a graphical way of looking at it. There are ’n’ different ways of reaching node A: Using this law, we get the unconditional probability density of observing a specific unemployment rate y_t at time t as follows: The astute reader may have noticed that in the above equation we are mixing probabilities with probability densities, but it is okay to do that here. The above equation written in summation form is as follows: In the above equation, the probabilities P(s_t=1) and P(s_t=2) are the state probabilities π_t1 and π_t2 of the 2-state Markov process: And we already know that to calculate the state probabilities, we need to assume some initial conditions and then use the following equation: Where π_0 is the initial value t=0, and P is the state transition matrix: The above model is a simple case of what’s known as the Markov Switching Dynamic Regression (MSDR) family of models. Training this model involves estimating the optimal values of the following variables: The state transition matrix P, i.e. essentially, transition probabilities p_11 and p_22, The state specific regression coefficients β_cap_0_1 and β_cap_0_2, which in our sample data set would correspond to the two predicted unemployment rate levels, and, The constant variance σ2. Estimation can be done using Maximum Likelihood which finds the values of P, β_cap_0_1, β_cap_0_2 (represented together using the β_cap_s) matrix and σ2 that would maximize the joint probability density of observing the entire training data set y. In other words, we would want to maximize the following product: In the above product, the probability density f(y=y_t) is given by Equation (1) that we saw earlier. It is usually easier to maximize the natural logarithm of this product which has the benefit of converting products into summations. Hence we maximize the following log-likelihood: Maximization of Log-Likelihood is done by taking partial derivatives of the log-likelihood w.r.t. each parameter p_11, p_22, β_cap_0_1, β_cap_0_2 and σ2 , setting each partial derivative to zero, and solving the resulting system of five equations using some optimization algorithm such as Newton-Raphson, Nelder-Mead, Powell’s etc. The general equations of the MSDR can be stated as follows: Where, μ_cap_t_j is a function of regression variables matrix x_t and regime-specific fitted coefficients vector β_cap_j. i.e., μ_cap_t_j = η(x_t, β_cap_j) But this time around, notice that the regression coefficients vector is called β_cap_j corresponding to the jth Markov state. If the Markov model operates over ‘k’ states [1,2,...,j,...,k], β_cap_s is a matrix of size [(m+1) X k] as follows: The central idea is that depending on which Markov state or ‘regime’ j in [1, 2,...,k] is currently in effect, the regression model coefficients will switch to the appropriate regime-specific vector β_cap_j from β_cap_s. Hence the name ‘Markov Switching Dynamic Regression model’. The k-state Markov process itself is governed by the following state transition matrix P: And it has the following state probability distribution π_t at time step t: So far, we have assumed a linearly specified conditional mean function for y_t as follows: In the above equation, μ_cap_t_j is the predicted mean at time t under Markov regime j. x_t is the vector of regression variables [x_1t, x_2t,...,x_mt] at time t, and β_cap_j is the vector of regime specific coefficients [β_cap_0j, β_cap_1j, β_cap_2j,...,β_cap_mj]. As we have seen in the 2-state Markov case (refer to Eq. 1), this yields a normally distributed probability density for y_t as follows: Equation (2) is just Equation (1) extended over k Markov states. y_t need not be normally distributed. In fact, suppose y_t represents a whole numbered random process i.e. y_t takes values 0,1,2,...etc. Examples of such processes are the number of motor vehicle accidents per day in New York City, or hourly number of hits on a website. Such processes can be modeled using a Poisson process model. In which case, the Probability Mass Function of a Poisson distributed y_t takes the following form: Where the regime specific mean function is expressed as follows: In the above equation, x_t and β_cap_j have the same meaning as with the linear mean function. Training of the Markov Switching Dynamic Regression model involves the estimation of the optimal values of the following variables: The model’s coefficients: The state transition probabilities: and variance σ2. As before, the estimation procedure can be Maximize Likelihood Estimation (MLE) in which we are solving a system of (k2 +(m+1)*k +1) equations (in practice, much fewer than that number) corresponding to k2 Markov transition probabilities, (m+1)*k coefficients in β_cap_s, and the variance σ2. In an upcoming article, we’ll look at how to build and train both Linear and Poisson MSDR models using Python and the statsmodels library. Let’s now look at another type of Hidden Markov Model known as the Markov Switching Auto Regressive (MSAR) model. Consider the following model equation for the monthly unemployment rate: Here, we are saying that the unemployment rate at time t fluctuates around a regime specific mean value μ_t_s_t. The fluctuation is caused by the sum of two components: The first component represents the fraction of the deviation of the observed value at the previous time step from the fitted regime-specific mean at the previous time step, and, The second component comes from the residual error ε_t. As with the MSDR model, the regime of the hidden Markov process influences the fitted mean of the model. Notice that this model depends not only on the value of the regime at time t but also on what regime was in effect at the previous time step (t-1). The above specification can be easily extended to include p time steps in the past so to get an MSAR model that follows the AR(p) design pattern. The general framework for model specification for the MSAR model, including the specification of the probability density function of y_t and the estimation procedure (MLE or Expectation Maximization) remains the same as with MSDR model. Unfortunately, the dependence of the model on Markov states at previous steps considerably complicates the specification process as well as estimation. We will not get into those details here, but as with the MSDR model, we will look at how to build and train an MSAR model in Python and statsmodels in an upcoming article. U.S. Bureau of Labor Statistics, Unemployment Rate [UNRATE], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/UNRATE, October 29, 2021. Available under Public license. Cameron A. Colin, Trivedi Pravin K., Regression Analysis of Count Data, Econometric Society Monograph No30, Cambridge University Press, 1998. ISBN: 0521635675 James D. Hamilton, Time Series Analysis, Princeton University Press, 2020. ISBN: 0691218633 All images are copyright Sachin Date under CC-BY-NC-SA, unless a different source and copyright are mentioned underneath the image. towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Thanks for reading! If you liked this article, please follow me to receive tips, how-tos and programming advice on regression and time series analysis. Some rights reserved
[ { "code": null, "e": 454, "s": 171, "text": "A Hidden Markov Model can be used to study phenomena in which only a portion of the phenomenon can be directly observed while the rest of it cannot be directly observed, although its effect can be felt on what is observed. The effect of the unobserved portion can only be estimated." }, { "code": null, "e": 523, "s": 454, "text": "We represent such phenomena using a mixture of two random processes." }, { "code": null, "e": 899, "s": 523, "text": "One of the two processes is a ‘visible process’. It is used to represent the observable portion of the phenomenon. The visible process is modeled using a suitable regression model such as ARIMA, the Integer Poisson model, or the ever popular Linear Model. The portion that cannot be observed is represented by a ‘hidden process’ which is modeled using a Markov process model." }, { "code": null, "e": 1014, "s": 899, "text": "If you are new to Markov processes, please read the following article and then come back here to continue reading:" }, { "code": null, "e": 1037, "s": 1014, "text": "towardsdatascience.com" }, { "code": null, "e": 1128, "s": 1037, "text": "Let’s illustrate how a Hidden Markov Model can be used to represent a real world data set." }, { "code": null, "e": 1208, "s": 1128, "text": "The following graphic shows the monthly unemployment rate in the United States:" }, { "code": null, "e": 1503, "s": 1208, "text": "The above graph shows large scale regions of positive and negative growth. We hypothesize that there is some hidden process at play that is unbeknownst to the observer, flip-flopping between two ‘regimes’ and the current regime in effect is influencing the observed trend in the inflation rate." }, { "code": null, "e": 1631, "s": 1503, "text": "While modeling the above data set, we will consider a regression model that is a mixture of the following two random variables:" }, { "code": null, "e": 1830, "s": 1631, "text": "The observable random variable y_t, which would be used to represent the observable pattern in unemployment rate. At each time step t, y_t is simply the observed value of the unemployment rate at t." }, { "code": null, "e": 2121, "s": 1830, "text": "A hidden random variable s_t which is assumed to change its state or regime, and each time the regime changes, it affects the observed pattern of employment. In other words, a change in value of s_t impacts the mean and variance of y_t. This is the primary idea behind Hidden Markov Models." }, { "code": null, "e": 2264, "s": 2121, "text": "We’ll see how to precisely express this relationship between y_t and s_t. For now, let’s assume that s_t switches between two regimes 1 and 2." }, { "code": null, "e": 2342, "s": 2264, "text": "The important question is: why are we calling s_t a ‘hidden’ random variable?" }, { "code": null, "e": 2569, "s": 2342, "text": "We call s_t hidden because we do not know exactly when it changes its regime. If we knew which regime was in effect at each time step, we would have simply made s_t a regression variable and we would have regressed y_t on s_t!" }, { "code": null, "e": 2702, "s": 2569, "text": "For the unemployment data set, we will assume that s_t obeys a 2-state Markov process having the following state transition diagram:" }, { "code": null, "e": 2854, "s": 2702, "text": "The Markov chain shown above has two states, or regimes numbered as 1 and 2. There are four kinds of state transitions possible between the two states:" }, { "code": null, "e": 3089, "s": 2854, "text": "State 1 to state 1: This transition happens with probability p_11. Thus p_11= P(s_t=1|s_(t-1)=1). This is read as the probability that the system is in regime 1 at time t, given that it was in regime 1 at the previous time step (t-1)." }, { "code": null, "e": 3162, "s": 3089, "text": "State 1 to State 2 with transition probability:p_12= P(s_t=2|s_(t-1)=1)." }, { "code": null, "e": 3234, "s": 3162, "text": "State 2 to State 1 with transition probability:p_21=P(s_t=1|s_(t-1)=2)." }, { "code": null, "e": 3307, "s": 3234, "text": "State 2 to State 2 with transition probability:p_22= P(s_t=2|s_(t-1)=2)." }, { "code": null, "e": 3394, "s": 3307, "text": "Since the Markov process needs to be in some state at each time step, it follows that:" }, { "code": null, "e": 3428, "s": 3394, "text": "p11 + p12 = 1, and, p21 + p22 = 1" }, { "code": null, "e": 3540, "s": 3428, "text": "The state transition matrix P lets us express all transition probabilities in a compact matrix form as follows:" }, { "code": null, "e": 3655, "s": 3540, "text": "P contains the probabilities of transition to the next state which are conditional upon what is the current state." }, { "code": null, "e": 3906, "s": 3655, "text": "The state probability vector π_t contains the unconditional probability of being in a certain state at time t. For our 2-step Markov random variable s_t, the state probability distribution π_t, (a.k.a. δ_t) is given by the following 2-element vector:" }, { "code": null, "e": 4139, "s": 3906, "text": "It can be shown that if we start with some prior (initial) probability distribution for s_t as π_0, then π_t can be computed by simply matrix multiplying P with itself t number of times and multiplying π_0 by the matrix product P^t:" }, { "code": null, "e": 4287, "s": 4139, "text": "We have thus completed the formulation of the Markov distributed random variable s_t. Recollect that we are assuming s_t to be the hidden variable." }, { "code": null, "e": 4378, "s": 4287, "text": "Let’s pause for a second and remind ourselves of two important things that we do not know:" }, { "code": null, "e": 4475, "s": 4378, "text": "We do not know the exact time steps at which s_t makes the transition from one state to another." }, { "code": null, "e": 4569, "s": 4475, "text": "We also do not know the transition probabilities P or the state probability distribution π_t." }, { "code": null, "e": 4816, "s": 4569, "text": "Therefore, what we have done so far is to hypothesize that there exists a two-regime Markov process characterized by the random variable s_t, and s_t is influencing the observed unemployment rate which is characterized by the random variable y_t." }, { "code": null, "e": 5026, "s": 4816, "text": "For a second, let’s assume that there is no hidden Markov process influencing the unemployment rate y_t. And with that assumption, let us construct the following regression model for the unemployment rate y_t:" }, { "code": null, "e": 5412, "s": 5026, "text": "We are saying that at any time t, the observed unemployment rate y_t is the sum of the modeled mean μ_cap_t and the residual error ε_t. The modeled mean μ_cap_t is the regression model’s prediction of unemployment rate at time t. The residual error ε_t is simply the predicted rate subtracted from the observed rate. We’ll use the terms modeled mean and predicted mean interchangeably." }, { "code": null, "e": 5795, "s": 5412, "text": "We will further assume that we have used a really good regression model to calculate the modeled mean μ_cap_t. And therefore, the residual error ε_t can be assumed to be homoskedastic i.e. its variance does not vary with the mean, and furthermore, ε_t is normally distributed around a zero mean and some variance σ2. In notation form, ε_t is an N(0, σ2) distributed random variable." }, { "code": null, "e": 5962, "s": 5795, "text": "Let us now return to μ_cap_t. Since μ_cap_t is the predicted value of the regression model, μ_cap_t is actually the output of some regression function η(.) such that:" }, { "code": null, "e": 5977, "s": 5962, "text": "μ_cap_t = η(.)" }, { "code": null, "e": 6055, "s": 5977, "text": "Different choices of η(.) will yield different families of regression models." }, { "code": null, "e": 6122, "s": 6055, "text": "For example, if η(.) = 0, we get the white noise model: y_t = ε_t." }, { "code": null, "e": 6243, "s": 6122, "text": "If η(.) is the constant mean y_bar of all observations i.e.: y_bar=(y_1+y2+...+y_n)/n, we get a mean model: y_t = y_bar." }, { "code": null, "e": 6498, "s": 6243, "text": "A more interesting model might rely upon a set of ‘m+1’ number of regression coefficients β_cap=[β_cap_0, β_cap_1, β_cap_2, ..., β_cap_m] that ‘link’ the dependent variable y to a matrix of regression variables X of size [n X (m+1)] as illustrated below:" }, { "code": null, "e": 6756, "s": 6498, "text": "In the above figure, the first column of ones in X acts as the placeholder for the fitted intercept of regression β_cap_0. The ‘cap’ symbol signifies that it is the fitted value of the coefficient after training the model. And x_t is one row of X at time t." }, { "code": null, "e": 6925, "s": 6756, "text": "If the link function η(x_t, β_cap) is linear, one gets the Linear model.If the link function is exponential, one gets the Poisson, NLS etc. regression models and so on." }, { "code": null, "e": 7020, "s": 6925, "text": "Let’s take a closer look at the Linear Model, characterized by the following set of equations:" }, { "code": null, "e": 7153, "s": 7020, "text": "At the risk of making the residual errors ε_ t correlated, one is also allowed to introduce lagged values of y_t in x_t, as follows:" }, { "code": null, "e": 7324, "s": 7153, "text": "In case you are wondering, no, the above model is not an Auto-Regressive model in the ARMA sense of that term. Later, we will look at how a ‘real’ AR(1) model looks like." }, { "code": null, "e": 7540, "s": 7324, "text": "Our model specification isn’t complete unless we also specify the probability (density) function of y_t. In the above model, we will assume y_t to be normally distributed with mean μ_cap_t, and constant variance σ2:" }, { "code": null, "e": 7869, "s": 7540, "text": "The above equation is to be read as follows: The probability (density) of the unemployment rate being y_t at time t, conditioned upon the regression variables vector x_t and the fitted coefficients vector β_cap is normally distributed with a constant variance σ2 and a conditional mean μ_cap_t given given by the equation below:" }, { "code": null, "e": 7932, "s": 7869, "text": "This completes the formulation of the visible process for y_t." }, { "code": null, "e": 8033, "s": 7932, "text": "Now let’s ‘mix’ the hidden Markov process and the visible process into a single Hidden Markov Model." }, { "code": null, "e": 8203, "s": 8033, "text": "The key to understanding Hidden Markov Models lies in understanding how the modeled mean and variance of the visible process are influenced by the hidden Markov process." }, { "code": null, "e": 8296, "s": 8203, "text": "We will introduce below two ways in which the Markov variable s_t influences μ_cap_t and σ2." }, { "code": null, "e": 8347, "s": 8296, "text": "Suppose we define our regression model as follows:" }, { "code": null, "e": 8514, "s": 8347, "text": "In the above equation, we are saying that the predicted mean of the model changes depending on which state the underlying Markov process variable s_t is in at time t." }, { "code": null, "e": 8640, "s": 8514, "text": "As before, the predicted mean μ_cap_t_s_t can be expressed as the output of some link function η(.), i.e. μ_cap_t_s_t = η(.)." }, { "code": null, "e": 8683, "s": 8640, "text": "For this model, we define η(.) as follows:" }, { "code": null, "e": 9175, "s": 8683, "text": "The above equation is a special simple case of the dot product x_t·β_cap, where there are no regression variables involved. So x_t is a matrix of size [1 X 1] containing the number 1 which as we have seen earlier, is the placeholder for the intercept of regression β_0. β_cap is also a [1 x 1] matrix containing only the intercept of regression β_0_s_t. The dot product of the two is the scalar value β_0_s_t which is the value that the intercept takes under the Markov regime s_t at time t." }, { "code": null, "e": 9321, "s": 9175, "text": "If we assume that the Markov process operates over the set of k states [1,2,3,...j,...,k], it is easier to express the above equation as follows:" }, { "code": null, "e": 9380, "s": 9321, "text": "And the regression model’s equation becomes the following:" }, { "code": null, "e": 9546, "s": 9380, "text": "In the above equation, y_t is the observed value, μ_cap_t_j is the predicted mean when the Markov process is in state j, and ε_t is the residual error of regression." }, { "code": null, "e": 9701, "s": 9546, "text": "In our unemployment rate data set, we have assumed that s_t toggles between two regimes 1 and 2, which gives us the following specification for μ_cap_t_j:" }, { "code": null, "e": 9814, "s": 9701, "text": "This in turn gives rise to a mixture process for y_t that switches between two means μ_s_1 and μ_s_2 as follows:" }, { "code": null, "e": 9893, "s": 9814, "text": "The corresponding two conditional probability densities of y_t are as follows:" }, { "code": null, "e": 9978, "s": 9893, "text": "But each observed y_t ought to have only one probability density associated with it." }, { "code": null, "e": 10241, "s": 9978, "text": "We will calculate this single density using the Law of Total Probability which states that if event A can take place pair-wise jointly with either event A1, or event A2, or event A3, and so on, then the unconditional probability of A can be expressed as follows:" }, { "code": null, "e": 10331, "s": 10241, "text": "Here’s a graphical way of looking at it. There are ’n’ different ways of reaching node A:" }, { "code": null, "e": 10460, "s": 10331, "text": "Using this law, we get the unconditional probability density of observing a specific unemployment rate y_t at time t as follows:" }, { "code": null, "e": 10670, "s": 10460, "text": "The astute reader may have noticed that in the above equation we are mixing probabilities with probability densities, but it is okay to do that here. The above equation written in summation form is as follows:" }, { "code": null, "e": 10806, "s": 10670, "text": "In the above equation, the probabilities P(s_t=1) and P(s_t=2) are the state probabilities π_t1 and π_t2 of the 2-state Markov process:" }, { "code": null, "e": 10948, "s": 10806, "text": "And we already know that to calculate the state probabilities, we need to assume some initial conditions and then use the following equation:" }, { "code": null, "e": 11022, "s": 10948, "text": "Where π_0 is the initial value t=0, and P is the state transition matrix:" }, { "code": null, "e": 11139, "s": 11022, "text": "The above model is a simple case of what’s known as the Markov Switching Dynamic Regression (MSDR) family of models." }, { "code": null, "e": 11226, "s": 11139, "text": "Training this model involves estimating the optimal values of the following variables:" }, { "code": null, "e": 11315, "s": 11226, "text": "The state transition matrix P, i.e. essentially, transition probabilities p_11 and p_22," }, { "code": null, "e": 11481, "s": 11315, "text": "The state specific regression coefficients β_cap_0_1 and β_cap_0_2, which in our sample data set would correspond to the two predicted unemployment rate levels, and," }, { "code": null, "e": 11507, "s": 11481, "text": "The constant variance σ2." }, { "code": null, "e": 11820, "s": 11507, "text": "Estimation can be done using Maximum Likelihood which finds the values of P, β_cap_0_1, β_cap_0_2 (represented together using the β_cap_s) matrix and σ2 that would maximize the joint probability density of observing the entire training data set y. In other words, we would want to maximize the following product:" }, { "code": null, "e": 11921, "s": 11820, "text": "In the above product, the probability density f(y=y_t) is given by Equation (1) that we saw earlier." }, { "code": null, "e": 12102, "s": 11921, "text": "It is usually easier to maximize the natural logarithm of this product which has the benefit of converting products into summations. Hence we maximize the following log-likelihood:" }, { "code": null, "e": 12434, "s": 12102, "text": "Maximization of Log-Likelihood is done by taking partial derivatives of the log-likelihood w.r.t. each parameter p_11, p_22, β_cap_0_1, β_cap_0_2 and σ2 , setting each partial derivative to zero, and solving the resulting system of five equations using some optimization algorithm such as Newton-Raphson, Nelder-Mead, Powell’s etc." }, { "code": null, "e": 12494, "s": 12434, "text": "The general equations of the MSDR can be stated as follows:" }, { "code": null, "e": 12622, "s": 12494, "text": "Where, μ_cap_t_j is a function of regression variables matrix x_t and regime-specific fitted coefficients vector β_cap_j. i.e.," }, { "code": null, "e": 12650, "s": 12622, "text": "μ_cap_t_j = η(x_t, β_cap_j)" }, { "code": null, "e": 12776, "s": 12650, "text": "But this time around, notice that the regression coefficients vector is called β_cap_j corresponding to the jth Markov state." }, { "code": null, "e": 12892, "s": 12776, "text": "If the Markov model operates over ‘k’ states [1,2,...,j,...,k], β_cap_s is a matrix of size [(m+1) X k] as follows:" }, { "code": null, "e": 13173, "s": 12892, "text": "The central idea is that depending on which Markov state or ‘regime’ j in [1, 2,...,k] is currently in effect, the regression model coefficients will switch to the appropriate regime-specific vector β_cap_j from β_cap_s. Hence the name ‘Markov Switching Dynamic Regression model’." }, { "code": null, "e": 13263, "s": 13173, "text": "The k-state Markov process itself is governed by the following state transition matrix P:" }, { "code": null, "e": 13339, "s": 13263, "text": "And it has the following state probability distribution π_t at time step t:" }, { "code": null, "e": 13430, "s": 13339, "text": "So far, we have assumed a linearly specified conditional mean function for y_t as follows:" }, { "code": null, "e": 13696, "s": 13430, "text": "In the above equation, μ_cap_t_j is the predicted mean at time t under Markov regime j. x_t is the vector of regression variables [x_1t, x_2t,...,x_mt] at time t, and β_cap_j is the vector of regime specific coefficients [β_cap_0j, β_cap_1j, β_cap_2j,...,β_cap_mj]." }, { "code": null, "e": 13832, "s": 13696, "text": "As we have seen in the 2-state Markov case (refer to Eq. 1), this yields a normally distributed probability density for y_t as follows:" }, { "code": null, "e": 13897, "s": 13832, "text": "Equation (2) is just Equation (1) extended over k Markov states." }, { "code": null, "e": 14330, "s": 13897, "text": "y_t need not be normally distributed. In fact, suppose y_t represents a whole numbered random process i.e. y_t takes values 0,1,2,...etc. Examples of such processes are the number of motor vehicle accidents per day in New York City, or hourly number of hits on a website. Such processes can be modeled using a Poisson process model. In which case, the Probability Mass Function of a Poisson distributed y_t takes the following form:" }, { "code": null, "e": 14395, "s": 14330, "text": "Where the regime specific mean function is expressed as follows:" }, { "code": null, "e": 14490, "s": 14395, "text": "In the above equation, x_t and β_cap_j have the same meaning as with the linear mean function." }, { "code": null, "e": 14622, "s": 14490, "text": "Training of the Markov Switching Dynamic Regression model involves the estimation of the optimal values of the following variables:" }, { "code": null, "e": 14648, "s": 14622, "text": "The model’s coefficients:" }, { "code": null, "e": 14684, "s": 14648, "text": "The state transition probabilities:" }, { "code": null, "e": 14701, "s": 14684, "text": "and variance σ2." }, { "code": null, "e": 14994, "s": 14701, "text": "As before, the estimation procedure can be Maximize Likelihood Estimation (MLE) in which we are solving a system of (k2 +(m+1)*k +1) equations (in practice, much fewer than that number) corresponding to k2 Markov transition probabilities, (m+1)*k coefficients in β_cap_s, and the variance σ2." }, { "code": null, "e": 15133, "s": 14994, "text": "In an upcoming article, we’ll look at how to build and train both Linear and Poisson MSDR models using Python and the statsmodels library." }, { "code": null, "e": 15247, "s": 15133, "text": "Let’s now look at another type of Hidden Markov Model known as the Markov Switching Auto Regressive (MSAR) model." }, { "code": null, "e": 15320, "s": 15247, "text": "Consider the following model equation for the monthly unemployment rate:" }, { "code": null, "e": 15489, "s": 15320, "text": "Here, we are saying that the unemployment rate at time t fluctuates around a regime specific mean value μ_t_s_t. The fluctuation is caused by the sum of two components:" }, { "code": null, "e": 15667, "s": 15489, "text": "The first component represents the fraction of the deviation of the observed value at the previous time step from the fitted regime-specific mean at the previous time step, and," }, { "code": null, "e": 15723, "s": 15667, "text": "The second component comes from the residual error ε_t." }, { "code": null, "e": 15828, "s": 15723, "text": "As with the MSDR model, the regime of the hidden Markov process influences the fitted mean of the model." }, { "code": null, "e": 15976, "s": 15828, "text": "Notice that this model depends not only on the value of the regime at time t but also on what regime was in effect at the previous time step (t-1)." }, { "code": null, "e": 16122, "s": 15976, "text": "The above specification can be easily extended to include p time steps in the past so to get an MSAR model that follows the AR(p) design pattern." }, { "code": null, "e": 16359, "s": 16122, "text": "The general framework for model specification for the MSAR model, including the specification of the probability density function of y_t and the estimation procedure (MLE or Expectation Maximization) remains the same as with MSDR model." }, { "code": null, "e": 16511, "s": 16359, "text": "Unfortunately, the dependence of the model on Markov states at previous steps considerably complicates the specification process as well as estimation." }, { "code": null, "e": 16683, "s": 16511, "text": "We will not get into those details here, but as with the MSDR model, we will look at how to build and train an MSAR model in Python and statsmodels in an upcoming article." }, { "code": null, "e": 16893, "s": 16683, "text": "U.S. Bureau of Labor Statistics, Unemployment Rate [UNRATE], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/UNRATE, October 29, 2021. Available under Public license." }, { "code": null, "e": 17052, "s": 16893, "text": "Cameron A. Colin, Trivedi Pravin K., Regression Analysis of Count Data, Econometric Society Monograph No30, Cambridge University Press, 1998. ISBN: 0521635675" }, { "code": null, "e": 17144, "s": 17052, "text": "James D. Hamilton, Time Series Analysis, Princeton University Press, 2020. ISBN: 0691218633" }, { "code": null, "e": 17276, "s": 17144, "text": "All images are copyright Sachin Date under CC-BY-NC-SA, unless a different source and copyright are mentioned underneath the image." }, { "code": null, "e": 17299, "s": 17276, "text": "towardsdatascience.com" }, { "code": null, "e": 17322, "s": 17299, "text": "towardsdatascience.com" }, { "code": null, "e": 17345, "s": 17322, "text": "towardsdatascience.com" }, { "code": null, "e": 17368, "s": 17345, "text": "towardsdatascience.com" }, { "code": null, "e": 17520, "s": 17368, "text": "Thanks for reading! If you liked this article, please follow me to receive tips, how-tos and programming advice on regression and time series analysis." } ]
Java & MySQL - Batching with PrepareStatement Object
Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object − Create SQL statements with placeholders. Create SQL statements with placeholders. Create PrepareStatement object using either prepareStatement() methods. Create PrepareStatement object using either prepareStatement() methods. Set auto-commit to false using setAutoCommit(). Set auto-commit to false using setAutoCommit(). Add as many as SQL statements you like into batch using addBatch() method on created statement object. Add as many as SQL statements you like into batch using addBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object. Finally, commit all the changes using commit() method. Finally, commit all the changes using commit() method. This sample code has been written based on the environment and database setup done in the previous chapters. Copy and paste the following example in TestApplication.java, compile and run as follows − 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 INSERT_QUERY = "INSERT INTO Employees(first,last,age) VALUES(?, ?, ?)"; public static void printResultSet(ResultSet rs) throws SQLException{ // Ensure we start with first row rs.beforeFirst(); while(rs.next()){ // Display values System.out.print("ID: " + rs.getInt("id")); System.out.print(", Age: " + rs.getInt("age")); System.out.print(", First: " + rs.getString("first")); System.out.println(", Last: " + rs.getString("last")); } System.out.println(); } public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); PreparedStatement stmt = conn.prepareStatement(INSERT_QUERY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) ) { conn.setAutoCommit(false); ResultSet rs = stmt.executeQuery("Select * from Employees"); printResultSet(rs); // Set the variables stmt.setString( 1, "Pappu" ); stmt.setString( 2, "Singh" ); stmt.setInt( 3, 33 ); // Add it to the batch stmt.addBatch(); // Set the variables stmt.setString( 1, "Pawan" ); stmt.setString( 2, "Singh" ); stmt.setInt( 3, 31 ); // Add it to the batch stmt.addBatch(); // Create an int[] to hold returned values int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes conn.commit(); rs = stmt.executeQuery("Select * from Employees"); printResultSet(rs); stmt.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac TestApplication.java C:\> When you run TestApplication, it produces the following result − C:\>java TestApplication ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal ID: 5, Age: 40, First: John, Last: Paul ID: 7, Age: 35, First: Sita, Last: Singh ID: 8, Age: 20, First: Rita, Last: Tez ID: 9, Age: 20, First: Sita, Last: Singh ID: 10, Age: 30, First: Zia, Last: Ali ID: 11, Age: 35, First: Raj, Last: Kumar ID: 1, Age: 23, First: Zara, Last: Ali ID: 2, Age: 30, First: Mahnaz, Last: Fatma ID: 3, Age: 35, First: Zaid, Last: Khan ID: 4, Age: 33, First: Sumit, Last: Mittal ID: 5, Age: 40, First: John, Last: Paul ID: 7, Age: 35, First: Sita, Last: Singh ID: 8, Age: 20, First: Rita, Last: Tez ID: 9, Age: 20, First: Sita, Last: Singh ID: 10, Age: 30, First: Zia, Last: Ali ID: 11, Age: 35, First: Raj, Last: Kumar ID: 12, Age: 33, First: Pappu, Last: Singh ID: 13, Age: 31, First: Pawan, Last: Singh 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": 2777, "s": 2686, "text": "Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object −" }, { "code": null, "e": 2818, "s": 2777, "text": "Create SQL statements with placeholders." }, { "code": null, "e": 2859, "s": 2818, "text": "Create SQL statements with placeholders." }, { "code": null, "e": 2932, "s": 2859, "text": "Create PrepareStatement object using either prepareStatement() methods." }, { "code": null, "e": 3005, "s": 2932, "text": "Create PrepareStatement object using either prepareStatement() methods." }, { "code": null, "e": 3053, "s": 3005, "text": "Set auto-commit to false using setAutoCommit()." }, { "code": null, "e": 3101, "s": 3053, "text": "Set auto-commit to false using setAutoCommit()." }, { "code": null, "e": 3204, "s": 3101, "text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object." }, { "code": null, "e": 3307, "s": 3204, "text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object." }, { "code": null, "e": 3395, "s": 3307, "text": "Execute all the SQL statements using executeBatch() method on created statement object." }, { "code": null, "e": 3483, "s": 3395, "text": "Execute all the SQL statements using executeBatch() method on created statement object." }, { "code": null, "e": 3538, "s": 3483, "text": "Finally, commit all the changes using commit() method." }, { "code": null, "e": 3593, "s": 3538, "text": "Finally, commit all the changes using commit() method." }, { "code": null, "e": 3702, "s": 3593, "text": "This sample code has been written based on the environment and database setup done in the previous chapters." }, { "code": null, "e": 3793, "s": 3702, "text": "Copy and paste the following example in TestApplication.java, compile and run as follows −" }, { "code": null, "e": 5980, "s": 3793, "text": "import 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 INSERT_QUERY = \"INSERT INTO Employees(first,last,age) VALUES(?, ?, ?)\";\n\n public static void printResultSet(ResultSet rs) throws SQLException{\n // Ensure we start with first row\n rs.beforeFirst();\n while(rs.next()){\n // Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n System.out.println();\n }\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n PreparedStatement stmt = conn.prepareStatement(INSERT_QUERY,\n ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_UPDATABLE)\n ) {\t\t \n conn.setAutoCommit(false);\t \t \n\n ResultSet rs = stmt.executeQuery(\"Select * from Employees\");\n printResultSet(rs);\n\n // Set the variables\n stmt.setString( 1, \"Pappu\" );\n stmt.setString( 2, \"Singh\" );\n stmt.setInt( 3, 33 );\n // Add it to the batch\n stmt.addBatch();\n\n // Set the variables\n stmt.setString( 1, \"Pawan\" );\n stmt.setString( 2, \"Singh\" );\n stmt.setInt( 3, 31 );\n // Add it to the batch\n stmt.addBatch();\n\n // Create an int[] to hold returned values\n int[] count = stmt.executeBatch();\n\n //Explicitly commit statements to apply changes\n conn.commit();\n\n rs = stmt.executeQuery(\"Select * from Employees\");\n printResultSet(rs);\t \n\n stmt.close();\n rs.close();\n\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 6030, "s": 5980, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 6067, "s": 6030, "text": "C:\\>javac TestApplication.java\nC:\\>\n" }, { "code": null, "e": 6132, "s": 6067, "text": "When you run TestApplication, it produces the following result −" }, { "code": null, "e": 7062, "s": 6132, "text": "C:\\>java TestApplication\nID: 1, Age: 23, First: Zara, Last: Ali\nID: 2, Age: 30, First: Mahnaz, Last: Fatma\nID: 3, Age: 35, First: Zaid, Last: Khan\nID: 4, Age: 33, First: Sumit, Last: Mittal\nID: 5, Age: 40, First: John, Last: Paul\nID: 7, Age: 35, First: Sita, Last: Singh\nID: 8, Age: 20, First: Rita, Last: Tez\nID: 9, Age: 20, First: Sita, Last: Singh\nID: 10, Age: 30, First: Zia, Last: Ali\nID: 11, Age: 35, First: Raj, Last: Kumar\n\nID: 1, Age: 23, First: Zara, Last: Ali\nID: 2, Age: 30, First: Mahnaz, Last: Fatma\nID: 3, Age: 35, First: Zaid, Last: Khan\nID: 4, Age: 33, First: Sumit, Last: Mittal\nID: 5, Age: 40, First: John, Last: Paul\nID: 7, Age: 35, First: Sita, Last: Singh\nID: 8, Age: 20, First: Rita, Last: Tez\nID: 9, Age: 20, First: Sita, Last: Singh\nID: 10, Age: 30, First: Zia, Last: Ali\nID: 11, Age: 35, First: Raj, Last: Kumar\nID: 12, Age: 33, First: Pappu, Last: Singh\nID: 13, Age: 31, First: Pawan, Last: Singh\nC:\\>\n" }, { "code": null, "e": 7095, "s": 7062, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 7111, "s": 7095, "text": " Malhar Lathkar" }, { "code": null, "e": 7144, "s": 7111, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7160, "s": 7144, "text": " Malhar Lathkar" }, { "code": null, "e": 7195, "s": 7160, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7209, "s": 7195, "text": " Anadi Sharma" }, { "code": null, "e": 7243, "s": 7209, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 7257, "s": 7243, "text": " Tushar Kale" }, { "code": null, "e": 7294, "s": 7257, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7309, "s": 7294, "text": " Monica Mittal" }, { "code": null, "e": 7342, "s": 7309, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7361, "s": 7342, "text": " Arnab Chakraborty" }, { "code": null, "e": 7368, "s": 7361, "text": " Print" }, { "code": null, "e": 7379, "s": 7368, "text": " Add Notes" } ]
Are you using Pipeline in Scikit-Learn? | by Ankit Goel | Towards Data Science
If you are doing Machine Learning, you would have come across pipelines as they help you to make a better machine learning workflow which is easy to understand and reproducible. In case you are not aware of the pipelines you can refer awesome blogs from Rebecca Vickery “A Simple Guide to Scikit-learn Pipelines” and Saptashwa Bhattacharyya “A Simple Example of Pipeline in Machine Learning with Scikit-learn”. I recently discovered that you can combine Pipeline with GridSearchCV to not only find best hyperparameters for your model but can also find the best transformers for your machine learning tasks like- Scaler to scale your data.Impute strategy to fill missing values.The number of components in PCA you should use. Scaler to scale your data. Impute strategy to fill missing values. The number of components in PCA you should use. and many others. Let’s see how it can be done. To best demonstrate, I am going to use the Titanic dataset from OpenML here to walkthrough on how you can create a data pipeline. You can download the dataset using the following commands- from sklearn.datasets import fetch_openml# Dataset details at- https://www.openml.org/d/40945X, y = fetch_openml("titanic", version=1, as_frame=True, return_X_y=True) Also, have a look at my notebook which have more details about each operation, feel free to download and import it in your environment and play around- github.com I am going to use a subset of features for the demo purposes here. The dataset has both categorical and numerical features and we would be applying different operations on them. Here is the flow- 1. Define numerical and categorical features. 2. For numerical features, fill the missing values and then scale the data. The numerical features in the dataset have few missing values and we are using SimpleImputer here to fill these values, other imputers can be used as well. Also, we should standardize the range of numerical features using Scaling as many machine learning models require features that follow the same scale. I have not defined the strategy for imputing and the scaler need to be used as the same can be searched using GridSearchCV. 3. For categorical features, fill the missing values and then apply one-hot encoding. The ‘Embarked’ feature in our dataset has few missing values. The reason to create a different imputer for this as we have different strategies to fill categorical features. Also, as categorical features have only a few values, I am using OneHotEncoder which is commonly used to create different features for each value in categorical columns. The strategy of imputing is searched using GridSearchCV. 4. Combine numerical and categorical transformer using ColumnTransformer. ColumnTransformer helps to define different transformers for different types of inputs and combine them into a single feature space after transformation. Here we are applying numerical transformer and categorical transformer created above for our numerical and categorical features. 5. Apply PCA to reduce dimensions. Principle Component Analysis aka PCA is a linear dimensionality reduction algorithm that is used to reduce the number of features in the dataset by keeping the maximum variance. We might not need to apply PCA here as it is a small dataset but the idea is to show how you can search for number_of _components in PCA using GridSearchCV. Above, we created a preprocessor pipeline with all the operations we would like to apply to our data. I am going to use Logistic Regression here as a classifier for our problem. In case you are interested to know how you can apply multiple models, Rebecca Vickery has mentioned a nice way of doing it in her blog. Every Data Scientist would be aware of GridSearchCV which helps us to find the best hyperparameters of the model. One thing which is missed is that you can even use it to find out the best transformers with the help of Pipeline. In the preprocessor pipeline we created above, you might have noticed that we didn’t define- The Scaler,Strategy for imputing missing values,The number of components in PCA The Scaler, Strategy for imputing missing values, The number of components in PCA as we can use GridSearchCV to find the optimal value for them. Here is how it can be done- Above, I am trying to find the best Scaler out of 3 different scalers and Impute strategy for our numerical and categorical columns as well as components for PCA along with hyper-parameters for our model. Helpful, isn’t it? Scikit-Learn 0.23.1 has added the functionality to visualize composite estimators which can be very helpful to cross-check the steps you applied. The below code can help you to visualize the data pipeline. Here I created many different transformers on the data which can be computationally intensive. The pipeline provides a parameter ‘memory’ which can be used to cache the transformer if the parameters and input data are identical. We can set ‘memory’ as the directory path where to cache the transformers or it can be a joblib.Memory object. Below, I am using the current directory as the cache directory where all the cache objects for the transformer would be created. cache_dir = "."cached_pipeline = Pipeline(estimators, memory=cache_dir) I use Pipeline all the time as it is super easy to implement and helps us to get rid of many problems. I hope this would help you guys as well to improve your machine learning workflow. If you are just starting your data science journey or would like to learn about some cool python libraries for data science, then check out this- Start your Data Science journey today. Stay Safe !!! Keep Learning !!!
[ { "code": null, "e": 350, "s": 172, "text": "If you are doing Machine Learning, you would have come across pipelines as they help you to make a better machine learning workflow which is easy to understand and reproducible." }, { "code": null, "e": 583, "s": 350, "text": "In case you are not aware of the pipelines you can refer awesome blogs from Rebecca Vickery “A Simple Guide to Scikit-learn Pipelines” and Saptashwa Bhattacharyya “A Simple Example of Pipeline in Machine Learning with Scikit-learn”." }, { "code": null, "e": 784, "s": 583, "text": "I recently discovered that you can combine Pipeline with GridSearchCV to not only find best hyperparameters for your model but can also find the best transformers for your machine learning tasks like-" }, { "code": null, "e": 897, "s": 784, "text": "Scaler to scale your data.Impute strategy to fill missing values.The number of components in PCA you should use." }, { "code": null, "e": 924, "s": 897, "text": "Scaler to scale your data." }, { "code": null, "e": 964, "s": 924, "text": "Impute strategy to fill missing values." }, { "code": null, "e": 1012, "s": 964, "text": "The number of components in PCA you should use." }, { "code": null, "e": 1059, "s": 1012, "text": "and many others. Let’s see how it can be done." }, { "code": null, "e": 1189, "s": 1059, "text": "To best demonstrate, I am going to use the Titanic dataset from OpenML here to walkthrough on how you can create a data pipeline." }, { "code": null, "e": 1248, "s": 1189, "text": "You can download the dataset using the following commands-" }, { "code": null, "e": 1415, "s": 1248, "text": "from sklearn.datasets import fetch_openml# Dataset details at- https://www.openml.org/d/40945X, y = fetch_openml(\"titanic\", version=1, as_frame=True, return_X_y=True)" }, { "code": null, "e": 1567, "s": 1415, "text": "Also, have a look at my notebook which have more details about each operation, feel free to download and import it in your environment and play around-" }, { "code": null, "e": 1578, "s": 1567, "text": "github.com" }, { "code": null, "e": 1774, "s": 1578, "text": "I am going to use a subset of features for the demo purposes here. The dataset has both categorical and numerical features and we would be applying different operations on them. Here is the flow-" }, { "code": null, "e": 1820, "s": 1774, "text": "1. Define numerical and categorical features." }, { "code": null, "e": 1896, "s": 1820, "text": "2. For numerical features, fill the missing values and then scale the data." }, { "code": null, "e": 2327, "s": 1896, "text": "The numerical features in the dataset have few missing values and we are using SimpleImputer here to fill these values, other imputers can be used as well. Also, we should standardize the range of numerical features using Scaling as many machine learning models require features that follow the same scale. I have not defined the strategy for imputing and the scaler need to be used as the same can be searched using GridSearchCV." }, { "code": null, "e": 2413, "s": 2327, "text": "3. For categorical features, fill the missing values and then apply one-hot encoding." }, { "code": null, "e": 2814, "s": 2413, "text": "The ‘Embarked’ feature in our dataset has few missing values. The reason to create a different imputer for this as we have different strategies to fill categorical features. Also, as categorical features have only a few values, I am using OneHotEncoder which is commonly used to create different features for each value in categorical columns. The strategy of imputing is searched using GridSearchCV." }, { "code": null, "e": 2888, "s": 2814, "text": "4. Combine numerical and categorical transformer using ColumnTransformer." }, { "code": null, "e": 3171, "s": 2888, "text": "ColumnTransformer helps to define different transformers for different types of inputs and combine them into a single feature space after transformation. Here we are applying numerical transformer and categorical transformer created above for our numerical and categorical features." }, { "code": null, "e": 3206, "s": 3171, "text": "5. Apply PCA to reduce dimensions." }, { "code": null, "e": 3541, "s": 3206, "text": "Principle Component Analysis aka PCA is a linear dimensionality reduction algorithm that is used to reduce the number of features in the dataset by keeping the maximum variance. We might not need to apply PCA here as it is a small dataset but the idea is to show how you can search for number_of _components in PCA using GridSearchCV." }, { "code": null, "e": 3855, "s": 3541, "text": "Above, we created a preprocessor pipeline with all the operations we would like to apply to our data. I am going to use Logistic Regression here as a classifier for our problem. In case you are interested to know how you can apply multiple models, Rebecca Vickery has mentioned a nice way of doing it in her blog." }, { "code": null, "e": 4177, "s": 3855, "text": "Every Data Scientist would be aware of GridSearchCV which helps us to find the best hyperparameters of the model. One thing which is missed is that you can even use it to find out the best transformers with the help of Pipeline. In the preprocessor pipeline we created above, you might have noticed that we didn’t define-" }, { "code": null, "e": 4257, "s": 4177, "text": "The Scaler,Strategy for imputing missing values,The number of components in PCA" }, { "code": null, "e": 4269, "s": 4257, "text": "The Scaler," }, { "code": null, "e": 4307, "s": 4269, "text": "Strategy for imputing missing values," }, { "code": null, "e": 4339, "s": 4307, "text": "The number of components in PCA" }, { "code": null, "e": 4430, "s": 4339, "text": "as we can use GridSearchCV to find the optimal value for them. Here is how it can be done-" }, { "code": null, "e": 4654, "s": 4430, "text": "Above, I am trying to find the best Scaler out of 3 different scalers and Impute strategy for our numerical and categorical columns as well as components for PCA along with hyper-parameters for our model. Helpful, isn’t it?" }, { "code": null, "e": 4860, "s": 4654, "text": "Scikit-Learn 0.23.1 has added the functionality to visualize composite estimators which can be very helpful to cross-check the steps you applied. The below code can help you to visualize the data pipeline." }, { "code": null, "e": 5329, "s": 4860, "text": "Here I created many different transformers on the data which can be computationally intensive. The pipeline provides a parameter ‘memory’ which can be used to cache the transformer if the parameters and input data are identical. We can set ‘memory’ as the directory path where to cache the transformers or it can be a joblib.Memory object. Below, I am using the current directory as the cache directory where all the cache objects for the transformer would be created." }, { "code": null, "e": 5401, "s": 5329, "text": "cache_dir = \".\"cached_pipeline = Pipeline(estimators, memory=cache_dir)" }, { "code": null, "e": 5772, "s": 5401, "text": "I use Pipeline all the time as it is super easy to implement and helps us to get rid of many problems. I hope this would help you guys as well to improve your machine learning workflow. If you are just starting your data science journey or would like to learn about some cool python libraries for data science, then check out this- Start your Data Science journey today." } ]
How to add button to notifications in android?
This example demonstrate about How to add button to notifications in android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding= "utf-8" ?> <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 :padding= "16dp" tools :context= ".MainActivity" > <Button android :id= "@+id/btnCreateNotification" android :layout_width= "wrap_content" android :layout_height= "wrap_content" android :layout_alignParentStart= "true" android :layout_alignParentEnd= "true" android :layout_centerInParent= "true" android :text= "Create Notification" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.app.PendingIntent ; import android.content.Intent ; import android.os.Bundle ; import android.support.v4.app.NotificationCompat ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; import android.widget.Button ; public class MainActivity extends AppCompatActivity { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ; btnCreateNotification.setOnClickListener( new View.OnClickListener() { @Override public void onClick (View v) { Intent snoozeIntent = new Intent(MainActivity. this, MainActivity. class ) ; snoozeIntent.setAction( "ACTION_SNOOZE" ) ; snoozeIntent.putExtra( "EXTRA_NOTIFICATION_ID" , 0 ) ; PendingIntent snoozePendingIntent = PendingIntent. getBroadcast (MainActivity. this, 0 , snoozeIntent , 0 ) ; NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ; mBuilder.setContentTitle( "My Notification" ) ; mBuilder.setContentText( "Notification Listener Service Example" ) ; mBuilder.setTicker( "Notification Listener Service Example" ) ; mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; mBuilder.addAction(R.drawable. ic_launcher_foreground , "Snooze" , snoozePendingIntent) ; mBuilder.setAutoCancel( true ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; assert mNotificationManager != null; mNotificationManager.createNotificationChannel(notificationChannel) ; } assert mNotificationManager != null; mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ; } }) ; } } Step 4 − Add the following code to AndroidManifest.xml <? xml version = "1.0" encoding = "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "app.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <application android :allowBackup = "true" android :icon = "@mipmap/ic_launcher" android :label = "@string/app_name" android :roundIcon = "@mipmap/ic_launcher_round" android :supportsRtl = "true" android :theme = "@style/AppTheme" > <activity android :name = ".MainActivity" > <intent-filter> <action android :name = "android.intent.action.MAIN" /> <category android :name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrate about How to add button to notifications in android" }, { "code": null, "e": 1268, "s": 1139, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1333, "s": 1268, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2005, "s": 1333, "text": "<? xml version = \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :padding= \"16dp\"\n tools :context= \".MainActivity\" >\n <Button\n android :id= \"@+id/btnCreateNotification\"\n android :layout_width= \"wrap_content\"\n android :layout_height= \"wrap_content\"\n android :layout_alignParentStart= \"true\"\n android :layout_alignParentEnd= \"true\"\n android :layout_centerInParent= \"true\"\n android :text= \"Create Notification\" />\n</RelativeLayout>" }, { "code": null, "e": 2058, "s": 2005, "text": "Step 3 − Add the following code to src/MainActivity." }, { "code": null, "e": 4749, "s": 2058, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.Button ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;\n btnCreateNotification.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n Intent snoozeIntent = new Intent(MainActivity. this, MainActivity. class ) ;\n snoozeIntent.setAction( \"ACTION_SNOOZE\" ) ;\n snoozeIntent.putExtra( \"EXTRA_NOTIFICATION_ID\" , 0 ) ;\n PendingIntent snoozePendingIntent = PendingIntent. getBroadcast (MainActivity. this, 0 , snoozeIntent , 0 ) ;\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setTicker( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.addAction(R.drawable. ic_launcher_foreground , \"Snooze\" , snoozePendingIntent) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n }) ;\n }\n}" }, { "code": null, "e": 4804, "s": 4749, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 5602, "s": 4804, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5949, "s": 5602, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5991, "s": 5949, "text": "Click here to download the project code" } ]
Python | Consecutive String Comparison - GeeksforGeeks
29 Nov, 2019 Sometimes, while working with data, we can have a problem in which we need to perform comparison between a string and it’s next element in a list and return all strings whose next element is similar list. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + loopThis is one way in which this task can be performed. In this, we use zip() to combine the element and it’s next element and then compare for truth and save it in list. # Python3 code to demonstrate working of# Consecutive String Comparison# using zip() + loop # initialize list test_list = ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Consecutive String Comparison# using zip() + loopres = []for i, j in zip(test_list, test_list[1: ]): if i == j: res.append(i) # printing resultprint("List of Consecutive similar elements : " + str(res)) The original list : ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks'] List of Consecutive similar elements : ['gfg', 'best', 'geeks'] Method #2 : Using list comprehension + zip()This task can also be performed using above functionalities. In this, we use one-liner approach to solve this problem using list comprehension. The method is similar to above one. # Python3 code to demonstrate working of# Consecutive String Comparison# using zip() + list comprehension # initialize list test_list = ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks'] # printing original list print("The original list : " + str(test_list)) # Consecutive String Comparison# using zip() + list comprehensionres = [i for (i, j) in zip(test_list, test_list[1:]) if i == j] # printing resultprint("List of Consecutive similar elements : " + str(res)) The original list : ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks'] List of Consecutive similar elements : ['gfg', 'best', 'geeks'] 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 ? 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 Python | os.path.join() method Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n29 Nov, 2019" }, { "code": null, "e": 24561, "s": 24292, "text": "Sometimes, while working with data, we can have a problem in which we need to perform comparison between a string and it’s next element in a list and return all strings whose next element is similar list. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24759, "s": 24561, "text": "Method #1 : Using zip() + loopThis is one way in which this task can be performed. In this, we use zip() to combine the element and it’s next element and then compare for truth and save it in list." }, { "code": "# Python3 code to demonstrate working of# Consecutive String Comparison# using zip() + loop # initialize list test_list = ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks'] # printing original list print(\"The original list : \" + str(test_list)) # Consecutive String Comparison# using zip() + loopres = []for i, j in zip(test_list, test_list[1: ]): if i == j: res.append(i) # printing resultprint(\"List of Consecutive similar elements : \" + str(res))", "e": 25234, "s": 24759, "text": null }, { "code": null, "e": 25381, "s": 25234, "text": "The original list : ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks']\nList of Consecutive similar elements : ['gfg', 'best', 'geeks']\n" }, { "code": null, "e": 25607, "s": 25383, "text": "Method #2 : Using list comprehension + zip()This task can also be performed using above functionalities. In this, we use one-liner approach to solve this problem using list comprehension. The method is similar to above one." }, { "code": "# Python3 code to demonstrate working of# Consecutive String Comparison# using zip() + list comprehension # initialize list test_list = ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks'] # printing original list print(\"The original list : \" + str(test_list)) # Consecutive String Comparison# using zip() + list comprehensionres = [i for (i, j) in zip(test_list, test_list[1:]) if i == j] # printing resultprint(\"List of Consecutive similar elements : \" + str(res))", "e": 26087, "s": 25607, "text": null }, { "code": null, "e": 26234, "s": 26087, "text": "The original list : ['gfg', 'gfg', 'is', 'best', 'best', 'for', 'geeks', 'geeks']\nList of Consecutive similar elements : ['gfg', 'best', 'geeks']\n" }, { "code": null, "e": 26255, "s": 26234, "text": "Python list-programs" }, { "code": null, "e": 26262, "s": 26255, "text": "Python" }, { "code": null, "e": 26278, "s": 26262, "text": "Python Programs" }, { "code": null, "e": 26376, "s": 26278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26408, "s": 26376, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26450, "s": 26408, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26506, "s": 26450, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26548, "s": 26506, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26579, "s": 26548, "text": "Python | os.path.join() method" }, { "code": null, "e": 26601, "s": 26579, "text": "Defaultdict in Python" }, { "code": null, "e": 26647, "s": 26601, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26686, "s": 26647, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26724, "s": 26686, "text": "Python | Convert a list to dictionary" } ]
Tryit Editor v3.7
Tryit: HTML external link
[]
LISP - Data Types
In LISP, variables are not typed, but data objects are. LISP data types can be categorized as. Scalar types − for example, number types, characters, symbols etc. Scalar types − for example, number types, characters, symbols etc. Data structures − for example, lists, vectors, bit-vectors, and strings. Data structures − for example, lists, vectors, bit-vectors, and strings. Any variable can take any LISP object as its value, unless you have declared it explicitly. Although, it is not necessary to specify a data type for a LISP variable, however, it helps in certain loop expansions, in method declarations and some other situations that we will discuss in later chapters. The data types are arranged into a hierarchy. A data type is a set of LISP objects and many objects may belong to one such set. The typep predicate is used for finding whether an object belongs to a specific type. The type-of function returns the data type of a given object. Type specifiers are system-defined symbols for data types. Apart from these system-defined types, you can create your own data types. When a structure type is defined using defstruct function, the name of the structure type becomes a valid type symbol. Create new source code file named main.lisp and type the following code in it. (setq x 10) (setq y 34.567) (setq ch nil) (setq n 123.78) (setq bg 11.0e+4) (setq r 124/2) (print x) (print y) (print n) (print ch) (print bg) (print r) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − 10 34.567 123.78 NIL 110000.0 62 Next let's check the types of the variables used in the previous example. Create new source code file named main. lisp and type the following code in it. (defvar x 10) (defvar y 34.567) (defvar ch nil) (defvar n 123.78) (defvar bg 11.0e+4) (defvar r 124/2) (print (type-of x)) (print (type-of y)) (print (type-of n)) (print (type-of ch)) (print (type-of bg)) (print (type-of r)) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − (INTEGER 0 281474976710655) SINGLE-FLOAT SINGLE-FLOAT NULL SINGLE-FLOAT (INTEGER 0 281474976710655) 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2116, "s": 2060, "text": "In LISP, variables are not typed, but data objects are." }, { "code": null, "e": 2155, "s": 2116, "text": "LISP data types can be categorized as." }, { "code": null, "e": 2222, "s": 2155, "text": "Scalar types − for example, number types, characters, symbols etc." }, { "code": null, "e": 2289, "s": 2222, "text": "Scalar types − for example, number types, characters, symbols etc." }, { "code": null, "e": 2362, "s": 2289, "text": "Data structures − for example, lists, vectors, bit-vectors, and strings." }, { "code": null, "e": 2435, "s": 2362, "text": "Data structures − for example, lists, vectors, bit-vectors, and strings." }, { "code": null, "e": 2527, "s": 2435, "text": "Any variable can take any LISP object as its value, unless you have declared it explicitly." }, { "code": null, "e": 2736, "s": 2527, "text": "Although, it is not necessary to specify a data type for a LISP variable, however, it helps in certain loop expansions, in method declarations and some other situations that we will discuss in later chapters." }, { "code": null, "e": 2864, "s": 2736, "text": "The data types are arranged into a hierarchy. A data type is a set of LISP objects and many objects may belong to one such set." }, { "code": null, "e": 2950, "s": 2864, "text": "The typep predicate is used for finding whether an object belongs to a specific type." }, { "code": null, "e": 3012, "s": 2950, "text": "The type-of function returns the data type of a given object." }, { "code": null, "e": 3071, "s": 3012, "text": "Type specifiers are system-defined symbols for data types." }, { "code": null, "e": 3265, "s": 3071, "text": "Apart from these system-defined types, you can create your own data types. When a structure type is defined using defstruct function, the name of the structure type becomes a valid type symbol." }, { "code": null, "e": 3344, "s": 3265, "text": "Create new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 3498, "s": 3344, "text": "(setq x 10)\n(setq y 34.567)\n(setq ch nil)\n(setq n 123.78)\n(setq bg 11.0e+4)\n(setq r 124/2)\n\n(print x)\n(print y)\n(print n)\n(print ch)\n(print bg)\n(print r)" }, { "code": null, "e": 3607, "s": 3498, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3646, "s": 3607, "text": "10 \n34.567 \n123.78 \nNIL \n110000.0 \n62\n" }, { "code": null, "e": 3800, "s": 3646, "text": "Next let's check the types of the variables used in the previous example. Create new source code file named main. lisp and type the following code in it." }, { "code": null, "e": 4026, "s": 3800, "text": "(defvar x 10)\n(defvar y 34.567)\n(defvar ch nil)\n(defvar n 123.78)\n(defvar bg 11.0e+4)\n(defvar r 124/2)\n\n(print (type-of x))\n(print (type-of y))\n(print (type-of n))\n(print (type-of ch))\n(print (type-of bg))\n(print (type-of r))" }, { "code": null, "e": 4135, "s": 4026, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 4241, "s": 4135, "text": "(INTEGER 0 281474976710655) \nSINGLE-FLOAT \nSINGLE-FLOAT \nNULL \nSINGLE-FLOAT \n(INTEGER 0 281474976710655)\n" }, { "code": null, "e": 4274, "s": 4241, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 4289, "s": 4274, "text": " Arnold Higuit" }, { "code": null, "e": 4296, "s": 4289, "text": " Print" }, { "code": null, "e": 4307, "s": 4296, "text": " Add Notes" } ]
Setting up your PC/Workstation for Deep Learning: Tensorflow and PyTorch — Windows | by Abhinand | Towards Data Science
This article will guide you through the whole process of setting up the required tools and installing drivers required for Deep Learning on your windows machine. Surprisingly, even setting up the environment for doing Deep Learning isn’t that easy. Chances of you breaking something during this process is actually pretty high. I have experienced setting up everything required for Deep Learning from scratch quite a few times, albeit in a different more programmer-friendly OS in Linux. (a guide on that is next in line) There are very few articles explaining the same process for Windows at the moment. So I decided to give it a shot. Recently, after breaking things a few times, I finally found a proper solution to this problem. Not only this method results in a successful setup but it is also much easier than what I’ve seen most others do. Who this tutorial is for and more importantly why Windows? Trust me I am also not a big fan of playing with CUDA on Windows. But more often than not, as developers, we end up working on a laptop or on a powerful rig that’s not only utilized for Deep Learning or programming. In that case, you can’t afford to completely get rid of Windows. If you’re one of those people or just another casual reader owning a Windows machine who’s not that comfortable with Linux in general, this guide is for you. Here are a few things we’ll be covering in this article, Minimum Hardware and Software Requirements Installing Python and required tools Some GPU jargon Installing GPU drivers Installing Tensorflow (CPU and GPU) Installing PyTorch (CPU and GPU) Validating your Installation My personal experience and alternative approaches Conclusion You definitely need an Nvidia GPU to follow along if you’re planning to set it up with GPU support. Developing Deep Learning applications involves training neural networks, which are compute-hungry by nature. It is also by nature more and more parallelization friendly which takes us more and more towards GPUs which are good at exactly that. That is why GPUs come in handy, the vast majority of the deep learning frameworks support GPU-acceleration out of the box so developers and researchers can get productive in minutes without doing any GPU programming which can tend to hold them back. Most of these frameworks (only) support something called CUDA — which can only work with Nvidia GPUs, that’s why you specifically need one from Nvidia. However, it is not impossible on AMD’s cards, for more information visit this page. If you’re not going to set up for GPU, no problem you can still follow along. But of course, you should have a decent CPU, RAM and Storage to be able to do some Deep Learning. My hardware — I set this up on my personal laptop which has the following configuration, CPU — AMD Ryzen 7 4800HS 8C -16T@ 4.2GHz on Turbo. RAM — 16 GB DDR4 RAM@ 3200MHz GPU — Nvidia GeForce RTX 2060 Max-Q @ 6GB GDDR6 Memory For anyone who is interested in knowing about the configurations, I recommend a decent CPU with a minimum of 4 cores and at 2.6GHz, at least 16GB of RAM and an Nvidia GPU with at least of 6GB VRAM. For this tutorial, you obviously need to be on Windows 10. I assume some basic knowledge of Python packages and environments. Nonetheless, it will all be explained. It is recommended that you’re in the latest stable build of 64-bit Windows 10. This tutorial also assumes that you start the installation process on a freshly installed Operating System. If not you can still follow along if you really know what you’re doing. The first step is, of course, to install Python. I recommend installing Python through Mini-Conda. For absolute beginners, I will briefly explain why. Conda is a package manager that helps you with installing, managing and removing all your different packages. It is not the only one though, there is pip — python’s default package manager which I really like. Here we go with conda as it is much more straight-forward and simple to set up in Windows. Anaconda and Mini-Conda are software distributions that come with some very useful Data Science/ML packages preinstalled to save some of your time. Anaconda contains over 150 packages that help in doing Data Science and Machine Learning, which includes everything you might ever need whereas Mini-Conda only comes with a handful of really necessary tools and packages. I recommend going with Mini-Conda because I like to have (almost) complete control over what packages get installed. Keeping things light is indeed not a bad thing at all. It can save you some storage space and of course, you’ll not have some 50 odd packages that you probably never use. To install Mini-Conda, go to this link below, https://docs.conda.io/en/latest/miniconda.html Download the Python3 installers for Windows 64-bit and install it as you’d install any other Windows software. Make sure to tick the checkbox which asks if you want conda and python to be added to PATH. Now you can check if you have python and conda installed by running the following commands. They should display the version numbers otherwise you might need to correctly install mini-conda and add it to PATH. > python --versionPython 3.8.3> conda --versionconda 4.8.4 Next step is to install jupyter-notebook, paste the following command in your command-line interface, > conda install -y jupyter You can verify your installation by running the jupyter notebook, which opens up jupyter notebook for you on the browser. > jupyter notebook This is an important step often missed by many people. It is understandable to use something that contains every known package like Anaconda but to work on your projects and actually build stuff you probably need a custom environment specific to that project or the nature of the work you’re doing. Another great advantage of using a dedicated virtual environment is you can isolate your packages from interacting with global settings which means if by any chance you mess up the packages in your environment you can always throw it away without affecting any of the global packages. It also gives you the flexibility to create environments with any python version backwards in time. So you can stay away from all the new unstable stuff for a while and upgrade later based on support. Creating a conda environment is fairly simple, I am creating it with the name tensorflow for the sake of explainability, you can set it to whatever you want. I am going with python 3.7 because I know it is well supported by Tensorflow. You can verify this through their documentation. By the way, this is where we will end up installing Tensorflow and create a similar environment with the name torch where PyTorch will be installed. > conda create --name tensorflow python=3.7 Once the environment is created you can enter in using this command below, where tensorflow just means the name we gave to this environment earlier. > conda activate tensorflow Once you enter inside the environment you’ll be able to see something like this one the left-hand side of the prompt If by any chance you don’t see this on Powershell, you might want to initialize conda in Powershell only once beforehand, > conda init powershell After that, you might see (base) on the left side as seen in the above image when you’re not inside any environments. You’ll see the env name whenever you enter an env after this. Additionally, you can also install nb tools inside this environment and link it with jupyter notebook which we installed earlier > conda install nb_conda To register the environment with Jupyter Notebooks run this command without breaking lines, > python -m ipykernel install --user --name tensorflow --display-name “Python 3.7 (tensorflow)” To exit out of the conda environment... > conda deactivate Now follow the same steps to create an environment with the name torch > conda create --name torch python=3.7> conda activate torch> conda install nb_conda> python -m ipykernel install --user --name torch --display-name “Python 3.7 (torch)” If the environments are successfully set up you would be able to see this while listing the environments, > conda env list To verify if the respective packages are actually installed inside each environment, you can enter into the environment and do conda list which displays the list of all packages installed in that environment. Before jumping in and installing a few GPU related stuff, it is necessary to understand what is what and why you’ll need these things in place. GPU Drivers — As the name suggests GPU driver is a piece of software that allows your Operating System and its programs to use the GPU hardware. Gamers certainly know this better, if you’re into gaming then you probably need to have this software up to date for the best experience. CUDA — In simple terms, it is a programming interface layer developed by Nvidia that gives access to the GPU’s instruction set and its parallel computation units. Since the GeForce 8 series of GPUs from the late 2010s, almost all GPUs are CUDA capable. For more information, you can visit this page from Nvidia’s website to know if your GPU is CUDA enabled or not. If you own a consumer GPU, for example, something from the GeForce lineup or Titan lineup, for instance, you can see a glimpse of what is supported and what is not in the image below, If you own a laptop you should check the Notebook products list and if you own a full-blown desktop GPU you must obviously look for the other lineup on the left-hand side. As mentioned before, I own an RTX 2060 Max-Q which is listed on the right side. By the way, you don’t have to worry about your card’s title exactly matching what’s listed in the webpage, Max-Q and Super are all just designs sharing the same underlying architecture with some differences in TDP, number of CUDA cores and Tensor cores. For instance, if you own an RTX 2080 Super or 2080 Max-Q or even a 2080 Super Max-Q — it is completely fine if you can just find RTX 2080 in that list. But if your own an RTX 2080Ti or something with Ti at the end, it just means you own the highest-end variant from that particular series, so most probably you’ll find it up there with more capability in terms of VRAM and number of CUDA and Tensor cores. As of Sept. 2020, To be able to use Tensorflow 2.0 your card’s compute capability must be higher than 3.5 but it is recommended that you have atleast 6 for a better experience. Tensorflow 2.0 also needs CUDA version 10 which in turn requires your driver version to be 418.x or higher. PyTorch requires your CUDA version to be atleast 9.2 or higher, it supports 10.1 and 10.2 as well. The compute capability must be atleast higher than 3.0 CuDNN — CUDA Deep Neural Network library (cuDNN) is a GPU-accelerated library of primitives for deep neural networks. cuDNN provides highly tuned implementations for standard routines such as forward and backward convolution, pooling, normalization, and activation layers. (Optional) TensorRT — NVIDIA TensorRT is an SDK for high-performance deep learning inference. It includes a deep learning inference optimizer and runtime that delivers low latency and high-throughput for deep learning inference applications. Before anything you need to identify which GPU you are using. It has to be a CUDA enabled GPU. If you don’t already have a driver installed, you might have to run a Windows Update which automatically handles the installation of useful softwares like Nvidia Control Panel. This will help you in getting to know a lot more information about the GPU, and also a bunch of setting which is off-topic for this article. If you have Nvidia Control Panel, you can open it up from the start menu or by right-clicking on the desktop and choosing Nvidia Control Panel. Once you open it you can verify the GPU driver version by clicking on Help -> System Information. The driver version will be listed at the top of the Details window. As shown in the above GIF, my driver version is 456.x, which is well above the minimum requirement of 418.x so I don’t have to worry about installing any new drivers. It might not be the case for you, to install the latest drivers you can go to this website and enter the correct information about your GPU to download the right driver required. After downloading the drivers, run the installers and choose Express Installation for an easier experience. Once you have the drivers installed, you can verify using Nvidia Control Panel. Another way to install the drivers using the GeForce Experience app from Nvidia if you own a consumer machine originally intended for gaming. This process is very straight forward. This step is OPTIONAL. You can safely ignore this if you’ve already installed the drivers by following the above step or yours isn’t a gaming machine. Download the application from this page. Follow the installer and install the application on your machine. Once it is done, you can open the application and go to the drivers tab, check for updates and install the new drivers. You can also verify the driver version in the application. Since the most important part of installing drivers is now complete, you can either install CUDA toolkit manually or leave conda to handle everything during TF or PyTorch installation which I highly recommend. If you decide to install it manually you can get the installers from this website and follow the instructions there. Once you have CUDA toolkit installed, you can verify it by running nvidia-smi command either in cmd or Powershell. Now finally on to the crux of this tutorial. If you have done everything else previously mentioned, this step is going to be super-easy. We will be installing Tensorflow 2.x through conda. It is very important to enter into the tensorflow environment we created earlier and then follow along, > conda activate tensorflow If you are planning to install with GPU support, run the command below > conda install -c anaconda tensorflow-gpu This installs TensorFlow GPU through the anaconda channel. One key benefit of installing TensorFlow using conda rather than pip is the conda package management system. When TensorFlow is installed using conda, conda installs all the necessary and compatible dependencies for the packages as well. This is done automatically, users do not need to install any additional software via system packages managers or other means. And that also includes the right version of CUDA toolkit required for Tensorflow or PyTorch which makes the process much more hassle-free. The CUDA toolkit that gets installed is only visible inside the environment in which we install tensorflow GPU, that is a huge advantage. Imagine this version of CUDA toolkit messing up your global system’s CUDA versions and PyTorch requiring a completely different version of CUDA to even run. This is the biggest advantage of using a virtual environment. It offers complete isolation between all virtual environments. If everything was successful you won’t get any error message during installation. To verify if tensorflow and required packages are successfully installed you can do conda list which displays the list of installed packages where you will find tensorflow related packages and the CUDA toolkit as well. You can open Python prompt and also verify if tensorflow is installed, >>> import tensorflow as tf>>> tf.__version__'2.1.0' If you get back the version number, congratulations! You’ve done it! Tensorflow is installed successfully. While using Tensorflow in the Python prompt you might get this message saying — “Opened Dynamic Library” which doesn’t mean anything bad, it is just a log message and a good sign that tf is able to open these libraries. Validating the installations on GPU will be covered later. To install Tensorflow for CPU-only you must make just a simple change to the installation command > conda install -c anaconda tensorflow This will install Tensorflow without CUDA toolkit and GPU support. Now that we have covered how to install Tensorflow, installing PyTorch is nothing different. Conda makes the whole process surprisingly simple. First, you should enter into the conda environment we created for torch. > conda activate torch If you want to install PyTorch with CUDA support use the following command, > conda install pytorch torchvision cudatoolkit -c pytorch The above command will install PyTorch with the compatible CUDA toolkit through the PyTorch channel in Conda. To install PyTorch for CPU-only, you can just remove cudatookit from the above command > conda install pytorch torchvision cpuonly -c pytorch This installs PyTorch without any CUDA support. You can verify the installation using > conda list as discussed before. To verify it on Python, use the following lines of code >>> import torch>>> torch.__version__'1.6.0' If it returns back the version number, you’re done installing PyTorch. You might think well everything is right and start using these tools but suddenly when you do that you’ll start to see some fatal errors. If by any chance this happens to you, it might be very specific to your machine and the way you have set things up which is too much for me to cover here before actually getting to know a lot more information specific to your case. So, I provide a couple of notebooks to at least help you better validate the installations and make sure TF or PyTorch is making use of the intended hardware. You can find the notebooks in this repository under the folder dl-setup-win. It is up to you to clone the notebook and run the cells. If it displays the correct information then you’re good to go. I have embedded the gist version of the same notebooks below. Note: You might face some errors if you do not launch the jupyter notebook from the correct environment. If you want to use tensorflow environment for example, you can launch the notebook from base env and change your kernel to tensorflow env but I have experienced errors while doing that. So to run TF launch your notebook from tensorflow environment and to run PyTorch launch your notebook from torch environment and not from base or something else. If you know a solution to this problem, let me know in the comments down below. I have been using this setup for some light Deep Learning workloads for which my local hardware is sufficient enough. It has been a couple of weeks and so far everything has been functioning as expected in this setup. However, I have tried several other methods before and broke things up quite badly. One such method I tried was this here, it involves enabling CUDA and Nvidia drivers inside WSL to utilize the GPU for Deep Learning. This, at the moment, is still in preview phase but once this comes out officially this is going to be a real game-changer for DL practitioners. It brings together the amazing WSL2 and the CUDA/GPU drivers. But as always there is a catch. It is required that you are part of the Windows Insider Program to make use of this feature. And of course, the Insider Preview builds tend to be buggy at best from my experience. For me, it caused a complete failure of all Windows applications at times, GSOD (Green Screen of Death) errors, not booting up properly and driver failures to name a few. I personally don’t like being in an unstable environment, so it was only a matter of time before I decided to opt-out for once and for all. You could still use a Preview Build with all those features without any problems, it is just that my experience is bad enough with Preview builds to not recommend anyone. Another alternative is to completely move away from Windows and opt for a Linux based operating system to make things much smoother. It is just that you do not get the fancy GUI installers that take care of everything like in Windows. In my next post, I’ll discuss how to set up your Deep Learning environment in Linux from scratch without conda. In this post, I have only covered the installation of Tensorflow, PyTorch and Jupyter tools. You might want to install everything else you need for your workflow. I hope you found this post useful. Hopefully, this helped you set up your Deep Learning environment without any problems. In case you faced any problems, I highly recommend checking out the StackOverflow and Nvidia forums. Also the discussions on PyTorch and Tensorflow GitHub repositories. I will be writing more tutorials and setup guides in the future too. You can follow me on Medium to never miss a thing. You can also follow me on, Twitter — LinkedIn — GitHub — Kaggle Thanks a lot for reading all the way. Have a great day!
[ { "code": null, "e": 694, "s": 172, "text": "This article will guide you through the whole process of setting up the required tools and installing drivers required for Deep Learning on your windows machine. Surprisingly, even setting up the environment for doing Deep Learning isn’t that easy. Chances of you breaking something during this process is actually pretty high. I have experienced setting up everything required for Deep Learning from scratch quite a few times, albeit in a different more programmer-friendly OS in Linux. (a guide on that is next in line)" }, { "code": null, "e": 1019, "s": 694, "text": "There are very few articles explaining the same process for Windows at the moment. So I decided to give it a shot. Recently, after breaking things a few times, I finally found a proper solution to this problem. Not only this method results in a successful setup but it is also much easier than what I’ve seen most others do." }, { "code": null, "e": 1078, "s": 1019, "text": "Who this tutorial is for and more importantly why Windows?" }, { "code": null, "e": 1517, "s": 1078, "text": "Trust me I am also not a big fan of playing with CUDA on Windows. But more often than not, as developers, we end up working on a laptop or on a powerful rig that’s not only utilized for Deep Learning or programming. In that case, you can’t afford to completely get rid of Windows. If you’re one of those people or just another casual reader owning a Windows machine who’s not that comfortable with Linux in general, this guide is for you." }, { "code": null, "e": 1574, "s": 1517, "text": "Here are a few things we’ll be covering in this article," }, { "code": null, "e": 1617, "s": 1574, "text": "Minimum Hardware and Software Requirements" }, { "code": null, "e": 1654, "s": 1617, "text": "Installing Python and required tools" }, { "code": null, "e": 1670, "s": 1654, "text": "Some GPU jargon" }, { "code": null, "e": 1693, "s": 1670, "text": "Installing GPU drivers" }, { "code": null, "e": 1729, "s": 1693, "text": "Installing Tensorflow (CPU and GPU)" }, { "code": null, "e": 1762, "s": 1729, "text": "Installing PyTorch (CPU and GPU)" }, { "code": null, "e": 1791, "s": 1762, "text": "Validating your Installation" }, { "code": null, "e": 1841, "s": 1791, "text": "My personal experience and alternative approaches" }, { "code": null, "e": 1852, "s": 1841, "text": "Conclusion" }, { "code": null, "e": 1952, "s": 1852, "text": "You definitely need an Nvidia GPU to follow along if you’re planning to set it up with GPU support." }, { "code": null, "e": 2445, "s": 1952, "text": "Developing Deep Learning applications involves training neural networks, which are compute-hungry by nature. It is also by nature more and more parallelization friendly which takes us more and more towards GPUs which are good at exactly that. That is why GPUs come in handy, the vast majority of the deep learning frameworks support GPU-acceleration out of the box so developers and researchers can get productive in minutes without doing any GPU programming which can tend to hold them back." }, { "code": null, "e": 2681, "s": 2445, "text": "Most of these frameworks (only) support something called CUDA — which can only work with Nvidia GPUs, that’s why you specifically need one from Nvidia. However, it is not impossible on AMD’s cards, for more information visit this page." }, { "code": null, "e": 2759, "s": 2681, "text": "If you’re not going to set up for GPU, no problem you can still follow along." }, { "code": null, "e": 2857, "s": 2759, "text": "But of course, you should have a decent CPU, RAM and Storage to be able to do some Deep Learning." }, { "code": null, "e": 2946, "s": 2857, "text": "My hardware — I set this up on my personal laptop which has the following configuration," }, { "code": null, "e": 2997, "s": 2946, "text": "CPU — AMD Ryzen 7 4800HS 8C -16T@ 4.2GHz on Turbo." }, { "code": null, "e": 3027, "s": 2997, "text": "RAM — 16 GB DDR4 RAM@ 3200MHz" }, { "code": null, "e": 3082, "s": 3027, "text": "GPU — Nvidia GeForce RTX 2060 Max-Q @ 6GB GDDR6 Memory" }, { "code": null, "e": 3280, "s": 3082, "text": "For anyone who is interested in knowing about the configurations, I recommend a decent CPU with a minimum of 4 cores and at 2.6GHz, at least 16GB of RAM and an Nvidia GPU with at least of 6GB VRAM." }, { "code": null, "e": 3445, "s": 3280, "text": "For this tutorial, you obviously need to be on Windows 10. I assume some basic knowledge of Python packages and environments. Nonetheless, it will all be explained." }, { "code": null, "e": 3524, "s": 3445, "text": "It is recommended that you’re in the latest stable build of 64-bit Windows 10." }, { "code": null, "e": 3704, "s": 3524, "text": "This tutorial also assumes that you start the installation process on a freshly installed Operating System. If not you can still follow along if you really know what you’re doing." }, { "code": null, "e": 3855, "s": 3704, "text": "The first step is, of course, to install Python. I recommend installing Python through Mini-Conda. For absolute beginners, I will briefly explain why." }, { "code": null, "e": 4156, "s": 3855, "text": "Conda is a package manager that helps you with installing, managing and removing all your different packages. It is not the only one though, there is pip — python’s default package manager which I really like. Here we go with conda as it is much more straight-forward and simple to set up in Windows." }, { "code": null, "e": 4525, "s": 4156, "text": "Anaconda and Mini-Conda are software distributions that come with some very useful Data Science/ML packages preinstalled to save some of your time. Anaconda contains over 150 packages that help in doing Data Science and Machine Learning, which includes everything you might ever need whereas Mini-Conda only comes with a handful of really necessary tools and packages." }, { "code": null, "e": 4813, "s": 4525, "text": "I recommend going with Mini-Conda because I like to have (almost) complete control over what packages get installed. Keeping things light is indeed not a bad thing at all. It can save you some storage space and of course, you’ll not have some 50 odd packages that you probably never use." }, { "code": null, "e": 4906, "s": 4813, "text": "To install Mini-Conda, go to this link below, https://docs.conda.io/en/latest/miniconda.html" }, { "code": null, "e": 5109, "s": 4906, "text": "Download the Python3 installers for Windows 64-bit and install it as you’d install any other Windows software. Make sure to tick the checkbox which asks if you want conda and python to be added to PATH." }, { "code": null, "e": 5318, "s": 5109, "text": "Now you can check if you have python and conda installed by running the following commands. They should display the version numbers otherwise you might need to correctly install mini-conda and add it to PATH." }, { "code": null, "e": 5377, "s": 5318, "text": "> python --versionPython 3.8.3> conda --versionconda 4.8.4" }, { "code": null, "e": 5479, "s": 5377, "text": "Next step is to install jupyter-notebook, paste the following command in your command-line interface," }, { "code": null, "e": 5506, "s": 5479, "text": "> conda install -y jupyter" }, { "code": null, "e": 5628, "s": 5506, "text": "You can verify your installation by running the jupyter notebook, which opens up jupyter notebook for you on the browser." }, { "code": null, "e": 5647, "s": 5628, "text": "> jupyter notebook" }, { "code": null, "e": 6231, "s": 5647, "text": "This is an important step often missed by many people. It is understandable to use something that contains every known package like Anaconda but to work on your projects and actually build stuff you probably need a custom environment specific to that project or the nature of the work you’re doing. Another great advantage of using a dedicated virtual environment is you can isolate your packages from interacting with global settings which means if by any chance you mess up the packages in your environment you can always throw it away without affecting any of the global packages." }, { "code": null, "e": 6432, "s": 6231, "text": "It also gives you the flexibility to create environments with any python version backwards in time. So you can stay away from all the new unstable stuff for a while and upgrade later based on support." }, { "code": null, "e": 6866, "s": 6432, "text": "Creating a conda environment is fairly simple, I am creating it with the name tensorflow for the sake of explainability, you can set it to whatever you want. I am going with python 3.7 because I know it is well supported by Tensorflow. You can verify this through their documentation. By the way, this is where we will end up installing Tensorflow and create a similar environment with the name torch where PyTorch will be installed." }, { "code": null, "e": 6910, "s": 6866, "text": "> conda create --name tensorflow python=3.7" }, { "code": null, "e": 7059, "s": 6910, "text": "Once the environment is created you can enter in using this command below, where tensorflow just means the name we gave to this environment earlier." }, { "code": null, "e": 7087, "s": 7059, "text": "> conda activate tensorflow" }, { "code": null, "e": 7204, "s": 7087, "text": "Once you enter inside the environment you’ll be able to see something like this one the left-hand side of the prompt" }, { "code": null, "e": 7326, "s": 7204, "text": "If by any chance you don’t see this on Powershell, you might want to initialize conda in Powershell only once beforehand," }, { "code": null, "e": 7350, "s": 7326, "text": "> conda init powershell" }, { "code": null, "e": 7530, "s": 7350, "text": "After that, you might see (base) on the left side as seen in the above image when you’re not inside any environments. You’ll see the env name whenever you enter an env after this." }, { "code": null, "e": 7659, "s": 7530, "text": "Additionally, you can also install nb tools inside this environment and link it with jupyter notebook which we installed earlier" }, { "code": null, "e": 7684, "s": 7659, "text": "> conda install nb_conda" }, { "code": null, "e": 7776, "s": 7684, "text": "To register the environment with Jupyter Notebooks run this command without breaking lines," }, { "code": null, "e": 7872, "s": 7776, "text": "> python -m ipykernel install --user --name tensorflow --display-name “Python 3.7 (tensorflow)”" }, { "code": null, "e": 7912, "s": 7872, "text": "To exit out of the conda environment..." }, { "code": null, "e": 7931, "s": 7912, "text": "> conda deactivate" }, { "code": null, "e": 8002, "s": 7931, "text": "Now follow the same steps to create an environment with the name torch" }, { "code": null, "e": 8172, "s": 8002, "text": "> conda create --name torch python=3.7> conda activate torch> conda install nb_conda> python -m ipykernel install --user --name torch --display-name “Python 3.7 (torch)”" }, { "code": null, "e": 8278, "s": 8172, "text": "If the environments are successfully set up you would be able to see this while listing the environments," }, { "code": null, "e": 8295, "s": 8278, "text": "> conda env list" }, { "code": null, "e": 8504, "s": 8295, "text": "To verify if the respective packages are actually installed inside each environment, you can enter into the environment and do conda list which displays the list of all packages installed in that environment." }, { "code": null, "e": 8648, "s": 8504, "text": "Before jumping in and installing a few GPU related stuff, it is necessary to understand what is what and why you’ll need these things in place." }, { "code": null, "e": 8931, "s": 8648, "text": "GPU Drivers — As the name suggests GPU driver is a piece of software that allows your Operating System and its programs to use the GPU hardware. Gamers certainly know this better, if you’re into gaming then you probably need to have this software up to date for the best experience." }, { "code": null, "e": 9094, "s": 8931, "text": "CUDA — In simple terms, it is a programming interface layer developed by Nvidia that gives access to the GPU’s instruction set and its parallel computation units." }, { "code": null, "e": 9184, "s": 9094, "text": "Since the GeForce 8 series of GPUs from the late 2010s, almost all GPUs are CUDA capable." }, { "code": null, "e": 9296, "s": 9184, "text": "For more information, you can visit this page from Nvidia’s website to know if your GPU is CUDA enabled or not." }, { "code": null, "e": 9480, "s": 9296, "text": "If you own a consumer GPU, for example, something from the GeForce lineup or Titan lineup, for instance, you can see a glimpse of what is supported and what is not in the image below," }, { "code": null, "e": 9652, "s": 9480, "text": "If you own a laptop you should check the Notebook products list and if you own a full-blown desktop GPU you must obviously look for the other lineup on the left-hand side." }, { "code": null, "e": 9986, "s": 9652, "text": "As mentioned before, I own an RTX 2060 Max-Q which is listed on the right side. By the way, you don’t have to worry about your card’s title exactly matching what’s listed in the webpage, Max-Q and Super are all just designs sharing the same underlying architecture with some differences in TDP, number of CUDA cores and Tensor cores." }, { "code": null, "e": 10392, "s": 9986, "text": "For instance, if you own an RTX 2080 Super or 2080 Max-Q or even a 2080 Super Max-Q — it is completely fine if you can just find RTX 2080 in that list. But if your own an RTX 2080Ti or something with Ti at the end, it just means you own the highest-end variant from that particular series, so most probably you’ll find it up there with more capability in terms of VRAM and number of CUDA and Tensor cores." }, { "code": null, "e": 10410, "s": 10392, "text": "As of Sept. 2020," }, { "code": null, "e": 10677, "s": 10410, "text": "To be able to use Tensorflow 2.0 your card’s compute capability must be higher than 3.5 but it is recommended that you have atleast 6 for a better experience. Tensorflow 2.0 also needs CUDA version 10 which in turn requires your driver version to be 418.x or higher." }, { "code": null, "e": 10831, "s": 10677, "text": "PyTorch requires your CUDA version to be atleast 9.2 or higher, it supports 10.1 and 10.2 as well. The compute capability must be atleast higher than 3.0" }, { "code": null, "e": 11104, "s": 10831, "text": "CuDNN — CUDA Deep Neural Network library (cuDNN) is a GPU-accelerated library of primitives for deep neural networks. cuDNN provides highly tuned implementations for standard routines such as forward and backward convolution, pooling, normalization, and activation layers." }, { "code": null, "e": 11346, "s": 11104, "text": "(Optional) TensorRT — NVIDIA TensorRT is an SDK for high-performance deep learning inference. It includes a deep learning inference optimizer and runtime that delivers low latency and high-throughput for deep learning inference applications." }, { "code": null, "e": 11441, "s": 11346, "text": "Before anything you need to identify which GPU you are using. It has to be a CUDA enabled GPU." }, { "code": null, "e": 11759, "s": 11441, "text": "If you don’t already have a driver installed, you might have to run a Windows Update which automatically handles the installation of useful softwares like Nvidia Control Panel. This will help you in getting to know a lot more information about the GPU, and also a bunch of setting which is off-topic for this article." }, { "code": null, "e": 11903, "s": 11759, "text": "If you have Nvidia Control Panel, you can open it up from the start menu or by right-clicking on the desktop and choosing Nvidia Control Panel." }, { "code": null, "e": 12069, "s": 11903, "text": "Once you open it you can verify the GPU driver version by clicking on Help -> System Information. The driver version will be listed at the top of the Details window." }, { "code": null, "e": 12236, "s": 12069, "text": "As shown in the above GIF, my driver version is 456.x, which is well above the minimum requirement of 418.x so I don’t have to worry about installing any new drivers." }, { "code": null, "e": 12415, "s": 12236, "text": "It might not be the case for you, to install the latest drivers you can go to this website and enter the correct information about your GPU to download the right driver required." }, { "code": null, "e": 12603, "s": 12415, "text": "After downloading the drivers, run the installers and choose Express Installation for an easier experience. Once you have the drivers installed, you can verify using Nvidia Control Panel." }, { "code": null, "e": 12784, "s": 12603, "text": "Another way to install the drivers using the GeForce Experience app from Nvidia if you own a consumer machine originally intended for gaming. This process is very straight forward." }, { "code": null, "e": 12935, "s": 12784, "text": "This step is OPTIONAL. You can safely ignore this if you’ve already installed the drivers by following the above step or yours isn’t a gaming machine." }, { "code": null, "e": 13221, "s": 12935, "text": "Download the application from this page. Follow the installer and install the application on your machine. Once it is done, you can open the application and go to the drivers tab, check for updates and install the new drivers. You can also verify the driver version in the application." }, { "code": null, "e": 13431, "s": 13221, "text": "Since the most important part of installing drivers is now complete, you can either install CUDA toolkit manually or leave conda to handle everything during TF or PyTorch installation which I highly recommend." }, { "code": null, "e": 13548, "s": 13431, "text": "If you decide to install it manually you can get the installers from this website and follow the instructions there." }, { "code": null, "e": 13663, "s": 13548, "text": "Once you have CUDA toolkit installed, you can verify it by running nvidia-smi command either in cmd or Powershell." }, { "code": null, "e": 13800, "s": 13663, "text": "Now finally on to the crux of this tutorial. If you have done everything else previously mentioned, this step is going to be super-easy." }, { "code": null, "e": 13852, "s": 13800, "text": "We will be installing Tensorflow 2.x through conda." }, { "code": null, "e": 13956, "s": 13852, "text": "It is very important to enter into the tensorflow environment we created earlier and then follow along," }, { "code": null, "e": 13984, "s": 13956, "text": "> conda activate tensorflow" }, { "code": null, "e": 14055, "s": 13984, "text": "If you are planning to install with GPU support, run the command below" }, { "code": null, "e": 14098, "s": 14055, "text": "> conda install -c anaconda tensorflow-gpu" }, { "code": null, "e": 14521, "s": 14098, "text": "This installs TensorFlow GPU through the anaconda channel. One key benefit of installing TensorFlow using conda rather than pip is the conda package management system. When TensorFlow is installed using conda, conda installs all the necessary and compatible dependencies for the packages as well. This is done automatically, users do not need to install any additional software via system packages managers or other means." }, { "code": null, "e": 14660, "s": 14521, "text": "And that also includes the right version of CUDA toolkit required for Tensorflow or PyTorch which makes the process much more hassle-free." }, { "code": null, "e": 15080, "s": 14660, "text": "The CUDA toolkit that gets installed is only visible inside the environment in which we install tensorflow GPU, that is a huge advantage. Imagine this version of CUDA toolkit messing up your global system’s CUDA versions and PyTorch requiring a completely different version of CUDA to even run. This is the biggest advantage of using a virtual environment. It offers complete isolation between all virtual environments." }, { "code": null, "e": 15162, "s": 15080, "text": "If everything was successful you won’t get any error message during installation." }, { "code": null, "e": 15381, "s": 15162, "text": "To verify if tensorflow and required packages are successfully installed you can do conda list which displays the list of installed packages where you will find tensorflow related packages and the CUDA toolkit as well." }, { "code": null, "e": 15452, "s": 15381, "text": "You can open Python prompt and also verify if tensorflow is installed," }, { "code": null, "e": 15505, "s": 15452, "text": ">>> import tensorflow as tf>>> tf.__version__'2.1.0'" }, { "code": null, "e": 15612, "s": 15505, "text": "If you get back the version number, congratulations! You’ve done it! Tensorflow is installed successfully." }, { "code": null, "e": 15832, "s": 15612, "text": "While using Tensorflow in the Python prompt you might get this message saying — “Opened Dynamic Library” which doesn’t mean anything bad, it is just a log message and a good sign that tf is able to open these libraries." }, { "code": null, "e": 15891, "s": 15832, "text": "Validating the installations on GPU will be covered later." }, { "code": null, "e": 15989, "s": 15891, "text": "To install Tensorflow for CPU-only you must make just a simple change to the installation command" }, { "code": null, "e": 16028, "s": 15989, "text": "> conda install -c anaconda tensorflow" }, { "code": null, "e": 16095, "s": 16028, "text": "This will install Tensorflow without CUDA toolkit and GPU support." }, { "code": null, "e": 16239, "s": 16095, "text": "Now that we have covered how to install Tensorflow, installing PyTorch is nothing different. Conda makes the whole process surprisingly simple." }, { "code": null, "e": 16312, "s": 16239, "text": "First, you should enter into the conda environment we created for torch." }, { "code": null, "e": 16335, "s": 16312, "text": "> conda activate torch" }, { "code": null, "e": 16411, "s": 16335, "text": "If you want to install PyTorch with CUDA support use the following command," }, { "code": null, "e": 16470, "s": 16411, "text": "> conda install pytorch torchvision cudatoolkit -c pytorch" }, { "code": null, "e": 16580, "s": 16470, "text": "The above command will install PyTorch with the compatible CUDA toolkit through the PyTorch channel in Conda." }, { "code": null, "e": 16667, "s": 16580, "text": "To install PyTorch for CPU-only, you can just remove cudatookit from the above command" }, { "code": null, "e": 16722, "s": 16667, "text": "> conda install pytorch torchvision cpuonly -c pytorch" }, { "code": null, "e": 16770, "s": 16722, "text": "This installs PyTorch without any CUDA support." }, { "code": null, "e": 16898, "s": 16770, "text": "You can verify the installation using > conda list as discussed before. To verify it on Python, use the following lines of code" }, { "code": null, "e": 16943, "s": 16898, "text": ">>> import torch>>> torch.__version__'1.6.0'" }, { "code": null, "e": 17014, "s": 16943, "text": "If it returns back the version number, you’re done installing PyTorch." }, { "code": null, "e": 17384, "s": 17014, "text": "You might think well everything is right and start using these tools but suddenly when you do that you’ll start to see some fatal errors. If by any chance this happens to you, it might be very specific to your machine and the way you have set things up which is too much for me to cover here before actually getting to know a lot more information specific to your case." }, { "code": null, "e": 17543, "s": 17384, "text": "So, I provide a couple of notebooks to at least help you better validate the installations and make sure TF or PyTorch is making use of the intended hardware." }, { "code": null, "e": 17740, "s": 17543, "text": "You can find the notebooks in this repository under the folder dl-setup-win. It is up to you to clone the notebook and run the cells. If it displays the correct information then you’re good to go." }, { "code": null, "e": 17802, "s": 17740, "text": "I have embedded the gist version of the same notebooks below." }, { "code": null, "e": 18255, "s": 17802, "text": "Note: You might face some errors if you do not launch the jupyter notebook from the correct environment. If you want to use tensorflow environment for example, you can launch the notebook from base env and change your kernel to tensorflow env but I have experienced errors while doing that. So to run TF launch your notebook from tensorflow environment and to run PyTorch launch your notebook from torch environment and not from base or something else." }, { "code": null, "e": 18335, "s": 18255, "text": "If you know a solution to this problem, let me know in the comments down below." }, { "code": null, "e": 18637, "s": 18335, "text": "I have been using this setup for some light Deep Learning workloads for which my local hardware is sufficient enough. It has been a couple of weeks and so far everything has been functioning as expected in this setup. However, I have tried several other methods before and broke things up quite badly." }, { "code": null, "e": 18976, "s": 18637, "text": "One such method I tried was this here, it involves enabling CUDA and Nvidia drivers inside WSL to utilize the GPU for Deep Learning. This, at the moment, is still in preview phase but once this comes out officially this is going to be a real game-changer for DL practitioners. It brings together the amazing WSL2 and the CUDA/GPU drivers." }, { "code": null, "e": 19499, "s": 18976, "text": "But as always there is a catch. It is required that you are part of the Windows Insider Program to make use of this feature. And of course, the Insider Preview builds tend to be buggy at best from my experience. For me, it caused a complete failure of all Windows applications at times, GSOD (Green Screen of Death) errors, not booting up properly and driver failures to name a few. I personally don’t like being in an unstable environment, so it was only a matter of time before I decided to opt-out for once and for all." }, { "code": null, "e": 19670, "s": 19499, "text": "You could still use a Preview Build with all those features without any problems, it is just that my experience is bad enough with Preview builds to not recommend anyone." }, { "code": null, "e": 19905, "s": 19670, "text": "Another alternative is to completely move away from Windows and opt for a Linux based operating system to make things much smoother. It is just that you do not get the fancy GUI installers that take care of everything like in Windows." }, { "code": null, "e": 20017, "s": 19905, "text": "In my next post, I’ll discuss how to set up your Deep Learning environment in Linux from scratch without conda." }, { "code": null, "e": 20180, "s": 20017, "text": "In this post, I have only covered the installation of Tensorflow, PyTorch and Jupyter tools. You might want to install everything else you need for your workflow." }, { "code": null, "e": 20471, "s": 20180, "text": "I hope you found this post useful. Hopefully, this helped you set up your Deep Learning environment without any problems. In case you faced any problems, I highly recommend checking out the StackOverflow and Nvidia forums. Also the discussions on PyTorch and Tensorflow GitHub repositories." }, { "code": null, "e": 20618, "s": 20471, "text": "I will be writing more tutorials and setup guides in the future too. You can follow me on Medium to never miss a thing. You can also follow me on," }, { "code": null, "e": 20655, "s": 20618, "text": "Twitter — LinkedIn — GitHub — Kaggle" } ]
How to Connect a Local or Remote Machine to a Databricks Cluster | Towards Data Science
When you start working with Databricks, you will reach the point that you decide to code outside of the Databricks and remotely connect to its computation power, a.k.a. Databricks Cluster. Why? Mostly because one of the main features of Databricks is its Spark job management that can make your life easy. Using this service, you can submit a series of Spark jobs to a large-scale dataset and get back your results in a matter of seconds; thanks to its Spark engines. In this article, I want to describe how you can configure your local or remote machine to connect to a Databricks Cluster as the first step in this process. Databricks is an abstract layer sitting on cold cloud infrastructures like AWS and Azure that let you easily manage computation power, data storage, job scheduling, and model management. It provides you a development environment to obtain preliminary results of your data science or AI project. Databricks is powered by Spark, an open-source data-processing engine that is specially designed for large-scale data. The simplicity that Databricks provides, comes with some limitations. For example, Databricks enables you as a data science newbie to generate results fast since you don’t need to deal with cloud configuration or visualization tools extensively. However, if you want to have control over every aspect of your development, Databricks certainly restricts you. Each Databricks Cluster must be run with a specialized operating system called Databricks Runtime. You will find many versions of the Databricks Runtime when you configure a cluster. If you want to remotely connect to a Databricks cluster, you must cautiously select the Databricks Runtime version. Why? Because a limited number of Databricks Runtime versions are supported by the databricks-connect client, the Spark client library enabling this remote connection. Databricks Runtime version must be compatible with the Databricks Connect library. In other words, you can not remotely connect to clusters whose Databricks Runtime are not supported by the databricks-connect. You can find the updated list of Databricks Runtime versions in the original documentation of Databricks Connect. docs.databricks.com After selecting a Databricks Runtime version that is compatible with databricks-connect, you must ensure using the compatible Python version on your machine. As instructed in the original documentation: “The minor version of your client Python installation must be the same as the minor Python version of your Databricks Cluster.” The Python version of development environment must be compatible with Databricks Runtime version working on the Databricks Cluster. Let’s say you selected 7.3 LTS for the Databricks Runtime version. In that case, you must install Python 3.7 on your local or remote machine to be compatible with it. You must also install Java Runtime Environment (JRE) 8 on your machine. These are instructed by the Databricks website. www.oracle.com As recommended for Python development, it is better to create an isolated virtual environment to ensure having no conflict. You can easily build a virtual environment with a library of your choice such as venv, pipenvor conda. I selected the latest one here. If you don’t want to create a new virtual environment, make sure to not install (or, uninstall)pyspark on the existing environment. You should uninstall the existing version of pyspark since it conflicts with databricks-connectclient. The databricks-connect has its own methods equivalent to pyspark that makes it run standalone. By the following code, you create a virtual environment with Python 3.7 and a version of databricks-connect. conda create --name ENVNAME python=3.7conda activate ENVNAMEpip3 uninstall pysparkpip3 install -U databricks-connect==7.3.* You may not need pip3 uninstall pyspark in the above since the virtual environment is clean. I put it there just for sake of completeness. If you want to build a docker image with Python 3.7 and Java 8, and a version of databricks-connectyou can use the following Dockerfile. FROM ubuntu:20.04RUN apt-get update && apt-get -y install sudoRUN sudo apt-get -y install software-properties-common### INSTALL PYTHONRUN sudo apt-get -y install libssl-dev opensslRUN sudo apt-get -y install libreadline-gplv2-dev libffi-devRUN sudo apt-get -y install libncursesw5-dev libsqlite3-devRUN sudo apt-get -y install tk-dev libgdbm-dev libc6-dev libbz2-dev RUN sudo apt-get -y install wgetRUN apt-get update && apt-get install makeRUN sudo apt-get -y install zlib1g-devRUN apt-get -y install gcc mono-mcs && \ rm -rf /var/lib/apt/lists/*RUN wget https://www.python.org/ftp/python/3.7.10/Python-3.7.10.tgzRUN tar xzvf Python-3.7.10.tgzRUN ./Python-3.7.10/configureRUN sudo make installRUN alias python=python3### INSTALL JAVARUN sudo add-apt-repository ppa:openjdk-r/ppaRUN sudo apt-get install -y openjdk-8-jre### INSTALL DATABRICKS-CONNECTRUN pip3 install --upgrade pipRUN pip3 uninstall pysparkRUN pip3 install -U databricks-connect==7.3.* Using databricks-connect configure , it is easy to configure the databricks-connect library to connect to a Databricks Cluster. After running this command, it interactively asks you questions about the Host, Token, Org Id, Port, and Cluster ID. For more information, you can check the official documentation below. docs.databricks.com However, if you want to automatedly configure the connection properties in the Docker image, you can add the below code to the end of the above Dockerfile. RUN export DATABRICKS_HOST=XXXXX && \ export DATABRICKS_API_TOKEN=XXXXX && \ export DATABRICKS_ORG_ID=XXXXX && \ export DATABRICKS_PORT=XXXXX && \ export DATABRICKS_CLUSTER_ID=XXXXX && \ echo "{\"host\": \"${DATABRICKS_HOST}\",\"token\": \"${DATABRICKS_API_TOKEN}\",\"cluster_id\":\"${DATABRICKS_CLUSTER_ID}\",\"org_id\": \"${DATABRICKS_ORG_ID}\", \"port\": \"${DATABRICKS_PORT}\" }" >> /root/.databricks-connectENV SPARK_HOME=/usr/local/lib/python3.7/site-packages/pyspark The above code creates the configuration file artificially and saves it in the proper address. Moreover, it sets the SPARK_HOME address to its correct value. When you run databricks-connect configure , these steps are being executed without your involvement. When you want to automatedly configure the connection properties, you should do it in this way. Last, but not least, you can check the health of the connection by running databricks-connect test . If you like this post and want to support me... Follow me on Medium! Check out my books on Amazon! Become a member on Medium! Connect on Linkedin! Follow me on Twitter!
[ { "code": null, "e": 797, "s": 172, "text": "When you start working with Databricks, you will reach the point that you decide to code outside of the Databricks and remotely connect to its computation power, a.k.a. Databricks Cluster. Why? Mostly because one of the main features of Databricks is its Spark job management that can make your life easy. Using this service, you can submit a series of Spark jobs to a large-scale dataset and get back your results in a matter of seconds; thanks to its Spark engines. In this article, I want to describe how you can configure your local or remote machine to connect to a Databricks Cluster as the first step in this process." }, { "code": null, "e": 1211, "s": 797, "text": "Databricks is an abstract layer sitting on cold cloud infrastructures like AWS and Azure that let you easily manage computation power, data storage, job scheduling, and model management. It provides you a development environment to obtain preliminary results of your data science or AI project. Databricks is powered by Spark, an open-source data-processing engine that is specially designed for large-scale data." }, { "code": null, "e": 1569, "s": 1211, "text": "The simplicity that Databricks provides, comes with some limitations. For example, Databricks enables you as a data science newbie to generate results fast since you don’t need to deal with cloud configuration or visualization tools extensively. However, if you want to have control over every aspect of your development, Databricks certainly restricts you." }, { "code": null, "e": 2035, "s": 1569, "text": "Each Databricks Cluster must be run with a specialized operating system called Databricks Runtime. You will find many versions of the Databricks Runtime when you configure a cluster. If you want to remotely connect to a Databricks cluster, you must cautiously select the Databricks Runtime version. Why? Because a limited number of Databricks Runtime versions are supported by the databricks-connect client, the Spark client library enabling this remote connection." }, { "code": null, "e": 2118, "s": 2035, "text": "Databricks Runtime version must be compatible with the Databricks Connect library." }, { "code": null, "e": 2359, "s": 2118, "text": "In other words, you can not remotely connect to clusters whose Databricks Runtime are not supported by the databricks-connect. You can find the updated list of Databricks Runtime versions in the original documentation of Databricks Connect." }, { "code": null, "e": 2379, "s": 2359, "text": "docs.databricks.com" }, { "code": null, "e": 2710, "s": 2379, "text": "After selecting a Databricks Runtime version that is compatible with databricks-connect, you must ensure using the compatible Python version on your machine. As instructed in the original documentation: “The minor version of your client Python installation must be the same as the minor Python version of your Databricks Cluster.”" }, { "code": null, "e": 2842, "s": 2710, "text": "The Python version of development environment must be compatible with Databricks Runtime version working on the Databricks Cluster." }, { "code": null, "e": 3129, "s": 2842, "text": "Let’s say you selected 7.3 LTS for the Databricks Runtime version. In that case, you must install Python 3.7 on your local or remote machine to be compatible with it. You must also install Java Runtime Environment (JRE) 8 on your machine. These are instructed by the Databricks website." }, { "code": null, "e": 3144, "s": 3129, "text": "www.oracle.com" }, { "code": null, "e": 3403, "s": 3144, "text": "As recommended for Python development, it is better to create an isolated virtual environment to ensure having no conflict. You can easily build a virtual environment with a library of your choice such as venv, pipenvor conda. I selected the latest one here." }, { "code": null, "e": 3842, "s": 3403, "text": "If you don’t want to create a new virtual environment, make sure to not install (or, uninstall)pyspark on the existing environment. You should uninstall the existing version of pyspark since it conflicts with databricks-connectclient. The databricks-connect has its own methods equivalent to pyspark that makes it run standalone. By the following code, you create a virtual environment with Python 3.7 and a version of databricks-connect." }, { "code": null, "e": 3966, "s": 3842, "text": "conda create --name ENVNAME python=3.7conda activate ENVNAMEpip3 uninstall pysparkpip3 install -U databricks-connect==7.3.*" }, { "code": null, "e": 4105, "s": 3966, "text": "You may not need pip3 uninstall pyspark in the above since the virtual environment is clean. I put it there just for sake of completeness." }, { "code": null, "e": 4242, "s": 4105, "text": "If you want to build a docker image with Python 3.7 and Java 8, and a version of databricks-connectyou can use the following Dockerfile." }, { "code": null, "e": 5198, "s": 4242, "text": "FROM ubuntu:20.04RUN apt-get update && apt-get -y install sudoRUN sudo apt-get -y install software-properties-common### INSTALL PYTHONRUN sudo apt-get -y install libssl-dev opensslRUN sudo apt-get -y install libreadline-gplv2-dev libffi-devRUN sudo apt-get -y install libncursesw5-dev libsqlite3-devRUN sudo apt-get -y install tk-dev libgdbm-dev libc6-dev libbz2-dev RUN sudo apt-get -y install wgetRUN apt-get update && apt-get install makeRUN sudo apt-get -y install zlib1g-devRUN apt-get -y install gcc mono-mcs && \\ rm -rf /var/lib/apt/lists/*RUN wget https://www.python.org/ftp/python/3.7.10/Python-3.7.10.tgzRUN tar xzvf Python-3.7.10.tgzRUN ./Python-3.7.10/configureRUN sudo make installRUN alias python=python3### INSTALL JAVARUN sudo add-apt-repository ppa:openjdk-r/ppaRUN sudo apt-get install -y openjdk-8-jre### INSTALL DATABRICKS-CONNECTRUN pip3 install --upgrade pipRUN pip3 uninstall pysparkRUN pip3 install -U databricks-connect==7.3.*" }, { "code": null, "e": 5513, "s": 5198, "text": "Using databricks-connect configure , it is easy to configure the databricks-connect library to connect to a Databricks Cluster. After running this command, it interactively asks you questions about the Host, Token, Org Id, Port, and Cluster ID. For more information, you can check the official documentation below." }, { "code": null, "e": 5533, "s": 5513, "text": "docs.databricks.com" }, { "code": null, "e": 5689, "s": 5533, "text": "However, if you want to automatedly configure the connection properties in the Docker image, you can add the below code to the end of the above Dockerfile." }, { "code": null, "e": 6178, "s": 5689, "text": "RUN export DATABRICKS_HOST=XXXXX && \\ export DATABRICKS_API_TOKEN=XXXXX && \\ export DATABRICKS_ORG_ID=XXXXX && \\ export DATABRICKS_PORT=XXXXX && \\ export DATABRICKS_CLUSTER_ID=XXXXX && \\ echo \"{\\\"host\\\": \\\"${DATABRICKS_HOST}\\\",\\\"token\\\": \\\"${DATABRICKS_API_TOKEN}\\\",\\\"cluster_id\\\":\\\"${DATABRICKS_CLUSTER_ID}\\\",\\\"org_id\\\": \\\"${DATABRICKS_ORG_ID}\\\", \\\"port\\\": \\\"${DATABRICKS_PORT}\\\" }\" >> /root/.databricks-connectENV SPARK_HOME=/usr/local/lib/python3.7/site-packages/pyspark" }, { "code": null, "e": 6533, "s": 6178, "text": "The above code creates the configuration file artificially and saves it in the proper address. Moreover, it sets the SPARK_HOME address to its correct value. When you run databricks-connect configure , these steps are being executed without your involvement. When you want to automatedly configure the connection properties, you should do it in this way." }, { "code": null, "e": 6634, "s": 6533, "text": "Last, but not least, you can check the health of the connection by running databricks-connect test ." }, { "code": null, "e": 6682, "s": 6634, "text": "If you like this post and want to support me..." }, { "code": null, "e": 6703, "s": 6682, "text": "Follow me on Medium!" }, { "code": null, "e": 6733, "s": 6703, "text": "Check out my books on Amazon!" }, { "code": null, "e": 6760, "s": 6733, "text": "Become a member on Medium!" }, { "code": null, "e": 6781, "s": 6760, "text": "Connect on Linkedin!" } ]
Node.js Assert module - GeeksforGeeks
07 Oct, 2021 Assert module in Node.js provides a bunch of facilities that are useful for the assertion of the function. The assert module provides a set of assertion functions for verifying invariants. If the condition is true it will output nothing else an assertion error is given by the console. Install the assert module using the following command: npm install assert Note: Installation is an optional step as it is inbuilt Node.js module. Importing module: const assert = require("assert"); Example 1: console.clear()const assert = require('assert'); let x = 4;let y = 5; try { // Checking condition assert(x == y);}catch { // Error output console.log( `${x} is not equal to ${y}`);} Output: Example 2: console.clear()const assert = require('assert'); let x = 4;let y = 5; assert(x > y); Note: In this example, no try-catch is given so an assertion error of the kind given below will be the output. Output: Note: Text Highlighted is the assertion error. Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 37280, "s": 37252, "text": "\n07 Oct, 2021" }, { "code": null, "e": 37566, "s": 37280, "text": "Assert module in Node.js provides a bunch of facilities that are useful for the assertion of the function. The assert module provides a set of assertion functions for verifying invariants. If the condition is true it will output nothing else an assertion error is given by the console." }, { "code": null, "e": 37621, "s": 37566, "text": "Install the assert module using the following command:" }, { "code": null, "e": 37640, "s": 37621, "text": "npm install assert" }, { "code": null, "e": 37712, "s": 37640, "text": "Note: Installation is an optional step as it is inbuilt Node.js module." }, { "code": null, "e": 37730, "s": 37712, "text": "Importing module:" }, { "code": null, "e": 37764, "s": 37730, "text": "const assert = require(\"assert\");" }, { "code": null, "e": 37775, "s": 37764, "text": "Example 1:" }, { "code": "console.clear()const assert = require('assert'); let x = 4;let y = 5; try { // Checking condition assert(x == y);}catch { // Error output console.log( `${x} is not equal to ${y}`);}", "e": 37982, "s": 37775, "text": null }, { "code": null, "e": 37990, "s": 37982, "text": "Output:" }, { "code": null, "e": 38001, "s": 37990, "text": "Example 2:" }, { "code": "console.clear()const assert = require('assert'); let x = 4;let y = 5; assert(x > y);", "e": 38088, "s": 38001, "text": null }, { "code": null, "e": 38199, "s": 38088, "text": "Note: In this example, no try-catch is given so an assertion error of the kind given below will be the output." }, { "code": null, "e": 38207, "s": 38199, "text": "Output:" }, { "code": null, "e": 38254, "s": 38207, "text": "Note: Text Highlighted is the assertion error." }, { "code": null, "e": 38267, "s": 38254, "text": "Node.js-Misc" }, { "code": null, "e": 38275, "s": 38267, "text": "Node.js" }, { "code": null, "e": 38292, "s": 38275, "text": "Web Technologies" }, { "code": null, "e": 38390, "s": 38292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38399, "s": 38390, "text": "Comments" }, { "code": null, "e": 38412, "s": 38399, "text": "Old Comments" }, { "code": null, "e": 38460, "s": 38412, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 38493, "s": 38460, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 38523, "s": 38493, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 38543, "s": 38523, "text": "How to update NPM ?" }, { "code": null, "e": 38597, "s": 38543, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 38639, "s": 38597, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 38682, "s": 38639, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 38744, "s": 38682, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 38794, "s": 38744, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
First Repeating Element | Practice | GeeksforGeeks
Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest. Example 1: Input: n = 7 arr[] = {1, 5, 3, 4, 3, 5, 6} Output: 2 Explanation: 5 is appearing twice and its first appearence is at index 2 which is less than 3 whose first occuring index is 3. Example 2: Input: n = 4 arr[] = {1, 2, 3, 4} Output: -1 Explanation: All elements appear only once so answer is -1. Your Task: You don't need to read input or print anything. Complete the function firstRepeated() which takes arr and n as input parameters and return the position of the first repeating element. If there is no such element, return -1. The position you return should be according to 1-based indexing. Expected Time Complexity: O(n) Expected Auxilliary Space: O(n) Constraints: 1 <= n <= 106 0 <= Ai<= 106 0 sayanghoshk613 days ago c++ int firstRepeated(int arr[], int n) { unordered_map<int,int>mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } for(int i=0;i<n;i++){ if(mp[arr[i]]>1) return i+1; } return -1;// code here } 0 shubham211019976 days ago public static int firstRepeated(int[] arr, int n) { HashMap<Integer,Integer>h=new HashMap<>(); for(int i:arr){ h.put(i,h.getOrDefault(i,0)+1); } for(int i=0;i<n;i++){ if(h.get(arr[i])>1) return i+1; } return -1; } 0 shubham211019976 days ago it is not index but need to be position 0 iamnobodyji1 week ago Java easy solution:- HashMap<Integer,Integer> map = new HashMap<>(); for(int h: arr){ map.putIfAbsent(h,0); map.put(h,map.get(h)+1); } for(int i=0;i<n;i++){ if(map.get(arr[i])>=2) return i+1; } return -1; 0 pradeepshillare1 week ago class Solution { // Function to return the position of the first repeating element. public static int firstRepeated(int[] arr, int n) { // Your code here HashMap<Integer,Integer> hs = new HashMap<Integer,Integer>(); int ans = -1; for(int i=0;i<arr.length;i++) { if(hs.containsKey(arr[i])==false) { hs.put(arr[i],1); } else { int s = hs.get(arr[i]); hs.put(arr[i],s+1); } } int i=0; while(i<arr.length) { if (hs.get(arr[i]) > 1) { ans = i+1; break; } else i++; } return ans; }} 0 vishutyagi71 week ago c++(easy) O(n) and O(n) int firstRepeated(int arr[], int n) { int i,min=5000; unordered_map<int, int> m1; for(i=0;i<n;i++) { auto it=m1.find(arr[i]); if(it!=m1.end()) { if(m1[arr[i]]<min) { min=m1[arr[i]]; } } else { m1[arr[i]]=i; } } if(min!=5000) { return min+1; } else { return -1; } 0 kousikbarik20001 week ago def repeatEle(nums): num_set = set() no_duplicate = -1 for i in range(len(nums)): if nums[i] in num_set: return nums[i] else: num_set.add(nums[i]) return no_duplicateprint(repeatEle([1, 2, 3, 4, 4, 5]))print(repeatEle([1,2,3,4]))print(repeatEle([1, 1, 2, 3, 3, 2, 2])) +2 moryasivam2 weeks ago int firstRepeated(int arr[], int n) { unordered_map<int,int>m; for(int i=0;i<n;i++){ m[arr[i]]++; } for(int i=0;i<n;i++){ if(m[arr[i]]>1){ return i+1; } } return -1; } +1 mohitraj27412 weeks ago 0.26/2.43 O(n) time and space; int firstRepeated(int arr[], int n) { int min_ind=INT_MAX; int x=*max_element(arr,arr+n)+1; vector<int> visited(x, -1); for(int i=0;i<=n-1;i++) { if(visited[arr[i]]==-1) visited[arr[i]]=i; else min_ind=min(min_ind,visited[arr[i]]+1); } return (min_ind<INT_MAX) ? min_ind :-1; } 0 vcreateforme92 weeks ago class Solution { public: // Function to return the position of the first repeating element. int firstRepeated(int arr[], int n) { // code here map<int,int> m; int MIN=-2; while((--n)>-1) { m[arr[n]]++; if(m[arr[n]]>=2){ MIN=n; } } return MIN+1; }}; 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": 407, "s": 238, "text": "Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest." }, { "code": null, "e": 420, "s": 409, "text": "Example 1:" }, { "code": null, "e": 604, "s": 420, "text": "Input:\nn = 7\narr[] = {1, 5, 3, 4, 3, 5, 6}\nOutput: 2\nExplanation: \n5 is appearing twice and \nits first appearence is at index 2 \nwhich is less than 3 whose first \noccuring index is 3." }, { "code": null, "e": 616, "s": 604, "text": "\nExample 2:" }, { "code": null, "e": 723, "s": 616, "text": "Input:\nn = 4\narr[] = {1, 2, 3, 4}\nOutput: -1\nExplanation: \nAll elements appear only once so \nanswer is -1." }, { "code": null, "e": 1025, "s": 723, "text": "\nYour Task:\nYou don't need to read input or print anything. Complete the function firstRepeated() which takes arr and n as input parameters and return the position of the first repeating element. If there is no such element, return -1.\nThe position you return should be according to 1-based indexing. " }, { "code": null, "e": 1090, "s": 1027, "text": "Expected Time Complexity: O(n)\nExpected Auxilliary Space: O(n)" }, { "code": null, "e": 1133, "s": 1092, "text": "Constraints:\n1 <= n <= 106\n0 <= Ai<= 106" }, { "code": null, "e": 1135, "s": 1133, "text": "0" }, { "code": null, "e": 1159, "s": 1135, "text": "sayanghoshk613 days ago" }, { "code": null, "e": 1163, "s": 1159, "text": "c++" }, { "code": null, "e": 1412, "s": 1163, "text": "int firstRepeated(int arr[], int n) { unordered_map<int,int>mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } for(int i=0;i<n;i++){ if(mp[arr[i]]>1) return i+1; } return -1;// code here }" }, { "code": null, "e": 1414, "s": 1412, "text": "0" }, { "code": null, "e": 1440, "s": 1414, "text": "shubham211019976 days ago" }, { "code": null, "e": 1705, "s": 1440, "text": " public static int firstRepeated(int[] arr, int n) {\n HashMap<Integer,Integer>h=new HashMap<>();\n \n for(int i:arr){\n h.put(i,h.getOrDefault(i,0)+1);\n }\n for(int i=0;i<n;i++){\n if(h.get(arr[i])>1) return i+1;\n }\n return -1;\n }" }, { "code": null, "e": 1707, "s": 1705, "text": "0" }, { "code": null, "e": 1733, "s": 1707, "text": "shubham211019976 days ago" }, { "code": null, "e": 1773, "s": 1733, "text": "it is not index but need to be position" }, { "code": null, "e": 1775, "s": 1773, "text": "0" }, { "code": null, "e": 1797, "s": 1775, "text": "iamnobodyji1 week ago" }, { "code": null, "e": 1818, "s": 1797, "text": "Java easy solution:-" }, { "code": null, "e": 2078, "s": 1818, "text": "HashMap<Integer,Integer> map = new HashMap<>();\n for(int h: arr){\n map.putIfAbsent(h,0);\n map.put(h,map.get(h)+1);\n }\n for(int i=0;i<n;i++){\n if(map.get(arr[i])>=2) return i+1;\n }\n return -1;" }, { "code": null, "e": 2080, "s": 2078, "text": "0" }, { "code": null, "e": 2106, "s": 2080, "text": "pradeepshillare1 week ago" }, { "code": null, "e": 2834, "s": 2106, "text": "class Solution { // Function to return the position of the first repeating element. public static int firstRepeated(int[] arr, int n) { // Your code here HashMap<Integer,Integer> hs = new HashMap<Integer,Integer>(); int ans = -1; for(int i=0;i<arr.length;i++) { if(hs.containsKey(arr[i])==false) { hs.put(arr[i],1); } else { int s = hs.get(arr[i]); hs.put(arr[i],s+1); } } int i=0; while(i<arr.length) { if (hs.get(arr[i]) > 1) { ans = i+1; break; } else i++; } return ans; }} " }, { "code": null, "e": 2836, "s": 2834, "text": "0" }, { "code": null, "e": 2858, "s": 2836, "text": "vishutyagi71 week ago" }, { "code": null, "e": 2882, "s": 2858, "text": "c++(easy) O(n) and O(n)" }, { "code": null, "e": 3274, "s": 2882, "text": "int firstRepeated(int arr[], int n) { int i,min=5000; unordered_map<int, int> m1; for(i=0;i<n;i++) { auto it=m1.find(arr[i]); if(it!=m1.end()) { if(m1[arr[i]]<min) { min=m1[arr[i]]; } } else { m1[arr[i]]=i; } } if(min!=5000) { return min+1; } else { return -1; }" }, { "code": null, "e": 3278, "s": 3276, "text": "0" }, { "code": null, "e": 3304, "s": 3278, "text": "kousikbarik20001 week ago" }, { "code": null, "e": 3621, "s": 3304, "text": "def repeatEle(nums): num_set = set() no_duplicate = -1 for i in range(len(nums)): if nums[i] in num_set: return nums[i] else: num_set.add(nums[i]) return no_duplicateprint(repeatEle([1, 2, 3, 4, 4, 5]))print(repeatEle([1,2,3,4]))print(repeatEle([1, 1, 2, 3, 3, 2, 2]))" }, { "code": null, "e": 3624, "s": 3621, "text": "+2" }, { "code": null, "e": 3646, "s": 3624, "text": "moryasivam2 weeks ago" }, { "code": null, "e": 3893, "s": 3646, "text": "int firstRepeated(int arr[], int n) { unordered_map<int,int>m; for(int i=0;i<n;i++){ m[arr[i]]++; } for(int i=0;i<n;i++){ if(m[arr[i]]>1){ return i+1; } } return -1; }" }, { "code": null, "e": 3896, "s": 3893, "text": "+1" }, { "code": null, "e": 3920, "s": 3896, "text": "mohitraj27412 weeks ago" }, { "code": null, "e": 3930, "s": 3920, "text": "0.26/2.43" }, { "code": null, "e": 3951, "s": 3930, "text": "O(n) time and space;" }, { "code": null, "e": 4331, "s": 3955, "text": "int firstRepeated(int arr[], int n) { int min_ind=INT_MAX; int x=*max_element(arr,arr+n)+1; vector<int> visited(x, -1); for(int i=0;i<=n-1;i++) { if(visited[arr[i]]==-1) visited[arr[i]]=i; else min_ind=min(min_ind,visited[arr[i]]+1); } return (min_ind<INT_MAX) ? min_ind :-1; }" }, { "code": null, "e": 4333, "s": 4331, "text": "0" }, { "code": null, "e": 4358, "s": 4333, "text": "vcreateforme92 weeks ago" }, { "code": null, "e": 4695, "s": 4358, "text": "class Solution { public: // Function to return the position of the first repeating element. int firstRepeated(int arr[], int n) { // code here map<int,int> m; int MIN=-2; while((--n)>-1) { m[arr[n]]++; if(m[arr[n]]>=2){ MIN=n; } } return MIN+1; }};" }, { "code": null, "e": 4841, "s": 4695, "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": 4877, "s": 4841, "text": " Login to access your submissions. " }, { "code": null, "e": 4887, "s": 4877, "text": "\nProblem\n" }, { "code": null, "e": 4897, "s": 4887, "text": "\nContest\n" }, { "code": null, "e": 4960, "s": 4897, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5108, "s": 4960, "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": 5316, "s": 5108, "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": 5422, "s": 5316, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
HTML <textarea> readonly Attribute
The readonly attribute of the <textarea> element is used to set a textarea as readonly. The visitor cannot change the text in the textarea if it is set as readonly. However, visitor can copy that content. Following is the syntax − <textarea readonly> Let us now see an example to implement the readonly attribute of the <textarea> element − Live Demo <!DOCTYPE html> <html> <body> <h2>Interview Questions</h2> <p>Q1</p> <textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)"> </textarea> <p>Q2</p> <textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)"> </textarea> <p>Guidelines to appear for interview:</p> <textarea rows="6" cols="70" readonly> The interviewee should reach at 10AM with the certificates. </textarea> </body> </html> In the above example, we have 3 textarea − <p>Q1</p> <textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)"> </textarea> <p>Q2</p> <textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)"> </textarea> <p>Guidelines to appear for interview:</p> <textarea rows="6" cols="70" readonly> The interviewee should reach at 10AM with the certificates. </textarea> One of this textarea is set as readonly, therefore users won’t be able to add any text in it − <textarea rows="6" cols="70" readonly> The interviewee should reach at 10AM with the certificates. </textarea>
[ { "code": null, "e": 1227, "s": 1062, "text": "The readonly attribute of the <textarea> element is used to set a textarea as readonly. The visitor cannot change the text in the textarea if it is set as readonly." }, { "code": null, "e": 1267, "s": 1227, "text": "However, visitor can copy that content." }, { "code": null, "e": 1293, "s": 1267, "text": "Following is the syntax −" }, { "code": null, "e": 1313, "s": 1293, "text": "<textarea readonly>" }, { "code": null, "e": 1403, "s": 1313, "text": "Let us now see an example to implement the readonly attribute of the <textarea> element −" }, { "code": null, "e": 1414, "s": 1403, "text": " Live Demo" }, { "code": null, "e": 1924, "s": 1414, "text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Interview Questions</h2>\n<p>Q1</p>\n <textarea rows=\"6\" cols=\"70\" placeholder=\"Why do you want go for the Editor Job Profile? (100 words)\">\n </textarea>\n <p>Q2</p>\n <textarea rows=\"6\" cols=\"70\" placeholder=\"Do you have any previous publishing experience? (100 words)\">\n </textarea>\n <p>Guidelines to appear for interview:</p>\n <textarea rows=\"6\" cols=\"70\" readonly>\n The interviewee should reach at 10AM with the certificates.\n </textarea>\n</body>\n</html>" }, { "code": null, "e": 1967, "s": 1924, "text": "In the above example, we have 3 textarea −" }, { "code": null, "e": 2375, "s": 1967, "text": "<p>Q1</p>\n<textarea rows=\"6\" cols=\"70\" placeholder=\"Why do you want go for the Editor Job Profile? (100 words)\">\n</textarea>\n<p>Q2</p>\n<textarea rows=\"6\" cols=\"70\" placeholder=\"Do you have any previous publishing experience? (100 words)\">\n</textarea>\n<p>Guidelines to appear for interview:</p>\n<textarea rows=\"6\" cols=\"70\" readonly>\n The interviewee should reach at 10AM with the certificates.\n</textarea>" }, { "code": null, "e": 2470, "s": 2375, "text": "One of this textarea is set as readonly, therefore users won’t be able to add any text in it −" }, { "code": null, "e": 2584, "s": 2470, "text": "<textarea rows=\"6\" cols=\"70\" readonly>\n The interviewee should reach at 10AM with the certificates.\n</textarea>" } ]
Java Program to format date in mm-dd-yyyy hh:mm:ss format
Let us format date in mm-dd-yyyy hh:mm:ss format − // displaying date in mm-dd-yyyy hh:mm:ss format Format f = new SimpleDateFormat("mm-dd-yyyy hh:mm:ss"); String str = f.format(new Date()); System.out.println("Current Date in MM-dd-yyyy hh:mm:ss format = "+str); Since we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date − import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; The following is an example − Live Demo import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class Demo { public static void main(String[] args) throws Exception { // displaying current date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z"); System.out.println("Today's date and time = "+simpleformat.format(cal.getTime())); // displaying date in mm-dd-yyyy hh:mm:ss format Format f = new SimpleDateFormat("mm-dd-yyyy hh:mm:ss"); String str = f.format(new Date()); System.out.println("Current Date in MM-dd-yyyy hh:mm:ss format = "+str); // displaying date f = new SimpleDateFormat("dd/MMMM/yyyy"); String strDate = f.format(new Date()); System.out.println("Current Date = "+strDate); // current time f = new SimpleDateFormat("HH.mm.ss Z"); String strTime = f.format(new Date()); System.out.println("Current Time = "+strTime); } } Today's date and time = Mon, 26 Nov 2018 09:34:11 +0000 Current Date in MM-dd-yyyy hh:mm:ss format = 11-26-2018 09:34:11 Current Date = 26/November/2018 Current Time = 09.34.11 +0000
[ { "code": null, "e": 1113, "s": 1062, "text": "Let us format date in mm-dd-yyyy hh:mm:ss format −" }, { "code": null, "e": 1326, "s": 1113, "text": "// displaying date in mm-dd-yyyy hh:mm:ss format\nFormat f = new SimpleDateFormat(\"mm-dd-yyyy hh:mm:ss\");\nString str = f.format(new Date());\nSystem.out.println(\"Current Date in MM-dd-yyyy hh:mm:ss format = \"+str);" }, { "code": null, "e": 1471, "s": 1326, "text": "Since we have used the Format and SimpleDateFormat class above, therefore import the following packages. With that, we have also used the Date −" }, { "code": null, "e": 1554, "s": 1471, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;" }, { "code": null, "e": 1584, "s": 1554, "text": "The following is an example −" }, { "code": null, "e": 1595, "s": 1584, "text": " Live Demo" }, { "code": null, "e": 2632, "s": 1595, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"E, dd MMM yyyy HH:mm:ss Z\");\n System.out.println(\"Today's date and time = \"+simpleformat.format(cal.getTime()));\n // displaying date in mm-dd-yyyy hh:mm:ss format\n Format f = new SimpleDateFormat(\"mm-dd-yyyy hh:mm:ss\");\n String str = f.format(new Date());\n System.out.println(\"Current Date in MM-dd-yyyy hh:mm:ss format = \"+str);\n // displaying date\n f = new SimpleDateFormat(\"dd/MMMM/yyyy\");\n String strDate = f.format(new Date());\n System.out.println(\"Current Date = \"+strDate);\n // current time\n f = new SimpleDateFormat(\"HH.mm.ss Z\");\n String strTime = f.format(new Date());\n System.out.println(\"Current Time = \"+strTime);\n }\n}" }, { "code": null, "e": 2815, "s": 2632, "text": "Today's date and time = Mon, 26 Nov 2018 09:34:11 +0000\nCurrent Date in MM-dd-yyyy hh:mm:ss format = 11-26-2018 09:34:11\nCurrent Date = 26/November/2018\nCurrent Time = 09.34.11 +0000" } ]
modal(options) method in Bootstrap
If you want to set content as a Bootstrap modal, then use the .modal(options) method. For this, use jQuery to set the model on the click of a button as in the following code snippet − $(document).ready(function(){ $("#button1").click(function(){ $("#newModal1").modal({backdrop: true}); }); }); Let us now implement the modal(“options”) class. Here, we have two buttons that would generate different types of modals on click. One of them would close on clicking outside the modal, but another one will not close. Here is the complete example − Live Demo <!DOCTYPE html> <html> <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/3.3.7/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/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Sample</h2> <button type="button" class="btn btn-default btn-lg" id="button1">Modal One</button> <button type="button" class="btn btn-default btn-lg" id="button2">Modal Two</button> <div class="modal fade" id="newModal1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Sample Modal 1</h4> </div> <div class="modal-body"> <p>Click outside to close it.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <div class="modal fade" id="newModal2" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Sample Modal 2</h4> </div> <div class="modal-body"> <p>It won't close on clicking outside.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <script> $(document).ready(function(){ $("#button1").click(function(){ $("#newModal1").modal({backdrop: true}); }); $("#button2").click(function(){ $("#newModal2").modal({backdrop: false}); }); }); </script> </body> </html>
[ { "code": null, "e": 1148, "s": 1062, "text": "If you want to set content as a Bootstrap modal, then use the .modal(options) method." }, { "code": null, "e": 1246, "s": 1148, "text": "For this, use jQuery to set the model on the click of a button as in the following code snippet −" }, { "code": null, "e": 1365, "s": 1246, "text": "$(document).ready(function(){\n $(\"#button1\").click(function(){\n $(\"#newModal1\").modal({backdrop: true});\n });\n});" }, { "code": null, "e": 1583, "s": 1365, "text": "Let us now implement the modal(“options”) class. Here, we have two buttons that would generate different types of modals on click. One of them would close on clicking outside the modal, but another one will not close." }, { "code": null, "e": 1614, "s": 1583, "text": "Here is the complete example −" }, { "code": null, "e": 1624, "s": 1614, "text": "Live Demo" }, { "code": null, "e": 3671, "s": 1624, "text": "<!DOCTYPE html>\n<html>\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/3.3.7/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/3.3.7/js/bootstrap.min.js\"></script>\n</head>\n<body>\n <div class=\"container\">\n <h2>Sample</h2>\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">Modal One</button>\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button2\">Modal Two</button>\n\n <div class=\"modal fade\" id=\"newModal1\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Sample Modal 1</h4>\n </div>\n <div class=\"modal-body\">\n <p>Click outside to close it.</p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"modal fade\" id=\"newModal2\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Sample Modal 2</h4>\n </div>\n <div class=\"modal-body\">\n <p>It won't close on clicking outside.</p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n<script>\n$(document).ready(function(){\n $(\"#button1\").click(function(){\n $(\"#newModal1\").modal({backdrop: true});\n });\n $(\"#button2\").click(function(){\n $(\"#newModal2\").modal({backdrop: false});\n });\n});\n</script>\n\n</body>\n</html>" } ]
Amazon RDS - MySQL DBA Tasks
As with every other database, Amazon RDS MYSQL also needs DBA tasks to fine tune the database and do periodic health checks etc. But as the AWS platform does not allow the shell access to the DB, there are a limited number of DBA tasks that can be performed as compared to the on-premise installation of MySQL. Below is a list of common DBA tasks that can be performed in AWS RDS MySQL database and their descriptions. The MySQL error log ( mysql-error.log) file can be viewed by using the Amazon RDS console or by retrieving the log using the Amazon RDS CLI. mysql-error.log is flushed every 5 minutes, and its contents are appended to mysql-error-running.log. The mysql-error-running.log file is then rotated every hour and the hourly files generated during the last 24 hours are retained. Below there are links to two log files described above. Using CLI the log files are published to CloudWatch Logs as a JSON Object. aws rds modify-db-instance \ --db-instance-identifier mydbinstance \ --cloudwatch-logs-export-configuration '{"EnableLogTypes":["audit","error","general","slowquery"]}' \ --apply-immediately Sometimes the DBA needs to kill a long running session or query which is not giving the result quick enough. This DBA task is done by first finding the process ID of the query and then using a RDS function to kill the query. The below commands are the examples. # get the ID Select * from INFORMATION_SCHEMA.PROCESSLIST #Apply the Kill Function CALL mysql.rds_kill(processID); We can improve the recovery time from a crash by setting a DB parameter called innodb_file_per_table. We can find this parameter in the RDS console as shown below. Next we can Search for the parameter name as shown below. Amazon RDS sets the default value for innodb_file_per_table parameter to 1, which allows you to drop individual InnoDB tables and reclaim storage used by those tables for the DB instance. This speeds up the recovery time from the crash. Stopping a DB, Rebooting it or creating snapshots etc can be done easily through RDS console as shown in the below diagram. Print Add Notes Bookmark this page
[ { "code": null, "e": 3004, "s": 2585, "text": "As with every other database, Amazon RDS MYSQL also needs DBA tasks to fine tune the database and do periodic health checks etc. But as the AWS platform does not allow the shell access to the DB, there are a limited number of DBA tasks that can be performed as compared to the on-premise installation of MySQL. Below is a list of common DBA tasks that can be performed in AWS RDS MySQL database and their descriptions." }, { "code": null, "e": 3377, "s": 3004, "text": "The MySQL error log ( mysql-error.log) file can be viewed by using the Amazon RDS console or by retrieving the log using the Amazon RDS CLI. mysql-error.log is flushed every 5 minutes, and its contents are appended to mysql-error-running.log. The mysql-error-running.log file is then rotated every hour and the hourly files generated during the last 24 hours are retained." }, { "code": null, "e": 3433, "s": 3377, "text": "Below there are links to two log files described above." }, { "code": null, "e": 3509, "s": 3433, "text": "Using CLI the log files are published to CloudWatch Logs as a JSON Object. " }, { "code": null, "e": 3716, "s": 3509, "text": "aws rds modify-db-instance \\\n --db-instance-identifier mydbinstance \\\n --cloudwatch-logs-export-configuration '{\"EnableLogTypes\":[\"audit\",\"error\",\"general\",\"slowquery\"]}' \\\n --apply-immediately\n " }, { "code": null, "e": 3978, "s": 3716, "text": "Sometimes the DBA needs to kill a long running session or query which is not giving the result quick enough. This DBA task is done by first finding the process ID of the query and then using a RDS function to kill the query. The below commands are the examples." }, { "code": null, "e": 4093, "s": 3978, "text": "# get the ID\nSelect * from INFORMATION_SCHEMA.PROCESSLIST\n#Apply the Kill Function\nCALL mysql.rds_kill(processID);" }, { "code": null, "e": 4257, "s": 4093, "text": "We can improve the recovery time from a crash by setting a DB parameter called innodb_file_per_table. We can find this parameter in the RDS console as shown below." }, { "code": null, "e": 4315, "s": 4257, "text": "Next we can Search for the parameter name as shown below." }, { "code": null, "e": 4552, "s": 4315, "text": "Amazon RDS sets the default value for innodb_file_per_table parameter to 1, which allows you to drop individual InnoDB tables and reclaim storage used by those tables for the DB instance. This speeds up the recovery time from the crash." }, { "code": null, "e": 4676, "s": 4552, "text": "Stopping a DB, Rebooting it or creating snapshots etc can be done easily through RDS console as shown in the below diagram." }, { "code": null, "e": 4683, "s": 4676, "text": " Print" }, { "code": null, "e": 4694, "s": 4683, "text": " Add Notes" } ]
Building and Exporting Python Logs in Jupyter Notebooks | by Brian Mattis | Towards Data Science
Logging is an important capability within Python to monitor the health of our code. In a way, log files share a lot of the same concepts as the debugger. We can use logs to place breadcrumbs in our code to help determine what’s going on inside. This is especially useful when our script crashes for an unknown reason — if we leave enough breadcrumbs behind we can track the path the code took, and we can focus our attention there. Typically the python debugger is useful when we’re first testing out our code, but at some point we consider our code “working” before we’ve tested every possible input case. If we use logging in the background, we’ll have a great idea of where we went wrong if something breaks down the road. In particular, if we use logging correctly, we can see the exact unique situation that broke our “working” code. Logs become even more critical when others use our code. When a script fails on another user’s machine, it can be challenging to replicate the error — but the logs can guide us down the path the script followed just before it failed on the user’s system. This is exceptionally useful in creating code that manages all of the “edge” cases (why do you think software always asks for permission to send crash data when you install it?!) Finally, there’s another awesome use for logs — as trackers of the code development cycle. Imagine that within the first week of release to other users your python script generates 200 errors, 500 warnings, and various other logging flags. As the code is refined and becomes more robust through iteration, we can see the rates of the different issues decrease over time. This gives us an idea of where we are in our development cycle and where to focus our future efforts by tackling the most common errors first. So let’s get started: Logging in Python when running scripts from the command line is very well documented, but we need to start with the basics before diving into the tricks and tools we can use. First, when we send messages to the logger, we choose which category the information fits into. These are organized by increasing severity, from NotSet to Critical as shown below. What’s powerful about this hierarchy is that when we output the log data, we can select which level to report. In this case, the logger will capture everything at that level and more severe. For example, if we were to chose a level of Warning, then the logger would capture all Warning, Error, and Critical messages. Complete documentation on the standards of when to use each level are found here. To build this in Python with the logging messages being posted to the console, it looks like this: import logging#create a loggerlogger = logging.getLogger()# to control the reporting levellogger.setLevel(logging.WARNING)#send two messages to the loggerlogging.info("This is an INFO message")logging.warning("This is a WARNING message") As the level is set to logging.WARNING we won’t see the info-level message. Setting the level is useful as during first coding we’ll send breadcrumbs in DEBUG and INFO to make sure we’re doing things right. Then, when we think we no longer need the breadcrumbs, we can eliminate them from the log and focus on functionality problems in warnings, errors, and criticals. This can work hand-in-hand with the debugger. To output to an actual log file instead of the command line, we need to set up the logger using basicConfig() where we can also set the level, like this: import logginglogging.basicConfig(filename='my_first_log.log', level=logging.INFO) Unfortunately, this method won’t work when operating in Jupyter Notebooks. At all. The problem lies in that at start-up, a Jupyter Notebook launches an IPython session that has already initiated logging. As a result, logging.basicConfig() won’t work. Logging is also particularly useful in Jupyter Notebooks, as the debugger can have some serious functionality issues. These debugger issues are avoided by using the enhanced debugger in JupyterLab— but if you’re constrained to Jupyter Notebooks, then logging gives you the flexibility to do what you need to handle a broader range of debug tasks. To export log messages to an external log file in Jupyter, we’ll need to set up a FileHandler and attach it to the logger: import logginglogger = logging.getLogger()fhandler = logging.FileHandler(filename='test_log.log', mode='a')logger.addHandler(fhandler)logging.warning('This is a warning message') It’s important to note the mode selection in the FileHandler setup: ‘a’ — append. All new messages are tacked onto the end of the log file ‘w’ — write. The log file is cleaned out and started fresh each time you run the python script If all went well, we should have a new ‘test_log.log’ file in the same directory as our Jupyter Notebook. We can also improve and customize our log outputs to contain more than the text we dictate in the logging messages. By using logging.Formatter() we can add in a host of fields to help us understand more about the messages, such as when the message was generated and by at which line in the code. Here are some of my favorites, with the complete list here: %(asctime)s — the date/time of the entry %(levelname)s — the logging level (so you don’t have to spell that out in your error) %(name)s — name of the logger used (as in, which file generated this message) %(lineno)s — the line number that generated the message %(message)s — of course! The message itself! To attach our formatting to the logger, we add it to the file handler like this: formatter = logging.Formatter('%(asctime)s - %(name)s - %(lineno)s - %(levelname)s - %(message)s')fhandler.setFormatter(formatter) We can also add another handler to show this formatting in the console as too. Here, we access the console through a StreamHandler() using sys.stdout and attach it to the logger: import sysconsoleHandler = logging.StreamHandler(sys.stdout)consoleHandler.setFormatter(formatter)logger.addHandler(consoleHandler) It gets even better! We can also independently adjust the levels outputted by each handler. For example, we can set our console to report down to the debug level like this: consoleHandler.setLevel(logging.DEBUG) Important note — The main logger level must be equal to or lower than the level given to the handlers, otherwise it won’t work, as the high-level logger level sets the floor. We can also pass more than static messages to our logger. Often, if our code is returning warnings or errors, we’ll want to know what user values triggered the event. Luckily, we can simply parse variable values into our messages like common strings using .format(). var1 = 1var2 = 'cat'logging.debug('var1: {}; var2: {}'.format(var1, var2)) With what we’ve learned so far, we can initiate a new logger in Jupyter Notebooks, adjust the reporting level, adjust the formatting, output to file, output to the console, and adjust the level of each output. Here’s a simple snapshot of what it looks like in action, with the console at DEBUG and the export file at INFO: And here’s what we see in that file_out.log file: And while it’s nice to have the ability to export the log to a file, sometimes we want to be a bit lazy and not switch over to a text editor to read our output file. To see the log file in Jupyter Notebook, we can just read and print the contents like this: with open("file_out.log") as log: print(log.read()) Because the logger is automatically set up as part of IPython when we start a notebook, certain configurations conflict with some of the functionality that exists for python files run in the console. One in particular is the use of the getLogger(__name__) functionality. When our python scripts become more complex, we will often break some functions into separate script files that are later imported as separate modules. We can pass all log messages to a common log file, with the %(name)s formatter telling us which python script generated the message. There’s even a tutorial on how to do this in python running from the console. Unfortunately, this capability is not immediately compatible in Jupyter Notebooks. I haven’t found a solution yet... but for now know that using __name__ will prevent anything from being printed to the log file or the formatted console handler. As you get deeper into python logs, you’ll find that we can even export log files though email. This is very advantageous — after our code is deployed we can monitor its health from afar. Even better, it only takes a couple of lines of code to add the SMTPHandler. Example code can be found here. Also, with the ability to set the level for each handler, we can create multiple log outputs simultaneously that report and different levels. For example, we may want one log file that captures every event down to the debug level, but we may also want one that is filtered to only report warning and above — this gives us a simple file to monitor for major problems, and a separate log file of everything for when we want to dive in deeper. Logs offer a great way to maintain the quality and functionality of our code, especially when we release our python scripts for others to use. It can help flag when our code to acts unexpectedly and leaves a trail of breadcrumbs to show how and why things broke. It’s extraordinarily challenging during development to anticipate every use case and every user input that our scripts are going to receive — logging gives us a way to continually iterate and improve the robustness of our code. There are a couple of differences when implementing logs in Jupyter Notebooks, but once you understand the modifications you can successfully generate truly useful logs. Thanks for reading, and as always, all of the code shown above can be accessed on my Github here.
[ { "code": null, "e": 1010, "s": 171, "text": "Logging is an important capability within Python to monitor the health of our code. In a way, log files share a lot of the same concepts as the debugger. We can use logs to place breadcrumbs in our code to help determine what’s going on inside. This is especially useful when our script crashes for an unknown reason — if we leave enough breadcrumbs behind we can track the path the code took, and we can focus our attention there. Typically the python debugger is useful when we’re first testing out our code, but at some point we consider our code “working” before we’ve tested every possible input case. If we use logging in the background, we’ll have a great idea of where we went wrong if something breaks down the road. In particular, if we use logging correctly, we can see the exact unique situation that broke our “working” code." }, { "code": null, "e": 1444, "s": 1010, "text": "Logs become even more critical when others use our code. When a script fails on another user’s machine, it can be challenging to replicate the error — but the logs can guide us down the path the script followed just before it failed on the user’s system. This is exceptionally useful in creating code that manages all of the “edge” cases (why do you think software always asks for permission to send crash data when you install it?!)" }, { "code": null, "e": 1980, "s": 1444, "text": "Finally, there’s another awesome use for logs — as trackers of the code development cycle. Imagine that within the first week of release to other users your python script generates 200 errors, 500 warnings, and various other logging flags. As the code is refined and becomes more robust through iteration, we can see the rates of the different issues decrease over time. This gives us an idea of where we are in our development cycle and where to focus our future efforts by tackling the most common errors first. So let’s get started:" }, { "code": null, "e": 2734, "s": 1980, "text": "Logging in Python when running scripts from the command line is very well documented, but we need to start with the basics before diving into the tricks and tools we can use. First, when we send messages to the logger, we choose which category the information fits into. These are organized by increasing severity, from NotSet to Critical as shown below. What’s powerful about this hierarchy is that when we output the log data, we can select which level to report. In this case, the logger will capture everything at that level and more severe. For example, if we were to chose a level of Warning, then the logger would capture all Warning, Error, and Critical messages. Complete documentation on the standards of when to use each level are found here." }, { "code": null, "e": 2833, "s": 2734, "text": "To build this in Python with the logging messages being posted to the console, it looks like this:" }, { "code": null, "e": 3071, "s": 2833, "text": "import logging#create a loggerlogger = logging.getLogger()# to control the reporting levellogger.setLevel(logging.WARNING)#send two messages to the loggerlogging.info(\"This is an INFO message\")logging.warning(\"This is a WARNING message\")" }, { "code": null, "e": 3486, "s": 3071, "text": "As the level is set to logging.WARNING we won’t see the info-level message. Setting the level is useful as during first coding we’ll send breadcrumbs in DEBUG and INFO to make sure we’re doing things right. Then, when we think we no longer need the breadcrumbs, we can eliminate them from the log and focus on functionality problems in warnings, errors, and criticals. This can work hand-in-hand with the debugger." }, { "code": null, "e": 3640, "s": 3486, "text": "To output to an actual log file instead of the command line, we need to set up the logger using basicConfig() where we can also set the level, like this:" }, { "code": null, "e": 3723, "s": 3640, "text": "import logginglogging.basicConfig(filename='my_first_log.log', level=logging.INFO)" }, { "code": null, "e": 3974, "s": 3723, "text": "Unfortunately, this method won’t work when operating in Jupyter Notebooks. At all. The problem lies in that at start-up, a Jupyter Notebook launches an IPython session that has already initiated logging. As a result, logging.basicConfig() won’t work." }, { "code": null, "e": 4321, "s": 3974, "text": "Logging is also particularly useful in Jupyter Notebooks, as the debugger can have some serious functionality issues. These debugger issues are avoided by using the enhanced debugger in JupyterLab— but if you’re constrained to Jupyter Notebooks, then logging gives you the flexibility to do what you need to handle a broader range of debug tasks." }, { "code": null, "e": 4444, "s": 4321, "text": "To export log messages to an external log file in Jupyter, we’ll need to set up a FileHandler and attach it to the logger:" }, { "code": null, "e": 4623, "s": 4444, "text": "import logginglogger = logging.getLogger()fhandler = logging.FileHandler(filename='test_log.log', mode='a')logger.addHandler(fhandler)logging.warning('This is a warning message')" }, { "code": null, "e": 4691, "s": 4623, "text": "It’s important to note the mode selection in the FileHandler setup:" }, { "code": null, "e": 4762, "s": 4691, "text": "‘a’ — append. All new messages are tacked onto the end of the log file" }, { "code": null, "e": 4857, "s": 4762, "text": "‘w’ — write. The log file is cleaned out and started fresh each time you run the python script" }, { "code": null, "e": 4963, "s": 4857, "text": "If all went well, we should have a new ‘test_log.log’ file in the same directory as our Jupyter Notebook." }, { "code": null, "e": 5319, "s": 4963, "text": "We can also improve and customize our log outputs to contain more than the text we dictate in the logging messages. By using logging.Formatter() we can add in a host of fields to help us understand more about the messages, such as when the message was generated and by at which line in the code. Here are some of my favorites, with the complete list here:" }, { "code": null, "e": 5360, "s": 5319, "text": "%(asctime)s — the date/time of the entry" }, { "code": null, "e": 5446, "s": 5360, "text": "%(levelname)s — the logging level (so you don’t have to spell that out in your error)" }, { "code": null, "e": 5524, "s": 5446, "text": "%(name)s — name of the logger used (as in, which file generated this message)" }, { "code": null, "e": 5580, "s": 5524, "text": "%(lineno)s — the line number that generated the message" }, { "code": null, "e": 5625, "s": 5580, "text": "%(message)s — of course! The message itself!" }, { "code": null, "e": 5706, "s": 5625, "text": "To attach our formatting to the logger, we add it to the file handler like this:" }, { "code": null, "e": 5837, "s": 5706, "text": "formatter = logging.Formatter('%(asctime)s - %(name)s - %(lineno)s - %(levelname)s - %(message)s')fhandler.setFormatter(formatter)" }, { "code": null, "e": 6016, "s": 5837, "text": "We can also add another handler to show this formatting in the console as too. Here, we access the console through a StreamHandler() using sys.stdout and attach it to the logger:" }, { "code": null, "e": 6148, "s": 6016, "text": "import sysconsoleHandler = logging.StreamHandler(sys.stdout)consoleHandler.setFormatter(formatter)logger.addHandler(consoleHandler)" }, { "code": null, "e": 6360, "s": 6148, "text": "It gets even better! We can also independently adjust the levels outputted by each handler. For example, we can set our console to report down to the debug level like this: consoleHandler.setLevel(logging.DEBUG)" }, { "code": null, "e": 6535, "s": 6360, "text": "Important note — The main logger level must be equal to or lower than the level given to the handlers, otherwise it won’t work, as the high-level logger level sets the floor." }, { "code": null, "e": 6802, "s": 6535, "text": "We can also pass more than static messages to our logger. Often, if our code is returning warnings or errors, we’ll want to know what user values triggered the event. Luckily, we can simply parse variable values into our messages like common strings using .format()." }, { "code": null, "e": 6877, "s": 6802, "text": "var1 = 1var2 = 'cat'logging.debug('var1: {}; var2: {}'.format(var1, var2))" }, { "code": null, "e": 7200, "s": 6877, "text": "With what we’ve learned so far, we can initiate a new logger in Jupyter Notebooks, adjust the reporting level, adjust the formatting, output to file, output to the console, and adjust the level of each output. Here’s a simple snapshot of what it looks like in action, with the console at DEBUG and the export file at INFO:" }, { "code": null, "e": 7250, "s": 7200, "text": "And here’s what we see in that file_out.log file:" }, { "code": null, "e": 7508, "s": 7250, "text": "And while it’s nice to have the ability to export the log to a file, sometimes we want to be a bit lazy and not switch over to a text editor to read our output file. To see the log file in Jupyter Notebook, we can just read and print the contents like this:" }, { "code": null, "e": 7563, "s": 7508, "text": "with open(\"file_out.log\") as log: print(log.read())" }, { "code": null, "e": 8442, "s": 7563, "text": "Because the logger is automatically set up as part of IPython when we start a notebook, certain configurations conflict with some of the functionality that exists for python files run in the console. One in particular is the use of the getLogger(__name__) functionality. When our python scripts become more complex, we will often break some functions into separate script files that are later imported as separate modules. We can pass all log messages to a common log file, with the %(name)s formatter telling us which python script generated the message. There’s even a tutorial on how to do this in python running from the console. Unfortunately, this capability is not immediately compatible in Jupyter Notebooks. I haven’t found a solution yet... but for now know that using __name__ will prevent anything from being printed to the log file or the formatted console handler." }, { "code": null, "e": 8739, "s": 8442, "text": "As you get deeper into python logs, you’ll find that we can even export log files though email. This is very advantageous — after our code is deployed we can monitor its health from afar. Even better, it only takes a couple of lines of code to add the SMTPHandler. Example code can be found here." }, { "code": null, "e": 9180, "s": 8739, "text": "Also, with the ability to set the level for each handler, we can create multiple log outputs simultaneously that report and different levels. For example, we may want one log file that captures every event down to the debug level, but we may also want one that is filtered to only report warning and above — this gives us a simple file to monitor for major problems, and a separate log file of everything for when we want to dive in deeper." }, { "code": null, "e": 9671, "s": 9180, "text": "Logs offer a great way to maintain the quality and functionality of our code, especially when we release our python scripts for others to use. It can help flag when our code to acts unexpectedly and leaves a trail of breadcrumbs to show how and why things broke. It’s extraordinarily challenging during development to anticipate every use case and every user input that our scripts are going to receive — logging gives us a way to continually iterate and improve the robustness of our code." } ]
Difference Between Daemon Threads and User Threads In Java - GeeksforGeeks
16 Nov, 2018 In Java, there are two types of threads: Daemon ThreadUser Thread Daemon Thread User Thread Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks. Difference Between Daemon Threads And User Threads In Java JVM doesn’t wait for daemon thread to finish but it waits for User Thread : First and foremost difference between daemon and user threads is that JVM will not wait for daemon thread to finish its task but it will wait for any active user thread.For example, one might have noticed this behavior while running Java program in NetBeans that even if the main thread has finished, the top left down button is still red, showing that Java program is still running. This is due to any user thread spawned from the main thread, but with main thread one don’t see that red dot in NetBeans.Thread Priority : The User threads are high priority as compare to daemon thread means they won’t get CPU as easily as a user thread can get.Creation of Thread : User thread is usually created by the application for executing some task concurrently. On the other hand, daemon thread is mostly created by JVM like for some garbage collection job.Termination of Thread : JVM will force daemon thread to terminate if all user threads have finished their execution but The user thread is closed by application or by itself. A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM. This is the most critical difference between user thread and daemon thread.Usage : The daemons threads are not used for any critical task. Any important task is done by user thread. A daemon thread is generally used for some background tasks which are not critical task. JVM doesn’t wait for daemon thread to finish but it waits for User Thread : First and foremost difference between daemon and user threads is that JVM will not wait for daemon thread to finish its task but it will wait for any active user thread.For example, one might have noticed this behavior while running Java program in NetBeans that even if the main thread has finished, the top left down button is still red, showing that Java program is still running. This is due to any user thread spawned from the main thread, but with main thread one don’t see that red dot in NetBeans. Thread Priority : The User threads are high priority as compare to daemon thread means they won’t get CPU as easily as a user thread can get. Creation of Thread : User thread is usually created by the application for executing some task concurrently. On the other hand, daemon thread is mostly created by JVM like for some garbage collection job. Termination of Thread : JVM will force daemon thread to terminate if all user threads have finished their execution but The user thread is closed by application or by itself. A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM. This is the most critical difference between user thread and daemon thread. Usage : The daemons threads are not used for any critical task. Any important task is done by user thread. A daemon thread is generally used for some background tasks which are not critical task. The Major Difference between User and Daemon Threads: Example: Check Thread is Daemon or not One can make a user thread as daemon thread by using setDaemon(boolean) method. In this example, thread type is being checked (User thread or Daemon thread) by using isDaemon() method. It returns true if it is daemon otherwise it returns false. // Java program check thread is Daemon or not class MyThread extends Thread { @Override public void run() { System.out.println("User Thread or Non-Daemon Thread"); }} class MainThread { public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); System.out.println("Main Thread"); System.out.println("Is " + mt.getName() + " a Daemon Thread: " + mt.isDaemon()); System.out.println("Is " + Thread.currentThread().getName() + " a Daemon Thread: " + Thread.currentThread().isDaemon()); }} Main Thread Is Thread-0 a Daemon Thread: false Is main a Daemon Thread: false User Thread or Non-Daemon Thread Example: Make Non-Daemon Thread as a Daemon Thread:In this example, a non-daemon thread is made a daemon using setDeamon(boolean). // Java program make user thread as a daemon thread class MyThread extends Thread { @Override public void run() { System.out.println("Non-Daemon thread"); }} class MainThread { public static void main(String[] args) { MyThread mt = new MyThread(); System.out.println("Before using setDaemon() method: "); System.out.println("Is " + mt.getName() + " a Daemon Thread: " + mt.isDaemon()); mt.setDaemon(true); System.out.println("After using setDaemon() method: "); System.out.println("Is " + mt.getName() + " a Daemon Thread: " + mt.isDaemon()); }} Before using setDaemon() method: Is Thread-0 a Daemon Thread: false After using setDaemon() method: Is Thread-0 a Daemon Thread: true Java-Multithreading Processes & Threads Technical Scripter 2018 Difference Between Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference Between Spark DataFrame and Pandas DataFrame Difference between Internal and External fragmentation Difference between Top down parsing and Bottom up parsing Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24804, "s": 24776, "text": "\n16 Nov, 2018" }, { "code": null, "e": 24845, "s": 24804, "text": "In Java, there are two types of threads:" }, { "code": null, "e": 24870, "s": 24845, "text": "Daemon ThreadUser Thread" }, { "code": null, "e": 24884, "s": 24870, "text": "Daemon Thread" }, { "code": null, "e": 24896, "s": 24884, "text": "User Thread" }, { "code": null, "e": 25174, "s": 24896, "text": "Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks." }, { "code": null, "e": 25233, "s": 25174, "text": "Difference Between Daemon Threads And User Threads In Java" }, { "code": null, "e": 26707, "s": 25233, "text": "JVM doesn’t wait for daemon thread to finish but it waits for User Thread : First and foremost difference between daemon and user threads is that JVM will not wait for daemon thread to finish its task but it will wait for any active user thread.For example, one might have noticed this behavior while running Java program in NetBeans that even if the main thread has finished, the top left down button is still red, showing that Java program is still running. This is due to any user thread spawned from the main thread, but with main thread one don’t see that red dot in NetBeans.Thread Priority : The User threads are high priority as compare to daemon thread means they won’t get CPU as easily as a user thread can get.Creation of Thread : User thread is usually created by the application for executing some task concurrently. On the other hand, daemon thread is mostly created by JVM like for some garbage collection job.Termination of Thread : JVM will force daemon thread to terminate if all user threads have finished their execution but The user thread is closed by application or by itself. A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM. This is the most critical difference between user thread and daemon thread.Usage : The daemons threads are not used for any critical task. Any important task is done by user thread. A daemon thread is generally used for some background tasks which are not critical task." }, { "code": null, "e": 27289, "s": 26707, "text": "JVM doesn’t wait for daemon thread to finish but it waits for User Thread : First and foremost difference between daemon and user threads is that JVM will not wait for daemon thread to finish its task but it will wait for any active user thread.For example, one might have noticed this behavior while running Java program in NetBeans that even if the main thread has finished, the top left down button is still red, showing that Java program is still running. This is due to any user thread spawned from the main thread, but with main thread one don’t see that red dot in NetBeans." }, { "code": null, "e": 27431, "s": 27289, "text": "Thread Priority : The User threads are high priority as compare to daemon thread means they won’t get CPU as easily as a user thread can get." }, { "code": null, "e": 27636, "s": 27431, "text": "Creation of Thread : User thread is usually created by the application for executing some task concurrently. On the other hand, daemon thread is mostly created by JVM like for some garbage collection job." }, { "code": null, "e": 27989, "s": 27636, "text": "Termination of Thread : JVM will force daemon thread to terminate if all user threads have finished their execution but The user thread is closed by application or by itself. A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM. This is the most critical difference between user thread and daemon thread." }, { "code": null, "e": 28185, "s": 27989, "text": "Usage : The daemons threads are not used for any critical task. Any important task is done by user thread. A daemon thread is generally used for some background tasks which are not critical task." }, { "code": null, "e": 28239, "s": 28185, "text": "The Major Difference between User and Daemon Threads:" }, { "code": null, "e": 28278, "s": 28239, "text": "Example: Check Thread is Daemon or not" }, { "code": null, "e": 28523, "s": 28278, "text": "One can make a user thread as daemon thread by using setDaemon(boolean) method. In this example, thread type is being checked (User thread or Daemon thread) by using isDaemon() method. It returns true if it is daemon otherwise it returns false." }, { "code": "// Java program check thread is Daemon or not class MyThread extends Thread { @Override public void run() { System.out.println(\"User Thread or Non-Daemon Thread\"); }} class MainThread { public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); System.out.println(\"Main Thread\"); System.out.println(\"Is \" + mt.getName() + \" a Daemon Thread: \" + mt.isDaemon()); System.out.println(\"Is \" + Thread.currentThread().getName() + \" a Daemon Thread: \" + Thread.currentThread().isDaemon()); }}", "e": 29213, "s": 28523, "text": null }, { "code": null, "e": 29325, "s": 29213, "text": "Main Thread\nIs Thread-0 a Daemon Thread: false\nIs main a Daemon Thread: false\nUser Thread or Non-Daemon Thread\n" }, { "code": null, "e": 29456, "s": 29325, "text": "Example: Make Non-Daemon Thread as a Daemon Thread:In this example, a non-daemon thread is made a daemon using setDeamon(boolean)." }, { "code": "// Java program make user thread as a daemon thread class MyThread extends Thread { @Override public void run() { System.out.println(\"Non-Daemon thread\"); }} class MainThread { public static void main(String[] args) { MyThread mt = new MyThread(); System.out.println(\"Before using setDaemon() method: \"); System.out.println(\"Is \" + mt.getName() + \" a Daemon Thread: \" + mt.isDaemon()); mt.setDaemon(true); System.out.println(\"After using setDaemon() method: \"); System.out.println(\"Is \" + mt.getName() + \" a Daemon Thread: \" + mt.isDaemon()); }}", "e": 30186, "s": 29456, "text": null }, { "code": null, "e": 30323, "s": 30186, "text": "Before using setDaemon() method: \nIs Thread-0 a Daemon Thread: false\nAfter using setDaemon() method: \nIs Thread-0 a Daemon Thread: true\n" }, { "code": null, "e": 30343, "s": 30323, "text": "Java-Multithreading" }, { "code": null, "e": 30363, "s": 30343, "text": "Processes & Threads" }, { "code": null, "e": 30387, "s": 30363, "text": "Technical Scripter 2018" }, { "code": null, "e": 30406, "s": 30387, "text": "Difference Between" }, { "code": null, "e": 30411, "s": 30406, "text": "Java" }, { "code": null, "e": 30430, "s": 30411, "text": "Technical Scripter" }, { "code": null, "e": 30435, "s": 30430, "text": "Java" }, { "code": null, "e": 30533, "s": 30435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30542, "s": 30533, "text": "Comments" }, { "code": null, "e": 30555, "s": 30542, "text": "Old Comments" }, { "code": null, "e": 30616, "s": 30555, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30684, "s": 30616, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 30740, "s": 30684, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 30795, "s": 30740, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 30853, "s": 30795, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 30868, "s": 30853, "text": "Arrays in Java" }, { "code": null, "e": 30912, "s": 30868, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30934, "s": 30912, "text": "For-each loop in Java" }, { "code": null, "e": 30959, "s": 30934, "text": "Reverse a string in Java" } ]
C# | Remove the first occurrence from the StringCollection - GeeksforGeeks
01 Feb, 2019 StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.StringCollection.Remove(String) method is used to remove the first occurrence of a specific string from the StringCollection. Syntax: public void Remove (string value); Here, value is the string which is to be removed from the StringCollection. The value can be null. Note: Duplicate strings are allowed in StringCollection. Only the first occurrence is removed. To remove all occurrences of the specified string, use RemoveAt(IndexOf(value)) repeatedly while IndexOf does not return -1. If the StringCollection does not contain the specified object, the StringCollection remains unchanged. No exception is thrown. This method performs a linear search; therefore, this method is an O(n) operation, where n is Count. Example: // C# code to remove the first// occurrence of a specific string// from the StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] {"A", "A", "A", "B", "C", "C", "D", "D", "E"}; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); Console.WriteLine("Elements in StringCollection are : "); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // "A" from the StringCollection myCol.Remove("A"); Console.WriteLine("Elements in StringCollection are : "); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // "C" from the StringCollection myCol.Remove("C"); Console.WriteLine("Elements in StringCollection are : "); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // "A" from the StringCollection myCol.Remove("A"); Console.WriteLine("Elements in StringCollection are : "); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // "Z" from the StringCollection // It would not throw exception even // if "Z" does not exist in myCol myCol.Remove("Z"); Console.WriteLine("Elements in StringCollection are : "); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); }} Elements in StringCollection are : A A A B C C D D E Elements in StringCollection are : A A B C C D D E Elements in StringCollection are : A A B C D D E Elements in StringCollection are : A B C D D E Elements in StringCollection are : A B C D D E Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection.remove?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-method CSharp-Specialized-Namespace CSharp-Specialized-StringCollection C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24237, "s": 23911, "text": "StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.StringCollection.Remove(String) method is used to remove the first occurrence of a specific string from the StringCollection." }, { "code": null, "e": 24245, "s": 24237, "text": "Syntax:" }, { "code": null, "e": 24281, "s": 24245, "text": "public void Remove (string value);\n" }, { "code": null, "e": 24380, "s": 24281, "text": "Here, value is the string which is to be removed from the StringCollection. The value can be null." }, { "code": null, "e": 24386, "s": 24380, "text": "Note:" }, { "code": null, "e": 24437, "s": 24386, "text": "Duplicate strings are allowed in StringCollection." }, { "code": null, "e": 24600, "s": 24437, "text": "Only the first occurrence is removed. To remove all occurrences of the specified string, use RemoveAt(IndexOf(value)) repeatedly while IndexOf does not return -1." }, { "code": null, "e": 24727, "s": 24600, "text": "If the StringCollection does not contain the specified object, the StringCollection remains unchanged. No exception is thrown." }, { "code": null, "e": 24828, "s": 24727, "text": "This method performs a linear search; therefore, this method is an O(n) operation, where n is Count." }, { "code": null, "e": 24837, "s": 24828, "text": "Example:" }, { "code": "// C# code to remove the first// occurrence of a specific string// from the StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] {\"A\", \"A\", \"A\", \"B\", \"C\", \"C\", \"D\", \"D\", \"E\"}; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); Console.WriteLine(\"Elements in StringCollection are : \"); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // \"A\" from the StringCollection myCol.Remove(\"A\"); Console.WriteLine(\"Elements in StringCollection are : \"); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // \"C\" from the StringCollection myCol.Remove(\"C\"); Console.WriteLine(\"Elements in StringCollection are : \"); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // \"A\" from the StringCollection myCol.Remove(\"A\"); Console.WriteLine(\"Elements in StringCollection are : \"); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); // Removing the first occurrence of // \"Z\" from the StringCollection // It would not throw exception even // if \"Z\" does not exist in myCol myCol.Remove(\"Z\"); Console.WriteLine(\"Elements in StringCollection are : \"); // Displaying elements in StringCollection // named myCol foreach(Object obj in myCol) Console.WriteLine(obj); }}", "e": 27076, "s": 24837, "text": null }, { "code": null, "e": 27329, "s": 27076, "text": "Elements in StringCollection are : \nA\nA\nA\nB\nC\nC\nD\nD\nE\nElements in StringCollection are : \nA\nA\nB\nC\nC\nD\nD\nE\nElements in StringCollection are : \nA\nA\nB\nC\nD\nD\nE\nElements in StringCollection are : \nA\nB\nC\nD\nD\nE\nElements in StringCollection are : \nA\nB\nC\nD\nD\nE\n" }, { "code": null, "e": 27340, "s": 27329, "text": "Reference:" }, { "code": null, "e": 27463, "s": 27340, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection.remove?view=netframework-4.7.2" }, { "code": null, "e": 27492, "s": 27463, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 27506, "s": 27492, "text": "CSharp-method" }, { "code": null, "e": 27535, "s": 27506, "text": "CSharp-Specialized-Namespace" }, { "code": null, "e": 27571, "s": 27535, "text": "CSharp-Specialized-StringCollection" }, { "code": null, "e": 27574, "s": 27571, "text": "C#" }, { "code": null, "e": 27672, "s": 27574, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27681, "s": 27672, "text": "Comments" }, { "code": null, "e": 27694, "s": 27681, "text": "Old Comments" }, { "code": null, "e": 27734, "s": 27694, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27757, "s": 27734, "text": "Extension Method in C#" }, { "code": null, "e": 27785, "s": 27757, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27807, "s": 27785, "text": "Partial Classes in C#" }, { "code": null, "e": 27824, "s": 27807, "text": "C# | Inheritance" }, { "code": null, "e": 27864, "s": 27824, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27897, "s": 27864, "text": "Linked List Implementation in C#" }, { "code": null, "e": 27940, "s": 27897, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27956, "s": 27940, "text": "C# | List Class" } ]
How to get the current index of an array while using forEach loop in Kotlin?
Sometimes it becomes necessary to access the index of an array. In this article, we will see how we can access the index of an array in Kotlin while using forEach loop. nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible. In the following example, we will traverse through the "Subject" array and we will print the index along with the value. fun main() { var subject = listOf("Java", "Kotlin", "JS", "C") subject.forEachIndexed {index, element -> println("index = $index, item = $element ") } } It will generate the following output − index = 0, item = Java index = 1, item = Kotlin index = 2, item = JS index = 3, item = C withIndex() is a library function of Kotlin using which you can access both the index and the corresponding values of an array. In the following example, we will be using the same array and we will be using withIndex() to print its values and index. This has to be used with a for loop. fun main() { var subject=listOf("Java", "Kotlin", "JS", "C") for ((index, value) in subject.withIndex()) { println("The subject of $index is $value") } } It will generate the following output − The subject of 0 is Java The subject of 1 is Kotlin The subject of 2 is JS The subject of 3 is C
[ { "code": null, "e": 1231, "s": 1062, "text": "Sometimes it becomes necessary to access the index of an array. In this article, we will see how we can access the index of an array in Kotlin while using forEach loop." }, { "code": null, "e": 1434, "s": 1231, "text": "nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible." }, { "code": null, "e": 1555, "s": 1434, "text": "In the following example, we will traverse through the \"Subject\" array and we will print the index along with the value." }, { "code": null, "e": 1724, "s": 1555, "text": "fun main() {\n var subject = listOf(\"Java\", \"Kotlin\", \"JS\", \"C\")\n\n subject.forEachIndexed {index, element ->\n println(\"index = $index, item = $element \")\n }\n}" }, { "code": null, "e": 1764, "s": 1724, "text": "It will generate the following output −" }, { "code": null, "e": 1853, "s": 1764, "text": "index = 0, item = Java\nindex = 1, item = Kotlin\nindex = 2, item = JS\nindex = 3, item = C" }, { "code": null, "e": 2140, "s": 1853, "text": "withIndex() is a library function of Kotlin using which you can access both the index and the corresponding values of an array. In the following example, we will be using the same array and we will be using withIndex() to print its values and index. This has to be used with a for loop." }, { "code": null, "e": 2310, "s": 2140, "text": "fun main() {\n var subject=listOf(\"Java\", \"Kotlin\", \"JS\", \"C\")\n\n for ((index, value) in subject.withIndex()) {\n println(\"The subject of $index is $value\")\n }\n}" }, { "code": null, "e": 2350, "s": 2310, "text": "It will generate the following output −" }, { "code": null, "e": 2447, "s": 2350, "text": "The subject of 0 is Java\nThe subject of 1 is Kotlin\nThe subject of 2 is JS\nThe subject of 3 is C" } ]
Chrome Custom Tabs in Android with Kotlin - GeeksforGeeks
30 Aug, 2021 As developers, we have the option of displaying web content to a user in their browser or via WebViews, but both have their own limitations: starting the browser is a large, non-customizable context transition for users, whereas WebViews don’t support all aspects of the web platform. To address this issue, Google launched chrome custom tabs. It is a browser feature that provides apps with more control over their web experiences and enables more seamless transitions between native and web content without the usage of a WebView. They allow developers to alter the appearance and feel of the browser. It offers numerous advantages and customizations: Ability to change toolbar color Add enter and exit animations Enable content sharing Add custom actions to the browser toolbar and overflow menu Optimizes the performance In this article, we will be using Chrome customs tabs to display the web content to users with several customizations. To give you an idea of what we’ll be doing in this article, here’s a sample video. 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 Kotlin as the programming language. Step 2: Add the library dependency Navigate to the Gradle Scripts > build.gradle(Module: app), add the library in the dependencies section, and sync the project. dependencies { implementation 'androidx.browser:browser:1.3.0' } Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. 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: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"> <!--Adding a button--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button" android:layout_centerInParent="true" android:padding="15dp" android:text="Open Custom Chrome Tabs" android:textColor="#0F9D58"/> </RelativeLayout> Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added to understand the code in more detail. Kotlin import android.content.Contextimport android.content.pm.PackageManagerimport android.net.Uriimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.browser.customtabs.*import androidx.core.content.ContextCompatimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private var GFG_URI = "https://www.geeksforgeeks.org" private var package_name = "com.android.chrome"; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { val builder = CustomTabsIntent.Builder() // to set the toolbar color use CustomTabColorSchemeParams // since CustomTabsIntent.Builder().setToolBarColor() is deprecated val params = CustomTabColorSchemeParams.Builder() params.setToolbarColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimary)) builder.setDefaultColorSchemeParams(params.build()) // shows the title of web-page in toolbar builder.setShowTitle(true) // setShareState(CustomTabsIntent.SHARE_STATE_ON) will add a menu to share the web-page builder.setShareState(CustomTabsIntent.SHARE_STATE_ON) // To modify the close button, use // builder.setCloseButtonIcon(bitmap) // to set weather instant apps is enabled for the custom tab or not, use builder.setInstantAppsEnabled(true) // To use animations use - // builder.setStartAnimations(this, android.R.anim.start_in_anim, android.R.anim.start_out_anim) // builder.setExitAnimations(this, android.R.anim.exit_in_anim, android.R.anim.exit_out_anim) val customBuilder = builder.build() if (this.isPackageInstalled(package_name)) { // if chrome is available use chrome custom tabs customBuilder.intent.setPackage(package_name) customBuilder.launchUrl(this, Uri.parse(GFG_URI)) } else { // if not available use WebView to launch the url } } }} fun Context.isPackageInstalled(packageName: String): Boolean { // check if chrome is installed or not return try { packageManager.getPackageInfo(packageName, 0) true } catch (e: PackageManager.NameNotFoundException) { false }} Output: Project Link: Click Here Picked Android Kotlin 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 Retrofit with Kotlin Coroutine in Android GridView in Android with Example Android Listview in Java with Example How to Change the Background Color After Clicking the Button in Android? Kotlin Array Android UI Layouts Retrofit with Kotlin Coroutine in Android Android Menus Kotlin Setters and Getters
[ { "code": null, "e": 25116, "s": 25088, "text": "\n30 Aug, 2021" }, { "code": null, "e": 25770, "s": 25116, "text": "As developers, we have the option of displaying web content to a user in their browser or via WebViews, but both have their own limitations: starting the browser is a large, non-customizable context transition for users, whereas WebViews don’t support all aspects of the web platform. To address this issue, Google launched chrome custom tabs. It is a browser feature that provides apps with more control over their web experiences and enables more seamless transitions between native and web content without the usage of a WebView. They allow developers to alter the appearance and feel of the browser. It offers numerous advantages and customizations:" }, { "code": null, "e": 25802, "s": 25770, "text": "Ability to change toolbar color" }, { "code": null, "e": 25832, "s": 25802, "text": "Add enter and exit animations" }, { "code": null, "e": 25855, "s": 25832, "text": "Enable content sharing" }, { "code": null, "e": 25915, "s": 25855, "text": "Add custom actions to the browser toolbar and overflow menu" }, { "code": null, "e": 25941, "s": 25915, "text": "Optimizes the performance" }, { "code": null, "e": 26143, "s": 25941, "text": "In this article, we will be using Chrome customs tabs to display the web content to users with several customizations. To give you an idea of what we’ll be doing in this article, here’s a sample video." }, { "code": null, "e": 26172, "s": 26143, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26336, "s": 26172, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 26371, "s": 26336, "text": "Step 2: Add the library dependency" }, { "code": null, "e": 26498, "s": 26371, "text": "Navigate to the Gradle Scripts > build.gradle(Module: app), add the library in the dependencies section, and sync the project." }, { "code": null, "e": 26569, "s": 26498, "text": "dependencies {\n implementation 'androidx.browser:browser:1.3.0'\n}" }, { "code": null, "e": 26617, "s": 26569, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26759, "s": 26617, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file." }, { "code": null, "e": 26763, "s": 26759, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Adding a button--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/button\" android:layout_centerInParent=\"true\" android:padding=\"15dp\" android:text=\"Open Custom Chrome Tabs\" android:textColor=\"#0F9D58\"/> </RelativeLayout>", "e": 27436, "s": 26763, "text": null }, { "code": null, "e": 27482, "s": 27436, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 27652, "s": 27482, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added to understand the code in more detail." }, { "code": null, "e": 27659, "s": 27652, "text": "Kotlin" }, { "code": "import android.content.Contextimport android.content.pm.PackageManagerimport android.net.Uriimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.browser.customtabs.*import androidx.core.content.ContextCompatimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private var GFG_URI = \"https://www.geeksforgeeks.org\" private var package_name = \"com.android.chrome\"; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { val builder = CustomTabsIntent.Builder() // to set the toolbar color use CustomTabColorSchemeParams // since CustomTabsIntent.Builder().setToolBarColor() is deprecated val params = CustomTabColorSchemeParams.Builder() params.setToolbarColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimary)) builder.setDefaultColorSchemeParams(params.build()) // shows the title of web-page in toolbar builder.setShowTitle(true) // setShareState(CustomTabsIntent.SHARE_STATE_ON) will add a menu to share the web-page builder.setShareState(CustomTabsIntent.SHARE_STATE_ON) // To modify the close button, use // builder.setCloseButtonIcon(bitmap) // to set weather instant apps is enabled for the custom tab or not, use builder.setInstantAppsEnabled(true) // To use animations use - // builder.setStartAnimations(this, android.R.anim.start_in_anim, android.R.anim.start_out_anim) // builder.setExitAnimations(this, android.R.anim.exit_in_anim, android.R.anim.exit_out_anim) val customBuilder = builder.build() if (this.isPackageInstalled(package_name)) { // if chrome is available use chrome custom tabs customBuilder.intent.setPackage(package_name) customBuilder.launchUrl(this, Uri.parse(GFG_URI)) } else { // if not available use WebView to launch the url } } }} fun Context.isPackageInstalled(packageName: String): Boolean { // check if chrome is installed or not return try { packageManager.getPackageInfo(packageName, 0) true } catch (e: PackageManager.NameNotFoundException) { false }}", "e": 30137, "s": 27659, "text": null }, { "code": null, "e": 30146, "s": 30137, "text": "Output: " }, { "code": null, "e": 30171, "s": 30146, "text": "Project Link: Click Here" }, { "code": null, "e": 30178, "s": 30171, "text": "Picked" }, { "code": null, "e": 30186, "s": 30178, "text": "Android" }, { "code": null, "e": 30193, "s": 30186, "text": "Kotlin" }, { "code": null, "e": 30201, "s": 30193, "text": "Android" }, { "code": null, "e": 30299, "s": 30201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30308, "s": 30299, "text": "Comments" }, { "code": null, "e": 30321, "s": 30308, "text": "Old Comments" }, { "code": null, "e": 30360, "s": 30321, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30402, "s": 30360, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30435, "s": 30402, "text": "GridView in Android with Example" }, { "code": null, "e": 30473, "s": 30435, "text": "Android Listview in Java with Example" }, { "code": null, "e": 30546, "s": 30473, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 30559, "s": 30546, "text": "Kotlin Array" }, { "code": null, "e": 30578, "s": 30559, "text": "Android UI Layouts" }, { "code": null, "e": 30620, "s": 30578, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30634, "s": 30620, "text": "Android Menus" } ]
Latitude and longitude of the user's position in JavaScript?
The geolocation property returns a Geolocation object that can be used to locate the user's position. The object provided was navigator.geolocation.This might be annoying to the privacy of the user, therefore, the position is not available unless the user approves it. navigator.geolocation; This method returns the latitude and longitude of the user's position without taking any parameter as an argument. In this example using position.coords, which is a read-only property, along with javascript's geolocation property, the latitude and longitude of the user's location is found out and the result is displayed in the output. Live Demo <html> <body> <p id = "location"></p> <script> var loc = document.getElementById("location"); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(getPos); } function getPos(position) { loc.innerHTML = "Latitude: " + position.coords.latitude + " </br> Longitude: " + position.coords.longitude; } </script> </body> </html> Latitude: 17.4381439 Longitude: 78.3948683
[ { "code": null, "e": 1331, "s": 1062, "text": "The geolocation property returns a Geolocation object that can be used to locate the user's position. The object provided was navigator.geolocation.This might be annoying to the privacy of the user, therefore, the position is not available unless the user approves it." }, { "code": null, "e": 1354, "s": 1331, "text": "navigator.geolocation;" }, { "code": null, "e": 1469, "s": 1354, "text": "This method returns the latitude and longitude of the user's position without taking any parameter as an argument." }, { "code": null, "e": 1691, "s": 1469, "text": "In this example using position.coords, which is a read-only property, along with javascript's geolocation property, the latitude and longitude of the user's location is found out and the result is displayed in the output." }, { "code": null, "e": 1701, "s": 1691, "text": "Live Demo" }, { "code": null, "e": 2073, "s": 1701, "text": "<html>\n<body>\n<p id = \"location\"></p>\n<script>\n var loc = document.getElementById(\"location\");\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(getPos);\n }\n function getPos(position) {\n loc.innerHTML = \"Latitude: \" + position.coords.latitude +\n \" </br> Longitude: \" + position.coords.longitude;\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2116, "s": 2073, "text": "Latitude: 17.4381439\nLongitude: 78.3948683" } ]
Multiplexer Design using Verilog HDL - GeeksforGeeks
07 Jun, 2021 Prerequisite – Multiplexers in Digital Logic Problem : Design of a 2:1 MUX using Verilog Hardware Description Language along with Testbench. Concepts : A multiplexer is a combinational type of digital circuits that are used to transfer one of the available input lines to the single output and, which input has to be transferred to the output it will be decided by the state(logic 0 or logic 1) of the select line signal. 2:1 Multiplexer is having two inputs, one select line (to select one of the two input) and a single output. Truth Table – Verilog HDL code of 2:1 MUX : Design – // define a module for the design module mux2_1(in1, in2, select, out); // define input port input in1, in2, select; // define the output port output out; // assign one of the inputs to the output based upon select line input assign out = select ? in2 : in1; endmodule :mux2_1 Testbench – module test; reg in1, in2, select; wire out; // design under test mux2_1 mux(.in1(in1), .in2(in2), .select(select), .out(out)); // list the input to the design initial begin in1=1'b0;in2=1'b0;select=1'b0; #2 in1=1'b1; #2 select=1'b1; #2 in2=1'b1; #2 $stop(); end // monitor the output whenever any of the input changes initial begin $monitor("time=%0d, input1=%b, input2=%b, select line=%b, output=%b", $time, in1, in2, select, out); end endmodule :test Expected Output – time=0, input1=0, input2=0, select line=0, out=0 time=2, input1=1, input2=0, select line=0, out=1 time=4, input1=1, input2=0, select line=1, out=0 time=6, input1=1, input2=1, select line=1, out=1 manishkj116 Code_Mech Digital Electronics & Logic Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. BCD to 7 Segment Decoder Carry Look-Ahead Adder Difference between Unipolar, Polar and Bipolar Line Coding Schemes Encoder in Digital Logic Shift Micro-Operations in Computer Architecture Half Adder in Digital Logic Encoders and Decoders in Digital Logic Difference between Half adder and full adder Analog to Digital Conversion Difference between Flip-flop and Latch
[ { "code": null, "e": 24456, "s": 24428, "text": "\n07 Jun, 2021" }, { "code": null, "e": 24598, "s": 24456, "text": "Prerequisite – Multiplexers in Digital Logic Problem : Design of a 2:1 MUX using Verilog Hardware Description Language along with Testbench. " }, { "code": null, "e": 24988, "s": 24598, "text": "Concepts : A multiplexer is a combinational type of digital circuits that are used to transfer one of the available input lines to the single output and, which input has to be transferred to the output it will be decided by the state(logic 0 or logic 1) of the select line signal. 2:1 Multiplexer is having two inputs, one select line (to select one of the two input) and a single output. " }, { "code": null, "e": 25006, "s": 24990, "text": "Truth Table – " }, { "code": null, "e": 25037, "s": 25006, "text": "Verilog HDL code of 2:1 MUX : " }, { "code": null, "e": 25046, "s": 25037, "text": "Design –" }, { "code": null, "e": 25327, "s": 25046, "text": "// define a module for the design\nmodule mux2_1(in1, in2, select, out);\n\n// define input port\ninput in1, in2, select;\n\n// define the output port\noutput out;\n\n// assign one of the inputs to the output based upon select line input\nassign out = select ? in2 : in1;\nendmodule :mux2_1" }, { "code": null, "e": 25341, "s": 25327, "text": "Testbench – " }, { "code": null, "e": 25922, "s": 25341, "text": "module test;\nreg in1, in2, select;\nwire out;\n\n// design under test \nmux2_1 mux(.in1(in1), .in2(in2), \n .select(select), .out(out));\n\n// list the input to the design\ninitial begin in1=1'b0;in2=1'b0;select=1'b0; \n #2 in1=1'b1;\n #2 select=1'b1;\n #2 in2=1'b1;\n #2 $stop();\n end\n\n// monitor the output whenever any of the input changes\ninitial begin $monitor(\"time=%0d, input1=%b, input2=%b, \n select line=%b, output=%b\", $time, \n in1, in2, select, out);\n end\nendmodule :test" }, { "code": null, "e": 25941, "s": 25922, "text": "Expected Output – " }, { "code": null, "e": 26138, "s": 25941, "text": "time=0, input1=0, input2=0, select line=0, out=0\ntime=2, input1=1, input2=0, select line=0, out=1\ntime=4, input1=1, input2=0, select line=1, out=0\ntime=6, input1=1, input2=1, select line=1, out=1 " }, { "code": null, "e": 26150, "s": 26138, "text": "manishkj116" }, { "code": null, "e": 26160, "s": 26150, "text": "Code_Mech" }, { "code": null, "e": 26195, "s": 26160, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 26293, "s": 26195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26318, "s": 26293, "text": "BCD to 7 Segment Decoder" }, { "code": null, "e": 26341, "s": 26318, "text": "Carry Look-Ahead Adder" }, { "code": null, "e": 26408, "s": 26341, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 26433, "s": 26408, "text": "Encoder in Digital Logic" }, { "code": null, "e": 26481, "s": 26433, "text": "Shift Micro-Operations in Computer Architecture" }, { "code": null, "e": 26509, "s": 26481, "text": "Half Adder in Digital Logic" }, { "code": null, "e": 26548, "s": 26509, "text": "Encoders and Decoders in Digital Logic" }, { "code": null, "e": 26593, "s": 26548, "text": "Difference between Half adder and full adder" }, { "code": null, "e": 26622, "s": 26593, "text": "Analog to Digital Conversion" } ]
fgetc() and fputc() in C - GeeksforGeeks
06 Jul, 2021 fgetc() fgetc() is used to obtain input from a file single character at a time. This function returns the ASCII code of the character read by the function. It returns the character present at position indicated by file pointer. After reading the character, the file pointer is advanced to next character. If pointer is at end of file or if an error occurs EOF file is returned by this function. Syntax: int fgetc(FILE *pointer) pointer: pointer to a FILE object that identifies the stream on which the operation is to be performed. C // C program to illustrate fgetc() function#include <stdio.h> int main (){ // open the file FILE *fp = fopen("test.txt","r"); // Return if could not open file if (fp == NULL) return 0; do { // Taking input single character at a time char c = fgetc(fp); // Checking for end of file if (feof(fp)) break ; printf("%c", c); } while(1); fclose(fp); return(0);} Output: The entire content of file is printed character by character till end of file. It reads newline character as well. Using fputc() fputc() is used to write a single character at a time to a given file. It writes the given character at the position denoted by the file pointer and then advances the file pointer. This function returns the character that is written in case of successful write operation else in case of error EOF is returned. Syntax: int fputc(int char, FILE *pointer) char: character to be written. This is passed as its int promotion. pointer: pointer to a FILE object that identifies the stream where the character is to be written. C // C program to illustrate fputc() function#include<stdio.h>int main(){ int i = 0; FILE *fp = fopen("output.txt","w"); // Return if could not open file if (fp == NULL) return 0; char string[] = "good bye", received_string[20]; for (i = 0; string[i]!='\0'; i++) // Input string into the file // single character at a time fputc(string[i], fp); fclose(fp); fp = fopen("output.txt","r"); // Reading the string from file fgets(received_string,20,fp); printf("%s", received_string); fclose(fp); return 0;} Output: good bye When fputc() is executed characters of string variable are written into the file one by one. When we read the line from the file we get the same string that we entered.This article is contributed by Hardik Gaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ryanaksd4 surinderdawra388 cpp-file-handling CPP-Library C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. rand() and srand() in C/C++ fork() in C Command line arguments in C/C++ Function Pointer in C Substring in C++ Structures in C Different methods to reverse a string in C/C++ TCP Server-Client implementation in C Enumeration (or enum) in C Data Types in C
[ { "code": null, "e": 24510, "s": 24482, "text": "\n06 Jul, 2021" }, { "code": null, "e": 24518, "s": 24510, "text": "fgetc()" }, { "code": null, "e": 24915, "s": 24518, "text": "fgetc() is used to obtain input from a file single character at a time. This function returns the ASCII code of the character read by the function. It returns the character present at position indicated by file pointer. After reading the character, the file pointer is advanced to next character. If pointer is at end of file or if an error occurs EOF file is returned by this function. Syntax: " }, { "code": null, "e": 25045, "s": 24915, "text": "int fgetc(FILE *pointer)\npointer: pointer to a FILE object that identifies \nthe stream on which the operation is to be performed." }, { "code": null, "e": 25049, "s": 25047, "text": "C" }, { "code": "// C program to illustrate fgetc() function#include <stdio.h> int main (){ // open the file FILE *fp = fopen(\"test.txt\",\"r\"); // Return if could not open file if (fp == NULL) return 0; do { // Taking input single character at a time char c = fgetc(fp); // Checking for end of file if (feof(fp)) break ; printf(\"%c\", c); } while(1); fclose(fp); return(0);}", "e": 25489, "s": 25049, "text": null }, { "code": null, "e": 25499, "s": 25489, "text": "Output: " }, { "code": null, "e": 25614, "s": 25499, "text": "The entire content of file is printed character by\ncharacter till end of file. It reads newline character\nas well." }, { "code": null, "e": 25630, "s": 25616, "text": "Using fputc()" }, { "code": null, "e": 25950, "s": 25630, "text": "fputc() is used to write a single character at a time to a given file. It writes the given character at the position denoted by the file pointer and then advances the file pointer. This function returns the character that is written in case of successful write operation else in case of error EOF is returned. Syntax: " }, { "code": null, "e": 26155, "s": 25950, "text": "int fputc(int char, FILE *pointer)\nchar: character to be written. \nThis is passed as its int promotion.\npointer: pointer to a FILE object that identifies the \nstream where the character is to be written." }, { "code": null, "e": 26159, "s": 26157, "text": "C" }, { "code": "// C program to illustrate fputc() function#include<stdio.h>int main(){ int i = 0; FILE *fp = fopen(\"output.txt\",\"w\"); // Return if could not open file if (fp == NULL) return 0; char string[] = \"good bye\", received_string[20]; for (i = 0; string[i]!='\\0'; i++) // Input string into the file // single character at a time fputc(string[i], fp); fclose(fp); fp = fopen(\"output.txt\",\"r\"); // Reading the string from file fgets(received_string,20,fp); printf(\"%s\", received_string); fclose(fp); return 0;}", "e": 26733, "s": 26159, "text": null }, { "code": null, "e": 26743, "s": 26733, "text": "Output: " }, { "code": null, "e": 26752, "s": 26743, "text": "good bye" }, { "code": null, "e": 27340, "s": 26752, "text": "When fputc() is executed characters of string variable are written into the file one by one. When we read the line from the file we get the same string that we entered.This article is contributed by Hardik Gaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27350, "s": 27340, "text": "ryanaksd4" }, { "code": null, "e": 27367, "s": 27350, "text": "surinderdawra388" }, { "code": null, "e": 27385, "s": 27367, "text": "cpp-file-handling" }, { "code": null, "e": 27397, "s": 27385, "text": "CPP-Library" }, { "code": null, "e": 27408, "s": 27397, "text": "C Language" }, { "code": null, "e": 27506, "s": 27408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27534, "s": 27506, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27546, "s": 27534, "text": "fork() in C" }, { "code": null, "e": 27578, "s": 27546, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27600, "s": 27578, "text": "Function Pointer in C" }, { "code": null, "e": 27617, "s": 27600, "text": "Substring in C++" }, { "code": null, "e": 27633, "s": 27617, "text": "Structures in C" }, { "code": null, "e": 27680, "s": 27633, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 27718, "s": 27680, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27745, "s": 27718, "text": "Enumeration (or enum) in C" } ]
C++ program to generate random number
Let us see how to generate random numbers using C++. Here we are generating a random number in range 0 to some value. (In this program the max value is 100). To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand. The declaration of srand() is like below void srand(unsigned int seed) It takes a parameter called seed. This is an integer value to be used as seed by the pseudo-random number generator algorithm. This function returns nothing. To get the number we need the rand() method. To get the number in range 0 to max, we are using modulus operator to get the remainder. For the seed value we are providing the time(0) function result into the srand() function. #include<iostream> #include<cstdlib> #include using namespace std; main() { int max; max = 100; //set the upper bound to generate the random number srand(time(0)); cout << "The random number is: "<<rand()%max; } The random number is: 51 The random number is: 29 The random number is: 47
[ { "code": null, "e": 1220, "s": 1062, "text": "Let us see how to generate random numbers using C++. Here we are generating a random number\nin range 0 to some value. (In this program the max value is 100)." }, { "code": null, "e": 1411, "s": 1220, "text": "To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand." }, { "code": null, "e": 1452, "s": 1411, "text": "The declaration of srand() is like below" }, { "code": null, "e": 1482, "s": 1452, "text": "void srand(unsigned int seed)" }, { "code": null, "e": 1640, "s": 1482, "text": "It takes a parameter called seed. This is an integer value to be used as seed by the pseudo-random\nnumber generator algorithm. This function returns nothing." }, { "code": null, "e": 1774, "s": 1640, "text": "To get the number we need the rand() method. To get the number in range 0 to max, we are using\nmodulus operator to get the remainder." }, { "code": null, "e": 1865, "s": 1774, "text": "For the seed value we are providing the time(0) function result into the srand() function." }, { "code": null, "e": 2089, "s": 1865, "text": "#include<iostream>\n#include<cstdlib>\n#include\nusing namespace std;\nmain() {\n int max;\n max = 100; //set the upper bound to generate the random number\n srand(time(0));\n cout << \"The random number is: \"<<rand()%max;\n}" }, { "code": null, "e": 2114, "s": 2089, "text": "The random number is: 51" }, { "code": null, "e": 2139, "s": 2114, "text": "The random number is: 29" }, { "code": null, "e": 2165, "s": 2139, "text": "The random number is: 47\n" } ]
Animating a Lightbox with CSS & JavaScript
We can style lightbox in our webpage using CSS and JavaScript. The following example styles lightbox. Live Demo <!DOCTYPE html> <html> <style> #parent { margin: 2%; padding: 0; box-sizing: border-box; background: cornflowerblue; text-align: center; } html,body { height:100%; max-height:100%; min-height:100%; } .smart { display: block; margin: 0 auto; width: 150px; height :150px; } .animation2 { -webkit-transition: .4s ease-in-out; -moz-transition: .4s ease-in-out; -ms-transition: .4s ease-in-out; -o-transition:.4s ease-in-out; transition:.4s ease-in-out; } .customLightbox img { position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0; max-width: 0%; max-height: 0%; } #lightbox-controls { position: fixed; height: 70px; width: 70px; top: -70px; right: 0; z-index: 2; background: rgba(0,0,0,.1); } #close-lightbox { display: block; position: absolute; overflow: hidden; height: 50px; width: 50px; text-indent: -5000px; right: 10px; top: 10px; -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); -ms-transform: rotate(45deg); -o-transform: rotate(45deg); transform: rotate(45deg); } #close-lightbox:before { content: ''; display: block; position: absolute; height: 0px; width: 3px; left: 24px; top :0; background: white; } #close-lightbox:after { content: ''; display: block; position: absolute; width: 0px; height: 3px; top: 24px; left:0; background: white; } .customLightbox:target { top: 0%; bottom: 0%; opacity: 1; } .customLightbox:target img { max-width: 100%; max-height: 100%; } .customLightbox:target ~ #lightbox-controls { top: 0px; } .customLightbox:target ~ #lightbox-controls #close-lightbox:after { width: 50px; } .customLightbox:target ~ #lightbox-controls #close-lightbox:before { height: 50px; } @-webkit-keyframes smart { 0% { -webkit-transform: rotate(2deg); } 20% {-webkit-transform: rotate(-2deg);} 40% {-webkit-transform: rotate(2deg);} 60% {-webkit-transform: rotate(-2deg);} 80% {-webkit-transform: rotate(2deg);} 100% {-webkit-transform: rotate(-2deg);} } </style> <body> <div id="parent"> <h3>Lightbox Example</h3> <a href="#picture" class="smart"><img src="https://images.unsplash.com/photo1611460116297- 586f43de8ba8?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=130&ixlib=rb1.2.1&q=80&w=130"/> <div class="customLightbox" id="picture"> <img class="animation2" src="https://images.unsplash.com/photo-1611460116297- 586f43de8ba8?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=630&ixlib=rb1.2.1&q=80&w=630"/> </div> <div id="lightbox-controls" > <a id="close-lightbox" class="animation2" href="#">Close Lightbox</a> </div> </div> </body> </html> This will produce the following result −
[ { "code": null, "e": 1164, "s": 1062, "text": "We can style lightbox in our webpage using CSS and JavaScript. The following example styles lightbox." }, { "code": null, "e": 1175, "s": 1164, "text": " Live Demo" }, { "code": null, "e": 3895, "s": 1175, "text": "<!DOCTYPE html>\n<html>\n<style>\n#parent {\n margin: 2%;\n padding: 0;\n box-sizing: border-box;\n background: cornflowerblue;\n text-align: center;\n}\nhtml,body {\n height:100%;\n max-height:100%;\n min-height:100%;\n}\n.smart {\n display: block;\n margin: 0 auto;\n width: 150px;\n height :150px;\n}\n.animation2 {\n -webkit-transition: .4s ease-in-out;\n -moz-transition: .4s ease-in-out;\n -ms-transition: .4s ease-in-out;\n -o-transition:.4s ease-in-out;\n transition:.4s ease-in-out;\n}\n.customLightbox img {\n position: absolute;\n margin: auto;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n max-width: 0%;\n max-height: 0%;\n}\n#lightbox-controls {\n position: fixed;\n height: 70px;\n width: 70px;\n top: -70px;\n right: 0;\n z-index: 2;\n background: rgba(0,0,0,.1);\n}\n#close-lightbox {\n display: block;\n position: absolute;\n overflow: hidden;\n height: 50px;\n width: 50px;\n text-indent: -5000px;\n right: 10px;\n top: 10px;\n -webkit-transform: rotate(45deg);\n -moz-transform: rotate(45deg);\n -ms-transform: rotate(45deg);\n -o-transform: rotate(45deg);\n transform: rotate(45deg);\n}\n#close-lightbox:before {\n content: '';\n display: block;\n position: absolute;\n height: 0px;\n width: 3px;\n left: 24px;\n top :0;\n background: white;\n}\n#close-lightbox:after {\n content: '';\n display: block;\n position: absolute;\n width: 0px;\n height: 3px;\n top: 24px;\n left:0;\n background: white;\n}\n.customLightbox:target {\n top: 0%;\n bottom: 0%;\n opacity: 1;\n}\n.customLightbox:target img {\n max-width: 100%;\n max-height: 100%;\n}\n.customLightbox:target ~ #lightbox-controls {\n top: 0px;\n}\n.customLightbox:target ~ #lightbox-controls #close-lightbox:after {\n width: 50px;\n}\n.customLightbox:target ~ #lightbox-controls #close-lightbox:before {\n height: 50px;\n}\n@-webkit-keyframes smart {\n 0% {\n -webkit-transform: rotate(2deg);\n }\n 20% {-webkit-transform: rotate(-2deg);}\n 40% {-webkit-transform: rotate(2deg);}\n 60% {-webkit-transform: rotate(-2deg);}\n 80% {-webkit-transform: rotate(2deg);}\n 100% {-webkit-transform: rotate(-2deg);}\n}\n</style>\n<body>\n<div id=\"parent\">\n<h3>Lightbox Example</h3>\n<a href=\"#picture\" class=\"smart\"><img src=\"https://images.unsplash.com/photo1611460116297-\n586f43de8ba8?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=130&ixlib=rb1.2.1&q=80&w=130\"/>\n<div class=\"customLightbox\" id=\"picture\">\n<img class=\"animation2\" src=\"https://images.unsplash.com/photo-1611460116297-\n586f43de8ba8?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=630&ixlib=rb1.2.1&q=80&w=630\"/>\n</div>\n<div id=\"lightbox-controls\" >\n<a id=\"close-lightbox\" class=\"animation2\" href=\"#\">Close Lightbox</a>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 3936, "s": 3895, "text": "This will produce the following result −" } ]
Changing the Mouse Cursor in Tkinter
Tkinter is a GUI-based Python library which is used to develop various types of functional and GUI-based applications. It provides lots of functions and methods that can be used to provide extensibility and various features while developing an application. In this article, we will see how we can change the mouse cursor while hovering on a button in the tkinter frame using the cursor property. There are plenty of cursor maps available in tkinter’s button library that provide different visuals for the end-user. Some of the cursor in the library are, "arrow" "circle" "clock" "cross" "dotbox" "exchange" "fleur" "heart" "heart" "man" "mouse" "pirate" "plus" "shuttle" "sizing" "spider" "spraycan" "star" "target" "tcross" "trek" "watch" Let us first create some buttons and then we will apply some of these cursors on the mouse pointer. from tkinter import * #Create an instance of window or frame win= Tk() #Set the geometry win.geometry("700x600") win.resizable(0,0) win.config(cursor= "fleur") #Let us create a text label Label(win, text= "Hover on each of these buttons", font=('Poppins', 20)).pack(pady=20) #Create some buttons with cursor property b1= Button(win, text= "Star",cursor="star") b1.pack(pady=20) b2= Button(win, text= "Arrow",cursor="arrow") b2.pack(pady=20) b3= Button(win, text= "Circle",cursor="circle") b3.pack(pady=20) b4= Button(win, text= "Clock",cursor="clock") b4.pack(pady=20) b5= Button(win, text= "Heart",cursor="heart") b5.pack(pady=20) b6= Button(win, text= "Man",cursor="man") b6.pack(pady=20) b7= Button(win, text= "Mouse",cursor="mouse") b7.pack(pady=20) #Keep Running the window win.mainloop() Running the above code will create different buttons with different mouse pointer shapes.
[ { "code": null, "e": 1319, "s": 1062, "text": "Tkinter is a GUI-based Python library which is used to develop various types of functional and GUI-based applications. It provides lots of functions and methods that can be used to provide extensibility and various features while developing an application." }, { "code": null, "e": 1616, "s": 1319, "text": "In this article, we will see how we can change the mouse cursor while hovering on a button in the tkinter frame using the cursor property. There are plenty of cursor maps available in tkinter’s button library that provide different visuals for the end-user. Some of the cursor in the library are," }, { "code": null, "e": 1624, "s": 1616, "text": "\"arrow\"" }, { "code": null, "e": 1633, "s": 1624, "text": "\"circle\"" }, { "code": null, "e": 1641, "s": 1633, "text": "\"clock\"" }, { "code": null, "e": 1649, "s": 1641, "text": "\"cross\"" }, { "code": null, "e": 1658, "s": 1649, "text": "\"dotbox\"" }, { "code": null, "e": 1669, "s": 1658, "text": "\"exchange\"" }, { "code": null, "e": 1677, "s": 1669, "text": "\"fleur\"" }, { "code": null, "e": 1685, "s": 1677, "text": "\"heart\"" }, { "code": null, "e": 1693, "s": 1685, "text": "\"heart\"" }, { "code": null, "e": 1699, "s": 1693, "text": "\"man\"" }, { "code": null, "e": 1707, "s": 1699, "text": "\"mouse\"" }, { "code": null, "e": 1716, "s": 1707, "text": "\"pirate\"" }, { "code": null, "e": 1723, "s": 1716, "text": "\"plus\"" }, { "code": null, "e": 1733, "s": 1723, "text": "\"shuttle\"" }, { "code": null, "e": 1742, "s": 1733, "text": "\"sizing\"" }, { "code": null, "e": 1751, "s": 1742, "text": "\"spider\"" }, { "code": null, "e": 1762, "s": 1751, "text": "\"spraycan\"" }, { "code": null, "e": 1769, "s": 1762, "text": "\"star\"" }, { "code": null, "e": 1778, "s": 1769, "text": "\"target\"" }, { "code": null, "e": 1787, "s": 1778, "text": "\"tcross\"" }, { "code": null, "e": 1794, "s": 1787, "text": "\"trek\"" }, { "code": null, "e": 1802, "s": 1794, "text": "\"watch\"" }, { "code": null, "e": 1902, "s": 1802, "text": "Let us first create some buttons and then we will apply some of these cursors on the mouse pointer." }, { "code": null, "e": 2699, "s": 1902, "text": "from tkinter import *\n#Create an instance of window or frame\nwin= Tk()\n#Set the geometry\nwin.geometry(\"700x600\")\nwin.resizable(0,0)\nwin.config(cursor= \"fleur\")\n#Let us create a text label\nLabel(win, text= \"Hover on each of these buttons\", font=('Poppins', 20)).pack(pady=20)\n\n#Create some buttons with cursor property\nb1= Button(win, text= \"Star\",cursor=\"star\")\nb1.pack(pady=20)\nb2= Button(win, text= \"Arrow\",cursor=\"arrow\")\nb2.pack(pady=20)\nb3= Button(win, text= \"Circle\",cursor=\"circle\")\nb3.pack(pady=20)\nb4= Button(win, text= \"Clock\",cursor=\"clock\")\nb4.pack(pady=20)\nb5= Button(win, text= \"Heart\",cursor=\"heart\")\nb5.pack(pady=20)\nb6= Button(win, text= \"Man\",cursor=\"man\")\nb6.pack(pady=20)\nb7= Button(win, text= \"Mouse\",cursor=\"mouse\")\nb7.pack(pady=20)\n\n#Keep Running the window\n\nwin.mainloop()" }, { "code": null, "e": 2789, "s": 2699, "text": "Running the above code will create different buttons with different mouse pointer shapes." } ]
time.Time.UnixNano() Function in Golang with Examples - GeeksforGeeks
24 Aug, 2021 In Go language, time packages supply functionality for determining as well as viewing time. The Time.UnixNano() function in Go language is used to yield “t” as a Unix time that is the number of seconds passed from January 1, 1970, in UTC and the output here doesn’t rely upon the location connected with t. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func (t Time) UnixNano() int64 Here, “t” is the stated time.Note: Here, the output returned is not defined if the given Unix time in nanoseconds is not formed by an int64 type(which is a date before the year 1678 or after the year 2262). This implies that the result of calling the UnixNano() method on the zero Time is ambiguous.Return value: It returns “t” as a Unix time which is of type int64. Example 1: Go // Golang program to illustrate the usage of// Time.UnixNano() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t in UTC // for UnixNano method t := time.Date(2019, 13, 15, 23, 90, 12, 04, time.UTC) // Calling UnixNano method unixnano := t.UnixNano() // Prints output fmt.Printf("%v\n", unixnano)} Output: 1579134612000000004 Example 2: Go // Golang program to illustrate the usage of// Time.UnixNano() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t in UTC // for UnixNano method t := time.Date(2001, 13, 15, 2e3, 1e1, 12e2, 04e1, time.UTC) // Calling UnixNano method unixnano := t.UnixNano() // Prints output fmt.Printf("%v\n", unixnano)} Output: input 1018254600000000040 Here, the time “t” stated in the above code has values which contain constant “e” but they are converted in usual range while conversion. f20171220 GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? Arrays in Go Golang Maps Slices in Golang How to convert a string in lower case in Golang? How to compare times in Golang? How to Trim a String in Golang? Inheritance in GoLang
[ { "code": null, "e": 24554, "s": 24526, "text": "\n24 Aug, 2021" }, { "code": null, "e": 24998, "s": 24554, "text": "In Go language, time packages supply functionality for determining as well as viewing time. The Time.UnixNano() function in Go language is used to yield “t” as a Unix time that is the number of seconds passed from January 1, 1970, in UTC and the output here doesn’t rely upon the location connected with t. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. " }, { "code": null, "e": 25007, "s": 24998, "text": "Syntax: " }, { "code": null, "e": 25038, "s": 25007, "text": "func (t Time) UnixNano() int64" }, { "code": null, "e": 25406, "s": 25038, "text": "Here, “t” is the stated time.Note: Here, the output returned is not defined if the given Unix time in nanoseconds is not formed by an int64 type(which is a date before the year 1678 or after the year 2262). This implies that the result of calling the UnixNano() method on the zero Time is ambiguous.Return value: It returns “t” as a Unix time which is of type int64. " }, { "code": null, "e": 25417, "s": 25406, "text": "Example 1:" }, { "code": null, "e": 25420, "s": 25417, "text": "Go" }, { "code": "// Golang program to illustrate the usage of// Time.UnixNano() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t in UTC // for UnixNano method t := time.Date(2019, 13, 15, 23, 90, 12, 04, time.UTC) // Calling UnixNano method unixnano := t.UnixNano() // Prints output fmt.Printf(\"%v\\n\", unixnano)}", "e": 25846, "s": 25420, "text": null }, { "code": null, "e": 25855, "s": 25846, "text": "Output: " }, { "code": null, "e": 25875, "s": 25855, "text": "1579134612000000004" }, { "code": null, "e": 25886, "s": 25875, "text": "Example 2:" }, { "code": null, "e": 25889, "s": 25886, "text": "Go" }, { "code": "// Golang program to illustrate the usage of// Time.UnixNano() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t in UTC // for UnixNano method t := time.Date(2001, 13, 15, 2e3, 1e1, 12e2, 04e1, time.UTC) // Calling UnixNano method unixnano := t.UnixNano() // Prints output fmt.Printf(\"%v\\n\", unixnano)}", "e": 26317, "s": 25889, "text": null }, { "code": null, "e": 26326, "s": 26317, "text": "Output: " }, { "code": null, "e": 26352, "s": 26326, "text": "input\n1018254600000000040" }, { "code": null, "e": 26490, "s": 26352, "text": "Here, the time “t” stated in the above code has values which contain constant “e” but they are converted in usual range while conversion." }, { "code": null, "e": 26500, "s": 26490, "text": "f20171220" }, { "code": null, "e": 26512, "s": 26500, "text": "GoLang-time" }, { "code": null, "e": 26524, "s": 26512, "text": "Go Language" }, { "code": null, "e": 26622, "s": 26524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26673, "s": 26622, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 26720, "s": 26673, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 26753, "s": 26720, "text": "How to Split a String in Golang?" }, { "code": null, "e": 26766, "s": 26753, "text": "Arrays in Go" }, { "code": null, "e": 26778, "s": 26766, "text": "Golang Maps" }, { "code": null, "e": 26795, "s": 26778, "text": "Slices in Golang" }, { "code": null, "e": 26844, "s": 26795, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 26876, "s": 26844, "text": "How to compare times in Golang?" }, { "code": null, "e": 26908, "s": 26876, "text": "How to Trim a String in Golang?" } ]
When Pandas is not enough. Non-Equi Joins with Pandas and PandaSQL | by Rahul Agarwal | Towards Data Science
Pandas is one of the best data manipulation libraries in recent times. It lets you slice and dice, groupby, join and do any arbitrary data transformation. You can take a look at this post, which talks about handling most of the data manipulation cases using a straightforward, simple, and matter of fact way using Pandas. But even with how awesome pandas generally is, there sometimes are moments when you would like to have just a bit more. Say you come from a SQL background in which the same operation was too easy. Or you wanted to have more readable code. Or you just wanted to run an ad-hoc SQL query on your data frame. Or, maybe you come from R and want a replacement for sqldf. For example, one of the operations that Pandas doesn’t have an alternative for is non-equi joins, which are quite trivial in SQL. In this series of posts named Python Shorts, I will explain some simple but very useful constructs provided by Python, some essential tips, and some use cases I come up with regularly in my Data Science work. This post is essentially about using SQL with pandas Dataframes. Let’s say you have to join two data frames. One shows us the periods where we offer some promotions on some items. And the second one is our transaction Dataframe. I want to know the sales that were driven by promotions, i.e., the sales that happen for an item in the promotion period. We can do this by doing a join on the item column as well as a join condition (TransactionDt≥StartDt and TransactionDt≤EndDt). Since now our join conditions have a greater than and less than signs as well, such joins are called non-equi joins. Do think about how you will do such a thing in Pandas before moving on. So how will you do it in Pandas? Yes, a Pandas based solution exists, though I don’t find it readable enough. Let’s start by generating some random data to work with. offerDf,transactionDf = generate_data(n=100000) You don’t need to worry about the random data generation code above. Just know how our random data looks like: Once we have the data, we can do the non-equi join by merging the data on the column item and then filtering by the required condition. merged_df = pd.merge(offerDf,transactionDf,on='Item')pandas_solution = merged_df[(merged_df['TransactionDt']>=merged_df['StartDt']) & (merged_df['TransactionDt']<=merged_df['EndDt'])] The result is below just as we wanted: The Pandas solution is alright, and it does what we want, but we could also have used PandaSQL to get the same thing done in a much more readable way. What is PandaSQL? PandaSQL provides us with a way to write SQL on Pandas Dataframes. So if you have got some SQL queries already written, it might make more sense to use pandaSQL rather than converting them to pandas syntax. To get started with PandaSQL we install it simply with: pip install -U pandasql Once we have pandaSQL installed, we can use it by creating a pysqldf function that takes a query as an input and runs the query to return a Pandas DF. Don’t worry about the syntax; it remains more or less constant. from pandasql import sqldfpysqldf = lambda q: sqldf(q, globals()) We can now run any SQL query on our Pandas data frames using this function. And, below is the non-equi join, we want to do in the much more readable SQL format. q = """ SELECT A.*,B.TransactionDt,B.Sales FROM offerDf A INNER JOIN transactionDf B ON A.Item = B.Item AND A.StartDt <= B.TransactionDt AND A.EndDt >= B.TransactionDt; """pandaSQL_solution = pysqldf(q) The result is a pandas Dataframe as we would expect. The index is already reset for us, unlike before. While the PandaSQL function lets us run SQL queries on our Pandas data frames and is an excellent tool to be aware of in certain situations, it is not as performant as pure pandas syntax. When we time Pandas against the more readable PandaSQL, we find that the PandaSQL takes around 10x the time of native Pandas. In this post of the Python Shorts series, we learned about pandaSQL, which lets us use SQL queries on our Dataframes. We also looked at how to do non-equi joins using both native pandas as well as pandaSQL. While the PandaSQL library is not as performant as native pandas, it is a great addition to our data analytics toolbox when we want to do ad-hoc analysis and to people who feel much more comfortable with using SQL queries. For a closer look at the code for this post, please visit my GitHub repository, where you can find the code for this post as well as all my posts. If you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 494, "s": 172, "text": "Pandas is one of the best data manipulation libraries in recent times. It lets you slice and dice, groupby, join and do any arbitrary data transformation. You can take a look at this post, which talks about handling most of the data manipulation cases using a straightforward, simple, and matter of fact way using Pandas." }, { "code": null, "e": 859, "s": 494, "text": "But even with how awesome pandas generally is, there sometimes are moments when you would like to have just a bit more. Say you come from a SQL background in which the same operation was too easy. Or you wanted to have more readable code. Or you just wanted to run an ad-hoc SQL query on your data frame. Or, maybe you come from R and want a replacement for sqldf." }, { "code": null, "e": 989, "s": 859, "text": "For example, one of the operations that Pandas doesn’t have an alternative for is non-equi joins, which are quite trivial in SQL." }, { "code": null, "e": 1198, "s": 989, "text": "In this series of posts named Python Shorts, I will explain some simple but very useful constructs provided by Python, some essential tips, and some use cases I come up with regularly in my Data Science work." }, { "code": null, "e": 1263, "s": 1198, "text": "This post is essentially about using SQL with pandas Dataframes." }, { "code": null, "e": 1549, "s": 1263, "text": "Let’s say you have to join two data frames. One shows us the periods where we offer some promotions on some items. And the second one is our transaction Dataframe. I want to know the sales that were driven by promotions, i.e., the sales that happen for an item in the promotion period." }, { "code": null, "e": 1865, "s": 1549, "text": "We can do this by doing a join on the item column as well as a join condition (TransactionDt≥StartDt and TransactionDt≤EndDt). Since now our join conditions have a greater than and less than signs as well, such joins are called non-equi joins. Do think about how you will do such a thing in Pandas before moving on." }, { "code": null, "e": 1975, "s": 1865, "text": "So how will you do it in Pandas? Yes, a Pandas based solution exists, though I don’t find it readable enough." }, { "code": null, "e": 2032, "s": 1975, "text": "Let’s start by generating some random data to work with." }, { "code": null, "e": 2080, "s": 2032, "text": "offerDf,transactionDf = generate_data(n=100000)" }, { "code": null, "e": 2191, "s": 2080, "text": "You don’t need to worry about the random data generation code above. Just know how our random data looks like:" }, { "code": null, "e": 2327, "s": 2191, "text": "Once we have the data, we can do the non-equi join by merging the data on the column item and then filtering by the required condition." }, { "code": null, "e": 2521, "s": 2327, "text": "merged_df = pd.merge(offerDf,transactionDf,on='Item')pandas_solution = merged_df[(merged_df['TransactionDt']>=merged_df['StartDt']) & (merged_df['TransactionDt']<=merged_df['EndDt'])]" }, { "code": null, "e": 2560, "s": 2521, "text": "The result is below just as we wanted:" }, { "code": null, "e": 2711, "s": 2560, "text": "The Pandas solution is alright, and it does what we want, but we could also have used PandaSQL to get the same thing done in a much more readable way." }, { "code": null, "e": 2729, "s": 2711, "text": "What is PandaSQL?" }, { "code": null, "e": 2992, "s": 2729, "text": "PandaSQL provides us with a way to write SQL on Pandas Dataframes. So if you have got some SQL queries already written, it might make more sense to use pandaSQL rather than converting them to pandas syntax. To get started with PandaSQL we install it simply with:" }, { "code": null, "e": 3016, "s": 2992, "text": "pip install -U pandasql" }, { "code": null, "e": 3231, "s": 3016, "text": "Once we have pandaSQL installed, we can use it by creating a pysqldf function that takes a query as an input and runs the query to return a Pandas DF. Don’t worry about the syntax; it remains more or less constant." }, { "code": null, "e": 3297, "s": 3231, "text": "from pandasql import sqldfpysqldf = lambda q: sqldf(q, globals())" }, { "code": null, "e": 3458, "s": 3297, "text": "We can now run any SQL query on our Pandas data frames using this function. And, below is the non-equi join, we want to do in the much more readable SQL format." }, { "code": null, "e": 3744, "s": 3458, "text": "q = \"\"\" SELECT A.*,B.TransactionDt,B.Sales FROM offerDf A INNER JOIN transactionDf B ON A.Item = B.Item AND A.StartDt <= B.TransactionDt AND A.EndDt >= B.TransactionDt; \"\"\"pandaSQL_solution = pysqldf(q)" }, { "code": null, "e": 3847, "s": 3744, "text": "The result is a pandas Dataframe as we would expect. The index is already reset for us, unlike before." }, { "code": null, "e": 4035, "s": 3847, "text": "While the PandaSQL function lets us run SQL queries on our Pandas data frames and is an excellent tool to be aware of in certain situations, it is not as performant as pure pandas syntax." }, { "code": null, "e": 4161, "s": 4035, "text": "When we time Pandas against the more readable PandaSQL, we find that the PandaSQL takes around 10x the time of native Pandas." }, { "code": null, "e": 4368, "s": 4161, "text": "In this post of the Python Shorts series, we learned about pandaSQL, which lets us use SQL queries on our Dataframes. We also looked at how to do non-equi joins using both native pandas as well as pandaSQL." }, { "code": null, "e": 4591, "s": 4368, "text": "While the PandaSQL library is not as performant as native pandas, it is a great addition to our data analytics toolbox when we want to do ad-hoc analysis and to people who feel much more comfortable with using SQL queries." }, { "code": null, "e": 4738, "s": 4591, "text": "For a closer look at the code for this post, please visit my GitHub repository, where you can find the code for this post as well as all my posts." }, { "code": null, "e": 4910, "s": 4738, "text": "If you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out." }, { "code": null, "e": 5153, "s": 4910, "text": "I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
Understanding K-means Clustering in Machine Learning | by Dr. Michael J. Garbade | Towards Data Science
K-means clustering is one of the simplest and popular unsupervised machine learning algorithms. Typically, unsupervised algorithms make inferences from datasets using only input vectors without referring to known, or labelled, outcomes. AndreyBu, who has more than 5 years of machine learning experience and currently teaches people his skills, says that “the objective of K-means is simple: group similar data points together and discover underlying patterns. To achieve this objective, K-means looks for a fixed number (k) of clusters in a dataset.” A cluster refers to a collection of data points aggregated together because of certain similarities. You’ll define a target number k, which refers to the number of centroids you need in the dataset. A centroid is the imaginary or real location representing the center of the cluster. Every data point is allocated to each of the clusters through reducing the in-cluster sum of squares. In other words, the K-means algorithm identifies k number of centroids, and then allocates every data point to the nearest cluster, while keeping the centroids as small as possible. The ‘means’ in the K-means refers to averaging of the data; that is, finding the centroid. To process the learning data, the K-means algorithm in data mining starts with a first group of randomly selected centroids, which are used as the beginning points for every cluster, and then performs iterative (repetitive) calculations to optimize the positions of the centroids It halts creating and optimizing clusters when either: The centroids have stabilized — there is no change in their values because the clustering has been successful. The defined number of iterations has been achieved. Let’s see the steps on how the K-means machine learning algorithm works using the Python programming language. We’ll use the Scikit-learn library and some random data to illustrate a K-means clustering simple explanation. Step 1: Import libraries import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans%matplotlib inline As you can see from the above code, we’ll import the following libraries in our project: Pandas for reading and writing spreadsheets Numpy for carrying out efficient computations Matplotlib for visualization of data Step 2: Generate random data Here is the code for generating some random data in a two-dimensional space: X= -2 * np.random.rand(100,2)X1 = 1 + 2 * np.random.rand(50,2)X[50:100, :] = X1plt.scatter(X[ : , 0], X[ :, 1], s = 50, c = ‘b’)plt.show() A total of 100 data points has been generated and divided into two groups, of 50 points each. Here is how the data is displayed on a two-dimensional space: Step 3: Use Scikit-Learn We’ll use some of the available functions in the Scikit-learn library to process the randomly generated data. Here is the code: from sklearn.cluster import KMeansKmean = KMeans(n_clusters=2)Kmean.fit(X) In this case, we arbitrarily gave k (n_clusters) an arbitrary value of two. Here is the output of the K-means parameters we get if we run the code: KMeans(algorithm=’auto’, copy_x=True, init=’k-means++’, max_iter=300 n_clusters=2, n_init=10, n_jobs=1, precompute_distances=’auto’, random_state=None, tol=0.0001, verbose=0) Step 4: Finding the centroid Here is the code for finding the center of the clusters: Kmean.cluster_centers_ Here is the result of the value of the centroids: array([[-0.94665068, -0.97138368], [ 2.01559419, 2.02597093]]) Let’s display the cluster centroids (using green and red color). plt.scatter(X[ : , 0], X[ : , 1], s =50, c=’b’)plt.scatter(-0.94665068, -0.97138368, s=200, c=’g’, marker=’s’)plt.scatter(2.01559419, 2.02597093, s=200, c=’r’, marker=’s’)plt.show() Here is the output: Step 5: Testing the algorithm Here is the code for getting the labels property of the K-means clustering example dataset; that is, how the data points are categorized into the two clusters. Kmean.labels_ Here is the result of running the above K-means algorithm code: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) As you can see above, 50 data points belong to the 0 cluster while the rest belong to the 1 cluster. For example, let’s use the code below for predicting the cluster of a data point: sample_test=np.array([-3.0,-3.0])second_test=sample_test.reshape(1, -1)Kmean.predict(second_test) Here is the result: array([0]) It shows that the test data point belongs to the 0 (green centroid) cluster. Here is the entire K-means clustering algorithm code in Python: import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans%matplotlib inlineX= -2 * np.random.rand(100,2)X1 = 1 + 2 * np.random.rand(50,2)X[50:100, :] = X1plt.scatter(X[ : , 0], X[ :, 1], s = 50, c = ‘b’)plt.show()from sklearn.cluster import KMeansKmean = KMeans(n_clusters=2)Kmean.fit(X)Kmean.cluster_centers_plt.scatter(X[ : , 0], X[ : , 1], s =50, c=’b’)plt.scatter(-0.94665068, -0.97138368, s=200, c=’g’, marker=’s’)plt.scatter(2.01559419, 2.02597093, s=200, c=’r’, marker=’s’)plt.show()Kmean.labels_sample_test=np.array([-3.0,-3.0])second_test=sample_test.reshape(1, -1)Kmean.predict(second_test) K-means clustering is an extensively used technique for data cluster analysis. It is easy to understand, especially if you accelerate your learning using a K-means clustering tutorial. Furthermore, it delivers training results quickly. However, its performance is usually not as competitive as those of the other sophisticated clustering techniques because slight variations in the data could lead to high variance. Furthermore, clusters are assumed to be spherical and evenly sized, something which may reduce the accuracy of the K-means clustering Python results. What’s your experience with K-means clustering in machine learning? Please share your comments below.
[ { "code": null, "e": 268, "s": 172, "text": "K-means clustering is one of the simplest and popular unsupervised machine learning algorithms." }, { "code": null, "e": 409, "s": 268, "text": "Typically, unsupervised algorithms make inferences from datasets using only input vectors without referring to known, or labelled, outcomes." }, { "code": null, "e": 724, "s": 409, "text": "AndreyBu, who has more than 5 years of machine learning experience and currently teaches people his skills, says that “the objective of K-means is simple: group similar data points together and discover underlying patterns. To achieve this objective, K-means looks for a fixed number (k) of clusters in a dataset.”" }, { "code": null, "e": 825, "s": 724, "text": "A cluster refers to a collection of data points aggregated together because of certain similarities." }, { "code": null, "e": 1008, "s": 825, "text": "You’ll define a target number k, which refers to the number of centroids you need in the dataset. A centroid is the imaginary or real location representing the center of the cluster." }, { "code": null, "e": 1110, "s": 1008, "text": "Every data point is allocated to each of the clusters through reducing the in-cluster sum of squares." }, { "code": null, "e": 1292, "s": 1110, "text": "In other words, the K-means algorithm identifies k number of centroids, and then allocates every data point to the nearest cluster, while keeping the centroids as small as possible." }, { "code": null, "e": 1383, "s": 1292, "text": "The ‘means’ in the K-means refers to averaging of the data; that is, finding the centroid." }, { "code": null, "e": 1663, "s": 1383, "text": "To process the learning data, the K-means algorithm in data mining starts with a first group of randomly selected centroids, which are used as the beginning points for every cluster, and then performs iterative (repetitive) calculations to optimize the positions of the centroids" }, { "code": null, "e": 1718, "s": 1663, "text": "It halts creating and optimizing clusters when either:" }, { "code": null, "e": 1829, "s": 1718, "text": "The centroids have stabilized — there is no change in their values because the clustering has been successful." }, { "code": null, "e": 1881, "s": 1829, "text": "The defined number of iterations has been achieved." }, { "code": null, "e": 1992, "s": 1881, "text": "Let’s see the steps on how the K-means machine learning algorithm works using the Python programming language." }, { "code": null, "e": 2103, "s": 1992, "text": "We’ll use the Scikit-learn library and some random data to illustrate a K-means clustering simple explanation." }, { "code": null, "e": 2128, "s": 2103, "text": "Step 1: Import libraries" }, { "code": null, "e": 2249, "s": 2128, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans%matplotlib inline" }, { "code": null, "e": 2338, "s": 2249, "text": "As you can see from the above code, we’ll import the following libraries in our project:" }, { "code": null, "e": 2382, "s": 2338, "text": "Pandas for reading and writing spreadsheets" }, { "code": null, "e": 2428, "s": 2382, "text": "Numpy for carrying out efficient computations" }, { "code": null, "e": 2465, "s": 2428, "text": "Matplotlib for visualization of data" }, { "code": null, "e": 2494, "s": 2465, "text": "Step 2: Generate random data" }, { "code": null, "e": 2571, "s": 2494, "text": "Here is the code for generating some random data in a two-dimensional space:" }, { "code": null, "e": 2710, "s": 2571, "text": "X= -2 * np.random.rand(100,2)X1 = 1 + 2 * np.random.rand(50,2)X[50:100, :] = X1plt.scatter(X[ : , 0], X[ :, 1], s = 50, c = ‘b’)plt.show()" }, { "code": null, "e": 2804, "s": 2710, "text": "A total of 100 data points has been generated and divided into two groups, of 50 points each." }, { "code": null, "e": 2866, "s": 2804, "text": "Here is how the data is displayed on a two-dimensional space:" }, { "code": null, "e": 2891, "s": 2866, "text": "Step 3: Use Scikit-Learn" }, { "code": null, "e": 3001, "s": 2891, "text": "We’ll use some of the available functions in the Scikit-learn library to process the randomly generated data." }, { "code": null, "e": 3019, "s": 3001, "text": "Here is the code:" }, { "code": null, "e": 3094, "s": 3019, "text": "from sklearn.cluster import KMeansKmean = KMeans(n_clusters=2)Kmean.fit(X)" }, { "code": null, "e": 3170, "s": 3094, "text": "In this case, we arbitrarily gave k (n_clusters) an arbitrary value of two." }, { "code": null, "e": 3242, "s": 3170, "text": "Here is the output of the K-means parameters we get if we run the code:" }, { "code": null, "e": 3417, "s": 3242, "text": "KMeans(algorithm=’auto’, copy_x=True, init=’k-means++’, max_iter=300 n_clusters=2, n_init=10, n_jobs=1, precompute_distances=’auto’, random_state=None, tol=0.0001, verbose=0)" }, { "code": null, "e": 3446, "s": 3417, "text": "Step 4: Finding the centroid" }, { "code": null, "e": 3503, "s": 3446, "text": "Here is the code for finding the center of the clusters:" }, { "code": null, "e": 3526, "s": 3503, "text": "Kmean.cluster_centers_" }, { "code": null, "e": 3576, "s": 3526, "text": "Here is the result of the value of the centroids:" }, { "code": null, "e": 3639, "s": 3576, "text": "array([[-0.94665068, -0.97138368], [ 2.01559419, 2.02597093]])" }, { "code": null, "e": 3704, "s": 3639, "text": "Let’s display the cluster centroids (using green and red color)." }, { "code": null, "e": 3886, "s": 3704, "text": "plt.scatter(X[ : , 0], X[ : , 1], s =50, c=’b’)plt.scatter(-0.94665068, -0.97138368, s=200, c=’g’, marker=’s’)plt.scatter(2.01559419, 2.02597093, s=200, c=’r’, marker=’s’)plt.show()" }, { "code": null, "e": 3906, "s": 3886, "text": "Here is the output:" }, { "code": null, "e": 3936, "s": 3906, "text": "Step 5: Testing the algorithm" }, { "code": null, "e": 4096, "s": 3936, "text": "Here is the code for getting the labels property of the K-means clustering example dataset; that is, how the data points are categorized into the two clusters." }, { "code": null, "e": 4110, "s": 4096, "text": "Kmean.labels_" }, { "code": null, "e": 4174, "s": 4110, "text": "Here is the result of running the above K-means algorithm code:" }, { "code": null, "e": 4482, "s": 4174, "text": "array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])" }, { "code": null, "e": 4583, "s": 4482, "text": "As you can see above, 50 data points belong to the 0 cluster while the rest belong to the 1 cluster." }, { "code": null, "e": 4665, "s": 4583, "text": "For example, let’s use the code below for predicting the cluster of a data point:" }, { "code": null, "e": 4763, "s": 4665, "text": "sample_test=np.array([-3.0,-3.0])second_test=sample_test.reshape(1, -1)Kmean.predict(second_test)" }, { "code": null, "e": 4783, "s": 4763, "text": "Here is the result:" }, { "code": null, "e": 4794, "s": 4783, "text": "array([0])" }, { "code": null, "e": 4871, "s": 4794, "text": "It shows that the test data point belongs to the 0 (green centroid) cluster." }, { "code": null, "e": 4935, "s": 4871, "text": "Here is the entire K-means clustering algorithm code in Python:" }, { "code": null, "e": 5581, "s": 4935, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeans%matplotlib inlineX= -2 * np.random.rand(100,2)X1 = 1 + 2 * np.random.rand(50,2)X[50:100, :] = X1plt.scatter(X[ : , 0], X[ :, 1], s = 50, c = ‘b’)plt.show()from sklearn.cluster import KMeansKmean = KMeans(n_clusters=2)Kmean.fit(X)Kmean.cluster_centers_plt.scatter(X[ : , 0], X[ : , 1], s =50, c=’b’)plt.scatter(-0.94665068, -0.97138368, s=200, c=’g’, marker=’s’)plt.scatter(2.01559419, 2.02597093, s=200, c=’r’, marker=’s’)plt.show()Kmean.labels_sample_test=np.array([-3.0,-3.0])second_test=sample_test.reshape(1, -1)Kmean.predict(second_test)" }, { "code": null, "e": 5660, "s": 5581, "text": "K-means clustering is an extensively used technique for data cluster analysis." }, { "code": null, "e": 5817, "s": 5660, "text": "It is easy to understand, especially if you accelerate your learning using a K-means clustering tutorial. Furthermore, it delivers training results quickly." }, { "code": null, "e": 5997, "s": 5817, "text": "However, its performance is usually not as competitive as those of the other sophisticated clustering techniques because slight variations in the data could lead to high variance." }, { "code": null, "e": 6147, "s": 5997, "text": "Furthermore, clusters are assumed to be spherical and evenly sized, something which may reduce the accuracy of the K-means clustering Python results." }, { "code": null, "e": 6215, "s": 6147, "text": "What’s your experience with K-means clustering in machine learning?" } ]
Control methods of Database Security - GeeksforGeeks
15 Dec, 2021 Database Security means keeping sensitive information safe and prevent the loss of data. Security of data base is controlled by Database Administrator (DBA). The following are the main control measures are used to provide security of data in databases: 1. Authentication 2. Access control 3. Inference control 4. Flow control 5. Database Security applying Statistical Method 6. Encryption These are explained as following below. Authentication : Authentication is the process of confirmation that whether the user log in only according to the rights provided to him to perform the activities of data base. A particular user can login only up to his privilege but he can’t access the other sensitive data. The privilege of accessing sensitive data is restricted by using Authentication. By using these authentication tools for biometrics such as retina and figure prints can prevent the data base from unauthorized/malicious users. Access Control : The security mechanism of DBMS must include some provisions for restricting access to the data base by unauthorized users. Access control is done by creating user accounts and to control login process by the DBMS. So, that database access of sensitive data is possible only to those people (database users) who are allowed to access such data and to restrict access to unauthorized persons. The database system must also keep the track of all operations performed by certain user throughout the entire login time. Inference Control : This method is known as the countermeasures to statistical database security problem. It is used to prevent the user from completing any inference channel. This method protect sensitive information from indirect disclosure. Inferences are of two types, identity disclosure or attribute disclosure. Flow Control : This prevents information from flowing in a way that it reaches unauthorized users. Channels are the pathways for information to flow implicitly in ways that violate the privacy policy of a company are called convert channels. Database Security applying Statistical Method : Statistical database security focuses on the protection of confidential individual values stored in and used for statistical purposes and used to retrieve the summaries of values based on categories. They do not permit to retrieve the individual information. This allows to access the database to get statistical information about the number of employees in the company but not to access the detailed confidential/personal information about the specific individual employee. Encryption : This method is mainly used to protect sensitive data (such as credit card numbers, OTP numbers) and other sensitive numbers. The data is encoded using some encoding algorithms. An unauthorized user who tries to access this encoded data will face difficulty in decoding it, but authorized users are given decoding keys to decode data. Authentication : Authentication is the process of confirmation that whether the user log in only according to the rights provided to him to perform the activities of data base. A particular user can login only up to his privilege but he can’t access the other sensitive data. The privilege of accessing sensitive data is restricted by using Authentication. By using these authentication tools for biometrics such as retina and figure prints can prevent the data base from unauthorized/malicious users. Access Control : The security mechanism of DBMS must include some provisions for restricting access to the data base by unauthorized users. Access control is done by creating user accounts and to control login process by the DBMS. So, that database access of sensitive data is possible only to those people (database users) who are allowed to access such data and to restrict access to unauthorized persons. The database system must also keep the track of all operations performed by certain user throughout the entire login time. Inference Control : This method is known as the countermeasures to statistical database security problem. It is used to prevent the user from completing any inference channel. This method protect sensitive information from indirect disclosure. Inferences are of two types, identity disclosure or attribute disclosure. Flow Control : This prevents information from flowing in a way that it reaches unauthorized users. Channels are the pathways for information to flow implicitly in ways that violate the privacy policy of a company are called convert channels. Database Security applying Statistical Method : Statistical database security focuses on the protection of confidential individual values stored in and used for statistical purposes and used to retrieve the summaries of values based on categories. They do not permit to retrieve the individual information. This allows to access the database to get statistical information about the number of employees in the company but not to access the detailed confidential/personal information about the specific individual employee. Encryption : This method is mainly used to protect sensitive data (such as credit card numbers, OTP numbers) and other sensitive numbers. The data is encoded using some encoding algorithms. An unauthorized user who tries to access this encoded data will face difficulty in decoding it, but authorized users are given decoding keys to decode data. sweetyty DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database Difference between Clustered and Non-clustered index Introduction of B-Tree Introduction of ER Model Introduction of DBMS (Database Management System) | Set 1 SQL | Views CTE in SQL Difference between DDL and DML in DBMS SQL Interview Questions Second Normal Form (2NF)
[ { "code": null, "e": 24522, "s": 24494, "text": "\n15 Dec, 2021" }, { "code": null, "e": 24681, "s": 24522, "text": "Database Security means keeping sensitive information safe and prevent the loss of data. Security of data base is controlled by Database Administrator (DBA). " }, { "code": null, "e": 24777, "s": 24681, "text": "The following are the main control measures are used to provide security of data in databases: " }, { "code": null, "e": 24914, "s": 24777, "text": "1. Authentication\n2. Access control\n3. Inference control\n4. Flow control\n5. Database Security applying Statistical Method\n6. Encryption " }, { "code": null, "e": 24956, "s": 24914, "text": "These are explained as following below. " }, { "code": null, "e": 27421, "s": 24956, "text": "Authentication : Authentication is the process of confirmation that whether the user log in only according to the rights provided to him to perform the activities of data base. A particular user can login only up to his privilege but he can’t access the other sensitive data. The privilege of accessing sensitive data is restricted by using Authentication. By using these authentication tools for biometrics such as retina and figure prints can prevent the data base from unauthorized/malicious users. Access Control : The security mechanism of DBMS must include some provisions for restricting access to the data base by unauthorized users. Access control is done by creating user accounts and to control login process by the DBMS. So, that database access of sensitive data is possible only to those people (database users) who are allowed to access such data and to restrict access to unauthorized persons. The database system must also keep the track of all operations performed by certain user throughout the entire login time. Inference Control : This method is known as the countermeasures to statistical database security problem. It is used to prevent the user from completing any inference channel. This method protect sensitive information from indirect disclosure. Inferences are of two types, identity disclosure or attribute disclosure. Flow Control : This prevents information from flowing in a way that it reaches unauthorized users. Channels are the pathways for information to flow implicitly in ways that violate the privacy policy of a company are called convert channels. Database Security applying Statistical Method : Statistical database security focuses on the protection of confidential individual values stored in and used for statistical purposes and used to retrieve the summaries of values based on categories. They do not permit to retrieve the individual information. This allows to access the database to get statistical information about the number of employees in the company but not to access the detailed confidential/personal information about the specific individual employee. Encryption : This method is mainly used to protect sensitive data (such as credit card numbers, OTP numbers) and other sensitive numbers. The data is encoded using some encoding algorithms. An unauthorized user who tries to access this encoded data will face difficulty in decoding it, but authorized users are given decoding keys to decode data. " }, { "code": null, "e": 27924, "s": 27421, "text": "Authentication : Authentication is the process of confirmation that whether the user log in only according to the rights provided to him to perform the activities of data base. A particular user can login only up to his privilege but he can’t access the other sensitive data. The privilege of accessing sensitive data is restricted by using Authentication. By using these authentication tools for biometrics such as retina and figure prints can prevent the data base from unauthorized/malicious users. " }, { "code": null, "e": 28456, "s": 27924, "text": "Access Control : The security mechanism of DBMS must include some provisions for restricting access to the data base by unauthorized users. Access control is done by creating user accounts and to control login process by the DBMS. So, that database access of sensitive data is possible only to those people (database users) who are allowed to access such data and to restrict access to unauthorized persons. The database system must also keep the track of all operations performed by certain user throughout the entire login time. " }, { "code": null, "e": 28775, "s": 28456, "text": "Inference Control : This method is known as the countermeasures to statistical database security problem. It is used to prevent the user from completing any inference channel. This method protect sensitive information from indirect disclosure. Inferences are of two types, identity disclosure or attribute disclosure. " }, { "code": null, "e": 29018, "s": 28775, "text": "Flow Control : This prevents information from flowing in a way that it reaches unauthorized users. Channels are the pathways for information to flow implicitly in ways that violate the privacy policy of a company are called convert channels. " }, { "code": null, "e": 29542, "s": 29018, "text": "Database Security applying Statistical Method : Statistical database security focuses on the protection of confidential individual values stored in and used for statistical purposes and used to retrieve the summaries of values based on categories. They do not permit to retrieve the individual information. This allows to access the database to get statistical information about the number of employees in the company but not to access the detailed confidential/personal information about the specific individual employee. " }, { "code": null, "e": 29891, "s": 29542, "text": "Encryption : This method is mainly used to protect sensitive data (such as credit card numbers, OTP numbers) and other sensitive numbers. The data is encoded using some encoding algorithms. An unauthorized user who tries to access this encoded data will face difficulty in decoding it, but authorized users are given decoding keys to decode data. " }, { "code": null, "e": 29902, "s": 29893, "text": "sweetyty" }, { "code": null, "e": 29907, "s": 29902, "text": "DBMS" }, { "code": null, "e": 29912, "s": 29907, "text": "DBMS" }, { "code": null, "e": 30010, "s": 29912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30019, "s": 30010, "text": "Comments" }, { "code": null, "e": 30032, "s": 30019, "text": "Old Comments" }, { "code": null, "e": 30063, "s": 30032, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 30116, "s": 30063, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 30139, "s": 30116, "text": "Introduction of B-Tree" }, { "code": null, "e": 30164, "s": 30139, "text": "Introduction of ER Model" }, { "code": null, "e": 30222, "s": 30164, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 30234, "s": 30222, "text": "SQL | Views" }, { "code": null, "e": 30245, "s": 30234, "text": "CTE in SQL" }, { "code": null, "e": 30284, "s": 30245, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 30308, "s": 30284, "text": "SQL Interview Questions" } ]
Python | TextBlob.correct() method
13 Apr, 2022 With the help of TextBlob.correct() method, we can get the corrected words if any sentence have spelling mistakes by using TextBlob.correct() method. Syntax : TextBlob.correct() Return : Return the correct sentence without spelling mistakes. Example #1 : In this example, we can say that by using TextBlob.correct() method, we are able to get the correct sentence without any spelling mistakes. Python3 # import TextBlobfrom textblob import TextBlob gfg = TextBlob("GFG is a good compny and alays value ttheir employes.") # using TextBlob.correct() methodgfg = gfg.correct() print(gfg) Output: GFG is a good company and always value their employed. Example #2: Python3 # import TextBlobfrom textblob import TextBlob gfg = TextBlob("I amm goodd at spelling mstake.") # using TextBlob.correct() methodgfg = gfg.correct() print(gfg) Output : I am good at spelling mistake. abhishek0719kadiyan varshagumber28 rkbhola5 Python-Functions 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 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 Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2022" }, { "code": null, "e": 178, "s": 28, "text": "With the help of TextBlob.correct() method, we can get the corrected words if any sentence have spelling mistakes by using TextBlob.correct() method." }, { "code": null, "e": 272, "s": 178, "text": "Syntax : TextBlob.correct() Return : Return the correct sentence without spelling mistakes. " }, { "code": null, "e": 425, "s": 272, "text": "Example #1 : In this example, we can say that by using TextBlob.correct() method, we are able to get the correct sentence without any spelling mistakes." }, { "code": null, "e": 433, "s": 425, "text": "Python3" }, { "code": "# import TextBlobfrom textblob import TextBlob gfg = TextBlob(\"GFG is a good compny and alays value ttheir employes.\") # using TextBlob.correct() methodgfg = gfg.correct() print(gfg)", "e": 616, "s": 433, "text": null }, { "code": null, "e": 624, "s": 616, "text": "Output:" }, { "code": null, "e": 680, "s": 624, "text": "GFG is a good company and always value their employed. " }, { "code": null, "e": 692, "s": 680, "text": "Example #2:" }, { "code": null, "e": 700, "s": 692, "text": "Python3" }, { "code": "# import TextBlobfrom textblob import TextBlob gfg = TextBlob(\"I amm goodd at spelling mstake.\") # using TextBlob.correct() methodgfg = gfg.correct() print(gfg)", "e": 861, "s": 700, "text": null }, { "code": null, "e": 870, "s": 861, "text": "Output :" }, { "code": null, "e": 902, "s": 870, "text": "I am good at spelling mistake. " }, { "code": null, "e": 922, "s": 902, "text": "abhishek0719kadiyan" }, { "code": null, "e": 937, "s": 922, "text": "varshagumber28" }, { "code": null, "e": 946, "s": 937, "text": "rkbhola5" }, { "code": null, "e": 963, "s": 946, "text": "Python-Functions" }, { "code": null, "e": 970, "s": 963, "text": "Python" }, { "code": null, "e": 1068, "s": 970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1086, "s": 1068, "text": "Python Dictionary" }, { "code": null, "e": 1128, "s": 1086, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1163, "s": 1128, "text": "Read a file line by line in Python" }, { "code": null, "e": 1189, "s": 1163, "text": "Python String | replace()" }, { "code": null, "e": 1221, "s": 1189, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1250, "s": 1221, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1277, "s": 1250, "text": "Python Classes and Objects" }, { "code": null, "e": 1313, "s": 1277, "text": "Convert integer to string in Python" }, { "code": null, "e": 1344, "s": 1313, "text": "Python | os.path.join() method" } ]
Encryption and Decryption In Perl
29 Jul, 2021 Crypt function in, Perl, is basically used to store sensitive data and passwords using ASCII characters as encrypted strings (this function encrypts the string). Strings can only be encrypted, they can not be decrypted in the same way as encryption is done. Syntax: $encyrpted_string = crypt $string, $salt;Arguments passed to the function: $string: it is the string that needs to be encrypted. $salt: used for selecting an encrypted version from different variations. Return Value: Function returns an encrypted string Note: $salt variable can be the combination of any two characters from the below given set: ['.', '/', 0..9, 'A'..'Z', 'a'..'z'] We can use/include more characters other than this given set of characters, this set is just used for the purpose of recommendation. First two characters in the encrypted string are stored as the salt character which can be used for later comparisons. We can even select the characters for salt by using rand function(random selection). We can observe /see large changes in the resulting / final encrypted string, if small changes are made in the $string or $salt.Example: Below is the example to illustrate the above mentioned crypt function for Encryption. Perl #!usr/bin/perlprint "Content-type: text/html\n\n"; # Setting the password$password = 'geekforgeeks'; # Encrypting the password using crypt function$hidden = crypt $password, join "", ('.', '/', 0..9, 'A'..'Z', 'a'..'z') [rand 64, rand 64]; print "$hidden \n"; $salt = substr ($hidden, 0, 2); # Taking user inputprint "Enter Your Password: \n";while (<STDIN>){ if ($hidden eq (crypt $_, $salt)) { print "Successfully Logged In \n"; exit; } else { print "Entered Password is Incorrect \n"; print "Please Try Again: \n"; }} Output: For decryption, the encrypted password in Perl needs to be decrypted using the MIME::Base64 module. For decrypting a string we can call or use decode_base64() function. A single argument in the form of the string is taken as the input by the function in order to return the decoded or decrypted data/password. Syntax: Use MIME::Base64; $decoded = decode_base64(); Example: Given below is the example that illustrate the decryption process in Perl. Perl #!/usr/bin/perluse strict;use warnings;use MIME::Base64; # Setting the passwordmy $password = "GeeksforGeeks"; # For encrypting the plaintext password# using crypt functionmy $encoded = crypt $password, join "", ('.', '/', 0..9, 'A'..'Z', 'a'..'z') [rand 64, rand 64]; my $salt = substr ($encoded, 0, 2); # For decrypting the encrypted password# using base_64 modulemy $decoded = decode_base64($encoded);print "\n"; # For printing the Encrypted passwordprint "Encrypted Password :: $encoded\n"; # For printing the Decrypted passwordprint "Decrypted Password :: $decoded\n"; # For printing the password in PlainTextprint "Password In Plain Text :: $password\n"; Output: Let the cerulean loquacious warbler lead you to your treasure. kapoorsagar226 Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | ne operator Perl | Basic Syntax of a Perl Program Perl | Opening and Reading a File Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif) Perl | File Handling Introduction Perl | Writing to a File Perl | Multidimensional Hashes Perl | qw Operator Perl | Data Types
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jul, 2021" }, { "code": null, "e": 314, "s": 54, "text": "Crypt function in, Perl, is basically used to store sensitive data and passwords using ASCII characters as encrypted strings (this function encrypts the string). Strings can only be encrypted, they can not be decrypted in the same way as encryption is done. " }, { "code": null, "e": 399, "s": 314, "text": "Syntax: $encyrpted_string = crypt $string, $salt;Arguments passed to the function: " }, { "code": null, "e": 453, "s": 399, "text": "$string: it is the string that needs to be encrypted." }, { "code": null, "e": 527, "s": 453, "text": "$salt: used for selecting an encrypted version from different variations." }, { "code": null, "e": 578, "s": 527, "text": "Return Value: Function returns an encrypted string" }, { "code": null, "e": 672, "s": 578, "text": "Note: $salt variable can be the combination of any two characters from the below given set: " }, { "code": null, "e": 709, "s": 672, "text": "['.', '/', 0..9, 'A'..'Z', 'a'..'z']" }, { "code": null, "e": 1269, "s": 709, "text": "We can use/include more characters other than this given set of characters, this set is just used for the purpose of recommendation. First two characters in the encrypted string are stored as the salt character which can be used for later comparisons. We can even select the characters for salt by using rand function(random selection). We can observe /see large changes in the resulting / final encrypted string, if small changes are made in the $string or $salt.Example: Below is the example to illustrate the above mentioned crypt function for Encryption. " }, { "code": null, "e": 1274, "s": 1269, "text": "Perl" }, { "code": "#!usr/bin/perlprint \"Content-type: text/html\\n\\n\"; # Setting the password$password = 'geekforgeeks'; # Encrypting the password using crypt function$hidden = crypt $password, join \"\", ('.', '/', 0..9, 'A'..'Z', 'a'..'z') [rand 64, rand 64]; print \"$hidden \\n\"; $salt = substr ($hidden, 0, 2); # Taking user inputprint \"Enter Your Password: \\n\";while (<STDIN>){ if ($hidden eq (crypt $_, $salt)) { print \"Successfully Logged In \\n\"; exit; } else { print \"Entered Password is Incorrect \\n\"; print \"Please Try Again: \\n\"; }}", "e": 1850, "s": 1274, "text": null }, { "code": null, "e": 1860, "s": 1850, "text": "Output: " }, { "code": null, "e": 2182, "s": 1862, "text": "For decryption, the encrypted password in Perl needs to be decrypted using the MIME::Base64 module. For decrypting a string we can call or use decode_base64() function. A single argument in the form of the string is taken as the input by the function in order to return the decoded or decrypted data/password. Syntax: " }, { "code": null, "e": 2230, "s": 2182, "text": "Use MIME::Base64; $decoded = decode_base64(); " }, { "code": null, "e": 2315, "s": 2230, "text": "Example: Given below is the example that illustrate the decryption process in Perl. " }, { "code": null, "e": 2320, "s": 2315, "text": "Perl" }, { "code": "#!/usr/bin/perluse strict;use warnings;use MIME::Base64; # Setting the passwordmy $password = \"GeeksforGeeks\"; # For encrypting the plaintext password# using crypt functionmy $encoded = crypt $password, join \"\", ('.', '/', 0..9, 'A'..'Z', 'a'..'z') [rand 64, rand 64]; my $salt = substr ($encoded, 0, 2); # For decrypting the encrypted password# using base_64 modulemy $decoded = decode_base64($encoded);print \"\\n\"; # For printing the Encrypted passwordprint \"Encrypted Password :: $encoded\\n\"; # For printing the Decrypted passwordprint \"Decrypted Password :: $decoded\\n\"; # For printing the password in PlainTextprint \"Password In Plain Text :: $password\\n\";", "e": 2993, "s": 2320, "text": null }, { "code": null, "e": 3003, "s": 2993, "text": "Output: " }, { "code": null, "e": 3067, "s": 3003, "text": "Let the cerulean loquacious warbler lead you to your treasure. " }, { "code": null, "e": 3082, "s": 3067, "text": "kapoorsagar226" }, { "code": null, "e": 3087, "s": 3082, "text": "Perl" }, { "code": null, "e": 3092, "s": 3087, "text": "Perl" }, { "code": null, "e": 3190, "s": 3092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3231, "s": 3190, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 3250, "s": 3231, "text": "Perl | ne operator" }, { "code": null, "e": 3288, "s": 3250, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 3322, "s": 3288, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 3422, "s": 3322, "text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)" }, { "code": null, "e": 3456, "s": 3422, "text": "Perl | File Handling Introduction" }, { "code": null, "e": 3481, "s": 3456, "text": "Perl | Writing to a File" }, { "code": null, "e": 3512, "s": 3481, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 3531, "s": 3512, "text": "Perl | qw Operator" } ]
Find positions of Matching Elements between Vectors in R Programming – match() Function
15 Jun, 2020 match() function in R Language is used to return the positions of the first match of the elements of the first vector in the second vector. If the element is not found, it returns NA. Syntax: match(x1, x2, nomatch) Parameters:x1: Vector 1x2: Vector 2nomatch: value to be returned in case of no match Example 1: # R program to match the vectors # Creating vectorsx1 <- c("a", "b", "c", "d", "e")x2 <- c("d", "f", "g", "a", "e", "k") # Calling match functionmatch(x1, x2) Output: [1] 4 NA NA 1 5 Example 2: # R program to match the vectors # Creating vectorsx1 <- c("a", "b", "c", "d", "e")x2 <- c("d", "f", "g", "a", "e", "k") # Calling match functionmatch(x1, x2, nomatch = "-1") Output: [1] 4 -1 -1 1 5 R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jun, 2020" }, { "code": null, "e": 212, "s": 28, "text": "match() function in R Language is used to return the positions of the first match of the elements of the first vector in the second vector. If the element is not found, it returns NA." }, { "code": null, "e": 243, "s": 212, "text": "Syntax: match(x1, x2, nomatch)" }, { "code": null, "e": 328, "s": 243, "text": "Parameters:x1: Vector 1x2: Vector 2nomatch: value to be returned in case of no match" }, { "code": null, "e": 339, "s": 328, "text": "Example 1:" }, { "code": "# R program to match the vectors # Creating vectorsx1 <- c(\"a\", \"b\", \"c\", \"d\", \"e\")x2 <- c(\"d\", \"f\", \"g\", \"a\", \"e\", \"k\") # Calling match functionmatch(x1, x2)", "e": 500, "s": 339, "text": null }, { "code": null, "e": 508, "s": 500, "text": "Output:" }, { "code": null, "e": 528, "s": 508, "text": "[1] 4 NA NA 1 5\n" }, { "code": null, "e": 539, "s": 528, "text": "Example 2:" }, { "code": "# R program to match the vectors # Creating vectorsx1 <- c(\"a\", \"b\", \"c\", \"d\", \"e\")x2 <- c(\"d\", \"f\", \"g\", \"a\", \"e\", \"k\") # Calling match functionmatch(x1, x2, nomatch = \"-1\")", "e": 716, "s": 539, "text": null }, { "code": null, "e": 724, "s": 716, "text": "Output:" }, { "code": null, "e": 744, "s": 724, "text": "[1] 4 -1 -1 1 5\n" }, { "code": null, "e": 762, "s": 744, "text": "R Vector-Function" }, { "code": null, "e": 773, "s": 762, "text": "R Language" }, { "code": null, "e": 871, "s": 773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 923, "s": 871, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 981, "s": 923, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 1033, "s": 981, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1091, "s": 1033, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1123, "s": 1091, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1158, "s": 1123, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1202, "s": 1158, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1234, "s": 1202, "text": "Printing Output of an R Program" }, { "code": null, "e": 1272, "s": 1234, "text": "How to Change Axis Scales in R Plots?" } ]
Collections.reverseOrder() in Java with Examples
07 Jul, 2022 The reverseOrder() method of Collections class that in itself is present inside java.util package returns a comparator and using this comparator we can order the Collection in reverse order. Natural ordering is the ordering imposed by the objects’ own compareTo method. Syntax: public static Comparator reverseOrder() Parameter: A comparator whose ordering is to be reversed by the returned comparator(it can also be null) Return Type: A comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. Now in order to dig deeper to understand to grassroots, we will be covering different use-cases s listed below as follows: To sort a list in descending orderTo Sort an Array in Descending OrderTo sort students in descending order of roll numbers when there is a user-defined comparator to do reverse. To sort a list in descending order To Sort an Array in Descending Order To sort students in descending order of roll numbers when there is a user-defined comparator to do reverse. Case 1: To sort a list in descending order Example Java // Java Program to Demonstrate Working of reverseOrder()// method of Collections class// To sort a list in descending order // Importing required utility classesimport java.util.*; // Main class// Collectionsortingpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a list of integers for which we // create an empty ArrayList by // declaring object of ArrayList class ArrayList<Integer> al = new ArrayList<Integer>(); // Custom input integer elements al.add(30); al.add(20); al.add(10); al.add(40); al.add(50); // Using sort() method of Collections class to // sort the elements and passing list and using // reverseOrder() method to sort in descending order Collections.sort(al, Collections.reverseOrder()); // Lastly printing the descending sorted list on // console System.out.println( "List after the use of Collection.reverseOrder()" + " and Collections.sort() :\n" + al); }} List after the use of Collection.reverseOrder() and Collections.sort() : [50, 40, 30, 20, 10] Note: Geeks now you must be thinking that can we use Arrays.sort()? Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If we try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder(), it will throw the error as shown below as follows: Tip: But this will work fine with ‘Array of Objects’ such as the Integer array but will not work with a primitive array such as the int array. Case 2: To Sort an Array in Descending Order Example Java // Java Program to Demonstrate Working of reverseOrder()// method of Collections class// To Sort an Array in Descending Order // Importing required utility classesimport java.util.*; // Main class// CollectionSortingpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an array to be sorted in descending // order Integer[] arr = { 30, 20, 40, 10 }; // Collections.sort method is sorting the // elements of arr[] in descending order // later on Arrays.sort() is applied to sort array Arrays.sort(arr, Collections.reverseOrder()); // Printing the sorted array on console System.out.println( "Array after the use of Collection.reverseOrder()" + " and Arrays.sort() :\n" + Arrays.toString(arr)); }} Array after the use of Collection.reverseOrder() and Arrays.sort() : [40, 30, 20, 10] Case 3: To sort students in descending order of roll numbers when there is a user-defined comparator to do reverse. public static Comparator reverseOrder(Comparator c) It returns a Comparator that imposes reverse order of a passed Comparator object. We can use this method to sort a list in reverse order of user-defined Comparator. For example, in the below program, we have created a reverse of the user-defined comparator to sort students in descending order of roll numbers. Example: Java // Java Program to Demonstrate Working of// reverseOrder(Comparator c)// To sort students in descending order of roll numbers// when there is a user defined comparator to do reverse // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// Helper student class// to represent a studentclass Student { int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current instance itself this.rollno = rollno; this.name = name; this.address = address; } // Method of Student class // To print student details inside main() method public String toString() { return this.rollno + " " + this.name + " " + this.address; }} // Class 2// Helper class implementing interfaceclass Sortbyroll implements Comparator<Student> { // Method // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList ArrayList<Student> ar = new ArrayList<Student>(); // Adding custom attributes defined in Student class // using add() method ar.add(new Student(111, "bbbb", "london")); ar.add(new Student(131, "aaaa", "nyc")); ar.add(new Student(121, "cccc", "jaipur")); // Display message for better readability System.out.println("Unsorted"); // Printing list of students for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); // Sorting a list of students in descending order of // roll numbers using a Comparator // that is reverse of Sortbyroll() Comparator c = Collections.reverseOrder(new Sortbyroll()); Collections.sort(ar, c); // Display message for better readability System.out.println("\nSorted by rollno"); // Printing sorted students in descending order for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); }} Output: Unsorted 111 bbbb london 131 aaaa nyc 121 cccc jaipur Sorted by rollno 131 aaaa nyc 121 cccc jaipur 111 bbbb london The key thing here to remember is above program uses unchecked and unsafe operations. This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. prasanthibonam259 solankimayank kashishsoda simmytarika5 germanshephered48 Java - util package Java-Collections Java-Collections-Class Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Set in Java Introduction to Java
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 322, "s": 52, "text": "The reverseOrder() method of Collections class that in itself is present inside java.util package returns a comparator and using this comparator we can order the Collection in reverse order. Natural ordering is the ordering imposed by the objects’ own compareTo method." }, { "code": null, "e": 330, "s": 322, "text": "Syntax:" }, { "code": null, "e": 371, "s": 330, "text": "public static Comparator reverseOrder()" }, { "code": null, "e": 476, "s": 371, "text": "Parameter: A comparator whose ordering is to be reversed by the returned comparator(it can also be null)" }, { "code": null, "e": 620, "s": 476, "text": "Return Type: A comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. " }, { "code": null, "e": 743, "s": 620, "text": "Now in order to dig deeper to understand to grassroots, we will be covering different use-cases s listed below as follows:" }, { "code": null, "e": 921, "s": 743, "text": "To sort a list in descending orderTo Sort an Array in Descending OrderTo sort students in descending order of roll numbers when there is a user-defined comparator to do reverse." }, { "code": null, "e": 956, "s": 921, "text": "To sort a list in descending order" }, { "code": null, "e": 993, "s": 956, "text": "To Sort an Array in Descending Order" }, { "code": null, "e": 1101, "s": 993, "text": "To sort students in descending order of roll numbers when there is a user-defined comparator to do reverse." }, { "code": null, "e": 1144, "s": 1101, "text": "Case 1: To sort a list in descending order" }, { "code": null, "e": 1153, "s": 1144, "text": "Example " }, { "code": null, "e": 1158, "s": 1153, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of reverseOrder()// method of Collections class// To sort a list in descending order // Importing required utility classesimport java.util.*; // Main class// Collectionsortingpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a list of integers for which we // create an empty ArrayList by // declaring object of ArrayList class ArrayList<Integer> al = new ArrayList<Integer>(); // Custom input integer elements al.add(30); al.add(20); al.add(10); al.add(40); al.add(50); // Using sort() method of Collections class to // sort the elements and passing list and using // reverseOrder() method to sort in descending order Collections.sort(al, Collections.reverseOrder()); // Lastly printing the descending sorted list on // console System.out.println( \"List after the use of Collection.reverseOrder()\" + \" and Collections.sort() :\\n\" + al); }}", "e": 2245, "s": 1158, "text": null }, { "code": null, "e": 2339, "s": 2245, "text": "List after the use of Collection.reverseOrder() and Collections.sort() :\n[50, 40, 30, 20, 10]" }, { "code": null, "e": 2407, "s": 2339, "text": "Note: Geeks now you must be thinking that can we use Arrays.sort()?" }, { "code": null, "e": 2654, "s": 2407, "text": "Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If we try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder(), it will throw the error as shown below as follows:" }, { "code": null, "e": 2797, "s": 2654, "text": "Tip: But this will work fine with ‘Array of Objects’ such as the Integer array but will not work with a primitive array such as the int array." }, { "code": null, "e": 2842, "s": 2797, "text": "Case 2: To Sort an Array in Descending Order" }, { "code": null, "e": 2851, "s": 2842, "text": "Example " }, { "code": null, "e": 2856, "s": 2851, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of reverseOrder()// method of Collections class// To Sort an Array in Descending Order // Importing required utility classesimport java.util.*; // Main class// CollectionSortingpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an array to be sorted in descending // order Integer[] arr = { 30, 20, 40, 10 }; // Collections.sort method is sorting the // elements of arr[] in descending order // later on Arrays.sort() is applied to sort array Arrays.sort(arr, Collections.reverseOrder()); // Printing the sorted array on console System.out.println( \"Array after the use of Collection.reverseOrder()\" + \" and Arrays.sort() :\\n\" + Arrays.toString(arr)); }}", "e": 3711, "s": 2856, "text": null }, { "code": null, "e": 3797, "s": 3711, "text": "Array after the use of Collection.reverseOrder() and Arrays.sort() :\n[40, 30, 20, 10]" }, { "code": null, "e": 3913, "s": 3797, "text": "Case 3: To sort students in descending order of roll numbers when there is a user-defined comparator to do reverse." }, { "code": null, "e": 3966, "s": 3913, "text": "public static Comparator reverseOrder(Comparator c) " }, { "code": null, "e": 4278, "s": 3966, "text": "It returns a Comparator that imposes reverse order of a passed Comparator object. We can use this method to sort a list in reverse order of user-defined Comparator. For example, in the below program, we have created a reverse of the user-defined comparator to sort students in descending order of roll numbers. " }, { "code": null, "e": 4287, "s": 4278, "text": "Example:" }, { "code": null, "e": 4292, "s": 4287, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of// reverseOrder(Comparator c)// To sort students in descending order of roll numbers// when there is a user defined comparator to do reverse // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// Helper student class// to represent a studentclass Student { int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current instance itself this.rollno = rollno; this.name = name; this.address = address; } // Method of Student class // To print student details inside main() method public String toString() { return this.rollno + \" \" + this.name + \" \" + this.address; }} // Class 2// Helper class implementing interfaceclass Sortbyroll implements Comparator<Student> { // Method // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList ArrayList<Student> ar = new ArrayList<Student>(); // Adding custom attributes defined in Student class // using add() method ar.add(new Student(111, \"bbbb\", \"london\")); ar.add(new Student(131, \"aaaa\", \"nyc\")); ar.add(new Student(121, \"cccc\", \"jaipur\")); // Display message for better readability System.out.println(\"Unsorted\"); // Printing list of students for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); // Sorting a list of students in descending order of // roll numbers using a Comparator // that is reverse of Sortbyroll() Comparator c = Collections.reverseOrder(new Sortbyroll()); Collections.sort(ar, c); // Display message for better readability System.out.println(\"\\nSorted by rollno\"); // Printing sorted students in descending order for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); }}", "e": 6541, "s": 4292, "text": null }, { "code": null, "e": 6550, "s": 6541, "text": "Output: " }, { "code": null, "e": 6667, "s": 6550, "text": "Unsorted\n111 bbbb london\n131 aaaa nyc\n121 cccc jaipur\n\nSorted by rollno\n131 aaaa nyc\n121 cccc jaipur\n111 bbbb london" }, { "code": null, "e": 6753, "s": 6667, "text": "The key thing here to remember is above program uses unchecked and unsafe operations." }, { "code": null, "e": 7050, "s": 6753, "text": "This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 7068, "s": 7050, "text": "prasanthibonam259" }, { "code": null, "e": 7082, "s": 7068, "text": "solankimayank" }, { "code": null, "e": 7094, "s": 7082, "text": "kashishsoda" }, { "code": null, "e": 7107, "s": 7094, "text": "simmytarika5" }, { "code": null, "e": 7125, "s": 7107, "text": "germanshephered48" }, { "code": null, "e": 7145, "s": 7125, "text": "Java - util package" }, { "code": null, "e": 7162, "s": 7145, "text": "Java-Collections" }, { "code": null, "e": 7185, "s": 7162, "text": "Java-Collections-Class" }, { "code": null, "e": 7200, "s": 7185, "text": "Java-Functions" }, { "code": null, "e": 7205, "s": 7200, "text": "Java" }, { "code": null, "e": 7210, "s": 7205, "text": "Java" }, { "code": null, "e": 7227, "s": 7210, "text": "Java-Collections" }, { "code": null, "e": 7325, "s": 7227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7344, "s": 7325, "text": "Interfaces in Java" }, { "code": null, "e": 7374, "s": 7344, "text": "HashMap in Java with Examples" }, { "code": null, "e": 7392, "s": 7374, "text": "ArrayList in Java" }, { "code": null, "e": 7412, "s": 7392, "text": "Collections in Java" }, { "code": null, "e": 7427, "s": 7412, "text": "Stream In Java" }, { "code": null, "e": 7459, "s": 7427, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7479, "s": 7459, "text": "Stack Class in Java" }, { "code": null, "e": 7503, "s": 7479, "text": "Singleton Class in Java" }, { "code": null, "e": 7515, "s": 7503, "text": "Set in Java" } ]
Python | Splitting Text and Number in string
01 Jul, 2019 Sometimes, we have a string, which is composed of text and number (or vice-versa), without any specific distinction between the two. There might be a requirement in which we require to separate the text from the number. Let’s discuss certain ways in which this can be performed. Method #1 : Using re.compile() + re.match() + re.groups()The combination of all the above regex functions can be used to perform this particular task. In this we compile a regex and match it to group text and numbers separately into a tuple. # Python3 code to demonstrate working of# Splitting text and number in string # Using re.compile() + re.match() + re.groups()import re # initializing string test_str = "Geeks4321" # printing original string print("The original string is : " + str(test_str)) # Using re.compile() + re.match() + re.groups()# Splitting text and number in string temp = re.compile("([a-zA-Z]+)([0-9]+)")res = temp.match(test_str).groups() # printing result print("The tuple after the split of string and number : " + str(res)) The original string is : Geeks4321 The tuple after the split of string and number : ('Geeks', '4321') Method #2 : Using re.findall()The slight modification of regex can provide the flexibility to reduce the number of regex functions required to perform this particular task. The findall function is alone enough for this task. # Python3 code to demonstrate working of# Splitting text and number in string # Using re.findall()import re # initializing string test_str = "Geeks4321" # printing original string print("The original string is : " + str(test_str)) # Using re.findall()# Splitting text and number in string res = [re.findall(r'(\w+?)(\d+)', test_str)[0] ] # printing result print("The tuple after the split of string and number : " + str(res)) The original string is : Geeks4321 The tuple after the split of string and number : ('Geeks', '4321') Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jul, 2019" }, { "code": null, "e": 307, "s": 28, "text": "Sometimes, we have a string, which is composed of text and number (or vice-versa), without any specific distinction between the two. There might be a requirement in which we require to separate the text from the number. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 549, "s": 307, "text": "Method #1 : Using re.compile() + re.match() + re.groups()The combination of all the above regex functions can be used to perform this particular task. In this we compile a regex and match it to group text and numbers separately into a tuple." }, { "code": "# Python3 code to demonstrate working of# Splitting text and number in string # Using re.compile() + re.match() + re.groups()import re # initializing string test_str = \"Geeks4321\" # printing original string print(\"The original string is : \" + str(test_str)) # Using re.compile() + re.match() + re.groups()# Splitting text and number in string temp = re.compile(\"([a-zA-Z]+)([0-9]+)\")res = temp.match(test_str).groups() # printing result print(\"The tuple after the split of string and number : \" + str(res))", "e": 1060, "s": 549, "text": null }, { "code": null, "e": 1163, "s": 1060, "text": "The original string is : Geeks4321\nThe tuple after the split of string and number : ('Geeks', '4321')\n" }, { "code": null, "e": 1390, "s": 1165, "text": "Method #2 : Using re.findall()The slight modification of regex can provide the flexibility to reduce the number of regex functions required to perform this particular task. The findall function is alone enough for this task." }, { "code": "# Python3 code to demonstrate working of# Splitting text and number in string # Using re.findall()import re # initializing string test_str = \"Geeks4321\" # printing original string print(\"The original string is : \" + str(test_str)) # Using re.findall()# Splitting text and number in string res = [re.findall(r'(\\w+?)(\\d+)', test_str)[0] ] # printing result print(\"The tuple after the split of string and number : \" + str(res))", "e": 1820, "s": 1390, "text": null }, { "code": null, "e": 1923, "s": 1820, "text": "The original string is : Geeks4321\nThe tuple after the split of string and number : ('Geeks', '4321')\n" }, { "code": null, "e": 1946, "s": 1923, "text": "Python string-programs" }, { "code": null, "e": 1953, "s": 1946, "text": "Python" }, { "code": null, "e": 1969, "s": 1953, "text": "Python Programs" } ]
C Program for Binary Search (Recursive and Iterative)
13 Jun, 2022 We basically ignore half of the elements just after one comparison. Compare x with the middle element.If x matches with middle element, we return the mid index.Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.Else (x is smaller) recur for the left half. Compare x with the middle element. If x matches with middle element, we return the mid index. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. Else (x is smaller) recur for the left half. Recursive : C #include <stdio.h>// A recursive binary search function. It returns location of x in// given array arr[l..r] is present, otherwise -1int binarySearch(int arr[], int l, int r, int x){if (r >= l){int mid = l + (r - l)/2;// If the element is present at the middle itselfif (arr[mid] == x) return mid;// If element is smaller than mid, then it can only be present// in left subarrayif (arr[mid] > x) return binarySearch(arr, l, mid-1, x);// Else the element can only be present in right subarrayreturn binarySearch(arr, mid+1, r, x);}// We reach here when element is not present in arrayreturn -1;}int main(void){int arr[] = {2, 3, 4, 10, 40};int n = sizeof(arr)/ sizeof(arr[0]);int x = 10;int result = binarySearch(arr, 0, n-1, x);(result == -1)? printf("Element is not present in array"): printf("Element is present at index %d", result);return 0;} Time Complexity: O(log n) Auxiliary Space: O(1) Iterative C/C++ C #include <stdio.h>// A iterative binary search function. It returns location of x in// given array arr[l..r] if present, otherwise -1int binarySearch(int arr[], int l, int r, int x){while (l <= r){int m = l + (r-l)/2;// Check if x is present at midif (arr[m] == x)return m;// If x greater, ignore left halfif (arr[m] < x)l = m + 1;// If x is smaller, ignore right halfelser = m - 1;}// if we reach here, then element was not presentreturn -1;}int main(void){int arr[] = {2, 3, 4, 10, 40};int n = sizeof(arr)/ sizeof(arr[0]);int x = 10;int result = binarySearch(arr, 0, n-1, x);(result == -1)? printf("Element is not present in array"): printf("Element is present at index %d", result);return 0;} Time Complexity: O(log n) Auxiliary Space: O(1) Please refer complete article on Binary Search for more details! chandramauliguptach Binary Search C Programs Searching Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 120, "s": 52, "text": "We basically ignore half of the elements just after one comparison." }, { "code": null, "e": 393, "s": 120, "text": "Compare x with the middle element.If x matches with middle element, we return the mid index.Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.Else (x is smaller) recur for the left half." }, { "code": null, "e": 428, "s": 393, "text": "Compare x with the middle element." }, { "code": null, "e": 487, "s": 428, "text": "If x matches with middle element, we return the mid index." }, { "code": null, "e": 624, "s": 487, "text": "Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half." }, { "code": null, "e": 669, "s": 624, "text": "Else (x is smaller) recur for the left half." }, { "code": null, "e": 681, "s": 669, "text": "Recursive :" }, { "code": null, "e": 683, "s": 681, "text": "C" }, { "code": "#include <stdio.h>// A recursive binary search function. It returns location of x in// given array arr[l..r] is present, otherwise -1int binarySearch(int arr[], int l, int r, int x){if (r >= l){int mid = l + (r - l)/2;// If the element is present at the middle itselfif (arr[mid] == x) return mid;// If element is smaller than mid, then it can only be present// in left subarrayif (arr[mid] > x) return binarySearch(arr, l, mid-1, x);// Else the element can only be present in right subarrayreturn binarySearch(arr, mid+1, r, x);}// We reach here when element is not present in arrayreturn -1;}int main(void){int arr[] = {2, 3, 4, 10, 40};int n = sizeof(arr)/ sizeof(arr[0]);int x = 10;int result = binarySearch(arr, 0, n-1, x);(result == -1)? printf(\"Element is not present in array\"): printf(\"Element is present at index %d\", result);return 0;}", "e": 1530, "s": 683, "text": null }, { "code": null, "e": 1556, "s": 1530, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 1579, "s": 1556, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 1589, "s": 1579, "text": "Iterative" }, { "code": null, "e": 1595, "s": 1589, "text": "C/C++" }, { "code": null, "e": 1597, "s": 1595, "text": "C" }, { "code": "#include <stdio.h>// A iterative binary search function. It returns location of x in// given array arr[l..r] if present, otherwise -1int binarySearch(int arr[], int l, int r, int x){while (l <= r){int m = l + (r-l)/2;// Check if x is present at midif (arr[m] == x)return m;// If x greater, ignore left halfif (arr[m] < x)l = m + 1;// If x is smaller, ignore right halfelser = m - 1;}// if we reach here, then element was not presentreturn -1;}int main(void){int arr[] = {2, 3, 4, 10, 40};int n = sizeof(arr)/ sizeof(arr[0]);int x = 10;int result = binarySearch(arr, 0, n-1, x);(result == -1)? printf(\"Element is not present in array\"): printf(\"Element is present at index %d\", result);return 0;}", "e": 2293, "s": 1597, "text": null }, { "code": null, "e": 2319, "s": 2293, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 2342, "s": 2319, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 2407, "s": 2342, "text": "Please refer complete article on Binary Search for more details!" }, { "code": null, "e": 2427, "s": 2407, "text": "chandramauliguptach" }, { "code": null, "e": 2441, "s": 2427, "text": "Binary Search" }, { "code": null, "e": 2452, "s": 2441, "text": "C Programs" }, { "code": null, "e": 2462, "s": 2452, "text": "Searching" }, { "code": null, "e": 2472, "s": 2462, "text": "Searching" }, { "code": null, "e": 2486, "s": 2472, "text": "Binary Search" } ]
How to Insert an element at a specific position in an Array in C++
21 Jun, 2022 An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C++. Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. Approach: Here’s how to do it. First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posThen shift the array elements from this position to one position forward, and do this for all the other elements next to pos.Insert the element x now at the position pos, as this is now empty. First get the element to be inserted, say x Then get the position at which this element is to be inserted, say pos Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos. Insert the element x now at the position pos, as this is now empty. Below is the implementation of the above approach: CPP // C++ Program to Insert an element// at a specific position in an Array #include <iostream>using namespace std; // Function to insert x in arr at position posint* insertX(int n, int arr[], int x, int pos){ int i; // increase the size by 1 n++; // shift elements forward for (i = n; i >= pos; i--) arr[i] = arr[i - 1]; // insert x at pos arr[pos - 1] = x; return arr;} // Driver Codeint main(){ int arr[100] = { 0 }; int i, x, pos, n = 10; // initial array of size 10 for (i = 0; i < 10; i++) arr[i] = i + 1; // print the original array for (i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; // element to be inserted x = 50; // position at which element is to be inserted pos = 5; // Insert x at pos insertX(n, arr, x, pos); // print the updated array for (i = 0; i < n + 1; i++) cout << arr[i] << " "; cout << endl; return 0;} 1 2 3 4 5 6 7 8 9 10 1 2 3 4 50 5 6 7 8 9 10 Time Complexity: O(n) Auxiliary Space: O(1) harshmaster07705 cpp-array C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 353, "s": 52, "text": "An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C++. Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. Approach: Here’s how to do it." }, { "code": null, "e": 659, "s": 353, "text": "First get the element to be inserted, say xThen get the position at which this element is to be inserted, say posThen shift the array elements from this position to one position forward, and do this for all the other elements next to pos.Insert the element x now at the position pos, as this is now empty." }, { "code": null, "e": 703, "s": 659, "text": "First get the element to be inserted, say x" }, { "code": null, "e": 774, "s": 703, "text": "Then get the position at which this element is to be inserted, say pos" }, { "code": null, "e": 900, "s": 774, "text": "Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos." }, { "code": null, "e": 968, "s": 900, "text": "Insert the element x now at the position pos, as this is now empty." }, { "code": null, "e": 1020, "s": 968, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1024, "s": 1020, "text": "CPP" }, { "code": "// C++ Program to Insert an element// at a specific position in an Array #include <iostream>using namespace std; // Function to insert x in arr at position posint* insertX(int n, int arr[], int x, int pos){ int i; // increase the size by 1 n++; // shift elements forward for (i = n; i >= pos; i--) arr[i] = arr[i - 1]; // insert x at pos arr[pos - 1] = x; return arr;} // Driver Codeint main(){ int arr[100] = { 0 }; int i, x, pos, n = 10; // initial array of size 10 for (i = 0; i < 10; i++) arr[i] = i + 1; // print the original array for (i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl; // element to be inserted x = 50; // position at which element is to be inserted pos = 5; // Insert x at pos insertX(n, arr, x, pos); // print the updated array for (i = 0; i < n + 1; i++) cout << arr[i] << \" \"; cout << endl; return 0;}", "e": 1984, "s": 1024, "text": null }, { "code": null, "e": 2030, "s": 1984, "text": "1 2 3 4 5 6 7 8 9 10 \n1 2 3 4 50 5 6 7 8 9 10" }, { "code": null, "e": 2052, "s": 2030, "text": "Time Complexity: O(n)" }, { "code": null, "e": 2074, "s": 2052, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2091, "s": 2074, "text": "harshmaster07705" }, { "code": null, "e": 2101, "s": 2091, "text": "cpp-array" }, { "code": null, "e": 2105, "s": 2101, "text": "C++" }, { "code": null, "e": 2109, "s": 2105, "text": "CPP" } ]
Print numbers in descending order along with their frequencies
14 Jun, 2022 Given an array arr, the task is to print the elements of the array in descending order along with their frequencies.Examples: Input: arr[] = {1, 3, 3, 3, 4, 4, 5} Output: 5 occurs 1 times 4 occurs 2 times 3 occurs 3 times 1 occurs 1 timesInput: arr[] = {1, 1, 1, 2, 3, 4, 9, 9, 10} Output: 10 occurs 1 times 9 occurs 2 times 4 occurs 1 times 3 occurs 1 times 2 occurs 1 times 1 occurs 3 times Naive approach: Use some Data-Structure (e.g. multiset) that stores elements in decreasing order and then print the elements one by one with its count and then erase it from the Data-structure. The time complexity will be O(N log N) and the auxiliary space will be O(N) for the Data-structure used.Below is the implementation of the above approach: CPP // C++ program to print the elements in// descending along with their frequencies#include <bits/stdc++.h>using namespace std; // Function to print the elements in descending// along with their frequenciesvoid printElements(int a[], int n){ // A multiset to store elements in decreasing order multiset<int, greater<int> > ms; // Insert elements in the multiset for (int i = 0; i < n; i++) { ms.insert(a[i]); } // Print the elements along with their frequencies while (!ms.empty()) { // Find the maximum element int maxel = *ms.begin(); // Number of times it occurs int times = ms.count(maxel); cout << maxel << " occurs " << times << " times\n"; // Erase the maxel ms.erase(maxel); }} // Driver Codeint main(){ int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); printElements(a, n); return 0;} 10 occurs 1 times 9 occurs 2 times 4 occurs 1 times 3 occurs 1 times 2 occurs 1 times 1 occurs 3 times Time Complexity: O(N*logN), as we are using a loop to traverse N times and in each traversal, we are doing a multiset operation which will cost us logN time. Auxiliary Space: O(N), as we are using extra space for the multiset. Efficient Approach: Sort the array in descending order and then start printing the elements from the beginning along with their frequencies.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to print the elements in// descending along with their frequencies#include <bits/stdc++.h>using namespace std; // Function to print the elements in descending// along with their frequenciesvoid printElements(int a[], int n){ // Sorts the element in decreasing order sort(a, a + n, greater<int>()); int cnt = 1; // traverse the array elements for (int i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { cout << a[i] << " occurs " << cnt << " times\n"; cnt = 1; } else cnt += 1; } // Prints the last step cout << a[n - 1] << " occurs " << cnt << " times\n";} // Driver Codeint main(){ int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); printElements(a, n); return 0;} // Java program to print the elements in// descending along with their frequenciesimport java.util.*; class GFG{ // Function to print the elements in descending// along with their frequenciesstatic void printElements(int a[], int n){ // Sorts the element in decreasing order Arrays.sort(a); a = reverse(a); int cnt = 1; // traverse the array elements for (int i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { System.out.print(a[i]+ " occurs " + cnt + " times\n"); cnt = 1; } else cnt += 1; } // Prints the last step System.out.print(a[n - 1]+ " occurs " + cnt + " times\n");} static int[] reverse(int a[]){ int i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = a.length; printElements(a, n);}} // This code is contributed by PrinciRaj1992 # Python3 program to print the elements in# descending along with their frequencies # Function to print the elements in# descending along with their frequenciesdef printElements(a, n) : # Sorts the element in decreasing order a.sort(reverse = True) cnt = 1 # traverse the array elements for i in range(n - 1) : # Prints the number and count if (a[i] != a[i + 1]) : print(a[i], " occurs ", cnt, "times") cnt = 1 else : cnt += 1 # Prints the last step print(a[n - 1], "occurs", cnt, "times") # Driver Codeif __name__ == "__main__" : a = [ 1, 1, 1, 2, 3, 4, 9, 9, 10 ] n = len(a) printElements(a, n) # This code is contributed by Ryuga // C# program to print the elements in// descending along with their frequenciesusing System; class GFG{ // Function to print the elements in descending// along with their frequenciesstatic void printElements(int []a, int n){ // Sorts the element in decreasing order Array.Sort(a); a = reverse(a); int cnt = 1; // traverse the array elements for (int i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { Console.Write(a[i]+ " occurs " + cnt + " times\n"); cnt = 1; } else cnt += 1; } // Prints the last step Console.Write(a[n - 1]+ " occurs " + cnt + " times\n");} static int[] reverse(int []a){ int i, n = a.Length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = a.Length; printElements(a, n);}} // This code is contributed by PrinciRaj1992 <?php// PHP program to print the elements in// descending along with their frequencies // Function to print the elements in// descending along with their frequenciesfunction printElements(&$a, $n){ // Sorts the element in // decreasing order rsort($a); $cnt = 1; // traverse the array elements for ($i = 0; $i < $n - 1; $i++) { // Prints the number and count if ($a[$i] != $a[$i + 1]) { echo ($a[$i]); echo (" occurs " ); echo $cnt ; echo (" times\n"); $cnt = 1; } else $cnt += 1; } // Prints the last step echo ($a[$n - 1]); echo (" occurs "); echo $cnt; echo (" times\n");} // Driver Code$a = array(1, 1, 1, 2, 3, 4, 9, 9, 10 );$n = sizeof($a); printElements($a, $n); // This code is contributed// by Shivi_Aggarwal?> <script> // javascript program to print the elements in// descending along with their frequencies // Function to print the elements in descending// along with their frequencies function printElements(a, n) { // Sorts the element in decreasing order a=a.sort(compare); a = reverse(a); var cnt = 1; // traverse the array elements for (var i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { document.write(a[i]+ " occurs " + cnt + " times" + "<br>"); cnt = 1; } else cnt += 1; } // Prints the last step document.write(a[n - 1]+ " occurs " + cnt + " times" + "<br>");} function reverse(a){ var i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} function compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; }} // Driver Code var a = [ 1, 1, 1, 2, 3, 4, 9, 9, 10 ]; var n = a.length; printElements(a, n); // This code is contributed by bunnyram19.</script> 10 occurs 1 times 9 occurs 2 times 4 occurs 1 times 3 occurs 1 times 2 occurs 1 times 1 occurs 3 times Time Complexity: O(N*logN), as we are using the sort function which will cost us O(N*logN) time. Auxiliary Space: O(1), as we are not using any extra space. ankthon Shivi_Aggarwal princiraj1992 bunnyram19 rohitsingh07052 cpp-multiset STL C++ Programs Competitive Programming Searching Searching STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Program to implement Singly Linked List in C++ using class Different ways to print elements of vector Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jun, 2022" }, { "code": null, "e": 156, "s": 28, "text": "Given an array arr, the task is to print the elements of the array in descending order along with their frequencies.Examples: " }, { "code": null, "e": 425, "s": 156, "text": "Input: arr[] = {1, 3, 3, 3, 4, 4, 5} Output: 5 occurs 1 times 4 occurs 2 times 3 occurs 3 times 1 occurs 1 timesInput: arr[] = {1, 1, 1, 2, 3, 4, 9, 9, 10} Output: 10 occurs 1 times 9 occurs 2 times 4 occurs 1 times 3 occurs 1 times 2 occurs 1 times 1 occurs 3 times " }, { "code": null, "e": 777, "s": 427, "text": "Naive approach: Use some Data-Structure (e.g. multiset) that stores elements in decreasing order and then print the elements one by one with its count and then erase it from the Data-structure. The time complexity will be O(N log N) and the auxiliary space will be O(N) for the Data-structure used.Below is the implementation of the above approach: " }, { "code": null, "e": 781, "s": 777, "text": "CPP" }, { "code": "// C++ program to print the elements in// descending along with their frequencies#include <bits/stdc++.h>using namespace std; // Function to print the elements in descending// along with their frequenciesvoid printElements(int a[], int n){ // A multiset to store elements in decreasing order multiset<int, greater<int> > ms; // Insert elements in the multiset for (int i = 0; i < n; i++) { ms.insert(a[i]); } // Print the elements along with their frequencies while (!ms.empty()) { // Find the maximum element int maxel = *ms.begin(); // Number of times it occurs int times = ms.count(maxel); cout << maxel << \" occurs \" << times << \" times\\n\"; // Erase the maxel ms.erase(maxel); }} // Driver Codeint main(){ int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); printElements(a, n); return 0;}", "e": 1698, "s": 781, "text": null }, { "code": null, "e": 1801, "s": 1698, "text": "10 occurs 1 times\n9 occurs 2 times\n4 occurs 1 times\n3 occurs 1 times\n2 occurs 1 times\n1 occurs 3 times" }, { "code": null, "e": 1961, "s": 1803, "text": "Time Complexity: O(N*logN), as we are using a loop to traverse N times and in each traversal, we are doing a multiset operation which will cost us logN time." }, { "code": null, "e": 2030, "s": 1961, "text": "Auxiliary Space: O(N), as we are using extra space for the multiset." }, { "code": null, "e": 2223, "s": 2030, "text": "Efficient Approach: Sort the array in descending order and then start printing the elements from the beginning along with their frequencies.Below is the implementation of the above approach: " }, { "code": null, "e": 2227, "s": 2223, "text": "C++" }, { "code": null, "e": 2232, "s": 2227, "text": "Java" }, { "code": null, "e": 2240, "s": 2232, "text": "Python3" }, { "code": null, "e": 2243, "s": 2240, "text": "C#" }, { "code": null, "e": 2247, "s": 2243, "text": "PHP" }, { "code": null, "e": 2258, "s": 2247, "text": "Javascript" }, { "code": "// C++ program to print the elements in// descending along with their frequencies#include <bits/stdc++.h>using namespace std; // Function to print the elements in descending// along with their frequenciesvoid printElements(int a[], int n){ // Sorts the element in decreasing order sort(a, a + n, greater<int>()); int cnt = 1; // traverse the array elements for (int i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { cout << a[i] << \" occurs \" << cnt << \" times\\n\"; cnt = 1; } else cnt += 1; } // Prints the last step cout << a[n - 1] << \" occurs \" << cnt << \" times\\n\";} // Driver Codeint main(){ int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = sizeof(a) / sizeof(a[0]); printElements(a, n); return 0;}", "e": 3095, "s": 2258, "text": null }, { "code": "// Java program to print the elements in// descending along with their frequenciesimport java.util.*; class GFG{ // Function to print the elements in descending// along with their frequenciesstatic void printElements(int a[], int n){ // Sorts the element in decreasing order Arrays.sort(a); a = reverse(a); int cnt = 1; // traverse the array elements for (int i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { System.out.print(a[i]+ \" occurs \" + cnt + \" times\\n\"); cnt = 1; } else cnt += 1; } // Prints the last step System.out.print(a[n - 1]+ \" occurs \" + cnt + \" times\\n\");} static int[] reverse(int a[]){ int i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = a.length; printElements(a, n);}} // This code is contributed by PrinciRaj1992", "e": 4225, "s": 3095, "text": null }, { "code": "# Python3 program to print the elements in# descending along with their frequencies # Function to print the elements in# descending along with their frequenciesdef printElements(a, n) : # Sorts the element in decreasing order a.sort(reverse = True) cnt = 1 # traverse the array elements for i in range(n - 1) : # Prints the number and count if (a[i] != a[i + 1]) : print(a[i], \" occurs \", cnt, \"times\") cnt = 1 else : cnt += 1 # Prints the last step print(a[n - 1], \"occurs\", cnt, \"times\") # Driver Codeif __name__ == \"__main__\" : a = [ 1, 1, 1, 2, 3, 4, 9, 9, 10 ] n = len(a) printElements(a, n) # This code is contributed by Ryuga", "e": 4974, "s": 4225, "text": null }, { "code": "// C# program to print the elements in// descending along with their frequenciesusing System; class GFG{ // Function to print the elements in descending// along with their frequenciesstatic void printElements(int []a, int n){ // Sorts the element in decreasing order Array.Sort(a); a = reverse(a); int cnt = 1; // traverse the array elements for (int i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { Console.Write(a[i]+ \" occurs \" + cnt + \" times\\n\"); cnt = 1; } else cnt += 1; } // Prints the last step Console.Write(a[n - 1]+ \" occurs \" + cnt + \" times\\n\");} static int[] reverse(int []a){ int i, n = a.Length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 1, 1, 2, 3, 4, 9, 9, 10 }; int n = a.Length; printElements(a, n);}} // This code is contributed by PrinciRaj1992", "e": 6089, "s": 4974, "text": null }, { "code": "<?php// PHP program to print the elements in// descending along with their frequencies // Function to print the elements in// descending along with their frequenciesfunction printElements(&$a, $n){ // Sorts the element in // decreasing order rsort($a); $cnt = 1; // traverse the array elements for ($i = 0; $i < $n - 1; $i++) { // Prints the number and count if ($a[$i] != $a[$i + 1]) { echo ($a[$i]); echo (\" occurs \" ); echo $cnt ; echo (\" times\\n\"); $cnt = 1; } else $cnt += 1; } // Prints the last step echo ($a[$n - 1]); echo (\" occurs \"); echo $cnt; echo (\" times\\n\");} // Driver Code$a = array(1, 1, 1, 2, 3, 4, 9, 9, 10 );$n = sizeof($a); printElements($a, $n); // This code is contributed// by Shivi_Aggarwal?>", "e": 6963, "s": 6089, "text": null }, { "code": "<script> // javascript program to print the elements in// descending along with their frequencies // Function to print the elements in descending// along with their frequencies function printElements(a, n) { // Sorts the element in decreasing order a=a.sort(compare); a = reverse(a); var cnt = 1; // traverse the array elements for (var i = 0; i < n - 1; i++) { // Prints the number and count if (a[i] != a[i + 1]) { document.write(a[i]+ \" occurs \" + cnt + \" times\" + \"<br>\"); cnt = 1; } else cnt += 1; } // Prints the last step document.write(a[n - 1]+ \" occurs \" + cnt + \" times\" + \"<br>\");} function reverse(a){ var i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} function compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; }} // Driver Code var a = [ 1, 1, 1, 2, 3, 4, 9, 9, 10 ]; var n = a.length; printElements(a, n); // This code is contributed by bunnyram19.</script>", "e": 8155, "s": 6963, "text": null }, { "code": null, "e": 8258, "s": 8155, "text": "10 occurs 1 times\n9 occurs 2 times\n4 occurs 1 times\n3 occurs 1 times\n2 occurs 1 times\n1 occurs 3 times" }, { "code": null, "e": 8357, "s": 8260, "text": "Time Complexity: O(N*logN), as we are using the sort function which will cost us O(N*logN) time." }, { "code": null, "e": 8417, "s": 8357, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 8425, "s": 8417, "text": "ankthon" }, { "code": null, "e": 8440, "s": 8425, "text": "Shivi_Aggarwal" }, { "code": null, "e": 8454, "s": 8440, "text": "princiraj1992" }, { "code": null, "e": 8465, "s": 8454, "text": "bunnyram19" }, { "code": null, "e": 8481, "s": 8465, "text": "rohitsingh07052" }, { "code": null, "e": 8494, "s": 8481, "text": "cpp-multiset" }, { "code": null, "e": 8498, "s": 8494, "text": "STL" }, { "code": null, "e": 8511, "s": 8498, "text": "C++ Programs" }, { "code": null, "e": 8535, "s": 8511, "text": "Competitive Programming" }, { "code": null, "e": 8545, "s": 8535, "text": "Searching" }, { "code": null, "e": 8555, "s": 8545, "text": "Searching" }, { "code": null, "e": 8559, "s": 8555, "text": "STL" }, { "code": null, "e": 8657, "s": 8559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8698, "s": 8657, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 8719, "s": 8698, "text": "Const keyword in C++" }, { "code": null, "e": 8731, "s": 8719, "text": "cout in C++" }, { "code": null, "e": 8790, "s": 8731, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 8833, "s": 8790, "text": "Different ways to print elements of vector" }, { "code": null, "e": 8876, "s": 8833, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 8919, "s": 8876, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 8960, "s": 8919, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 8987, "s": 8960, "text": "Modulo 10^9+7 (1000000007)" } ]