title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Count of integers in an Array whose length is a multiple of K - GeeksforGeeks
27 May, 2021 Given an array arr of N elements and an integer K, the task is to count all the elements whose length is a multiple of K.Examples: Input: arr[]={1, 12, 3444, 544, 9}, K = 2 Output: 2 Explanation: There are 2 numbers whose digit count is multiple of 2 {12, 3444}. Input: arr[]={12, 345, 2, 68, 7896}, K = 3 Output: 1 Explanation: There is 1 number whose digit count is multiple of 3 {345}. Approach: Traverse the numbers in the array one by oneCount the digits of every number in the arrayCheck if its digit count is a multiple of K or not. Traverse the numbers in the array one by one Count the digits of every number in the array Check if its digit count is a multiple of K or not. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function to find// digit count of numbersint digit_count(int x){ int sum = 0; while (x) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersint find_count(vector<int> arr, int k){ int ans = 0; for (int i : arr) { // Get the digit count of each element int x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver codeint main(){ vector<int> arr = { 12, 345, 2, 68, 7896 }; int K = 2; cout << find_count(arr, K); return 0;} // Java implementation of above approach class GFG{ // Function to find// digit count of numbersstatic int digit_count(int x){ int sum = 0; while (x > 0) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersstatic int find_count(int []arr, int k){ int ans = 0; for (int i : arr) { // Get the digit count of each element int x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver codepublic static void main(String[] args){ int []arr = { 12, 345, 2, 68, 7896 }; int K = 2; System.out.print(find_count(arr, K)); }} // This code is contributed by 29AjayKumar # Python3 implementation of above approach # Function to find# digit count of numbersdef digit_count(x): sum = 0 while (x): sum += 1 x = x // 10 return sum # Function to find the count of numbersdef find_count(arr,k): ans = 0 for i in arr: # Get the digit count of each element x = digit_count(i) # Check if the digit count # is divisible by K if (x % k == 0): # Increment the count # of required numbers by 1 ans += 1 return ans # Driver codeif __name__ == '__main__': arr = [12, 345, 2, 68, 7896] K = 2 print(find_count(arr, K)) # This code is contributed by Surendra_Gangwar // C# implementation of above approach using System; public class GFG{ // Function to find// digit count of numbersstatic int digit_count(int x){ int sum = 0; while (x > 0) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersstatic int find_count(int []arr, int k){ int ans = 0; foreach (int i in arr) { // Get the digit count of each element int x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 345, 2, 68, 7896 }; int K = 2; Console.Write(find_count(arr, K)); }} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of above approach // Function to find// digit count of numbersfunction digit_count(x){ let sum = 0; while (x) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersfunction find_count(arr, k){ let ans = 0; for (let i of arr) { // Get the digit count of each element let x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver code let arr = [ 12, 345, 2, 68, 7896 ];let K = 2; document.write(find_count(arr, K)); // This code is contributed by _saurabh_jaiswal </script> 3 Time complexity:- O(N*M), where N is the size of array, and M is the digit count of the largest number in the array. Space complexity:- O(1) SURENDRA_GANGWAR 29AjayKumar Rajput-Ji _saurabh_jaiswal divisibility number-digits Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Find subarray with given sum | Set 1 (Nonnegative Numbers) Remove duplicates from sorted array Move all negative numbers to beginning and positive to end with constant extra space Building Heap from Array
[ { "code": null, "e": 26041, "s": 26013, "text": "\n27 May, 2021" }, { "code": null, "e": 26174, "s": 26041, "text": "Given an array arr of N elements and an integer K, the task is to count all the elements whose length is a multiple of K.Examples: " }, { "code": null, "e": 26433, "s": 26174, "text": "Input: arr[]={1, 12, 3444, 544, 9}, K = 2\nOutput: 2\nExplanation:\nThere are 2 numbers whose digit count is multiple of 2 {12, 3444}.\n\nInput: arr[]={12, 345, 2, 68, 7896}, K = 3\nOutput: 1\nExplanation:\nThere is 1 number whose digit count is multiple of 3 {345}." }, { "code": null, "e": 26447, "s": 26435, "text": "Approach: " }, { "code": null, "e": 26588, "s": 26447, "text": "Traverse the numbers in the array one by oneCount the digits of every number in the arrayCheck if its digit count is a multiple of K or not." }, { "code": null, "e": 26633, "s": 26588, "text": "Traverse the numbers in the array one by one" }, { "code": null, "e": 26679, "s": 26633, "text": "Count the digits of every number in the array" }, { "code": null, "e": 26731, "s": 26679, "text": "Check if its digit count is a multiple of K or not." }, { "code": null, "e": 26780, "s": 26731, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 26784, "s": 26780, "text": "C++" }, { "code": null, "e": 26789, "s": 26784, "text": "Java" }, { "code": null, "e": 26797, "s": 26789, "text": "Python3" }, { "code": null, "e": 26800, "s": 26797, "text": "C#" }, { "code": null, "e": 26811, "s": 26800, "text": "Javascript" }, { "code": "// C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function to find// digit count of numbersint digit_count(int x){ int sum = 0; while (x) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersint find_count(vector<int> arr, int k){ int ans = 0; for (int i : arr) { // Get the digit count of each element int x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver codeint main(){ vector<int> arr = { 12, 345, 2, 68, 7896 }; int K = 2; cout << find_count(arr, K); return 0;}", "e": 27592, "s": 26811, "text": null }, { "code": "// Java implementation of above approach class GFG{ // Function to find// digit count of numbersstatic int digit_count(int x){ int sum = 0; while (x > 0) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersstatic int find_count(int []arr, int k){ int ans = 0; for (int i : arr) { // Get the digit count of each element int x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver codepublic static void main(String[] args){ int []arr = { 12, 345, 2, 68, 7896 }; int K = 2; System.out.print(find_count(arr, K)); }} // This code is contributed by 29AjayKumar", "e": 28418, "s": 27592, "text": null }, { "code": "# Python3 implementation of above approach # Function to find# digit count of numbersdef digit_count(x): sum = 0 while (x): sum += 1 x = x // 10 return sum # Function to find the count of numbersdef find_count(arr,k): ans = 0 for i in arr: # Get the digit count of each element x = digit_count(i) # Check if the digit count # is divisible by K if (x % k == 0): # Increment the count # of required numbers by 1 ans += 1 return ans # Driver codeif __name__ == '__main__': arr = [12, 345, 2, 68, 7896] K = 2 print(find_count(arr, K)) # This code is contributed by Surendra_Gangwar", "e": 29110, "s": 28418, "text": null }, { "code": "// C# implementation of above approach using System; public class GFG{ // Function to find// digit count of numbersstatic int digit_count(int x){ int sum = 0; while (x > 0) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersstatic int find_count(int []arr, int k){ int ans = 0; foreach (int i in arr) { // Get the digit count of each element int x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 345, 2, 68, 7896 }; int K = 2; Console.Write(find_count(arr, K)); }} // This code is contributed by Rajput-Ji", "e": 29945, "s": 29110, "text": null }, { "code": "<script> // JavaScript implementation of above approach // Function to find// digit count of numbersfunction digit_count(x){ let sum = 0; while (x) { sum++; x = x / 10; } return sum;} // Function to find the count of numbersfunction find_count(arr, k){ let ans = 0; for (let i of arr) { // Get the digit count of each element let x = digit_count(i); // Check if the digit count // is divisible by K if (x % k == 0) // Increment the count // of required numbers by 1 ans += 1; } return ans;} // Driver code let arr = [ 12, 345, 2, 68, 7896 ];let K = 2; document.write(find_count(arr, K)); // This code is contributed by _saurabh_jaiswal </script>", "e": 30702, "s": 29945, "text": null }, { "code": null, "e": 30704, "s": 30702, "text": "3" }, { "code": null, "e": 30848, "s": 30706, "text": "Time complexity:- O(N*M), where N is the size of array, and M is the digit count of the largest number in the array. Space complexity:- O(1) " }, { "code": null, "e": 30865, "s": 30848, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 30877, "s": 30865, "text": "29AjayKumar" }, { "code": null, "e": 30887, "s": 30877, "text": "Rajput-Ji" }, { "code": null, "e": 30904, "s": 30887, "text": "_saurabh_jaiswal" }, { "code": null, "e": 30917, "s": 30904, "text": "divisibility" }, { "code": null, "e": 30931, "s": 30917, "text": "number-digits" }, { "code": null, "e": 30938, "s": 30931, "text": "Arrays" }, { "code": null, "e": 30945, "s": 30938, "text": "Arrays" }, { "code": null, "e": 31043, "s": 30945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31070, "s": 31043, "text": "Count pairs with given sum" }, { "code": null, "e": 31101, "s": 31070, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31126, "s": 31101, "text": "Window Sliding Technique" }, { "code": null, "e": 31164, "s": 31126, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31185, "s": 31164, "text": "Next Greater Element" }, { "code": null, "e": 31243, "s": 31185, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 31302, "s": 31243, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 31338, "s": 31302, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 31423, "s": 31338, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
Class getMethods() method in Java with Examples - GeeksforGeeks
25 Jan, 2022 The getMethods() method of java.lang.Class class is used to get the methods of this class, which are the methods that are public and its members or the members of its member classes and interfaces. The method returns the methods of this class in the form of an array of Method objects. Syntax: public Method[] getMethods() Parameter: This method does not accept any parameter.Return Value: This method returns the methods of this class in the form of an array of Method objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getMethods() method.Example 1: Java // Java program to demonstrate getMethods() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the methods of myClass // using getMethods() method System.out.println("Methods of myClass: " + Arrays.toString( myClass.getMethods())); }} Class represented by myClass: class Test Methods of myClass: [ public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException, public final void java.lang.Object.wait(long, int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final void java.lang.Object.wait() throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll() ] Example 2: Java // Java program to demonstrate getMethods() method import java.util.*; class Main { public Object obj; private void function() {} Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the methods of myClass // using getMethods() method System.out.println("Methods of myClass: " + Arrays.toString( myClass.getMethods())); }} Methods of myClass: [ public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException, public final void java.lang.Object.wait(long, int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final void java.lang.Object.wait() throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll() ] Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getMethods– adnanirshad158 Java-Functions Java-lang package Java.lang.Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n25 Jan, 2022" }, { "code": null, "e": 25521, "s": 25225, "text": "The getMethods() method of java.lang.Class class is used to get the methods of this class, which are the methods that are public and its members or the members of its member classes and interfaces. The method returns the methods of this class in the form of an array of Method objects. Syntax: " }, { "code": null, "e": 25550, "s": 25521, "text": "public Method[] getMethods()" }, { "code": null, "e": 25889, "s": 25550, "text": "Parameter: This method does not accept any parameter.Return Value: This method returns the methods of this class in the form of an array of Method objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getMethods() method.Example 1: " }, { "code": null, "e": 25894, "s": 25889, "text": "Java" }, { "code": "// Java program to demonstrate getMethods() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the methods of myClass // using getMethods() method System.out.println(\"Methods of myClass: \" + Arrays.toString( myClass.getMethods())); }}", "e": 26505, "s": 25894, "text": null }, { "code": null, "e": 27253, "s": 26505, "text": "Class represented by myClass: class Test Methods of myClass: [ public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException, public final void java.lang.Object.wait(long, int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final void java.lang.Object.wait() throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll() ] " }, { "code": null, "e": 27267, "s": 27255, "text": "Example 2: " }, { "code": null, "e": 27272, "s": 27267, "text": "Java" }, { "code": "// Java program to demonstrate getMethods() method import java.util.*; class Main { public Object obj; private void function() {} Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the methods of myClass // using getMethods() method System.out.println(\"Methods of myClass: \" + Arrays.toString( myClass.getMethods())); }}", "e": 27905, "s": 27272, "text": null }, { "code": null, "e": 28612, "s": 27905, "text": "Methods of myClass: [ public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException, public final void java.lang.Object.wait(long, int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final void java.lang.Object.wait() throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll() ] " }, { "code": null, "e": 28701, "s": 28614, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getMethods– " }, { "code": null, "e": 28716, "s": 28701, "text": "adnanirshad158" }, { "code": null, "e": 28731, "s": 28716, "text": "Java-Functions" }, { "code": null, "e": 28749, "s": 28731, "text": "Java-lang package" }, { "code": null, "e": 28765, "s": 28749, "text": "Java.lang.Class" }, { "code": null, "e": 28770, "s": 28765, "text": "Java" }, { "code": null, "e": 28775, "s": 28770, "text": "Java" }, { "code": null, "e": 28873, "s": 28775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28888, "s": 28873, "text": "Stream In Java" }, { "code": null, "e": 28909, "s": 28888, "text": "Constructors in Java" }, { "code": null, "e": 28928, "s": 28909, "text": "Exceptions in Java" }, { "code": null, "e": 28958, "s": 28928, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29004, "s": 28958, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29021, "s": 29004, "text": "Generics in Java" }, { "code": null, "e": 29042, "s": 29021, "text": "Introduction to Java" }, { "code": null, "e": 29085, "s": 29042, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29121, "s": 29085, "text": "Internal Working of HashMap in Java" } ]
numpy.defchararray.encode() in Python - GeeksforGeeks
28 Nov, 2018 numpy.core.defchararray.encode(arr, encoding): This nuympy function encodes the string(object) based on the specified codec. Parameters:arr : array-like or string.encoding : [str] Name of encoding being followed.error : Specifying how to handle error. Returns : Encoded string Code: # Python Program illustrating # numpy.char.encode() method import numpy as np arr1 = ['eAAAa', 'ttttds', 'AAtAAt']arr2 = ['11sf', 'sdsf2', '1111f2'] # Printing the arrayprint ("\narr1 : ", arr1)print ("\narr2 : ", arr2) print ("\nEncoded arr1 : \n", np.char.encode(arr1, encoding ='cp037'))print ("\nEncoded arr2 : \n", np.char.encode(arr2, encoding ='utf8'))print ("\nEncoded arr2 : \n", np.char.encode(arr2, encoding ='utf8', errors = 'strict')) Output: arr1 : ['eAAAa', 'ttttds', 'AAtAAt'] arr2 : ['11sf', 'sdsf2', '1111f2'] Encoded arr1 : [b'\x85\xc1\xc1\xc1\x81' b'\xa3\xa3\xa3\xa3\x84\xa2' b'\xc1\xc1\xa3\xc1\xc1\xa3'] Encoded arr2 : [b'11sf' b'sdsf2' b'1111f2'] Encoded arr2 : [b'11sf' b'sdsf2' b'1111f2'] Python numpy-String Operation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n28 Nov, 2018" }, { "code": null, "e": 25680, "s": 25555, "text": "numpy.core.defchararray.encode(arr, encoding): This nuympy function encodes the string(object) based on the specified codec." }, { "code": null, "e": 25807, "s": 25680, "text": "Parameters:arr : array-like or string.encoding : [str] Name of encoding being followed.error : Specifying how to handle error." }, { "code": null, "e": 25832, "s": 25807, "text": "Returns : Encoded string" }, { "code": null, "e": 25838, "s": 25832, "text": "Code:" }, { "code": "# Python Program illustrating # numpy.char.encode() method import numpy as np arr1 = ['eAAAa', 'ttttds', 'AAtAAt']arr2 = ['11sf', 'sdsf2', '1111f2'] # Printing the arrayprint (\"\\narr1 : \", arr1)print (\"\\narr2 : \", arr2) print (\"\\nEncoded arr1 : \\n\", np.char.encode(arr1, encoding ='cp037'))print (\"\\nEncoded arr2 : \\n\", np.char.encode(arr2, encoding ='utf8'))print (\"\\nEncoded arr2 : \\n\", np.char.encode(arr2, encoding ='utf8', errors = 'strict'))", "e": 26339, "s": 25838, "text": null }, { "code": null, "e": 26347, "s": 26339, "text": "Output:" }, { "code": null, "e": 26617, "s": 26347, "text": "arr1 : ['eAAAa', 'ttttds', 'AAtAAt']\narr2 : ['11sf', 'sdsf2', '1111f2']\n\nEncoded arr1 : \n [b'\\x85\\xc1\\xc1\\xc1\\x81' b'\\xa3\\xa3\\xa3\\xa3\\x84\\xa2'\n b'\\xc1\\xc1\\xa3\\xc1\\xc1\\xa3']\n\nEncoded arr2 : \n [b'11sf' b'sdsf2' b'1111f2']\n\nEncoded arr2 : \n [b'11sf' b'sdsf2' b'1111f2']\n" }, { "code": null, "e": 26647, "s": 26617, "text": "Python numpy-String Operation" }, { "code": null, "e": 26660, "s": 26647, "text": "Python-numpy" }, { "code": null, "e": 26667, "s": 26660, "text": "Python" }, { "code": null, "e": 26765, "s": 26667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26797, "s": 26765, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26839, "s": 26797, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26881, "s": 26839, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26937, "s": 26881, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26964, "s": 26937, "text": "Python Classes and Objects" }, { "code": null, "e": 26995, "s": 26964, "text": "Python | os.path.join() method" }, { "code": null, "e": 27034, "s": 26995, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27063, "s": 27034, "text": "Create a directory in Python" }, { "code": null, "e": 27085, "s": 27063, "text": "Defaultdict in Python" } ]
Change plot size in Matplotlib - Python - GeeksforGeeks
26 Nov, 2020 Prerequisite: Matplotlib Plots are an effective way of visually representing data and summarizing it in a beautiful manner. However, if not plotted efficiently it seems appears complicated. In python’s matplotlib provides several libraries for the purpose of data representation. While making a plot it is important for us to optimize its size. Here are various ways to change the default plot size as per our required dimensions or resize a given plot. Method 1: Using set_figheight() and set_figwidth() For changing height and width of a plot set_figheight and set_figwidth are used Python3 # importing the matplotlib libraryimport matplotlib.pyplot as plt # values on x-axisx = [1, 2, 3, 4, 5]# values on y-axisy = [1, 2, 3, 4, 5] # naming the x and y axisplt.xlabel('x - axis')plt.ylabel('y - axis') # plotting a line plot with it's default sizeprint("Plot in it's default size: ")plt.plot(x, y)plt.show() # plotting a line plot after changing it's width and heightf = plt.figure()f.set_figwidth(4)f.set_figheight(1) print("Plot after re-sizing: ")plt.plot(x, y)plt.show() Output: Method 2: Using figsize figsize() takes two parameters- width and height (in inches). By default the values for width and height are 6.4 and 4.8 respectively. Syntax: plt.figure(figsize=(x,y)) Where, x and y are width and height respectively in inches. Python3 import matplotlib.pyplot as plt # values on x and y axisx = [1, 2, 3, 4, 5]y = [6, 7, 8, 9, 10] # plot in it's default sizedisplay(plt.plot(x, y)) # changing the size of figure to 2X2plt.figure(figsize=(2, 2))display(plt.plot(x, y)) Output: output screenshot Method 3: Changing the default rcParams We can permanently change the default size of a figure as per our needs by setting the figure.figsize. Python3 # importing the matplotlib libraryimport matplotlib.pyplot as plt # values on x-axisx = [1, 2, 3, 4, 5]# values on y-axisy = [1, 2, 3, 4, 5] # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis') # plotting a line plot with it's default sizeplt.plot(x, y)plt.show() # changing the rc parameters and plotting a line plotplt.rcParams['figure.figsize'] = [2, 2] plt.plot(x, y)plt.show() plt.scatter(x, y)plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 31572, "s": 31544, "text": "\n26 Nov, 2020" }, { "code": null, "e": 31597, "s": 31572, "text": "Prerequisite: Matplotlib" }, { "code": null, "e": 31854, "s": 31597, "text": "Plots are an effective way of visually representing data and summarizing it in a beautiful manner. However, if not plotted efficiently it seems appears complicated. In python’s matplotlib provides several libraries for the purpose of data representation. " }, { "code": null, "e": 32029, "s": 31854, "text": "While making a plot it is important for us to optimize its size. Here are various ways to change the default plot size as per our required dimensions or resize a given plot. " }, { "code": null, "e": 32081, "s": 32029, "text": "Method 1: Using set_figheight() and set_figwidth() " }, { "code": null, "e": 32161, "s": 32081, "text": "For changing height and width of a plot set_figheight and set_figwidth are used" }, { "code": null, "e": 32169, "s": 32161, "text": "Python3" }, { "code": "# importing the matplotlib libraryimport matplotlib.pyplot as plt # values on x-axisx = [1, 2, 3, 4, 5]# values on y-axisy = [1, 2, 3, 4, 5] # naming the x and y axisplt.xlabel('x - axis')plt.ylabel('y - axis') # plotting a line plot with it's default sizeprint(\"Plot in it's default size: \")plt.plot(x, y)plt.show() # plotting a line plot after changing it's width and heightf = plt.figure()f.set_figwidth(4)f.set_figheight(1) print(\"Plot after re-sizing: \")plt.plot(x, y)plt.show()", "e": 32658, "s": 32169, "text": null }, { "code": null, "e": 32666, "s": 32658, "text": "Output:" }, { "code": null, "e": 32690, "s": 32666, "text": "Method 2: Using figsize" }, { "code": null, "e": 32826, "s": 32690, "text": "figsize() takes two parameters- width and height (in inches). By default the values for width and height are 6.4 and 4.8 respectively. " }, { "code": null, "e": 32834, "s": 32826, "text": "Syntax:" }, { "code": null, "e": 32861, "s": 32834, "text": "plt.figure(figsize=(x,y)) " }, { "code": null, "e": 32921, "s": 32861, "text": "Where, x and y are width and height respectively in inches." }, { "code": null, "e": 32929, "s": 32921, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # values on x and y axisx = [1, 2, 3, 4, 5]y = [6, 7, 8, 9, 10] # plot in it's default sizedisplay(plt.plot(x, y)) # changing the size of figure to 2X2plt.figure(figsize=(2, 2))display(plt.plot(x, y))", "e": 33165, "s": 32929, "text": null }, { "code": null, "e": 33173, "s": 33165, "text": "Output:" }, { "code": null, "e": 33191, "s": 33173, "text": "output screenshot" }, { "code": null, "e": 33231, "s": 33191, "text": "Method 3: Changing the default rcParams" }, { "code": null, "e": 33335, "s": 33231, "text": "We can permanently change the default size of a figure as per our needs by setting the figure.figsize. " }, { "code": null, "e": 33343, "s": 33335, "text": "Python3" }, { "code": "# importing the matplotlib libraryimport matplotlib.pyplot as plt # values on x-axisx = [1, 2, 3, 4, 5]# values on y-axisy = [1, 2, 3, 4, 5] # naming the x axisplt.xlabel('x - axis')# naming the y axisplt.ylabel('y - axis') # plotting a line plot with it's default sizeplt.plot(x, y)plt.show() # changing the rc parameters and plotting a line plotplt.rcParams['figure.figsize'] = [2, 2] plt.plot(x, y)plt.show() plt.scatter(x, y)plt.show()", "e": 33789, "s": 33343, "text": null }, { "code": null, "e": 33797, "s": 33789, "text": "Output:" }, { "code": null, "e": 33815, "s": 33797, "text": "Python-matplotlib" }, { "code": null, "e": 33822, "s": 33815, "text": "Python" }, { "code": null, "e": 33920, "s": 33822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33948, "s": 33920, "text": "Read JSON file using Python" }, { "code": null, "e": 33998, "s": 33948, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34020, "s": 33998, "text": "Python map() function" }, { "code": null, "e": 34064, "s": 34020, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 34082, "s": 34064, "text": "Python Dictionary" }, { "code": null, "e": 34105, "s": 34082, "text": "Taking input in Python" }, { "code": null, "e": 34140, "s": 34105, "text": "Read a file line by line in Python" }, { "code": null, "e": 34172, "s": 34140, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34194, "s": 34172, "text": "Enumerate() in Python" } ]
How to detect the change in DIV's dimension ? - GeeksforGeeks
31 Oct, 2019 The change in a div’s dimension can be detected using 2 approaches: Method 1: Checking for changes using the ResizeObserver InterfaceThe ResizeObserver Interface is used to report changes in dimensions of an element.The element to be tracked is first selected using jQuery. A ResizeObserver object is created with a callback function that defines what action should be performed when a change in dimension is detected.The observe() method of this object is used on the element that is to be tracked. This will check for any changes and execute the callback function when any dimension change is detected. Syntax: let resizeObserver = new ResizeObserver(() => { console.log("The element was resized");}); resizeObserver.observe(elem); Example: <!DOCTYPE html><html> <head> <title> How to detect DIV’s dimension changed? </title> <style> #box { resize: both; border: solid; background-color: green; height: 100px; width: 100px; overflow: auto; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to detect DIV’s dimension changed? </b> <p>Check the console to know if the div's dimensions have changed. </p> <div id="box"></div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script> elem = $("#box")[0]; let resizeObserver = new ResizeObserver(() => { console.log("The element was resized"); }); resizeObserver.observe(elem); </script></body> </html> Output: Before resizing the element: After resizing the element: Method 2: Checking for changes in dimensions every 500 millisecondsThis method involves checking the dimensions of the element to be tracked every 500 milliseconds. The values of the dimensions are compared with the values of the older iteration to check if there is any difference. The height and width of the element to be tracked is found out using the height() and width() method in jQuery. These dimensions will be used as the last tracked baseline dimensions of the element and stored in a variable. A new function is created in which the element’s height and width are found out. This will be the new dimensions which will be compared with the previous ones. An if-statement is used where this new height and width are compared with the previously found baseline. If the dimensions do not match, it means that the dimensions have changed. The required action to be taken when dimensions change would be executed here.The new dimensions found would be assigned to the older ones as a baseline so that the next iteration can be checked with them.The function created is continuously in a loop every 500 milliseconds using the setInterval() function. This will continuously check for the changes in height and width and execute the given function whenever there is a difference.This method is considerably slower than the previous one and decreasing the time between each check would further reduce the performance. Syntax: let lastHeight = $("#box").height();let lastWidth = $("#box").width(); function checkHeightChange() { newHeight = $("#box").height(); newWidth = $("#box").width(); if (lastHeight != newHeight || lastWidth != newWidth) { console.log("The element was resized"); // assign the new dimensions lastHeight = newHeight; lastWidth = newWidth; } } setInterval(checkHeightChange, 500); Example: <!DOCTYPE html><html> <head> <title> How to detect DIV’s dimension changed? </title> <style> #box { resize: both; border: solid; background-color: green; height: 100px; width: 100px; overflow: auto; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to detect DIV’s dimension changed? </b> <p>Check the console to know if the div's dimensions have changed. </p> <div id="box"></div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> let lastHeight = $("#box").height(); let lastWidth = $("#box").width(); function checkHeightChange() { newHeight = $("#box").height(); newWidth = $("#box").width(); if (lastHeight != newHeight || lastWidth != newWidth) { console.log("The element was resized"); // assign the new dimensions lastHeight = newHeight; lastWidth = newWidth; } } setInterval(checkHeightChange, 500); </script></body> </html> Output: Before resizing the element: After resizing the element: jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? Scroll to the top of the page using JavaScript/jQuery How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26236, "s": 26208, "text": "\n31 Oct, 2019" }, { "code": null, "e": 26304, "s": 26236, "text": "The change in a div’s dimension can be detected using 2 approaches:" }, { "code": null, "e": 26841, "s": 26304, "text": "Method 1: Checking for changes using the ResizeObserver InterfaceThe ResizeObserver Interface is used to report changes in dimensions of an element.The element to be tracked is first selected using jQuery. A ResizeObserver object is created with a callback function that defines what action should be performed when a change in dimension is detected.The observe() method of this object is used on the element that is to be tracked. This will check for any changes and execute the callback function when any dimension change is detected." }, { "code": null, "e": 26849, "s": 26841, "text": "Syntax:" }, { "code": "let resizeObserver = new ResizeObserver(() => { console.log(\"The element was resized\");}); resizeObserver.observe(elem);", "e": 26974, "s": 26849, "text": null }, { "code": null, "e": 26983, "s": 26974, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to detect DIV’s dimension changed? </title> <style> #box { resize: both; border: solid; background-color: green; height: 100px; width: 100px; overflow: auto; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to detect DIV’s dimension changed? </b> <p>Check the console to know if the div's dimensions have changed. </p> <div id=\"box\"></div> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script> elem = $(\"#box\")[0]; let resizeObserver = new ResizeObserver(() => { console.log(\"The element was resized\"); }); resizeObserver.observe(elem); </script></body> </html>", "e": 27830, "s": 26983, "text": null }, { "code": null, "e": 27838, "s": 27830, "text": "Output:" }, { "code": null, "e": 27867, "s": 27838, "text": "Before resizing the element:" }, { "code": null, "e": 27895, "s": 27867, "text": "After resizing the element:" }, { "code": null, "e": 28178, "s": 27895, "text": "Method 2: Checking for changes in dimensions every 500 millisecondsThis method involves checking the dimensions of the element to be tracked every 500 milliseconds. The values of the dimensions are compared with the values of the older iteration to check if there is any difference." }, { "code": null, "e": 28401, "s": 28178, "text": "The height and width of the element to be tracked is found out using the height() and width() method in jQuery. These dimensions will be used as the last tracked baseline dimensions of the element and stored in a variable." }, { "code": null, "e": 29315, "s": 28401, "text": "A new function is created in which the element’s height and width are found out. This will be the new dimensions which will be compared with the previous ones. An if-statement is used where this new height and width are compared with the previously found baseline. If the dimensions do not match, it means that the dimensions have changed. The required action to be taken when dimensions change would be executed here.The new dimensions found would be assigned to the older ones as a baseline so that the next iteration can be checked with them.The function created is continuously in a loop every 500 milliseconds using the setInterval() function. This will continuously check for the changes in height and width and execute the given function whenever there is a difference.This method is considerably slower than the previous one and decreasing the time between each check would further reduce the performance." }, { "code": null, "e": 29323, "s": 29315, "text": "Syntax:" }, { "code": "let lastHeight = $(\"#box\").height();let lastWidth = $(\"#box\").width(); function checkHeightChange() { newHeight = $(\"#box\").height(); newWidth = $(\"#box\").width(); if (lastHeight != newHeight || lastWidth != newWidth) { console.log(\"The element was resized\"); // assign the new dimensions lastHeight = newHeight; lastWidth = newWidth; } } setInterval(checkHeightChange, 500);", "e": 29746, "s": 29323, "text": null }, { "code": null, "e": 29755, "s": 29746, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to detect DIV’s dimension changed? </title> <style> #box { resize: both; border: solid; background-color: green; height: 100px; width: 100px; overflow: auto; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to detect DIV’s dimension changed? </b> <p>Check the console to know if the div's dimensions have changed. </p> <div id=\"box\"></div> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> let lastHeight = $(\"#box\").height(); let lastWidth = $(\"#box\").width(); function checkHeightChange() { newHeight = $(\"#box\").height(); newWidth = $(\"#box\").width(); if (lastHeight != newHeight || lastWidth != newWidth) { console.log(\"The element was resized\"); // assign the new dimensions lastHeight = newHeight; lastWidth = newWidth; } } setInterval(checkHeightChange, 500); </script></body> </html>", "e": 30978, "s": 29755, "text": null }, { "code": null, "e": 30986, "s": 30978, "text": "Output:" }, { "code": null, "e": 31015, "s": 30986, "text": "Before resizing the element:" }, { "code": null, "e": 31043, "s": 31015, "text": "After resizing the element:" }, { "code": null, "e": 31055, "s": 31043, "text": "jQuery-Misc" }, { "code": null, "e": 31062, "s": 31055, "text": "Picked" }, { "code": null, "e": 31069, "s": 31062, "text": "JQuery" }, { "code": null, "e": 31086, "s": 31069, "text": "Web Technologies" }, { "code": null, "e": 31113, "s": 31086, "text": "Web technologies Questions" }, { "code": null, "e": 31211, "s": 31113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31240, "s": 31211, "text": "Form validation using jQuery" }, { "code": null, "e": 31296, "s": 31240, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 31350, "s": 31296, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 31405, "s": 31350, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 31478, "s": 31405, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 31518, "s": 31478, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31551, "s": 31518, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31596, "s": 31551, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31639, "s": 31596, "text": "How to fetch data from an API in ReactJS ?" } ]
How to trigger events in JavaScript ? - GeeksforGeeks
03 Dec, 2020 Javascript is a high level, interpreted, dynamically typed client side scripting language. HTML is static and Javascript is used to add functionality to static HTML code. HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document. In order to work on JavaScript trigger events, it is important to know what is an event. An event is an interaction between JavaScript and HTML. Some common HTML events are as follows: onload: It is triggered when the browser completes loading a page onchange: It is triggered when an HTML element changes. onclick: It is triggered when an HTML element is clicked. onmouseover: It is triggered when the mouse is moved over a HTML element. onmouseout: It is triggered when the mouse is moved out of a HTML element. Events can be handled either through addEventListener() method or we can trigger events on individual components by defining specific JavaScript functions. Let us consider the following examples: Using document.addEventListener() method Syntax : document.addEventListener(event, function, phase) Parameters: event: Mandatory parameter. Specifies the name of the event. function: Mandatory parameter. Specifies the function that is supposed to handle the event. phase: This is an optional parameter and accepts a boolean value. If true value is passed then the event handler is executed in the capturing phase and if false value is passed then the event handler is executed in the bubbling phase. If an element is a child element and it triggers an event then the event is registered for both the parent and child element. If the phase value is passed as true then the event handler is first executed by the parent element (capturing phase) and if false is passed then the child element executes the event handler first. By default, false is passed as the phase value. Example 1: HTML <!DOCTYPE html><html> <body> <h3>Click on the page to trigger click event</h3> <h3>Click on the page to trigger mouseover event</h3> <h3>Click on the page to trigger mouseoutevent</h3> <script type="text/javascript"> document.addEventListener("click", function() { alert("You clicked inside the document"); }); document.addEventListener("mouseover", function() { document.body.style.backgroundColor = "lavender"; }); document.addEventListener("mouseout", function() { document.body.style.backgroundColor = "white"; }); </script></body></html> Output Trigger mouseover Event: Trigger mouseout Event: Trigger click Event: Explanation: In this example, when the mouse is moved over the document the background color of the document changes to lavender. When the mouse is moved out the background color of the document changes back to white. And when the user clicks anywhere inside the document an alert pops up. These actions are handled by event handlers that is triggered when an event occurs. Example 2: Triggering events on individual elements HTML <!DOCTYPE html><html> <body> <button onclick="clickFunction()"> Click Me </button> <br><br> <div class="container" id="myDiv" onmouseenter="enterFunction()" onmouseleave="leaveFunction()"> Hello World...How are you </div> <script type="text/javascript"> function clickFunction(){ document.body.style .backgroundColor = "pink"; } function enterFunction(){ document.getElementById("myDiv") .style.border = "1px solid black"; } function leaveFunction(){ document.getElementById("myDiv") .style.border = "2px solid blue"; } </script></body> </html> Output: Click on Button:Mouse move over the page Explanation Here individual elements in the HTML document trigger different events and those events invoke different JavaScript functions. The logic to handle the events are specified in the functions. When the button is clicked, it changes the background color of the webpage. The other events that are handled are mouseenter and mouseleave. When the mouse enters the container with id named myDiv the border of the division turns black. When the mouse leaves the container the border of the division turns blue. HTML-Misc JavaScript-Misc Picked Technical Scripter 2020 HTML JavaScript Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n03 Dec, 2020" }, { "code": null, "e": 26809, "s": 26139, "text": "Javascript is a high level, interpreted, dynamically typed client side scripting language. HTML is static and Javascript is used to add functionality to static HTML code. HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document. In order to work on JavaScript trigger events, it is important to know what is an event. An event is an interaction between JavaScript and HTML. Some common HTML events are as follows:" }, { "code": null, "e": 26875, "s": 26809, "text": "onload: It is triggered when the browser completes loading a page" }, { "code": null, "e": 26931, "s": 26875, "text": "onchange: It is triggered when an HTML element changes." }, { "code": null, "e": 26989, "s": 26931, "text": "onclick: It is triggered when an HTML element is clicked." }, { "code": null, "e": 27063, "s": 26989, "text": "onmouseover: It is triggered when the mouse is moved over a HTML element." }, { "code": null, "e": 27138, "s": 27063, "text": "onmouseout: It is triggered when the mouse is moved out of a HTML element." }, { "code": null, "e": 27334, "s": 27138, "text": "Events can be handled either through addEventListener() method or we can trigger events on individual components by defining specific JavaScript functions. Let us consider the following examples:" }, { "code": null, "e": 27375, "s": 27334, "text": "Using document.addEventListener() method" }, { "code": null, "e": 27385, "s": 27375, "text": "Syntax : " }, { "code": null, "e": 27435, "s": 27385, "text": "document.addEventListener(event, function, phase)" }, { "code": null, "e": 27447, "s": 27435, "text": "Parameters:" }, { "code": null, "e": 27509, "s": 27447, "text": "event: Mandatory parameter. Specifies the name of the event. " }, { "code": null, "e": 27601, "s": 27509, "text": "function: Mandatory parameter. Specifies the function that is supposed to handle the event." }, { "code": null, "e": 28208, "s": 27601, "text": "phase: This is an optional parameter and accepts a boolean value. If true value is passed then the event handler is executed in the capturing phase and if false value is passed then the event handler is executed in the bubbling phase. If an element is a child element and it triggers an event then the event is registered for both the parent and child element. If the phase value is passed as true then the event handler is first executed by the parent element (capturing phase) and if false is passed then the child element executes the event handler first. By default, false is passed as the phase value." }, { "code": null, "e": 28219, "s": 28208, "text": "Example 1:" }, { "code": null, "e": 28224, "s": 28219, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h3>Click on the page to trigger click event</h3> <h3>Click on the page to trigger mouseover event</h3> <h3>Click on the page to trigger mouseoutevent</h3> <script type=\"text/javascript\"> document.addEventListener(\"click\", function() { alert(\"You clicked inside the document\"); }); document.addEventListener(\"mouseover\", function() { document.body.style.backgroundColor = \"lavender\"; }); document.addEventListener(\"mouseout\", function() { document.body.style.backgroundColor = \"white\"; }); </script></body></html>", "e": 28880, "s": 28224, "text": null }, { "code": null, "e": 28887, "s": 28880, "text": "Output" }, { "code": null, "e": 28912, "s": 28887, "text": "Trigger mouseover Event:" }, { "code": null, "e": 28936, "s": 28912, "text": "Trigger mouseout Event:" }, { "code": null, "e": 28957, "s": 28936, "text": "Trigger click Event:" }, { "code": null, "e": 29331, "s": 28957, "text": "Explanation: In this example, when the mouse is moved over the document the background color of the document changes to lavender. When the mouse is moved out the background color of the document changes back to white. And when the user clicks anywhere inside the document an alert pops up. These actions are handled by event handlers that is triggered when an event occurs." }, { "code": null, "e": 29383, "s": 29331, "text": "Example 2: Triggering events on individual elements" }, { "code": null, "e": 29388, "s": 29383, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <button onclick=\"clickFunction()\"> Click Me </button> <br><br> <div class=\"container\" id=\"myDiv\" onmouseenter=\"enterFunction()\" onmouseleave=\"leaveFunction()\"> Hello World...How are you </div> <script type=\"text/javascript\"> function clickFunction(){ document.body.style .backgroundColor = \"pink\"; } function enterFunction(){ document.getElementById(\"myDiv\") .style.border = \"1px solid black\"; } function leaveFunction(){ document.getElementById(\"myDiv\") .style.border = \"2px solid blue\"; } </script></body> </html>", "e": 30134, "s": 29388, "text": null }, { "code": null, "e": 30142, "s": 30134, "text": "Output:" }, { "code": null, "e": 30183, "s": 30142, "text": "Click on Button:Mouse move over the page" }, { "code": null, "e": 30697, "s": 30183, "text": "Explanation Here individual elements in the HTML document trigger different events and those events invoke different JavaScript functions. The logic to handle the events are specified in the functions. When the button is clicked, it changes the background color of the webpage. The other events that are handled are mouseenter and mouseleave. When the mouse enters the container with id named myDiv the border of the division turns black. When the mouse leaves the container the border of the division turns blue." }, { "code": null, "e": 30707, "s": 30697, "text": "HTML-Misc" }, { "code": null, "e": 30723, "s": 30707, "text": "JavaScript-Misc" }, { "code": null, "e": 30730, "s": 30723, "text": "Picked" }, { "code": null, "e": 30754, "s": 30730, "text": "Technical Scripter 2020" }, { "code": null, "e": 30759, "s": 30754, "text": "HTML" }, { "code": null, "e": 30770, "s": 30759, "text": "JavaScript" }, { "code": null, "e": 30789, "s": 30770, "text": "Technical Scripter" }, { "code": null, "e": 30806, "s": 30789, "text": "Web Technologies" }, { "code": null, "e": 30833, "s": 30806, "text": "Web technologies Questions" }, { "code": null, "e": 30838, "s": 30833, "text": "HTML" }, { "code": null, "e": 30936, "s": 30838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30960, "s": 30936, "text": "REST API (Introduction)" }, { "code": null, "e": 31001, "s": 30960, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 31038, "s": 31001, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31067, "s": 31038, "text": "Form validation using jQuery" }, { "code": null, "e": 31087, "s": 31067, "text": "Angular File Upload" }, { "code": null, "e": 31127, "s": 31087, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31172, "s": 31127, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31233, "s": 31172, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31305, "s": 31233, "text": "Differences between Functional Components and Class Components in React" } ]
Import Only Selected Columns of Data from CSV in R - GeeksforGeeks
17 Jun, 2021 In this article, we will be looking at two different approaches to import selected columns of the Data from a CSV file in the R programming language. In this method of only importing the selected columns of the CSV file data, the user needs to call the read.table() function, which is an in-built function of R programming language, and then passes the selected column in its arguments to import particular columns from the data. Here, the user has to pass the null value to the parameter, to avoid importing that particular column. read.table() function reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file. Syntax: read.table(file, header, nrows, skip, colClasses, sep) Parameters: file: Specifies the name of the file. header:The header is a logical flag indicating whether the first line is a header line contains data or not. nrows: Specifies number of rows in the dataset. skip: Helps in skipping of lines from the beginning. colClasses: It is a character vector which indicates class of each column of the data set. sep: It a string indicating the way the columns are separated that is by commas, spaces, colons, tabs etc. Dataset in Use: Example: R gfg_data <- read.table("gfg_data.csv", header = TRUE, sep = ",", colClasses = c("numeric", "NULL", "NULL", "numeric", "NULL")) gfg_data Output: In this approach to import only selected columns to the R programming language, the user first needs to install and import the data.table package in the R console and call the read() function which is the function of the data.table package, with the file location and the selected columns which are to be imported in the select argument of this function. Further, this will lead to importing of the selected columns fread() function is fast and more convenient to controls such as sep, colClasses, and nrows are automatically detected Syntax: fread(file, sep, colClasses, nrows) Parameter: file: Specifies the name of the file. colClasses: It is a character vector which indicates class of each column of the data set. sep: It a string indicating the way the columns are separated that is by commas, spaces, colons, tabs etc. nrows: Specifies number of rows in the dataset. Example: R library("data.table") gfg_data <- fread("gfg_data.csv", select = c("A", "C", "E")) gfg_data Output: Picked R-CSV R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R Plot mean and standard deviation using ggplot2 in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n17 Jun, 2021" }, { "code": null, "e": 26637, "s": 26487, "text": "In this article, we will be looking at two different approaches to import selected columns of the Data from a CSV file in the R programming language." }, { "code": null, "e": 27020, "s": 26637, "text": "In this method of only importing the selected columns of the CSV file data, the user needs to call the read.table() function, which is an in-built function of R programming language, and then passes the selected column in its arguments to import particular columns from the data. Here, the user has to pass the null value to the parameter, to avoid importing that particular column." }, { "code": null, "e": 27176, "s": 27020, "text": "read.table() function reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file." }, { "code": null, "e": 27184, "s": 27176, "text": "Syntax:" }, { "code": null, "e": 27239, "s": 27184, "text": "read.table(file, header, nrows, skip, colClasses, sep)" }, { "code": null, "e": 27251, "s": 27239, "text": "Parameters:" }, { "code": null, "e": 27289, "s": 27251, "text": "file: Specifies the name of the file." }, { "code": null, "e": 27398, "s": 27289, "text": "header:The header is a logical flag indicating whether the first line is a header line contains data or not." }, { "code": null, "e": 27446, "s": 27398, "text": "nrows: Specifies number of rows in the dataset." }, { "code": null, "e": 27499, "s": 27446, "text": "skip: Helps in skipping of lines from the beginning." }, { "code": null, "e": 27590, "s": 27499, "text": "colClasses: It is a character vector which indicates class of each column of the data set." }, { "code": null, "e": 27697, "s": 27590, "text": "sep: It a string indicating the way the columns are separated that is by commas, spaces, colons, tabs etc." }, { "code": null, "e": 27713, "s": 27697, "text": "Dataset in Use:" }, { "code": null, "e": 27722, "s": 27713, "text": "Example:" }, { "code": null, "e": 27724, "s": 27722, "text": "R" }, { "code": "gfg_data <- read.table(\"gfg_data.csv\", header = TRUE, sep = \",\", colClasses = c(\"numeric\", \"NULL\", \"NULL\", \"numeric\", \"NULL\")) gfg_data", "e": 27928, "s": 27724, "text": null }, { "code": null, "e": 27936, "s": 27928, "text": "Output:" }, { "code": null, "e": 28354, "s": 27936, "text": "In this approach to import only selected columns to the R programming language, the user first needs to install and import the data.table package in the R console and call the read() function which is the function of the data.table package, with the file location and the selected columns which are to be imported in the select argument of this function. Further, this will lead to importing of the selected columns " }, { "code": null, "e": 28473, "s": 28354, "text": "fread() function is fast and more convenient to controls such as sep, colClasses, and nrows are automatically detected" }, { "code": null, "e": 28481, "s": 28473, "text": "Syntax:" }, { "code": null, "e": 28517, "s": 28481, "text": "fread(file, sep, colClasses, nrows)" }, { "code": null, "e": 28528, "s": 28517, "text": "Parameter:" }, { "code": null, "e": 28566, "s": 28528, "text": "file: Specifies the name of the file." }, { "code": null, "e": 28657, "s": 28566, "text": "colClasses: It is a character vector which indicates class of each column of the data set." }, { "code": null, "e": 28764, "s": 28657, "text": "sep: It a string indicating the way the columns are separated that is by commas, spaces, colons, tabs etc." }, { "code": null, "e": 28812, "s": 28764, "text": "nrows: Specifies number of rows in the dataset." }, { "code": null, "e": 28821, "s": 28812, "text": "Example:" }, { "code": null, "e": 28823, "s": 28821, "text": "R" }, { "code": "library(\"data.table\") gfg_data <- fread(\"gfg_data.csv\", select = c(\"A\", \"C\", \"E\")) gfg_data", "e": 28937, "s": 28823, "text": null }, { "code": null, "e": 28946, "s": 28937, "text": "Output: " }, { "code": null, "e": 28953, "s": 28946, "text": "Picked" }, { "code": null, "e": 28959, "s": 28953, "text": "R-CSV" }, { "code": null, "e": 28970, "s": 28959, "text": "R Language" }, { "code": null, "e": 29068, "s": 28970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29120, "s": 29068, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29155, "s": 29120, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29193, "s": 29155, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29251, "s": 29193, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29294, "s": 29251, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29343, "s": 29294, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29380, "s": 29343, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29397, "s": 29380, "text": "R - if statement" }, { "code": null, "e": 29423, "s": 29397, "text": "Time Series Analysis in R" } ]
How to Scrape Multiple Pages of a Website Using Python?
30 Nov, 2021 Web Scraping is a method of extracting useful data from a website using computer programs without having to manually do it. This data can then be exported and categorically organized for various purposes. Some common places where Web Scraping finds its use are Market research & Analysis Websites, Price Comparison Tools, Search Engines, Data Collection for AI/ML projects, etc. Let’s dive deep and scrape a website. In this article, we are going to take the GeeksforGeeks website and extract the titles of all the articles available on the Homepage using a Python script. If you notice, there are thousands of articles on the website and to extract all of them, we will have to scrape through all pages so that we don’t miss out on any! GeeksforGeeks Homepage Now, there may arise various instances where you may want to get data from multiple pages from the same website or multiple different URLs as well, and manually writing code for each webpage is a time-consuming and tedious task. Plus, it defines all basic principles of automation. Duh! To solve this exact problem, we will see two main techniques that will help us extract data from multiple webpages: The same website Different website URLs Approach: The approach of the program will be fairly simple, and it will be easier to understand it in a POINT format: We’ll import all the necessary libraries. Set up our URL strings for making a connection using the requests library. Parsing the available data from the target page using the BeautifulSoup library’s parser. From the target page, Identify and Extract the classes and tags which contain the information that is valuable to us. Prototype it for one page using a loop and then apply it to all the pages. Example 1: Looping through the page numbers page numbers at the bottom of the GeeksforGeeks website Most websites have pages labeled from 1 to N. This makes it really simple for us to loop through these pages and extract data from them as these pages have similar structures. For example: notice the last section of the URL – page/4/ Here, we can see the page details at the end of the URL. Using this information we can easily create a for loop iterating over as many pages as we want (by putting page/(i)/ in the URL string and iterating “i” till N) and scrape all the useful data from them. The following code will give you more clarity over how to scrape data by using a For Loop in Python. Python import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/1/' req = requests.get(URL)soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs = {'class','head'}) print(titles[4].text) Output: Output for the above code Now, using the above code, we can get the titles of all the articles by just sandwiching those lines with a loop. Python import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/' for page in range(1,10): # pls note that the total number of # pages in the website is more than 5000 so i'm only taking the # first 10 as this is just an example req = requests.get(URL + str(page) + '/') soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4,19): if page>1: print(f"{(i-3)+page*15}" + titles[i].text) else: print(f"{i-3}" + titles[i].text) Output: Output for the above code Note: The above code will fetch the first 10 pages from the website and scrape all the 150 titles of the articles that fall under those pages. Example 2: Looping through a list of different URLs. The above technique is absolutely wonderful, but what if you need to scrape different pages, and you don’t know their page numbers? You’ll need to scrape those different URLs one by one and manually code a script for every such webpage. Instead, you could just make a list of these URLs and loop through them. By simply iterating the items in the list i.e. the URLs, we will be able to extract the titles of those pages without having to write code for each page. Here’s an example code of how you can do it. Python import requestsfrom bs4 import BeautifulSoup as bsURL = ['https://www.geeksforgeeks.org','https://www.geeksforgeeks.org/page/10/'] for url in range(0,2): req = requests.get(URL[url]) soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4, 19): if url+1 > 1: print(f"{(i - 3) + url * 15}" + titles[i].text) else: print(f"{i - 3}" + titles[i].text) Output: Output for the above code Controlling the crawl rate is the most important thing to keep in mind when carrying out a very large extraction. Bombarding the server with multiple requests within a very short amount of time will most likely result in getting your IP address blacklisted. To avoid this, we can simply carry out our crawling in short random bursts of time. In other words, we add pauses or little breaks between crawling periods, which help us look like actual humans as websites can easily identify a crawler because of the speed it possesses compared to a human trying to visit the website. This helps avoid unnecessary traffic and overloading of the website servers. Win-Win! Now, how do we control the crawling rate? It’s simple. By using two functions, randint() and sleep() from python modules ‘random’ and ‘time’ respectively. Python3 from random import randintfrom time import sleep print(randint(1,10)) 1 The randint() function will choose a random integer between the given upper and lower limits, in this case, 10 and 1 respectively, for every iteration of the loop. Using the randint() function in combination with the sleep() function will help in adding short and random breaks in the crawling rate of the program. The sleep() function will basically cease the execution of the program for the given number of seconds. Here, the number of seconds will randomly be fed into the sleep function by using the randint() function. Use the code given below for reference. Python3 from time import *from random import randint for i in range(0,3): # selects random integer in given range x = randint(2,5) print(x) sleep(x) print(f'I waited {x} seconds') 5 I waited 5 seconds 4 I waited 4 seconds 5 I waited 5 seconds To get you a clear idea of this function in action, refer to the code given below. Python3 import requestsfrom bs4 import BeautifulSoup as bsfrom random import randintfrom time import sleep URL = 'https://www.geeksforgeeks.org/page/' for page in range(1,10): # pls note that the total number of # pages in the website is more than 5000 so i'm only taking the # first 10 as this is just an example req = requests.get(URL + str(page) + '/') soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4,19): if page>1: print(f"{(i-3)+page*15}" + titles[i].text) else: print(f"{i-3}" + titles[i].text) sleep(randint(2,10)) Output: The program has paused its execution and is waiting to resume The output of the above code sagar0719kumar Picked Python web-scraping-exercises Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Nov, 2021" }, { "code": null, "e": 432, "s": 53, "text": "Web Scraping is a method of extracting useful data from a website using computer programs without having to manually do it. This data can then be exported and categorically organized for various purposes. Some common places where Web Scraping finds its use are Market research & Analysis Websites, Price Comparison Tools, Search Engines, Data Collection for AI/ML projects, etc." }, { "code": null, "e": 627, "s": 432, "text": "Let’s dive deep and scrape a website. In this article, we are going to take the GeeksforGeeks website and extract the titles of all the articles available on the Homepage using a Python script. " }, { "code": null, "e": 793, "s": 627, "text": "If you notice, there are thousands of articles on the website and to extract all of them, we will have to scrape through all pages so that we don’t miss out on any! " }, { "code": null, "e": 816, "s": 793, "text": "GeeksforGeeks Homepage" }, { "code": null, "e": 1105, "s": 816, "text": "Now, there may arise various instances where you may want to get data from multiple pages from the same website or multiple different URLs as well, and manually writing code for each webpage is a time-consuming and tedious task. Plus, it defines all basic principles of automation. Duh! " }, { "code": null, "e": 1221, "s": 1105, "text": "To solve this exact problem, we will see two main techniques that will help us extract data from multiple webpages:" }, { "code": null, "e": 1238, "s": 1221, "text": "The same website" }, { "code": null, "e": 1261, "s": 1238, "text": "Different website URLs" }, { "code": null, "e": 1271, "s": 1261, "text": "Approach:" }, { "code": null, "e": 1380, "s": 1271, "text": "The approach of the program will be fairly simple, and it will be easier to understand it in a POINT format:" }, { "code": null, "e": 1422, "s": 1380, "text": "We’ll import all the necessary libraries." }, { "code": null, "e": 1497, "s": 1422, "text": "Set up our URL strings for making a connection using the requests library." }, { "code": null, "e": 1587, "s": 1497, "text": "Parsing the available data from the target page using the BeautifulSoup library’s parser." }, { "code": null, "e": 1705, "s": 1587, "text": "From the target page, Identify and Extract the classes and tags which contain the information that is valuable to us." }, { "code": null, "e": 1780, "s": 1705, "text": "Prototype it for one page using a loop and then apply it to all the pages." }, { "code": null, "e": 1825, "s": 1780, "text": "Example 1: Looping through the page numbers " }, { "code": null, "e": 1881, "s": 1825, "text": "page numbers at the bottom of the GeeksforGeeks website" }, { "code": null, "e": 2070, "s": 1881, "text": "Most websites have pages labeled from 1 to N. This makes it really simple for us to loop through these pages and extract data from them as these pages have similar structures. For example:" }, { "code": null, "e": 2115, "s": 2070, "text": "notice the last section of the URL – page/4/" }, { "code": null, "e": 2476, "s": 2115, "text": "Here, we can see the page details at the end of the URL. Using this information we can easily create a for loop iterating over as many pages as we want (by putting page/(i)/ in the URL string and iterating “i” till N) and scrape all the useful data from them. The following code will give you more clarity over how to scrape data by using a For Loop in Python." }, { "code": null, "e": 2483, "s": 2476, "text": "Python" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/1/' req = requests.get(URL)soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs = {'class','head'}) print(titles[4].text)", "e": 2719, "s": 2483, "text": null }, { "code": null, "e": 2727, "s": 2719, "text": "Output:" }, { "code": null, "e": 2753, "s": 2727, "text": "Output for the above code" }, { "code": null, "e": 2867, "s": 2753, "text": "Now, using the above code, we can get the titles of all the articles by just sandwiching those lines with a loop." }, { "code": null, "e": 2874, "s": 2867, "text": "Python" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/' for page in range(1,10): # pls note that the total number of # pages in the website is more than 5000 so i'm only taking the # first 10 as this is just an example req = requests.get(URL + str(page) + '/') soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4,19): if page>1: print(f\"{(i-3)+page*15}\" + titles[i].text) else: print(f\"{i-3}\" + titles[i].text)", "e": 3444, "s": 2874, "text": null }, { "code": null, "e": 3452, "s": 3444, "text": "Output:" }, { "code": null, "e": 3478, "s": 3452, "text": "Output for the above code" }, { "code": null, "e": 3622, "s": 3478, "text": "Note: The above code will fetch the first 10 pages from the website and scrape all the 150 titles of the articles that fall under those pages. " }, { "code": null, "e": 3675, "s": 3622, "text": "Example 2: Looping through a list of different URLs." }, { "code": null, "e": 3912, "s": 3675, "text": "The above technique is absolutely wonderful, but what if you need to scrape different pages, and you don’t know their page numbers? You’ll need to scrape those different URLs one by one and manually code a script for every such webpage." }, { "code": null, "e": 4184, "s": 3912, "text": "Instead, you could just make a list of these URLs and loop through them. By simply iterating the items in the list i.e. the URLs, we will be able to extract the titles of those pages without having to write code for each page. Here’s an example code of how you can do it." }, { "code": null, "e": 4191, "s": 4184, "text": "Python" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bsURL = ['https://www.geeksforgeeks.org','https://www.geeksforgeeks.org/page/10/'] for url in range(0,2): req = requests.get(URL[url]) soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4, 19): if url+1 > 1: print(f\"{(i - 3) + url * 15}\" + titles[i].text) else: print(f\"{i - 3}\" + titles[i].text)", "e": 4640, "s": 4191, "text": null }, { "code": null, "e": 4648, "s": 4640, "text": "Output:" }, { "code": null, "e": 4674, "s": 4648, "text": "Output for the above code" }, { "code": null, "e": 5338, "s": 4674, "text": "Controlling the crawl rate is the most important thing to keep in mind when carrying out a very large extraction. Bombarding the server with multiple requests within a very short amount of time will most likely result in getting your IP address blacklisted. To avoid this, we can simply carry out our crawling in short random bursts of time. In other words, we add pauses or little breaks between crawling periods, which help us look like actual humans as websites can easily identify a crawler because of the speed it possesses compared to a human trying to visit the website. This helps avoid unnecessary traffic and overloading of the website servers. Win-Win!" }, { "code": null, "e": 5494, "s": 5338, "text": "Now, how do we control the crawling rate? It’s simple. By using two functions, randint() and sleep() from python modules ‘random’ and ‘time’ respectively. " }, { "code": null, "e": 5502, "s": 5494, "text": "Python3" }, { "code": "from random import randintfrom time import sleep print(randint(1,10))", "e": 5574, "s": 5502, "text": null }, { "code": null, "e": 5576, "s": 5574, "text": "1" }, { "code": null, "e": 6141, "s": 5576, "text": "The randint() function will choose a random integer between the given upper and lower limits, in this case, 10 and 1 respectively, for every iteration of the loop. Using the randint() function in combination with the sleep() function will help in adding short and random breaks in the crawling rate of the program. The sleep() function will basically cease the execution of the program for the given number of seconds. Here, the number of seconds will randomly be fed into the sleep function by using the randint() function. Use the code given below for reference." }, { "code": null, "e": 6149, "s": 6141, "text": "Python3" }, { "code": "from time import *from random import randint for i in range(0,3): # selects random integer in given range x = randint(2,5) print(x) sleep(x) print(f'I waited {x} seconds')", "e": 6327, "s": 6149, "text": null }, { "code": null, "e": 6390, "s": 6327, "text": "5\nI waited 5 seconds\n4\nI waited 4 seconds\n5\nI waited 5 seconds" }, { "code": null, "e": 6473, "s": 6390, "text": "To get you a clear idea of this function in action, refer to the code given below." }, { "code": null, "e": 6481, "s": 6473, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bsfrom random import randintfrom time import sleep URL = 'https://www.geeksforgeeks.org/page/' for page in range(1,10): # pls note that the total number of # pages in the website is more than 5000 so i'm only taking the # first 10 as this is just an example req = requests.get(URL + str(page) + '/') soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4,19): if page>1: print(f\"{(i-3)+page*15}\" + titles[i].text) else: print(f\"{i-3}\" + titles[i].text) sleep(randint(2,10))", "e": 7126, "s": 6481, "text": null }, { "code": null, "e": 7134, "s": 7126, "text": "Output:" }, { "code": null, "e": 7196, "s": 7134, "text": "The program has paused its execution and is waiting to resume" }, { "code": null, "e": 7225, "s": 7196, "text": "The output of the above code" }, { "code": null, "e": 7240, "s": 7225, "text": "sagar0719kumar" }, { "code": null, "e": 7247, "s": 7240, "text": "Picked" }, { "code": null, "e": 7277, "s": 7247, "text": "Python web-scraping-exercises" }, { "code": null, "e": 7290, "s": 7277, "text": "Web-scraping" }, { "code": null, "e": 7297, "s": 7290, "text": "Python" }, { "code": null, "e": 7395, "s": 7297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7427, "s": 7395, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7454, "s": 7427, "text": "Python Classes and Objects" }, { "code": null, "e": 7475, "s": 7454, "text": "Python OOPs Concepts" }, { "code": null, "e": 7498, "s": 7475, "text": "Introduction To PYTHON" }, { "code": null, "e": 7554, "s": 7498, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7585, "s": 7554, "text": "Python | os.path.join() method" }, { "code": null, "e": 7627, "s": 7585, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7669, "s": 7627, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7708, "s": 7669, "text": "Python | Get unique values from a list" } ]
PHP - Files & I/O
This chapter will explain following functions related to files − Opening a file Reading a file Writing a file Closing a file The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate. Files modes can be specified as one of the six options in this table. r Opens the file for reading only. Places the file pointer at the beginning of the file. r+ Opens the file for reading and writing. Places the file pointer at the beginning of the file. w Opens the file for writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attempts to create a file. w+ Opens the file for reading and writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attempts to create a file. a Opens the file for writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file. a+ Opens the file for reading and writing only. Places the file pointer at the end of the file. If files does not exist then it attempts to create a file. If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file. After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails. Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes. The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes. So here are the steps required to read a file with PHP. Open a file using fopen() function. Open a file using fopen() function. Get the file's length using filesize() function. Get the file's length using filesize() function. Read the file's content using fread() function. Read the file's content using fread() function. Close the file with fclose() function. Close the file with fclose() function. The following example assigns the content of a text file to a variable then displays those contents on the web page. <html> <head> <title>Reading a file using PHP</title> </head> <body> <?php $filename = "tmp.txt"; $file = fopen( $filename, "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $filesize = filesize( $filename ); $filetext = fread( $file, $filesize ); fclose( $file ); echo ( "File size : $filesize bytes" ); echo ( "<pre>$filetext</pre>" ); ?> </body> </html> It will produce the following result − A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached. The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument <?php $filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple test\n" ); fclose( $file ); ?> <html> <head> <title>Writing a file using PHP</title> </head> <body> <?php $filename = "newfile.txt"; $file = fopen( $filename, "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $filesize = filesize( $filename ); $filetext = fread( $file, $filesize ); fclose( $file ); echo ( "File size : $filesize bytes" ); echo ( "$filetext" ); echo("file name: $filename"); ?> </body> </html> It will produce the following result − We have covered all the function related to file input and out in PHP File System Function chapter.
[ { "code": null, "e": 2956, "s": 2891, "text": "This chapter will explain following functions related to files −" }, { "code": null, "e": 2971, "s": 2956, "text": "Opening a file" }, { "code": null, "e": 2986, "s": 2971, "text": "Reading a file" }, { "code": null, "e": 3001, "s": 2986, "text": "Writing a file" }, { "code": null, "e": 3016, "s": 3001, "text": "Closing a file" }, { "code": null, "e": 3154, "s": 3016, "text": "The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate." }, { "code": null, "e": 3224, "s": 3154, "text": "Files modes can be specified as one of the six options in this table." }, { "code": null, "e": 3226, "s": 3224, "text": "r" }, { "code": null, "e": 3259, "s": 3226, "text": "Opens the file for reading only." }, { "code": null, "e": 3313, "s": 3259, "text": "Places the file pointer at the beginning of the file." }, { "code": null, "e": 3316, "s": 3313, "text": "r+" }, { "code": null, "e": 3356, "s": 3316, "text": "Opens the file for reading and writing." }, { "code": null, "e": 3410, "s": 3356, "text": "Places the file pointer at the beginning of the file." }, { "code": null, "e": 3412, "s": 3410, "text": "w" }, { "code": null, "e": 3445, "s": 3412, "text": "Opens the file for writing only." }, { "code": null, "e": 3499, "s": 3445, "text": "Places the file pointer at the beginning of the file." }, { "code": null, "e": 3556, "s": 3499, "text": "and truncates the file to zero length. If files does not" }, { "code": null, "e": 3597, "s": 3556, "text": "exist then it attempts to create a file." }, { "code": null, "e": 3600, "s": 3597, "text": "w+" }, { "code": null, "e": 3645, "s": 3600, "text": "Opens the file for reading and writing only." }, { "code": null, "e": 3699, "s": 3645, "text": "Places the file pointer at the beginning of the file." }, { "code": null, "e": 3756, "s": 3699, "text": "and truncates the file to zero length. If files does not" }, { "code": null, "e": 3797, "s": 3756, "text": "exist then it attempts to create a file." }, { "code": null, "e": 3799, "s": 3797, "text": "a" }, { "code": null, "e": 3832, "s": 3799, "text": "Opens the file for writing only." }, { "code": null, "e": 3880, "s": 3832, "text": "Places the file pointer at the end of the file." }, { "code": null, "e": 3939, "s": 3880, "text": "If files does not exist then it attempts to create a file." }, { "code": null, "e": 3942, "s": 3939, "text": "a+" }, { "code": null, "e": 3987, "s": 3942, "text": "Opens the file for reading and writing only." }, { "code": null, "e": 4035, "s": 3987, "text": "Places the file pointer at the end of the file." }, { "code": null, "e": 4094, "s": 4035, "text": "If files does not exist then it attempts to create a file." }, { "code": null, "e": 4260, "s": 4094, "text": "If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file." }, { "code": null, "e": 4490, "s": 4260, "text": "After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails." }, { "code": null, "e": 4699, "s": 4490, "text": "Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes." }, { "code": null, "e": 4854, "s": 4699, "text": "The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes." }, { "code": null, "e": 4910, "s": 4854, "text": "So here are the steps required to read a file with PHP." }, { "code": null, "e": 4946, "s": 4910, "text": "Open a file using fopen() function." }, { "code": null, "e": 4982, "s": 4946, "text": "Open a file using fopen() function." }, { "code": null, "e": 5031, "s": 4982, "text": "Get the file's length using filesize() function." }, { "code": null, "e": 5080, "s": 5031, "text": "Get the file's length using filesize() function." }, { "code": null, "e": 5128, "s": 5080, "text": "Read the file's content using fread() function." }, { "code": null, "e": 5176, "s": 5128, "text": "Read the file's content using fread() function." }, { "code": null, "e": 5215, "s": 5176, "text": "Close the file with fclose() function." }, { "code": null, "e": 5254, "s": 5215, "text": "Close the file with fclose() function." }, { "code": null, "e": 5371, "s": 5254, "text": "The following example assigns the content of a text file to a variable then displays those contents on the web page." }, { "code": null, "e": 5936, "s": 5371, "text": "<html>\n\n <head>\n <title>Reading a file using PHP</title>\n </head>\n \n <body>\n \n <?php\n $filename = \"tmp.txt\";\n $file = fopen( $filename, \"r\" );\n \n if( $file == false ) {\n echo ( \"Error in opening file\" );\n exit();\n }\n \n $filesize = filesize( $filename );\n $filetext = fread( $file, $filesize );\n fclose( $file );\n \n echo ( \"File size : $filesize bytes\" );\n echo ( \"<pre>$filetext</pre>\" );\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 5975, "s": 5936, "text": "It will produce the following result −" }, { "code": null, "e": 6387, "s": 5975, "text": "A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached." }, { "code": null, "e": 6593, "s": 6387, "text": "The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument" }, { "code": null, "e": 7456, "s": 6593, "text": "<?php\n $filename = \"/home/user/guest/newfile.txt\";\n $file = fopen( $filename, \"w\" );\n \n if( $file == false ) {\n echo ( \"Error in opening new file\" );\n exit();\n }\n fwrite( $file, \"This is a simple test\\n\" );\n fclose( $file );\n?>\n<html>\n \n <head>\n <title>Writing a file using PHP</title>\n </head>\n \n <body>\n \n <?php\n $filename = \"newfile.txt\";\n $file = fopen( $filename, \"r\" );\n \n if( $file == false ) {\n echo ( \"Error in opening file\" );\n exit();\n }\n \n $filesize = filesize( $filename );\n $filetext = fread( $file, $filesize );\n \n fclose( $file );\n \n echo ( \"File size : $filesize bytes\" );\n echo ( \"$filetext\" );\n echo(\"file name: $filename\");\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 7495, "s": 7456, "text": "It will produce the following result −" } ]
Difference between const int*, const int * const, and int const *
22 Jun, 2022 int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn’t be changed. Const qualifier doesn’t affect the pointer in this scenario so the pointer is allowed to point to some other address. The first const keyword can go either side of data type, hence int const* is equivalent to const int*. C #include <stdio.h> int main(){ const int q = 5; int const* p = &q; //Compilation error *p = 7; const int q2 = 7; //Valid p = &q2; return 0;} int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer. Effectively, this implies that the pointer shouldn’t point to some other address. Const qualifier doesn’t affect the value of integer in this scenario so the value being stored in the address is allowed to change. C #include <stdio.h> int main(){ int q = 5; int *const p = &q; //Valid *p = 7; const int q2 = 7; //Compilation error p = &q2; return 0;} const int* const is a constant pointer to constant integer This means that the variable being declared is a constant pointer pointing to a constant integer. Effectively, this implies that a constant pointer is pointing to a constant value. Hence, neither the pointer should point to a new address nor the value being pointed to should be changed. The first const keyword can go either side of data type, hence const int* const is equivalent to int const* const. C #include <stdio.h> int main(){ const int q = 5; //Valid const int* const p = &q; //Compilation error *p = 7; const int q2 = 7; //Compilation error p = &q2; return 0;} One way to remember the syntax (according to Bjarne Stroustrup) is the spiral rule- The rule says, start from the name of the variable and move clockwise to the next pointer or type. Repeat until expression ends. The rule can also be seen as decoding the syntax from right to left. Hence, int const* is pointer to const int int *const is const pointer to int int const* const is const pointer to const int Using this rule, even complex declarations can be decoded like, int ** const is a const pointer to pointer to an int. int * const * is a pointer to const pointer to an int. int const ** is a pointer to a pointer to a const int. int * const * const is a const pointer to a const pointer to an int. RanaShaktiSingh dcdschaudhary needgyan Picked Pointers C Language C Programs Difference Between Programming Language Pointers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Strings in C Arrow operator -> in C/C++ with Examples Basics of File Handling in C UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 499, "s": 52, "text": "int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn’t be changed. Const qualifier doesn’t affect the pointer in this scenario so the pointer is allowed to point to some other address. The first const keyword can go either side of data type, hence int const* is equivalent to const int*. " }, { "code": null, "e": 501, "s": 499, "text": "C" }, { "code": "#include <stdio.h> int main(){ const int q = 5; int const* p = &q; //Compilation error *p = 7; const int q2 = 7; //Valid p = &q2; return 0;}", "e": 674, "s": 501, "text": null }, { "code": null, "e": 1023, "s": 674, "text": "int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer. Effectively, this implies that the pointer shouldn’t point to some other address. Const qualifier doesn’t affect the value of integer in this scenario so the value being stored in the address is allowed to change. " }, { "code": null, "e": 1025, "s": 1023, "text": "C" }, { "code": "#include <stdio.h> int main(){ int q = 5; int *const p = &q; //Valid *p = 7; const int q2 = 7; //Compilation error p = &q2; return 0;}", "e": 1188, "s": 1025, "text": null }, { "code": null, "e": 1651, "s": 1188, "text": "const int* const is a constant pointer to constant integer This means that the variable being declared is a constant pointer pointing to a constant integer. Effectively, this implies that a constant pointer is pointing to a constant value. Hence, neither the pointer should point to a new address nor the value being pointed to should be changed. The first const keyword can go either side of data type, hence const int* const is equivalent to int const* const. " }, { "code": null, "e": 1653, "s": 1651, "text": "C" }, { "code": "#include <stdio.h> int main(){ const int q = 5; //Valid const int* const p = &q; //Compilation error *p = 7; const int q2 = 7; //Compilation error p = &q2; return 0;}", "e": 1860, "s": 1653, "text": null }, { "code": null, "e": 2151, "s": 1860, "text": "One way to remember the syntax (according to Bjarne Stroustrup) is the spiral rule- The rule says, start from the name of the variable and move clockwise to the next pointer or type. Repeat until expression ends. The rule can also be seen as decoding the syntax from right to left. Hence," }, { "code": null, "e": 2186, "s": 2151, "text": "int const* is pointer to const int" }, { "code": null, "e": 2221, "s": 2186, "text": "int *const is const pointer to int" }, { "code": null, "e": 2268, "s": 2221, "text": "int const* const is const pointer to const int" }, { "code": null, "e": 2332, "s": 2268, "text": "Using this rule, even complex declarations can be decoded like," }, { "code": null, "e": 2386, "s": 2332, "text": "int ** const is a const pointer to pointer to an int." }, { "code": null, "e": 2441, "s": 2386, "text": "int * const * is a pointer to const pointer to an int." }, { "code": null, "e": 2496, "s": 2441, "text": "int const ** is a pointer to a pointer to a const int." }, { "code": null, "e": 2565, "s": 2496, "text": "int * const * const is a const pointer to a const pointer to an int." }, { "code": null, "e": 2581, "s": 2565, "text": "RanaShaktiSingh" }, { "code": null, "e": 2595, "s": 2581, "text": "dcdschaudhary" }, { "code": null, "e": 2604, "s": 2595, "text": "needgyan" }, { "code": null, "e": 2611, "s": 2604, "text": "Picked" }, { "code": null, "e": 2620, "s": 2611, "text": "Pointers" }, { "code": null, "e": 2631, "s": 2620, "text": "C Language" }, { "code": null, "e": 2642, "s": 2631, "text": "C Programs" }, { "code": null, "e": 2661, "s": 2642, "text": "Difference Between" }, { "code": null, "e": 2682, "s": 2661, "text": "Programming Language" }, { "code": null, "e": 2691, "s": 2682, "text": "Pointers" }, { "code": null, "e": 2789, "s": 2691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2806, "s": 2789, "text": "Substring in C++" }, { "code": null, "e": 2828, "s": 2806, "text": "Function Pointer in C" }, { "code": null, "e": 2873, "s": 2828, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2898, "s": 2873, "text": "std::string class in C++" }, { "code": null, "e": 2946, "s": 2898, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2959, "s": 2946, "text": "Strings in C" }, { "code": null, "e": 3000, "s": 2959, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 3029, "s": 3000, "text": "Basics of File Handling in C" }, { "code": null, "e": 3067, "s": 3029, "text": "UDP Server-Client implementation in C" } ]
How to Avoid Duplicate User Defined Objects in TreeSet in Java?
17 Dec, 2020 TreeSet class in Java is part of Java’s collections framework which implements the NavigableSet interface, which provides functionalities to navigate through the SortedSet. The NavigableSet further extends the SortedSet interface, which provides functionalities to keep the elements sorted. As the TreeSet class implements a NavigableSet interface, it has features of both – the NavigableSet and the SortedSet. The TreeSet sort or orders the elements according to the natural ordering. All the Wrapper classes and the String class already implements Comparable interface. But in the case of custom objects, one has to implement Comparable or Comparator interfaces in the corresponding class, so that TreeSet can sort the objects as we desire. TreeSet with user-defined objects An object is said to be comparable if and only if the corresponding class implements Comparable or Comparator interface. The compare() method of Comparator interface and compareTo() method of Comparable interface provide the sorting logic to TreeSet, which enables the TreeSet to insert values accordingly. Now, if you want to avoid any duplicate entry of objects in TreeSet, you have to implement these interfaces with equality verification. And we can do this in multiple ways, Example: 1. Using the comparable interface: Let us make a student class, Student, that includes student name and the rank of student in any course. Here, no more than one student can have the same rank. So, if made a new entry of any student with a rank that is previously occupied by another student, then that entry would be a duplicate entry. Otherwise, the student will be sorted on the basis of its name in ascending order. Override compareTo() method to provide the sorting logic. In the compareTo() method of the Comparable interface, we first check whether the ranks of the two student objects are the same, if they are the same, then return 0, which means the two objects are the same. Else, if the rank isn’t the same, compare the names of the student objects and return 1 or -1 accordingly. Java // Java Program to Avoid Duplicate User// Defined Objects in TreeSetimport java.util.*; // implementing comparable interfacepublic class Student implements Comparable<Student> { private String name; private int rank; // constructor Student(String name, int rank) { this.name = name; this.rank = rank; } // returns the student name private String getName() { return name; } // returns student rank public int getRank() { return rank; } /* overriding compareTo() method. if the object has same rank then it is considered as a duplicate entry, else, the entry is sorted on the basis of the student name. */ @Override public int compareTo(Student o) { if (rank == o.getRank()) { return 0; } else if (name.compareTo(o.getName()) < 0) { return -1; } else return 1; } // overriding toString() to print the student detail @Override public String toString() { return name + " (" + rank + ")"; }} // driver classclass Gfg { public static void main(String args[]) { // create a TreeSet which stores objects of type // Student TreeSet<Student> students = new TreeSet<>(); // add objects to the TreeSet students.add(new Student("Raghav", 12)); students.add(new Student("Tilak", 11)); // adding an object with same rank students.add(new Student("Ayush", 12)); // adding an object with same name but different // rank students.add(new Student("Raghav", 32)); // print the TreeSet for (Student s : students) { System.out.println(s); } }} Raghav (12) Raghav (32) Tilak (11) 2. Using the comparator interface: Let us make a class Employee that has employee name and employee id. Here, no two or more employees can have the same ids. And the employees are sorted on the basis of their ids. (We can implement the same logic as above in this method also). While using Comparator, pass the instance of the comparator in the constructor of the TreeSet while creating one. This ensures that TreeSet is ordered in the way we desire and not by the natural ordering used by the TreeSet. Java // Java Program to Avoid Duplicate User// Defined Objects in TreeSetimport java.util.*; // implementing comparator interfacepublic class Employee implements Comparator<Employee> { private String name; private int id; // constructor public Employee(String name, int id) { this.name = name; this.id = id; } // default constructor is required, since we have to // pass the instance of Comparator in the constructor, // while creating a TreeSet public Employee() {} // returns employee name public String getName() { return name; } // returns id of the employee public int getId() { return id; } /* overriding the compare() method, this method compare two objects of type Employee on the basis of their id, if the ids of two employees is same then its considered a duplicate entry. else, it is sorted of the basis of id. */ @Override public int compare(Employee emp1, Employee emp2) { if (emp1.getId() == emp2.getId()) { return 0; } else if (emp1.getId() < emp2.getId()) { return -1; } else { return 1; } } // overriding toString() to print the employee detail @Override public String toString() { return name + " (" + id + ")"; }}// driver classclass Gfg { public static void main(String args[]) { // create a TreeSet which stores objects of type // Employee TreeSet<Employee> employees = new TreeSet<>(new Employee()); // add objects to the TreeSet employees.add(new Employee("Raghav", 934)); employees.add(new Employee("Tilak", 435)); employees.add(new Employee("Mumukshi", 252)); // adding an object with same id employees.add(new Employee("Shalu", 934)); // printing the TreeSet for (Employee s : employees) { System.out.println(s); } }} Mumukshi (252) Tilak (435) Raghav (934) java-treeset Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2020" }, { "code": null, "e": 343, "s": 52, "text": "TreeSet class in Java is part of Java’s collections framework which implements the NavigableSet interface, which provides functionalities to navigate through the SortedSet. The NavigableSet further extends the SortedSet interface, which provides functionalities to keep the elements sorted." }, { "code": null, "e": 463, "s": 343, "text": "As the TreeSet class implements a NavigableSet interface, it has features of both – the NavigableSet and the SortedSet." }, { "code": null, "e": 795, "s": 463, "text": "The TreeSet sort or orders the elements according to the natural ordering. All the Wrapper classes and the String class already implements Comparable interface. But in the case of custom objects, one has to implement Comparable or Comparator interfaces in the corresponding class, so that TreeSet can sort the objects as we desire." }, { "code": null, "e": 829, "s": 795, "text": "TreeSet with user-defined objects" }, { "code": null, "e": 1309, "s": 829, "text": "An object is said to be comparable if and only if the corresponding class implements Comparable or Comparator interface. The compare() method of Comparator interface and compareTo() method of Comparable interface provide the sorting logic to TreeSet, which enables the TreeSet to insert values accordingly. Now, if you want to avoid any duplicate entry of objects in TreeSet, you have to implement these interfaces with equality verification. And we can do this in multiple ways," }, { "code": null, "e": 1318, "s": 1309, "text": "Example:" }, { "code": null, "e": 1738, "s": 1318, "text": "1. Using the comparable interface: Let us make a student class, Student, that includes student name and the rank of student in any course. Here, no more than one student can have the same rank. So, if made a new entry of any student with a rank that is previously occupied by another student, then that entry would be a duplicate entry. Otherwise, the student will be sorted on the basis of its name in ascending order." }, { "code": null, "e": 2111, "s": 1738, "text": "Override compareTo() method to provide the sorting logic. In the compareTo() method of the Comparable interface, we first check whether the ranks of the two student objects are the same, if they are the same, then return 0, which means the two objects are the same. Else, if the rank isn’t the same, compare the names of the student objects and return 1 or -1 accordingly." }, { "code": null, "e": 2116, "s": 2111, "text": "Java" }, { "code": "// Java Program to Avoid Duplicate User// Defined Objects in TreeSetimport java.util.*; // implementing comparable interfacepublic class Student implements Comparable<Student> { private String name; private int rank; // constructor Student(String name, int rank) { this.name = name; this.rank = rank; } // returns the student name private String getName() { return name; } // returns student rank public int getRank() { return rank; } /* overriding compareTo() method. if the object has same rank then it is considered as a duplicate entry, else, the entry is sorted on the basis of the student name. */ @Override public int compareTo(Student o) { if (rank == o.getRank()) { return 0; } else if (name.compareTo(o.getName()) < 0) { return -1; } else return 1; } // overriding toString() to print the student detail @Override public String toString() { return name + \" (\" + rank + \")\"; }} // driver classclass Gfg { public static void main(String args[]) { // create a TreeSet which stores objects of type // Student TreeSet<Student> students = new TreeSet<>(); // add objects to the TreeSet students.add(new Student(\"Raghav\", 12)); students.add(new Student(\"Tilak\", 11)); // adding an object with same rank students.add(new Student(\"Ayush\", 12)); // adding an object with same name but different // rank students.add(new Student(\"Raghav\", 32)); // print the TreeSet for (Student s : students) { System.out.println(s); } }}", "e": 3874, "s": 2116, "text": null }, { "code": null, "e": 3909, "s": 3874, "text": "Raghav (12)\nRaghav (32)\nTilak (11)" }, { "code": null, "e": 4412, "s": 3909, "text": "2. Using the comparator interface: Let us make a class Employee that has employee name and employee id. Here, no two or more employees can have the same ids. And the employees are sorted on the basis of their ids. (We can implement the same logic as above in this method also). While using Comparator, pass the instance of the comparator in the constructor of the TreeSet while creating one. This ensures that TreeSet is ordered in the way we desire and not by the natural ordering used by the TreeSet." }, { "code": null, "e": 4417, "s": 4412, "text": "Java" }, { "code": "// Java Program to Avoid Duplicate User// Defined Objects in TreeSetimport java.util.*; // implementing comparator interfacepublic class Employee implements Comparator<Employee> { private String name; private int id; // constructor public Employee(String name, int id) { this.name = name; this.id = id; } // default constructor is required, since we have to // pass the instance of Comparator in the constructor, // while creating a TreeSet public Employee() {} // returns employee name public String getName() { return name; } // returns id of the employee public int getId() { return id; } /* overriding the compare() method, this method compare two objects of type Employee on the basis of their id, if the ids of two employees is same then its considered a duplicate entry. else, it is sorted of the basis of id. */ @Override public int compare(Employee emp1, Employee emp2) { if (emp1.getId() == emp2.getId()) { return 0; } else if (emp1.getId() < emp2.getId()) { return -1; } else { return 1; } } // overriding toString() to print the employee detail @Override public String toString() { return name + \" (\" + id + \")\"; }}// driver classclass Gfg { public static void main(String args[]) { // create a TreeSet which stores objects of type // Employee TreeSet<Employee> employees = new TreeSet<>(new Employee()); // add objects to the TreeSet employees.add(new Employee(\"Raghav\", 934)); employees.add(new Employee(\"Tilak\", 435)); employees.add(new Employee(\"Mumukshi\", 252)); // adding an object with same id employees.add(new Employee(\"Shalu\", 934)); // printing the TreeSet for (Employee s : employees) { System.out.println(s); } }}", "e": 6394, "s": 4417, "text": null }, { "code": null, "e": 6434, "s": 6394, "text": "Mumukshi (252)\nTilak (435)\nRaghav (934)" }, { "code": null, "e": 6447, "s": 6434, "text": "java-treeset" }, { "code": null, "e": 6454, "s": 6447, "text": "Picked" }, { "code": null, "e": 6478, "s": 6454, "text": "Technical Scripter 2020" }, { "code": null, "e": 6483, "s": 6478, "text": "Java" }, { "code": null, "e": 6497, "s": 6483, "text": "Java Programs" }, { "code": null, "e": 6516, "s": 6497, "text": "Technical Scripter" }, { "code": null, "e": 6521, "s": 6516, "text": "Java" }, { "code": null, "e": 6619, "s": 6521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6634, "s": 6619, "text": "Stream In Java" }, { "code": null, "e": 6655, "s": 6634, "text": "Introduction to Java" }, { "code": null, "e": 6676, "s": 6655, "text": "Constructors in Java" }, { "code": null, "e": 6695, "s": 6676, "text": "Exceptions in Java" }, { "code": null, "e": 6712, "s": 6695, "text": "Generics in Java" }, { "code": null, "e": 6738, "s": 6712, "text": "Java Programming Examples" }, { "code": null, "e": 6772, "s": 6738, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 6819, "s": 6772, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 6857, "s": 6819, "text": "Factory method design pattern in Java" } ]
Python | Pandas Extracting rows using .loc[]
30 Sep, 2019 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 provide a unique method to retrieve rows from a Data frame. DataFrame.loc[] method is a method that takes only index labels and returns row or dataframe if the index label exists in the caller data frame. Syntax: pandas.DataFrame.loc[] Parameters:Index label: String or list of string of index label of rows Return type: Data frame or Series depending on parameters To download the CSV used in code, click here. Example #1: Extracting single Row In this example, Name column is made as the index column and then two single rows are extracted one by one in the form of series using index label of rows. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving row by loc methodfirst = data.loc["Avery Bradley"]second = data.loc["R.J. Hunter"] print(first, "\n\n\n", second) Output:As shown in the output image, two series were returned since there was only one parameter both of the times. Example #2: Multiple parameters In this example, Name column is made as the index column and then two single rows are extracted at the same time by passing a list as parameter. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving rows by loc methodrows = data.loc[["Avery Bradley", "R.J. Hunter"]] # checking data type of rowsprint(type(rows)) # displayrows Output:As shown in the output image, this time the data type of returned value is a data frame. Both of the rows were extracted and displayed like a new data frame. Example #3: Extracting multiple rows with same index In this example, Team name is made as the index column and one team name is passed to .loc method to check if all values with same team name have been returned or not. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Team") # retrieving rows by loc methodrows = data.loc["Utah Jazz"] # checking data type of rowsprint(type(rows)) # displayrows Output:As shown in the output image, All rows with team name “Utah Jazz” were returned in the form of a data frame. Example #4: Extracting rows between two index labels In this example, two index label of rows are passed and all the rows that fall between those two index label have been returned (Both index labels Inclusive). # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving rows by loc methodrows = data.loc["Avery Bradley":"Isaiah Thomas"] # checking data type of rowsprint(type(rows)) # displayrows Output:As shown in the output image, all the rows that fall between passed two index labels are returned in the form of a data frame. Akanksha_Rai Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Sep, 2019" }, { "code": null, "e": 266, "s": 52, "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": 478, "s": 266, "text": "Pandas provide a unique method to retrieve rows from a Data frame. DataFrame.loc[] method is a method that takes only index labels and returns row or dataframe if the index label exists in the caller data frame." }, { "code": null, "e": 509, "s": 478, "text": "Syntax: pandas.DataFrame.loc[]" }, { "code": null, "e": 581, "s": 509, "text": "Parameters:Index label: String or list of string of index label of rows" }, { "code": null, "e": 639, "s": 581, "text": "Return type: Data frame or Series depending on parameters" }, { "code": null, "e": 685, "s": 639, "text": "To download the CSV used in code, click here." }, { "code": null, "e": 719, "s": 685, "text": "Example #1: Extracting single Row" }, { "code": null, "e": 875, "s": 719, "text": "In this example, Name column is made as the index column and then two single rows are extracted one by one in the form of series using index label of rows." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving row by loc methodfirst = data.loc[\"Avery Bradley\"]second = data.loc[\"R.J. Hunter\"] print(first, \"\\n\\n\\n\", second)", "e": 1135, "s": 875, "text": null }, { "code": null, "e": 1251, "s": 1135, "text": "Output:As shown in the output image, two series were returned since there was only one parameter both of the times." }, { "code": null, "e": 1284, "s": 1251, "text": " Example #2: Multiple parameters" }, { "code": null, "e": 1429, "s": 1284, "text": "In this example, Name column is made as the index column and then two single rows are extracted at the same time by passing a list as parameter." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving rows by loc methodrows = data.loc[[\"Avery Bradley\", \"R.J. Hunter\"]] # checking data type of rowsprint(type(rows)) # displayrows", "e": 1702, "s": 1429, "text": null }, { "code": null, "e": 1867, "s": 1702, "text": "Output:As shown in the output image, this time the data type of returned value is a data frame. Both of the rows were extracted and displayed like a new data frame." }, { "code": null, "e": 1922, "s": 1869, "text": "Example #3: Extracting multiple rows with same index" }, { "code": null, "e": 2090, "s": 1922, "text": "In this example, Team name is made as the index column and one team name is passed to .loc method to check if all values with same team name have been returned or not." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Team\") # retrieving rows by loc methodrows = data.loc[\"Utah Jazz\"] # checking data type of rowsprint(type(rows)) # displayrows", "e": 2342, "s": 2090, "text": null }, { "code": null, "e": 2458, "s": 2342, "text": "Output:As shown in the output image, All rows with team name “Utah Jazz” were returned in the form of a data frame." }, { "code": null, "e": 2513, "s": 2460, "text": "Example #4: Extracting rows between two index labels" }, { "code": null, "e": 2672, "s": 2513, "text": "In this example, two index label of rows are passed and all the rows that fall between those two index label have been returned (Both index labels Inclusive)." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving rows by loc methodrows = data.loc[\"Avery Bradley\":\"Isaiah Thomas\"] # checking data type of rowsprint(type(rows)) # displayrows", "e": 2944, "s": 2672, "text": null }, { "code": null, "e": 3078, "s": 2944, "text": "Output:As shown in the output image, all the rows that fall between passed two index labels are returned in the form of a data frame." }, { "code": null, "e": 3091, "s": 3078, "text": "Akanksha_Rai" }, { "code": null, "e": 3115, "s": 3091, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3147, "s": 3115, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 3161, "s": 3147, "text": "Python-pandas" }, { "code": null, "e": 3168, "s": 3161, "text": "Python" }, { "code": null, "e": 3266, "s": 3168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3294, "s": 3266, "text": "Read JSON file using Python" }, { "code": null, "e": 3344, "s": 3294, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3366, "s": 3344, "text": "Python map() function" }, { "code": null, "e": 3410, "s": 3366, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3452, "s": 3410, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3474, "s": 3452, "text": "Enumerate() in Python" }, { "code": null, "e": 3509, "s": 3474, "text": "Read a file line by line in Python" }, { "code": null, "e": 3535, "s": 3509, "text": "Python String | replace()" }, { "code": null, "e": 3567, "s": 3535, "text": "How to Install PIP on Windows ?" } ]
Numbers having Unique (or Distinct) digits
16 Jun, 2022 Given a range, print all numbers having unique digits. Examples : Input : 10 20 Output : 10 12 13 14 15 16 17 18 19 20 (Except 11) Input : 1 10 Output : 1 2 3 4 5 6 7 8 9 10 Approach: As the problem is pretty simple, the only thing to be done is :- 1- Find the digits one by one and keep marking visited digits. 2- If all digits occurs one time only then print that number. 3- Else not. C++ Java Python3 C# PHP Javascript // C++ implementation to find unique digit// numbers in a range#include<bits/stdc++.h>using namespace std; // Function to print unique digit numbers// in range from l to r.void printUnique(int l, int r){ // Start traversing the numbers for (int i=l ; i<=r ; i++) { int num = i; bool visited[10] = {false}; // Find digits and maintain its hash while (num) { // if a digit occurs more than 1 time // then break if (visited[num % 10]) break; visited[num%10] = true; num = num/10; } // num will be 0 only when above loop // doesn't get break that means the // number is unique so print it. if (num == 0) cout << i << " "; }} // Driver codeint main(){ int l = 1, r = 20; printUnique(l, r); return 0;} // Java implementation to find unique digit// numbers in a rangeclass Test{ // Method to print unique digit numbers // in range from l to r. static void printUnique(int l, int r) { // Start traversing the numbers for (int i=l ; i<=r ; i++) { int num = i; boolean visited[] = new boolean[10]; // Find digits and maintain its hash while (num != 0) { // if a digit occurs more than 1 time // then break if (visited[num % 10]) break; visited[num%10] = true; num = num/10; } // num will be 0 only when above loop // doesn't get break that means the // number is unique so print it. if (num == 0) System.out.print(i + " "); } } // Driver method public static void main(String args[]) { int l = 1, r = 20; printUnique(l, r); }} # Python3 implementation# to find unique digit# numbers in a range # Function to print# unique digit numbers# in range from l to r.def printUnique(l,r): # Start traversing # the numbers for i in range (l, r + 1): num = i; visited = [0,0,0,0,0,0,0,0,0,0]; # Find digits and # maintain its hash while (num): # if a digit occurs # more than 1 time # then break if visited[num % 10] == 1: break; visited[num % 10] = 1; num = (int)(num / 10); # num will be 0 only when # above loop doesn't get # break that means the # number is unique so # print it. if num == 0: print(i, end = " "); # Driver codel = 1;r = 20;printUnique(l, r); # This code is# contributed by mits // C# implementation to find unique digit// numbers in a rangeusing System; public class GFG { // Method to print unique digit numbers // in range from l to r. static void printUnique(int l, int r) { // Start traversing the numbers for (int i = l ; i <= r ; i++) { int num = i; bool []visited = new bool[10]; // Find digits and maintain // its hash while (num != 0) { // if a digit occurs more // than 1 time then break if (visited[num % 10]) break; visited[num % 10] = true; num = num / 10; } // num will be 0 only when // above loop doesn't get // break that means the number // is unique so print it. if (num == 0) Console.Write(i + " "); } } // Driver method public static void Main() { int l = 1, r = 20; printUnique(l, r); }} // This code is contributed by Sam007. <?php// PHP implementation to find unique// digit numbers in a range // Function to print unique digit// numbers in range from l to r.function printUnique($l, $r){ // Start traversing the numbers for ($i = $l ; $i <= $r; $i++) { $num = $i; $visited = (false); // Find digits and // maintain its hash while ($num) { // if a digit occurs more // than 1 time then break if ($visited[$num % 10]) $visited[$num % 10] = true; $num = (int)$num / 10; } // num will be 0 only when above // loop doesn't get break that // means the number is unique // so print it. if ($num == 0) echo $i , " "; }} // Driver code$l = 1; $r = 20;printUnique($l, $r); // This code is contributed by aj_36?> <script> // Javascript implementation to find unique digit// numbers in a range // Function to print unique digit numbers// in range from l to r.function printUnique(l, r){ // Start traversing the numbers for (let i=l ; i<=r ; i++) { let num = i; let visited = new Array(10); // Find digits and maintain its hash while (num) { // if a digit occurs more than 1 time // then break if (visited[num % 10]) break; visited[num%10] = true; num = Math.floor(num/10); } // num will be 0 only when above loop // doesn't get break that means the // number is unique so print it. if (num == 0) document.write(i + " "); }} // Driver code let l = 1, r = 20; printUnique(l, r); // This code is contributed by Mayank Tyagi </script> Output: 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 Time Complexity : O(nlogn) Auxiliary Space: O(1) Another Approach: Use set STL for C++ and Java Collections for Java in order to check if a number has only unique digits. Then we can compare the size of string s formed from a given number and newly created set. For example, let us consider the number 1987, then we can convert the number into the string, C++ Java int n;cin>>n;string s = to_string(n); //creating scanner class object for taking user inputScanner sc = new Scanner(System.in); int n=sc.nextInt(); //converting the number to string using String.valueof(number);string s = String.valueof(n); After that, initialize a set with the contents of string s. C++ Java set<int> uniDigits(s.begin(), s.end()); HashSet<Integer> uniDigits = new HashSet<Integer>();for(int i:s.tocharArray()){ uniDigits.add(i);} Then we can compare the size of string s and newly created set uniDigits. Here is the code for the above approach: C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to print unique// numbersvoid printUnique(int l, int r){ // Iterate from l to r for (int i = l; i <= r; i++) { // Convert the no. to // string string s = to_string(i); // Convert string to set using stl set<int> uniDigits(s.begin(), s.end()); // Output if condition satisfies if (s.size() == uniDigits.size()) { cout << i << " "; } }} // Driver Codeint main(){ // Input of the lower and // higher limits int l = 1, r = 20; // Function Call printUnique(l, r); return 0;} // Java code for the above approachimport java.util.*; class GFG{ // Function to print unique// numbersstatic void printUnique(int l, int r){ // Iterate from l to r for(int i = l; i <= r; i++) { // Convert the no. to // String String s = String.valueOf(i); // Convert String to set using Java Collections HashSet<Integer> uniDigits = new HashSet<Integer>(); for(int c : s.toCharArray()) uniDigits.add(c); // Output if condition satisfies if (s.length() == uniDigits.size()) { System.out.print(i+ " "); } }} // Driver Codepublic static void main(String[] args){ // Input of the lower and // higher limits int l = 1, r = 20; // Function Call printUnique(l, r);}} // This code is contributed by Princi Singh # Python code for the above approach # Function to print unique# numbersdef printUnique(l, r): # Iterate from l to r for i in range(l, r+1): # Convert the no. to # string s = list(str(i)) # print(s) # Convert string to set using stl unitDigits = set() for j in range(len(s)): unitDigits.add(s[j]) # Output if condition satisfies if len(s) == len(unitDigits): print(i, end = " ") # Driver Code# Input of the lower and# higher limitsl = 1r = 20 # Function CallprintUnique(l, r) # The code is contributed by Nidhi goel // C# code for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print unique// numbersstatic void printUnique(int l, int r){ // Iterate from l to r for(int i = l; i <= r; i++) { // Convert the no. to // String String s = String.Join("", i); // Convert String to set using stl HashSet<int> uniDigits = new HashSet<int>(); foreach(int c in s.ToCharArray()) uniDigits.Add(c); // Output if condition satisfies if (s.Length == uniDigits.Count) { Console.Write(i + " "); } }} // Driver Codepublic static void Main(String[] args){ // Input of the lower and // higher limits int l = 1, r = 20; // Function Call printUnique(l, r);}} // This code is contributed by Princi Singh <script> // JavaScript code for the above approach // Function to print unique// numbersfunction printUnique(l, r) { // Iterate from l to r for (let i = l; i <= r; i++) { // Convert the no. to // string let s = String(i); // Convert string to set using stl let uniDigits = new Set(); for(let c of s.split("")) uniDigits.add(c); // Output if condition satisfies if (s.length == uniDigits.size) { document.write(i + " "); } }} // Driver Code // Input of the lower and// higher limitslet l = 1, r = 20; // Function CallprintUnique(l, r); </script> 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 Time Complexity: O(nlogn) Auxiliary Space: O(n) This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 jit_t Mithun Kumar Sahil_Chhabra svrrrsvr mayanktyagi1709 princi singh gfgking mdayyanfahim shivamanandrj9 classroompxico Amazon number-digits Hash Mathematical Amazon Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Longest Consecutive Subsequence Sort string of characters Counting frequencies of array elements Hashing | Set 2 (Separate Chaining) Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 108, "s": 52, "text": "Given a range, print all numbers having unique digits. " }, { "code": null, "e": 120, "s": 108, "text": "Examples : " }, { "code": null, "e": 230, "s": 120, "text": "Input : 10 20\nOutput : 10 12 13 14 15 16 17 18 19 20 (Except 11)\n\nInput : 1 10\nOutput : 1 2 3 4 5 6 7 8 9 10" }, { "code": null, "e": 240, "s": 230, "text": "Approach:" }, { "code": null, "e": 443, "s": 240, "text": "As the problem is pretty simple, the only thing to be done is :-\n1- Find the digits one by one and keep marking visited digits.\n2- If all digits occurs one time only then print that number.\n3- Else not." }, { "code": null, "e": 447, "s": 443, "text": "C++" }, { "code": null, "e": 452, "s": 447, "text": "Java" }, { "code": null, "e": 460, "s": 452, "text": "Python3" }, { "code": null, "e": 463, "s": 460, "text": "C#" }, { "code": null, "e": 467, "s": 463, "text": "PHP" }, { "code": null, "e": 478, "s": 467, "text": "Javascript" }, { "code": "// C++ implementation to find unique digit// numbers in a range#include<bits/stdc++.h>using namespace std; // Function to print unique digit numbers// in range from l to r.void printUnique(int l, int r){ // Start traversing the numbers for (int i=l ; i<=r ; i++) { int num = i; bool visited[10] = {false}; // Find digits and maintain its hash while (num) { // if a digit occurs more than 1 time // then break if (visited[num % 10]) break; visited[num%10] = true; num = num/10; } // num will be 0 only when above loop // doesn't get break that means the // number is unique so print it. if (num == 0) cout << i << \" \"; }} // Driver codeint main(){ int l = 1, r = 20; printUnique(l, r); return 0;}", "e": 1350, "s": 478, "text": null }, { "code": "// Java implementation to find unique digit// numbers in a rangeclass Test{ // Method to print unique digit numbers // in range from l to r. static void printUnique(int l, int r) { // Start traversing the numbers for (int i=l ; i<=r ; i++) { int num = i; boolean visited[] = new boolean[10]; // Find digits and maintain its hash while (num != 0) { // if a digit occurs more than 1 time // then break if (visited[num % 10]) break; visited[num%10] = true; num = num/10; } // num will be 0 only when above loop // doesn't get break that means the // number is unique so print it. if (num == 0) System.out.print(i + \" \"); } } // Driver method public static void main(String args[]) { int l = 1, r = 20; printUnique(l, r); }}", "e": 2388, "s": 1350, "text": null }, { "code": "# Python3 implementation# to find unique digit# numbers in a range # Function to print# unique digit numbers# in range from l to r.def printUnique(l,r): # Start traversing # the numbers for i in range (l, r + 1): num = i; visited = [0,0,0,0,0,0,0,0,0,0]; # Find digits and # maintain its hash while (num): # if a digit occurs # more than 1 time # then break if visited[num % 10] == 1: break; visited[num % 10] = 1; num = (int)(num / 10); # num will be 0 only when # above loop doesn't get # break that means the # number is unique so # print it. if num == 0: print(i, end = \" \"); # Driver codel = 1;r = 20;printUnique(l, r); # This code is# contributed by mits", "e": 3267, "s": 2388, "text": null }, { "code": "// C# implementation to find unique digit// numbers in a rangeusing System; public class GFG { // Method to print unique digit numbers // in range from l to r. static void printUnique(int l, int r) { // Start traversing the numbers for (int i = l ; i <= r ; i++) { int num = i; bool []visited = new bool[10]; // Find digits and maintain // its hash while (num != 0) { // if a digit occurs more // than 1 time then break if (visited[num % 10]) break; visited[num % 10] = true; num = num / 10; } // num will be 0 only when // above loop doesn't get // break that means the number // is unique so print it. if (num == 0) Console.Write(i + \" \"); } } // Driver method public static void Main() { int l = 1, r = 20; printUnique(l, r); }} // This code is contributed by Sam007.", "e": 4412, "s": 3267, "text": null }, { "code": "<?php// PHP implementation to find unique// digit numbers in a range // Function to print unique digit// numbers in range from l to r.function printUnique($l, $r){ // Start traversing the numbers for ($i = $l ; $i <= $r; $i++) { $num = $i; $visited = (false); // Find digits and // maintain its hash while ($num) { // if a digit occurs more // than 1 time then break if ($visited[$num % 10]) $visited[$num % 10] = true; $num = (int)$num / 10; } // num will be 0 only when above // loop doesn't get break that // means the number is unique // so print it. if ($num == 0) echo $i , \" \"; }} // Driver code$l = 1; $r = 20;printUnique($l, $r); // This code is contributed by aj_36?>", "e": 5268, "s": 4412, "text": null }, { "code": "<script> // Javascript implementation to find unique digit// numbers in a range // Function to print unique digit numbers// in range from l to r.function printUnique(l, r){ // Start traversing the numbers for (let i=l ; i<=r ; i++) { let num = i; let visited = new Array(10); // Find digits and maintain its hash while (num) { // if a digit occurs more than 1 time // then break if (visited[num % 10]) break; visited[num%10] = true; num = Math.floor(num/10); } // num will be 0 only when above loop // doesn't get break that means the // number is unique so print it. if (num == 0) document.write(i + \" \"); }} // Driver code let l = 1, r = 20; printUnique(l, r); // This code is contributed by Mayank Tyagi </script>", "e": 6163, "s": 5268, "text": null }, { "code": null, "e": 6172, "s": 6163, "text": "Output: " }, { "code": null, "e": 6220, "s": 6172, "text": "1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20" }, { "code": null, "e": 6247, "s": 6220, "text": "Time Complexity : O(nlogn)" }, { "code": null, "e": 6269, "s": 6247, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6287, "s": 6269, "text": "Another Approach:" }, { "code": null, "e": 6576, "s": 6287, "text": "Use set STL for C++ and Java Collections for Java in order to check if a number has only unique digits. Then we can compare the size of string s formed from a given number and newly created set. For example, let us consider the number 1987, then we can convert the number into the string," }, { "code": null, "e": 6580, "s": 6576, "text": "C++" }, { "code": null, "e": 6585, "s": 6580, "text": "Java" }, { "code": "int n;cin>>n;string s = to_string(n);", "e": 6623, "s": 6585, "text": null }, { "code": "//creating scanner class object for taking user inputScanner sc = new Scanner(System.in); int n=sc.nextInt(); //converting the number to string using String.valueof(number);string s = String.valueof(n);", "e": 6826, "s": 6623, "text": null }, { "code": null, "e": 6886, "s": 6826, "text": "After that, initialize a set with the contents of string s." }, { "code": null, "e": 6890, "s": 6886, "text": "C++" }, { "code": null, "e": 6895, "s": 6890, "text": "Java" }, { "code": "set<int> uniDigits(s.begin(), s.end());", "e": 6935, "s": 6895, "text": null }, { "code": "HashSet<Integer> uniDigits = new HashSet<Integer>();for(int i:s.tocharArray()){ uniDigits.add(i);}", "e": 7037, "s": 6935, "text": null }, { "code": null, "e": 7111, "s": 7037, "text": "Then we can compare the size of string s and newly created set uniDigits." }, { "code": null, "e": 7152, "s": 7111, "text": "Here is the code for the above approach:" }, { "code": null, "e": 7156, "s": 7152, "text": "C++" }, { "code": null, "e": 7161, "s": 7156, "text": "Java" }, { "code": null, "e": 7169, "s": 7161, "text": "Python3" }, { "code": null, "e": 7172, "s": 7169, "text": "C#" }, { "code": null, "e": 7183, "s": 7172, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to print unique// numbersvoid printUnique(int l, int r){ // Iterate from l to r for (int i = l; i <= r; i++) { // Convert the no. to // string string s = to_string(i); // Convert string to set using stl set<int> uniDigits(s.begin(), s.end()); // Output if condition satisfies if (s.size() == uniDigits.size()) { cout << i << \" \"; } }} // Driver Codeint main(){ // Input of the lower and // higher limits int l = 1, r = 20; // Function Call printUnique(l, r); return 0;}", "e": 7866, "s": 7183, "text": null }, { "code": "// Java code for the above approachimport java.util.*; class GFG{ // Function to print unique// numbersstatic void printUnique(int l, int r){ // Iterate from l to r for(int i = l; i <= r; i++) { // Convert the no. to // String String s = String.valueOf(i); // Convert String to set using Java Collections HashSet<Integer> uniDigits = new HashSet<Integer>(); for(int c : s.toCharArray()) uniDigits.add(c); // Output if condition satisfies if (s.length() == uniDigits.size()) { System.out.print(i+ \" \"); } }} // Driver Codepublic static void main(String[] args){ // Input of the lower and // higher limits int l = 1, r = 20; // Function Call printUnique(l, r);}} // This code is contributed by Princi Singh", "e": 8732, "s": 7866, "text": null }, { "code": "# Python code for the above approach # Function to print unique# numbersdef printUnique(l, r): # Iterate from l to r for i in range(l, r+1): # Convert the no. to # string s = list(str(i)) # print(s) # Convert string to set using stl unitDigits = set() for j in range(len(s)): unitDigits.add(s[j]) # Output if condition satisfies if len(s) == len(unitDigits): print(i, end = \" \") # Driver Code# Input of the lower and# higher limitsl = 1r = 20 # Function CallprintUnique(l, r) # The code is contributed by Nidhi goel", "e": 9359, "s": 8732, "text": null }, { "code": "// C# code for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print unique// numbersstatic void printUnique(int l, int r){ // Iterate from l to r for(int i = l; i <= r; i++) { // Convert the no. to // String String s = String.Join(\"\", i); // Convert String to set using stl HashSet<int> uniDigits = new HashSet<int>(); foreach(int c in s.ToCharArray()) uniDigits.Add(c); // Output if condition satisfies if (s.Length == uniDigits.Count) { Console.Write(i + \" \"); } }} // Driver Codepublic static void Main(String[] args){ // Input of the lower and // higher limits int l = 1, r = 20; // Function Call printUnique(l, r);}} // This code is contributed by Princi Singh", "e": 10230, "s": 9359, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to print unique// numbersfunction printUnique(l, r) { // Iterate from l to r for (let i = l; i <= r; i++) { // Convert the no. to // string let s = String(i); // Convert string to set using stl let uniDigits = new Set(); for(let c of s.split(\"\")) uniDigits.add(c); // Output if condition satisfies if (s.length == uniDigits.size) { document.write(i + \" \"); } }} // Driver Code // Input of the lower and// higher limitslet l = 1, r = 20; // Function CallprintUnique(l, r); </script>", "e": 10885, "s": 10230, "text": null }, { "code": null, "e": 10934, "s": 10885, "text": "1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 " }, { "code": null, "e": 10960, "s": 10934, "text": "Time Complexity: O(nlogn)" }, { "code": null, "e": 10982, "s": 10960, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 11403, "s": 10982, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 11410, "s": 11403, "text": "Sam007" }, { "code": null, "e": 11416, "s": 11410, "text": "jit_t" }, { "code": null, "e": 11429, "s": 11416, "text": "Mithun Kumar" }, { "code": null, "e": 11443, "s": 11429, "text": "Sahil_Chhabra" }, { "code": null, "e": 11452, "s": 11443, "text": "svrrrsvr" }, { "code": null, "e": 11468, "s": 11452, "text": "mayanktyagi1709" }, { "code": null, "e": 11481, "s": 11468, "text": "princi singh" }, { "code": null, "e": 11489, "s": 11481, "text": "gfgking" }, { "code": null, "e": 11502, "s": 11489, "text": "mdayyanfahim" }, { "code": null, "e": 11517, "s": 11502, "text": "shivamanandrj9" }, { "code": null, "e": 11532, "s": 11517, "text": "classroompxico" }, { "code": null, "e": 11539, "s": 11532, "text": "Amazon" }, { "code": null, "e": 11553, "s": 11539, "text": "number-digits" }, { "code": null, "e": 11558, "s": 11553, "text": "Hash" }, { "code": null, "e": 11571, "s": 11558, "text": "Mathematical" }, { "code": null, "e": 11578, "s": 11571, "text": "Amazon" }, { "code": null, "e": 11583, "s": 11578, "text": "Hash" }, { "code": null, "e": 11596, "s": 11583, "text": "Mathematical" }, { "code": null, "e": 11694, "s": 11596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11732, "s": 11694, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 11764, "s": 11732, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 11790, "s": 11764, "text": "Sort string of characters" }, { "code": null, "e": 11829, "s": 11790, "text": "Counting frequencies of array elements" }, { "code": null, "e": 11865, "s": 11829, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 11895, "s": 11865, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 11938, "s": 11895, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 11998, "s": 11938, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 12013, "s": 11998, "text": "C++ Data Types" } ]
setlinestyle() function in C
25 Jan, 2018 The header file graphics.h contains setlinestyle() function which sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on. Syntax : void setlinestyle(int linestyle, unsigned upattern, int thickness); Examples : Input : x = 200, y = 100 Output : x and y are initialized as (200, 100). For every line, value of y increments by 25 to change the position. The line style keep changing corresponding to value of first parameter(c). Explanation : linestyle specifies in which of several styles subsequent lines will be drawn (such as solid, dotted, centered, dashed).upattern is a 16-bit pattern that applies only if linestyle is USERBIT_LINE (4). In that case, whenever a bit in the pattern word is 1, the corresponding pixel in the line is drawn in the current drawing color. A value for ‘upattern’ must always be supplied. It is simply ignored if ‘linestyle’ is not USERBIT_LINE (4).thickness specifies whether the width of subsequent lines drawn will be normal or thick. Below is the implementation of setlinestyle() function : // C Implementation for setlinestyle()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // variable to change the // line styles int c; // initial coordinate to // draw line int x = 200, y = 100; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // To keep track of lines for ( c = 0 ; c < 5 ; c++ ) { // setlinestyle function setlinestyle(c, 0, 1); // Drawing line line(x, y, x+200, y); y = y + 25; } getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;} Output : c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jan, 2018" }, { "code": null, "e": 204, "s": 54, "text": "The header file graphics.h contains setlinestyle() function which sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on." }, { "code": null, "e": 213, "s": 204, "text": "Syntax :" }, { "code": null, "e": 317, "s": 213, "text": "void setlinestyle(int linestyle, unsigned upattern,\n int thickness);\n" }, { "code": null, "e": 328, "s": 317, "text": "Examples :" }, { "code": null, "e": 551, "s": 328, "text": "Input : x = 200, y = 100\nOutput : \n\nx and y are initialized as (200, 100). \nFor every line, value of y increments \nby 25 to change the position. \nThe line style keep changing corresponding\nto value of first parameter(c). \n" }, { "code": null, "e": 1093, "s": 551, "text": "Explanation : linestyle specifies in which of several styles subsequent lines will be drawn (such as solid, dotted, centered, dashed).upattern is a 16-bit pattern that applies only if linestyle is USERBIT_LINE (4). In that case, whenever a bit in the pattern word is 1, the corresponding pixel in the line is drawn in the current drawing color. A value for ‘upattern’ must always be supplied. It is simply ignored if ‘linestyle’ is not USERBIT_LINE (4).thickness specifies whether the width of subsequent lines drawn will be normal or thick." }, { "code": null, "e": 1150, "s": 1093, "text": "Below is the implementation of setlinestyle() function :" }, { "code": "// C Implementation for setlinestyle()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // variable to change the // line styles int c; // initial coordinate to // draw line int x = 200, y = 100; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // To keep track of lines for ( c = 0 ; c < 5 ; c++ ) { // setlinestyle function setlinestyle(c, 0, 1); // Drawing line line(x, y, x+200, y); y = y + 25; } getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}", "e": 2069, "s": 1150, "text": null }, { "code": null, "e": 2078, "s": 2069, "text": "Output :" }, { "code": null, "e": 2091, "s": 2080, "text": "c-graphics" }, { "code": null, "e": 2109, "s": 2091, "text": "computer-graphics" }, { "code": null, "e": 2120, "s": 2109, "text": "C Language" } ]
File.GetCreationTime() Method in C# with Examples
28 Apr, 2020 File.GetCreationTime(String) is an inbuilt File class method which is used to return the creation date and time of the specified file or directory. Syntax: public static DateTime GetCreationTime (string path); Parameter: This function accepts a parameter which is illustrated below: path: This is the specified file path whose creation date and time is going to be returned. Exceptions: UnauthorizedAccessException: The caller does not have the required permission. ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. ArgumentNullException: The path is null. PathTooLongException: The given path, file name, or both exceed the system-defined maximum length. NotSupportedException: The path is in an invalid format. Return Value: Returns the creation date and time of the specified file or directory. Below are the programs to illustrate the File.GetCreationTime(String) method. Program 1: Before running the below code, a file file.txt is created with some contents shown below: // C# program to illustrate the usage// of File.GetCreationTime(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main(string[] args) { // Calling the GetCreationTime() function DateTime fileCreatedDate = File.GetCreationTime(@"file.txt"); // Printing the creation date and time of the // specified file Console.WriteLine("File created on: " + fileCreatedDate); }} Executing: File created on: 4/19/2020 4:02:54 AM Program 2: Before running the below code, two files were created shown below: // C# program to illustrate the usage// of File.GetCreationTime(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main(string[] args) { // Calling the GetCreationTime() function DateTime fileCreatedDate1 = File.GetCreationTime(@"file.txt"); DateTime fileCreatedDate2 = File.GetCreationTime(@"gfg.txt"); // Printing the creation date and time of the // specified file Console.WriteLine("File created on: " + fileCreatedDate1); Console.WriteLine("File created on: " + fileCreatedDate2); }} Executing: File created on: 4/19/2020 4:02:54 AM File created on: 4/19/2020 4:07:02 AM CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | Class and Object Extension Method in C# C# | Replace() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2020" }, { "code": null, "e": 176, "s": 28, "text": "File.GetCreationTime(String) is an inbuilt File class method which is used to return the creation date and time of the specified file or directory." }, { "code": null, "e": 184, "s": 176, "text": "Syntax:" }, { "code": null, "e": 238, "s": 184, "text": "public static DateTime GetCreationTime (string path);" }, { "code": null, "e": 311, "s": 238, "text": "Parameter: This function accepts a parameter which is illustrated below:" }, { "code": null, "e": 403, "s": 311, "text": "path: This is the specified file path whose creation date and time is going to be returned." }, { "code": null, "e": 415, "s": 403, "text": "Exceptions:" }, { "code": null, "e": 494, "s": 415, "text": "UnauthorizedAccessException: The caller does not have the required permission." }, { "code": null, "e": 640, "s": 494, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars." }, { "code": null, "e": 681, "s": 640, "text": "ArgumentNullException: The path is null." }, { "code": null, "e": 780, "s": 681, "text": "PathTooLongException: The given path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 837, "s": 780, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 922, "s": 837, "text": "Return Value: Returns the creation date and time of the specified file or directory." }, { "code": null, "e": 1000, "s": 922, "text": "Below are the programs to illustrate the File.GetCreationTime(String) method." }, { "code": null, "e": 1101, "s": 1000, "text": "Program 1: Before running the below code, a file file.txt is created with some contents shown below:" }, { "code": "// C# program to illustrate the usage// of File.GetCreationTime(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main(string[] args) { // Calling the GetCreationTime() function DateTime fileCreatedDate = File.GetCreationTime(@\"file.txt\"); // Printing the creation date and time of the // specified file Console.WriteLine(\"File created on: \" + fileCreatedDate); }}", "e": 1573, "s": 1101, "text": null }, { "code": null, "e": 1584, "s": 1573, "text": "Executing:" }, { "code": null, "e": 1623, "s": 1584, "text": "File created on: 4/19/2020 4:02:54 AM\n" }, { "code": null, "e": 1701, "s": 1623, "text": "Program 2: Before running the below code, two files were created shown below:" }, { "code": "// C# program to illustrate the usage// of File.GetCreationTime(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main(string[] args) { // Calling the GetCreationTime() function DateTime fileCreatedDate1 = File.GetCreationTime(@\"file.txt\"); DateTime fileCreatedDate2 = File.GetCreationTime(@\"gfg.txt\"); // Printing the creation date and time of the // specified file Console.WriteLine(\"File created on: \" + fileCreatedDate1); Console.WriteLine(\"File created on: \" + fileCreatedDate2); }}", "e": 2310, "s": 1701, "text": null }, { "code": null, "e": 2321, "s": 2310, "text": "Executing:" }, { "code": null, "e": 2398, "s": 2321, "text": "File created on: 4/19/2020 4:02:54 AM\nFile created on: 4/19/2020 4:07:02 AM\n" }, { "code": null, "e": 2419, "s": 2398, "text": "CSharp-File-Handling" }, { "code": null, "e": 2422, "s": 2419, "text": "C#" }, { "code": null, "e": 2520, "s": 2422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2551, "s": 2520, "text": "Introduction to .NET Framework" }, { "code": null, "e": 2566, "s": 2551, "text": "C# | Delegates" }, { "code": null, "e": 2609, "s": 2566, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2658, "s": 2609, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2681, "s": 2658, "text": "C# | Method Overriding" }, { "code": null, "e": 2697, "s": 2681, "text": "C# | Data Types" }, { "code": null, "e": 2715, "s": 2697, "text": "C# | Constructors" }, { "code": null, "e": 2737, "s": 2715, "text": "C# | Class and Object" }, { "code": null, "e": 2760, "s": 2737, "text": "Extension Method in C#" } ]
How to convert value to string using $toString in MongoDB?
Let us see an example to understand the $toString in MongoDB. To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows − > db.objectidToStringDemo.insertOne({"UserName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c92b80036de59bd9de0639d") } > db.objectidToStringDemo.insertOne({"UserName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5c92b80436de59bd9de0639e") } > db.objectidToStringDemo.insertOne({"UserName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c92b80936de59bd9de0639f") } > db.objectidToStringDemo.insertOne({"UserName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5c92b81836de59bd9de063a0") } Display all documents from a collection with the help of find() method. The query is as follows − > db.objectidToStringDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c92b80036de59bd9de0639d"), "UserName" : "John" } { "_id" : ObjectId("5c92b80436de59bd9de0639e"), "UserName" : "Chris" } { "_id" : ObjectId("5c92b80936de59bd9de0639f"), "UserName" : "Larry" } { "_id" : ObjectId("5c92b81836de59bd9de063a0"), "UserName" : "Robert" } Here is the query to convert ObjectId to a string value in MongoDB aggregate. The query is as follows − > db.objectidToStringDemo.aggregate([ ... { ... $project: { ... _id: { ... $toString: "$_id" ... } ... } ... } ... ] ... ); The following is the output − { "_id" : "5c92b80036de59bd9de0639d" } { "_id" : "5c92b80436de59bd9de0639e" } { "_id" : "5c92b80936de59bd9de0639f" } { "_id" : "5c92b81836de59bd9de063a0" } In order to get the original ObjectId, use the $toObjectId operator − > db.objectidToStringDemo.aggregate([ { $project: { _id: { $toObjectId: "$_id" } } } ] ); The following is the output − { "_id" : ObjectId("5c92b80036de59bd9de0639d") } { "_id" : ObjectId("5c92b80436de59bd9de0639e") } { "_id" : ObjectId("5c92b80936de59bd9de0639f") } { "_id" : ObjectId("5c92b81836de59bd9de063a0") }
[ { "code": null, "e": 1393, "s": 1187, "text": "Let us see an example to understand the $toString in MongoDB. To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −" }, { "code": null, "e": 1969, "s": 1393, "text": "> db.objectidToStringDemo.insertOne({\"UserName\":\"John\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92b80036de59bd9de0639d\")\n}\n> db.objectidToStringDemo.insertOne({\"UserName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92b80436de59bd9de0639e\")\n}\n> db.objectidToStringDemo.insertOne({\"UserName\":\"Larry\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92b80936de59bd9de0639f\")\n}\n> db.objectidToStringDemo.insertOne({\"UserName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c92b81836de59bd9de063a0\")\n}" }, { "code": null, "e": 2067, "s": 1969, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 2110, "s": 2067, "text": "> db.objectidToStringDemo.find().pretty();" }, { "code": null, "e": 2140, "s": 2110, "text": "The following is the output −" }, { "code": null, "e": 2424, "s": 2140, "text": "{ \"_id\" : ObjectId(\"5c92b80036de59bd9de0639d\"), \"UserName\" : \"John\" }\n{ \"_id\" : ObjectId(\"5c92b80436de59bd9de0639e\"), \"UserName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5c92b80936de59bd9de0639f\"), \"UserName\" : \"Larry\" }\n{ \"_id\" : ObjectId(\"5c92b81836de59bd9de063a0\"), \"UserName\" : \"Robert\" }" }, { "code": null, "e": 2528, "s": 2424, "text": "Here is the query to convert ObjectId to a string value in MongoDB aggregate. The query is as follows −" }, { "code": null, "e": 2700, "s": 2528, "text": "> db.objectidToStringDemo.aggregate([\n ... {\n ... $project: {\n ... _id: {\n ... $toString: \"$_id\"\n ... }\n ... }\n ... }\n... ]\n... );" }, { "code": null, "e": 2730, "s": 2700, "text": "The following is the output −" }, { "code": null, "e": 2886, "s": 2730, "text": "{ \"_id\" : \"5c92b80036de59bd9de0639d\" }\n{ \"_id\" : \"5c92b80436de59bd9de0639e\" }\n{ \"_id\" : \"5c92b80936de59bd9de0639f\" }\n{ \"_id\" : \"5c92b81836de59bd9de063a0\" }" }, { "code": null, "e": 2956, "s": 2886, "text": "In order to get the original ObjectId, use the $toObjectId operator −" }, { "code": null, "e": 3046, "s": 2956, "text": "> db.objectidToStringDemo.aggregate([ { $project: { _id: { $toObjectId: \"$_id\" } } } ] );" }, { "code": null, "e": 3076, "s": 3046, "text": "The following is the output −" }, { "code": null, "e": 3272, "s": 3076, "text": "{ \"_id\" : ObjectId(\"5c92b80036de59bd9de0639d\") }\n{ \"_id\" : ObjectId(\"5c92b80436de59bd9de0639e\") }\n{ \"_id\" : ObjectId(\"5c92b80936de59bd9de0639f\") }\n{ \"_id\" : ObjectId(\"5c92b81836de59bd9de063a0\") }" } ]
How to set div with left image and button at bottom using bootstrap?
05 May, 2022 We can set div with left image and button at the bottom by two methods as follows: Method 1: Using bootstrap Float-left These utility classes float-left a component to the left or disable floating, based on the current viewport size utilizing the CSS float property. !important is included to dodge (avoid) specificity issues. These utilize the same viewport breakpoints as our grid system. Position-relative: It is same as CSS property position: relative. Position-absolute: It is same as CSS property position: absolute. Example: HTML <!DOCTYPE html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"/> <script src="https://kit.fontawesome.com/577845f6a5.js" crossorigin="anonymous"> </script> <title>Set div with left image </title> <style type="text/css"> .bottom-left { left: 0; } </style></head><body> <h1 style="color: #006400;"> <br/> GeeksforGeeks </h1> <div class="float-left"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG" height="150"/> </div> <div class="position-relative" style="color: green;"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p>Here I have used class float-left of bootstrap to set div with left image.</p> <br/> </div> <div class="position-relative"> <div class="position-absolute bottom-left"> <button type="button" class="btn btn-success"> Click me! </button> </div> </div></body></html> Output: Note: If your content is less then kindly place <br> tag at end of content or else button will misplace as it is position-relative to content. Using bootstrap 3 we can set div with left image & button at the bottom and right image & button at the bottom by a bootstrap grid system too as follows: Example: HTML <!DOCTYPE html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <!-- Bootstrap CSS --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous" /> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"> </script> <title>Set div with left image</title> <style type="text/css"> .bottom-left { left: 0; } .bottom-right { right: 0; } </style></head><body> <div class="container-fluid"> <div class="col-md-6"> <div class="pull-right"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG" height="150" /> </div> <div style="color: green; text-align: left;"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p>Here I have used class pull-right of bootstrap to set div with right image. </p> <br/> <br/> </div> <div class="pull-right bottom-right"> <button type="button" class="btn btn-success"> Click me! </button> </div> </div> <div class="col-md-6"> <div class="pull-left"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG" height="150" /> </div> <div style="color: green; text-align: right;"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p> Here I have used class pull-left of bootstrap to set div with left image. </p> <br/> <br/> </div> <div class="pull-left bottom-left"> <button type="button" class="btn btn-success"> Click me! </button> </div> </div> </div></body></html> Output: Note: Due to the bootstrap grid system output will look different when code will be run on IDE hence run this code on your source. Method 2: Using Flexbox Example: HTML <!DOCTYPE html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <title>Set div with left image</title> <style type="text/css"> .flex_row { display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: flex-start; align-content: stretch; align-items: flex-start; } .article { box-sizing: border-box; flex: 1 1 50%; align-self: stretch; padding: 10px; } .content { box-sizing: border-box; flex: 1 1 auto; align-self: stretch; padding: 0 10px; display: flex; flex-direction: column; flex-wrap: nowrap; } .innercontent { flex: 1 1 auto; align-self: stretch; color: green; } .buttonBar { flex: 0 0 auto; } .onRight { text-align: left; } </style></head><body> <h1 style="color: #006400;"> <br /> GeeksforGeeks </h1> <div class="flex_row"> <div class="article onRight flex_row"> <div class="image"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG" height="150" /> </div> <div class="content"> <div class="innercontent"> <h1>Hey There..!!</h1> <p> <b>This is an Example..</b> </p> <p>Here I have used Flexbox model to set div with left image and button at bottom. </p> <br/> </div> <div class="buttonBar"> <button>Click me!</button> </div> </div> </div> </div></body></html> Output: sahilintern Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 May, 2022" }, { "code": null, "e": 111, "s": 28, "text": "We can set div with left image and button at the bottom by two methods as follows:" }, { "code": null, "e": 137, "s": 111, "text": "Method 1: Using bootstrap" }, { "code": null, "e": 148, "s": 137, "text": "Float-left" }, { "code": null, "e": 419, "s": 148, "text": "These utility classes float-left a component to the left or disable floating, based on the current viewport size utilizing the CSS float property. !important is included to dodge (avoid) specificity issues. These utilize the same viewport breakpoints as our grid system." }, { "code": null, "e": 438, "s": 419, "text": "Position-relative:" }, { "code": null, "e": 485, "s": 438, "text": "It is same as CSS property position: relative." }, { "code": null, "e": 504, "s": 485, "text": "Position-absolute:" }, { "code": null, "e": 551, "s": 504, "text": "It is same as CSS property position: absolute." }, { "code": null, "e": 560, "s": 551, "text": "Example:" }, { "code": null, "e": 565, "s": 560, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Required meta tags --> <meta charset=\"utf-8\"/> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"/> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"/> <script src=\"https://kit.fontawesome.com/577845f6a5.js\" crossorigin=\"anonymous\"> </script> <title>Set div with left image </title> <style type=\"text/css\"> .bottom-left { left: 0; } </style></head><body> <h1 style=\"color: #006400;\"> <br/> GeeksforGeeks </h1> <div class=\"float-left\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG\" height=\"150\"/> </div> <div class=\"position-relative\" style=\"color: green;\"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p>Here I have used class float-left of bootstrap to set div with left image.</p> <br/> </div> <div class=\"position-relative\"> <div class=\"position-absolute bottom-left\"> <button type=\"button\" class=\"btn btn-success\"> Click me! </button> </div> </div></body></html>", "e": 1998, "s": 565, "text": null }, { "code": null, "e": 2006, "s": 1998, "text": "Output:" }, { "code": null, "e": 2149, "s": 2006, "text": "Note: If your content is less then kindly place <br> tag at end of content or else button will misplace as it is position-relative to content." }, { "code": null, "e": 2303, "s": 2149, "text": "Using bootstrap 3 we can set div with left image & button at the bottom and right image & button at the bottom by a bootstrap grid system too as follows:" }, { "code": null, "e": 2312, "s": 2303, "text": "Example:" }, { "code": null, "e": 2317, "s": 2312, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"/> <!-- Bootstrap CSS --> <!-- Latest compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\"/> <!-- Optional theme --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css\" integrity=\"sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp\" crossorigin=\"anonymous\" /> <!-- Latest compiled and minified JavaScript --> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"> </script> <title>Set div with left image</title> <style type=\"text/css\"> .bottom-left { left: 0; } .bottom-right { right: 0; } </style></head><body> <div class=\"container-fluid\"> <div class=\"col-md-6\"> <div class=\"pull-right\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG\" height=\"150\" /> </div> <div style=\"color: green; text-align: left;\"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p>Here I have used class pull-right of bootstrap to set div with right image. </p> <br/> <br/> </div> <div class=\"pull-right bottom-right\"> <button type=\"button\" class=\"btn btn-success\"> Click me! </button> </div> </div> <div class=\"col-md-6\"> <div class=\"pull-left\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG\" height=\"150\" /> </div> <div style=\"color: green; text-align: right;\"> <h1>Hey There..!!</h1> <p><b>This is an Example..</b></p> <p> Here I have used class pull-left of bootstrap to set div with left image. </p> <br/> <br/> </div> <div class=\"pull-left bottom-left\"> <button type=\"button\" class=\"btn btn-success\"> Click me! </button> </div> </div> </div></body></html>", "e": 5189, "s": 2317, "text": null }, { "code": null, "e": 5197, "s": 5189, "text": "Output:" }, { "code": null, "e": 5328, "s": 5197, "text": "Note: Due to the bootstrap grid system output will look different when code will be run on IDE hence run this code on your source." }, { "code": null, "e": 5352, "s": 5328, "text": "Method 2: Using Flexbox" }, { "code": null, "e": 5361, "s": 5352, "text": "Example:" }, { "code": null, "e": 5366, "s": 5361, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /> <title>Set div with left image</title> <style type=\"text/css\"> .flex_row { display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: flex-start; align-content: stretch; align-items: flex-start; } .article { box-sizing: border-box; flex: 1 1 50%; align-self: stretch; padding: 10px; } .content { box-sizing: border-box; flex: 1 1 auto; align-self: stretch; padding: 0 10px; display: flex; flex-direction: column; flex-wrap: nowrap; } .innercontent { flex: 1 1 auto; align-self: stretch; color: green; } .buttonBar { flex: 0 0 auto; } .onRight { text-align: left; } </style></head><body> <h1 style=\"color: #006400;\"> <br /> GeeksforGeeks </h1> <div class=\"flex_row\"> <div class=\"article onRight flex_row\"> <div class=\"image\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200712114621/testimg.JPG\" height=\"150\" /> </div> <div class=\"content\"> <div class=\"innercontent\"> <h1>Hey There..!!</h1> <p> <b>This is an Example..</b> </p> <p>Here I have used Flexbox model to set div with left image and button at bottom. </p> <br/> </div> <div class=\"buttonBar\"> <button>Click me!</button> </div> </div> </div> </div></body></html>", "e": 7434, "s": 5366, "text": null }, { "code": null, "e": 7442, "s": 7434, "text": "Output:" }, { "code": null, "e": 7454, "s": 7442, "text": "sahilintern" }, { "code": null, "e": 7469, "s": 7454, "text": "Bootstrap-Misc" }, { "code": null, "e": 7476, "s": 7469, "text": "Picked" }, { "code": null, "e": 7486, "s": 7476, "text": "Bootstrap" }, { "code": null, "e": 7503, "s": 7486, "text": "Web Technologies" }, { "code": null, "e": 7601, "s": 7503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7651, "s": 7601, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 7680, "s": 7651, "text": "Form validation using jQuery" }, { "code": null, "e": 7721, "s": 7680, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 7777, "s": 7721, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 7818, "s": 7777, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 7851, "s": 7818, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7913, "s": 7851, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7974, "s": 7913, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8024, "s": 7974, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program for cube sum of first n natural numbers
17 Mar, 2022 Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.Examples: Input : n = 5 Output : 225 13 + 23 + 33 + 43 + 53 = 225 Input : n = 7 Output : 784 13 + 23 + 33 + 43 + 53 + 63 + 73 = 784 Java Java // Simple Java program to find sum of series// with cubes of first n natural numbers import java.util.*;import java.lang.*;class GFG{ /* Returns the sum of series */ public static int sumOfSeries(int n) { int sum = 0; for (int x=1; x<=n; x++) sum += x*x*x; return sum; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)> Output : 225 Time Complexity : O(n) An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2 For n = 5 sum by formula is (5*(5 + 1 ) / 2)) ^ 2 = (5*6/2) ^ 2 = (15) ^ 2 = 225 For n = 7, sum by formula is (7*(7 + 1 ) / 2)) ^ 2 = (7*8/2) ^ 2 = (28) ^ 2 = 784 Java Java // A formula based Java program to find sum// of series with cubes of first n natural// numbers import java.util.*;import java.lang.*;class GFG{ /* Returns the sum of series */ public static int sumOfSeries(int n) { int x = (n * (n + 1) / 2); return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)> Output: 225 Time Complexity : O(1) How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1. Let the formula be true for n = k-1. Sum of first (k-1) natural numbers = [((k - 1) * k)/2]2 Sum of first k natural numbers = = Sum of (k-1) numbers + k3 = [((k - 1) * k)/2]2 + k3 = [k2(k2 - 2k + 1) + 4k3]/4 = [k4 + 2k3 + k2]/4 = k2(k2 + 2k + 1)/4 = [k*(k+1)/2]2 The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first. Java Java // Efficient Java program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be within// limits.import java.util.*;import java.lang.*;class GFG{ /* Returns the sum of series */ public static int sumOfSeries(int n) { int x; if (n % 2 == 0) x = (n/2) * (n+1); else x = ((n + 1) / 2) * n; return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }}// Code Contributed by Mohit Gupta_OMG <(0_o)> Output: 225 Please refer complete article on Program for cube sum of first n natural numbers for more details! surinderdawra388 maths-cube Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Mar, 2022" }, { "code": null, "e": 135, "s": 52, "text": "Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.Examples: " }, { "code": null, "e": 259, "s": 135, "text": "Input : n = 5\nOutput : 225\n13 + 23 + 33 + 43 + 53 = 225\n\nInput : n = 7\nOutput : 784\n13 + 23 + 33 + 43 + 53 + \n63 + 73 = 784" }, { "code": null, "e": 264, "s": 259, "text": "Java" }, { "code": null, "e": 269, "s": 264, "text": "Java" }, { "code": "// Simple Java program to find sum of series// with cubes of first n natural numbers import java.util.*;import java.lang.*;class GFG{ /* Returns the sum of series */ public static int sumOfSeries(int n) { int sum = 0; for (int x=1; x<=n; x++) sum += x*x*x; return sum; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 766, "s": 269, "text": null }, { "code": null, "e": 776, "s": 766, "text": "Output : " }, { "code": null, "e": 780, "s": 776, "text": "225" }, { "code": null, "e": 896, "s": 780, "text": "Time Complexity : O(n) An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2 " }, { "code": null, "e": 1134, "s": 896, "text": "For n = 5 sum by formula is\n (5*(5 + 1 ) / 2)) ^ 2\n = (5*6/2) ^ 2\n = (15) ^ 2\n = 225\n\nFor n = 7, sum by formula is\n (7*(7 + 1 ) / 2)) ^ 2\n = (7*8/2) ^ 2\n = (28) ^ 2\n = 784" }, { "code": null, "e": 1139, "s": 1134, "text": "Java" }, { "code": null, "e": 1144, "s": 1139, "text": "Java" }, { "code": "// A formula based Java program to find sum// of series with cubes of first n natural// numbers import java.util.*;import java.lang.*;class GFG{ /* Returns the sum of series */ public static int sumOfSeries(int n) { int x = (n * (n + 1) / 2); return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 1620, "s": 1144, "text": null }, { "code": null, "e": 1629, "s": 1620, "text": "Output: " }, { "code": null, "e": 1633, "s": 1629, "text": "225" }, { "code": null, "e": 1838, "s": 1633, "text": "Time Complexity : O(1) How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1. " }, { "code": null, "e": 2176, "s": 1838, "text": "Let the formula be true for n = k-1.\nSum of first (k-1) natural numbers = \n [((k - 1) * k)/2]2\n\nSum of first k natural numbers = \n = Sum of (k-1) numbers + k3\n = [((k - 1) * k)/2]2 + k3\n = [k2(k2 - 2k + 1) + 4k3]/4\n = [k4 + 2k3 + k2]/4\n = k2(k2 + 2k + 1)/4\n = [k*(k+1)/2]2" }, { "code": null, "e": 2340, "s": 2176, "text": "The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first. " }, { "code": null, "e": 2345, "s": 2340, "text": "Java" }, { "code": null, "e": 2350, "s": 2345, "text": "Java" }, { "code": "// Efficient Java program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be within// limits.import java.util.*;import java.lang.*;class GFG{ /* Returns the sum of series */ public static int sumOfSeries(int n) { int x; if (n % 2 == 0) x = (n/2) * (n+1); else x = ((n + 1) / 2) * n; return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }}// Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 2937, "s": 2350, "text": null }, { "code": null, "e": 2946, "s": 2937, "text": "Output: " }, { "code": null, "e": 2950, "s": 2946, "text": "225" }, { "code": null, "e": 3050, "s": 2950, "text": "Please refer complete article on Program for cube sum of first n natural numbers for more details! " }, { "code": null, "e": 3067, "s": 3050, "text": "surinderdawra388" }, { "code": null, "e": 3078, "s": 3067, "text": "maths-cube" }, { "code": null, "e": 3092, "s": 3078, "text": "Java Programs" } ]
Python | Check if a list is contained in another list
21 Nov, 2019 Given two lists A and B, write a Python program to Check if list A is contained in list B without breaking A’s order. Examples: Input : A = [1, 2], B = [1, 2, 3, 1, 1, 2, 2] Output : True Input : A = ['x', 'y', 'z'], B = ['x', 'a', 'y', 'x', 'b', 'z'] Output : False Approach #1 : Naive Approach A simple naive approach is to use two for loops and check if the whole list A is contained within list B or not. If such a position is met in list A, then break the loop and return true, otherwise false # Python3 program to Check if a list is # contained in another list without breaking order def removeElements(A, B): for i in range(len(B)-len(A)+1): for j in range(len(A)): if B[i + j] != A[j]: break else: return True return False # Driver codeA = [1, 2]B = [1, 2, 3, 1, 1, 2, 2]print(removeElements(A, B)) True Approach #2 : List comprehension A more efficient approach is to use List comprehension. We first initialize ‘n’ with length of A. Now use a for loop till len(B)-n and check in each iteration if A == B[i:i+n] or not. # Python3 program to Remove elements of # list that repeated less than k times def removeElements(A, B): n = len(A) return any(A == B[i:i + n] for i in range(len(B)-n + 1)) # Driver codeA = [1, 2]B = [1, 2, 3, 1, 1, 2, 2]print(removeElements(A, B)) True Approach #3 : Using join and map module Here we use join to join both lists to strings and then use in operator to check if list A is contained in B or not. # Python3 program to Remove elements of # list that repeated less than k times def removeElements(A, B): return ', '.join(map(str, A)) in ', '.join(map(str, B)) # Driver codeA = ['x', 'y', 'z']B = ['x', 'a', 'y', 'x', 'b', 'z']print(removeElements(A, B)) False ManasChhabra2 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 ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2019" }, { "code": null, "e": 146, "s": 28, "text": "Given two lists A and B, write a Python program to Check if list A is contained in list B without breaking A’s order." }, { "code": null, "e": 156, "s": 146, "text": "Examples:" }, { "code": null, "e": 297, "s": 156, "text": "Input : A = [1, 2], B = [1, 2, 3, 1, 1, 2, 2]\nOutput : True\n\nInput : A = ['x', 'y', 'z'], B = ['x', 'a', 'y', 'x', 'b', 'z']\nOutput : False\n" }, { "code": null, "e": 327, "s": 297, "text": " Approach #1 : Naive Approach" }, { "code": null, "e": 530, "s": 327, "text": "A simple naive approach is to use two for loops and check if the whole list A is contained within list B or not. If such a position is met in list A, then break the loop and return true, otherwise false" }, { "code": "# Python3 program to Check if a list is # contained in another list without breaking order def removeElements(A, B): for i in range(len(B)-len(A)+1): for j in range(len(A)): if B[i + j] != A[j]: break else: return True return False # Driver codeA = [1, 2]B = [1, 2, 3, 1, 1, 2, 2]print(removeElements(A, B))", "e": 897, "s": 530, "text": null }, { "code": null, "e": 903, "s": 897, "text": "True\n" }, { "code": null, "e": 937, "s": 903, "text": " Approach #2 : List comprehension" }, { "code": null, "e": 1121, "s": 937, "text": "A more efficient approach is to use List comprehension. We first initialize ‘n’ with length of A. Now use a for loop till len(B)-n and check in each iteration if A == B[i:i+n] or not." }, { "code": "# Python3 program to Remove elements of # list that repeated less than k times def removeElements(A, B): n = len(A) return any(A == B[i:i + n] for i in range(len(B)-n + 1)) # Driver codeA = [1, 2]B = [1, 2, 3, 1, 1, 2, 2]print(removeElements(A, B))", "e": 1396, "s": 1121, "text": null }, { "code": null, "e": 1402, "s": 1396, "text": "True\n" }, { "code": null, "e": 1443, "s": 1402, "text": " Approach #3 : Using join and map module" }, { "code": null, "e": 1560, "s": 1443, "text": "Here we use join to join both lists to strings and then use in operator to check if list A is contained in B or not." }, { "code": "# Python3 program to Remove elements of # list that repeated less than k times def removeElements(A, B): return ', '.join(map(str, A)) in ', '.join(map(str, B)) # Driver codeA = ['x', 'y', 'z']B = ['x', 'a', 'y', 'x', 'b', 'z']print(removeElements(A, B))", "e": 1834, "s": 1560, "text": null }, { "code": null, "e": 1841, "s": 1834, "text": "False\n" }, { "code": null, "e": 1855, "s": 1841, "text": "ManasChhabra2" }, { "code": null, "e": 1876, "s": 1855, "text": "Python list-programs" }, { "code": null, "e": 1883, "s": 1876, "text": "Python" }, { "code": null, "e": 1899, "s": 1883, "text": "Python Programs" }, { "code": null, "e": 1997, "s": 1899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2029, "s": 1997, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2058, "s": 2029, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2085, "s": 2058, "text": "Python Classes and Objects" }, { "code": null, "e": 2106, "s": 2085, "text": "Python OOPs Concepts" }, { "code": null, "e": 2142, "s": 2106, "text": "Convert integer to string in Python" }, { "code": null, "e": 2164, "s": 2142, "text": "Defaultdict in Python" }, { "code": null, "e": 2203, "s": 2164, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2241, "s": 2203, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2290, "s": 2241, "text": "Python | Convert string dictionary to dictionary" } ]
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
28 Apr, 2022 In Set 1, unweighted graph is discussed. In this post, weighted graph representation using STL is discussed. The implementation is for adjacency list representation of weighted graph. Undirected Weighted Graph We use two STL containers to represent graph: vector : A sequence container. Here we use it to store adjacency lists of all vertices. We use vertex number as index in this vector. pair : A simple container to store pair of elements. Here we use it to store adjacent vertex number and weight of edge connecting to the adjacent. The idea is to use a vector of pair vectors. Below code implements the same. C++ Python3 Javascript // C++ program to represent undirected and weighted graph// using STL. The program basically prints adjacency list// representation of graph#include <bits/stdc++.h>using namespace std; // To add an edgevoid addEdge(vector <pair<int, int> > adj[], int u, int v, int wt){ adj[u].push_back(make_pair(v, wt)); adj[v].push_back(make_pair(u, wt));} // Print adjacency list representation of graphvoid printGraph(vector<pair<int,int> > adj[], int V){ int v, w; for (int u = 0; u < V; u++) { cout << "Node " << u << " makes an edge with \n"; for (auto it = adj[u].begin(); it!=adj[u].end(); it++) { v = it->first; w = it->second; cout << "\tNode " << v << " with edge weight =" << w << "\n"; } cout << "\n"; }} // Driver codeint main(){ int V = 5; vector<pair<int, int> > adj[V]; addEdge(adj, 0, 1, 10); addEdge(adj, 0, 4, 20); addEdge(adj, 1, 2, 30); addEdge(adj, 1, 3, 40); addEdge(adj, 1, 4, 50); addEdge(adj, 2, 3, 60); addEdge(adj, 3, 4, 70); printGraph(adj, V); return 0;} # Python3 program to represent undirected# and weighted graph. The program basically# prints adjacency list representation of graph # To add an edgedef addEdge(adj, u, v, wt): adj[u].append([v, wt]) adj[v].append([u, wt]) return adj # Print adjacency list representation of graphdef printGraph(adj, V): v, w = 0, 0 for u in range(V): print("Node", u, "makes an edge with") for it in adj[u]: v = it[0] w = it[1] print("\tNode", v, "with edge weight =", w) print() # Driver codeif __name__ == '__main__': V = 5 adj = [[] for i in range(V)] adj = addEdge(adj, 0, 1, 10) adj = addEdge(adj, 0, 4, 20) adj = addEdge(adj, 1, 2, 30) adj = addEdge(adj, 1, 3, 40) adj = addEdge(adj, 1, 4, 50) adj = addEdge(adj, 2, 3, 60) adj = addEdge(adj, 3, 4, 70) printGraph(adj, V) # This code is contributed by mohit kumar 29 <script>// Javascript program to represent undirected and weighted graph// using STL. The program basically prints adjacency list// representation of graph // To add an edge function addEdge(adj,u,v,wt) { adj[u].push([v,wt]); adj[v].push([u,wt]); return adj; } //Print adjacency list representation of graph function printGraph(adj, V) { let v=0,w=0; for(let u=0;u<V;u++) { document.write("Node "+u+ " makes an edge with<br>"); for(let it=0;it<adj[u].length;it++) { v=adj[u][it][0]; w=adj[u][it][1]; document.write(" Node "+ v+ " with edge weight ="+ w+"<br>") } } } // Driver code let V = 5; // The below line may not work on all // compilers. If it does not work on // your compiler, please replace it with // following // vector<int> *adj = new vector<int>[V]; let adj=new Array(V); for(let i=0;i<V;i++) { adj[i]=[]; } // Vertex numbers should be from 0 to 4. adj = addEdge(adj, 0, 1, 10) adj = addEdge(adj, 0, 4, 20) adj = addEdge(adj, 1, 2, 30) adj = addEdge(adj, 1, 3, 40) adj = addEdge(adj, 1, 4, 50) adj = addEdge(adj, 2, 3, 60) adj = addEdge(adj, 3, 4, 70) printGraph(adj, V); // This code is contributed by unknown2108</script> Output: Node 0 makes an edge with Node 1 with edge weight =10 Node 4 with edge weight =20 Node 1 makes an edge with Node 0 with edge weight =10 Node 2 with edge weight =30 Node 3 with edge weight =40 Node 4 with edge weight =50 Node 2 makes an edge with Node 1 with edge weight =30 Node 3 with edge weight =60 Node 3 makes an edge with Node 1 with edge weight =40 Node 2 with edge weight =60 Node 4 with edge weight =70 Node 4 makes an edge with Node 0 with edge weight =20 Node 1 with edge weight =50 Node 3 with edge weight =70 This article is contributed by Sahil Chhabra. and improved by Kunal Verma If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Ritesh Ghorse mohit kumar 29 unknown2108 2020kucp1093 simmytarika5 surinderdawra388 STL Competitive Programming Graph Graph STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Bitwise Hacks for Competitive Programming Algorithm Library | C++ Magicians STL Algorithm 7 Best Coding Challenge Websites in 2020 Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Topological Sorting Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2022" }, { "code": null, "e": 237, "s": 52, "text": "In Set 1, unweighted graph is discussed. In this post, weighted graph representation using STL is discussed. The implementation is for adjacency list representation of weighted graph. " }, { "code": null, "e": 263, "s": 237, "text": "Undirected Weighted Graph" }, { "code": null, "e": 310, "s": 263, "text": "We use two STL containers to represent graph: " }, { "code": null, "e": 444, "s": 310, "text": "vector : A sequence container. Here we use it to store adjacency lists of all vertices. We use vertex number as index in this vector." }, { "code": null, "e": 591, "s": 444, "text": "pair : A simple container to store pair of elements. Here we use it to store adjacent vertex number and weight of edge connecting to the adjacent." }, { "code": null, "e": 668, "s": 591, "text": "The idea is to use a vector of pair vectors. Below code implements the same." }, { "code": null, "e": 672, "s": 668, "text": "C++" }, { "code": null, "e": 680, "s": 672, "text": "Python3" }, { "code": null, "e": 691, "s": 680, "text": "Javascript" }, { "code": "// C++ program to represent undirected and weighted graph// using STL. The program basically prints adjacency list// representation of graph#include <bits/stdc++.h>using namespace std; // To add an edgevoid addEdge(vector <pair<int, int> > adj[], int u, int v, int wt){ adj[u].push_back(make_pair(v, wt)); adj[v].push_back(make_pair(u, wt));} // Print adjacency list representation of graphvoid printGraph(vector<pair<int,int> > adj[], int V){ int v, w; for (int u = 0; u < V; u++) { cout << \"Node \" << u << \" makes an edge with \\n\"; for (auto it = adj[u].begin(); it!=adj[u].end(); it++) { v = it->first; w = it->second; cout << \"\\tNode \" << v << \" with edge weight =\" << w << \"\\n\"; } cout << \"\\n\"; }} // Driver codeint main(){ int V = 5; vector<pair<int, int> > adj[V]; addEdge(adj, 0, 1, 10); addEdge(adj, 0, 4, 20); addEdge(adj, 1, 2, 30); addEdge(adj, 1, 3, 40); addEdge(adj, 1, 4, 50); addEdge(adj, 2, 3, 60); addEdge(adj, 3, 4, 70); printGraph(adj, V); return 0;}", "e": 1833, "s": 691, "text": null }, { "code": "# Python3 program to represent undirected# and weighted graph. The program basically# prints adjacency list representation of graph # To add an edgedef addEdge(adj, u, v, wt): adj[u].append([v, wt]) adj[v].append([u, wt]) return adj # Print adjacency list representation of graphdef printGraph(adj, V): v, w = 0, 0 for u in range(V): print(\"Node\", u, \"makes an edge with\") for it in adj[u]: v = it[0] w = it[1] print(\"\\tNode\", v, \"with edge weight =\", w) print() # Driver codeif __name__ == '__main__': V = 5 adj = [[] for i in range(V)] adj = addEdge(adj, 0, 1, 10) adj = addEdge(adj, 0, 4, 20) adj = addEdge(adj, 1, 2, 30) adj = addEdge(adj, 1, 3, 40) adj = addEdge(adj, 1, 4, 50) adj = addEdge(adj, 2, 3, 60) adj = addEdge(adj, 3, 4, 70) printGraph(adj, V) # This code is contributed by mohit kumar 29", "e": 2768, "s": 1833, "text": null }, { "code": "<script>// Javascript program to represent undirected and weighted graph// using STL. The program basically prints adjacency list// representation of graph // To add an edge function addEdge(adj,u,v,wt) { adj[u].push([v,wt]); adj[v].push([u,wt]); return adj; } //Print adjacency list representation of graph function printGraph(adj, V) { let v=0,w=0; for(let u=0;u<V;u++) { document.write(\"Node \"+u+ \" makes an edge with<br>\"); for(let it=0;it<adj[u].length;it++) { v=adj[u][it][0]; w=adj[u][it][1]; document.write(\" Node \"+ v+ \" with edge weight =\"+ w+\"<br>\") } } } // Driver code let V = 5; // The below line may not work on all // compilers. If it does not work on // your compiler, please replace it with // following // vector<int> *adj = new vector<int>[V]; let adj=new Array(V); for(let i=0;i<V;i++) { adj[i]=[]; } // Vertex numbers should be from 0 to 4. adj = addEdge(adj, 0, 1, 10) adj = addEdge(adj, 0, 4, 20) adj = addEdge(adj, 1, 2, 30) adj = addEdge(adj, 1, 3, 40) adj = addEdge(adj, 1, 4, 50) adj = addEdge(adj, 2, 3, 60) adj = addEdge(adj, 3, 4, 70) printGraph(adj, V); // This code is contributed by unknown2108</script>", "e": 4194, "s": 2768, "text": null }, { "code": null, "e": 4203, "s": 4194, "text": "Output: " }, { "code": null, "e": 4790, "s": 4203, "text": "Node 0 makes an edge with \n Node 1 with edge weight =10\n Node 4 with edge weight =20\n\nNode 1 makes an edge with \n Node 0 with edge weight =10\n Node 2 with edge weight =30\n Node 3 with edge weight =40\n Node 4 with edge weight =50\n\nNode 2 makes an edge with \n Node 1 with edge weight =30\n Node 3 with edge weight =60\n\nNode 3 makes an edge with \n Node 1 with edge weight =40\n Node 2 with edge weight =60\n Node 4 with edge weight =70\n\nNode 4 makes an edge with \n Node 0 with edge weight =20\n Node 1 with edge weight =50\n Node 3 with edge weight =70" }, { "code": null, "e": 5240, "s": 4790, "text": "This article is contributed by Sahil Chhabra. and improved by Kunal Verma If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5254, "s": 5240, "text": "Ritesh Ghorse" }, { "code": null, "e": 5269, "s": 5254, "text": "mohit kumar 29" }, { "code": null, "e": 5281, "s": 5269, "text": "unknown2108" }, { "code": null, "e": 5294, "s": 5281, "text": "2020kucp1093" }, { "code": null, "e": 5307, "s": 5294, "text": "simmytarika5" }, { "code": null, "e": 5324, "s": 5307, "text": "surinderdawra388" }, { "code": null, "e": 5328, "s": 5324, "text": "STL" }, { "code": null, "e": 5352, "s": 5328, "text": "Competitive Programming" }, { "code": null, "e": 5358, "s": 5352, "text": "Graph" }, { "code": null, "e": 5364, "s": 5358, "text": "Graph" }, { "code": null, "e": 5368, "s": 5364, "text": "STL" }, { "code": null, "e": 5466, "s": 5368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5504, "s": 5466, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 5563, "s": 5504, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 5605, "s": 5563, "text": "Bitwise Hacks for Competitive Programming" }, { "code": null, "e": 5653, "s": 5605, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 5694, "s": 5653, "text": "7 Best Coding Challenge Websites in 2020" }, { "code": null, "e": 5745, "s": 5694, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 5796, "s": 5745, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 5816, "s": 5796, "text": "Topological Sorting" }, { "code": null, "e": 5881, "s": 5816, "text": "Find if there is a path between two vertices in a directed graph" } ]
5 Different Meanings of Underscore in Python | by Xiaoxu Gao | Towards Data Science
If you are a Python programmer, you are probably familiar with underscores. Python works with two types of underscore: single underscore _ and double underscores __. Don’t underestimate the underscore in Python, it’s a very powerful syntax. In this article, I will talk about 5 different underscore patterns. Single standalone underscore _ is a valid character for a Python identifier, so it can be used as a variable name. Represent the last expression in the interpreter Represent the last expression in the interpreter According to Python doc, the special identifier _ is used in the interactive interpreter to store the result of the last evaluation. It is stored in the builtin module. Here is an example. At first, we check that _ is not stored in the builtin module, then we write a single expression without a variable name. If we check the builtin module again, we will find _ in the module and the value is the last evaluation. >>> '_' in dir(__builtins__)False>>> 1+12>>> '_' in dir(__builtins__)True>>> _2 2. Represent the values that we don’t care Another use case of single underscore _ is to represent the value that you don’t care or will not be used later in the program. If you apply a linter like Flake8 to your program, you will get an error from the linter (F841) if you have a variable name assigned but never used. Assigning variables that you don’t care to _ can solve this problem. Let’s see some code. Example1 uses _ to represent the index of each element in a list. In Example2, we only care about year, month and day from the tuple, so we assign _ to the rest (hour, minute, second). But if we print out _, we will only get the last expression which is 59. From Python 3.*, it supports extended iterable unpacking which means we can use *_ to represent multiple values. In Example3, _ actually represents a list of values that we want to ignore. Lambda function also supports _. In Example4, lambda function is used to monkeypatch function random.randint, and will always generate the same output. In this case, the input argument is not important anymore. 3. Visual separator for digit grouping purposes From Python 3.6, underscore _ can also be used as a visual separator for digit grouping purposes. As stated in PEP515, it works for integers, floating-point, and complex number literals. integer = 1_000amount = 1_000_000.1binary = 0b_0100_1110hex = 0xCAFE_F00D>>> print(amount)1000000.1>>> print(binary)78>>> print(hex)3405705229 According to PEP8, single leading underscore _var is intended for internal use. from M import * doesn’t import objects whose names start with an underscore. _ in front of a variable or method name is a weak internal use indicator. It warns the developer that this variable, method, or function is not supposed to be imported and used publicly. Nevertheless, Python doesn’t completely prevent them from being imported and used. In the following example, we have a public variable external and a private variable _internal. If we do wildcard import from m import *, it doesn’t include _internal variable (main1.py). But it works if we import _internal explicitly (main2.py) or use regular import (main3.py). Single leading underscore is used a lot in classes. Programmers can create private variables and methods, but like the previous examples, these variables and methods can still be used from the outside. In general, the single leading underscore is only a naming convention to indicate the variable or function is for internal use. Programmers are still able to import the name if they really want. There is only one reason to use single trailing underscore which is to avoid conflicts with Python keywords. This is also mentioned in PEP8. We can use keyword module to check the list of keywords in Python. If you want to have a variable name called global, then you should name it gloabl_. The patterns we’ve discussed so far are basically different naming conventions, but with a double leading underscore, Python will behave somewhat differently. Python interpreter will do name mangling to identifiers with leading underscores. Name mangling is the process to overwrite such identifiers in a class to avoid conflicts of names between the current class and its subclasses. In summary, __var will have a different name in the class. Let’s look at the following example. The example uses built-in function dir to return the list of names in the current local scope. At the end of the list, we see _hour, day, month and year, which means we can directly retrieve these attributes by time._hour or time.year. However, for __minute, it has another story. Its name is overwritten to _Time__minute. This will have 2 consequences: Attribute __day is not accessible outside class Time. As you can see, __day is not recognized by the class Time, and it is replaced with _Time__day. Attribute __day is not accessible outside class Time. As you can see, __day is not recognized by the class Time, and it is replaced with _Time__day. print(time.__day)# AttributeError: 'Time' object has no attribute '__day'print(time._Time__day)# 10 2. Attribute __day can’t be overwritten in the subclasses of Time. In the example below, we create a subclass TimeSubClass which is extended from class Time, and use dir to check the local names. In the output, you can find _TimeSubclass__day, _Time__day, _month and year. It means that _month and year have been overwritten with new values, but not for __day. Let’s check the values. _TimeSubclass__day is assigned with the new value, and _Time__day still has the original value. print(time_subclass._TimeSubclass__day)# 30print(time_subclass._Time__day)# 1 Although you can’t get the value via direct access, you can still get the value via a method, and in the method, you return self.__day. It also works for @property. Unlike single trailing underscore, there is no special meaning for double trailing underscores. You can probably think of var__ as an extension of var_. However, double leading and trailing underscore __var__ is completely different and it’s a very important pattern in Python. Python doesn’t apply name mangling to such attributes, but names with double leading and trailing underscores are reserved for special use in Python. They are called Magic Names. You can check Python documentation to get a list of magic names. Names like __init__, __call__, __slots__ are all magic methods. These magic attributes and magic methods are allowed to be overwritten, but you need to know what you are doing. Let’s look at an example. __str__ is a method that returns the string representation of the object. This method is called when you do print() or str(). In the example, we overwrite the string presentation, then we will get a new format in the output. You are allowed to have a customized name with double leading and trailing underscore like __day__. Python will just take it as a regular attribute name and will not apply name mangling on it. However, it’s not a good practice to have a name like this without a strong reason. In this article, we’ve discussed 5 different patterns of underscore in Python. Let’s summarize it. Single standalone underscore _ & Single leading underscore _var & Single trailing underscore var_. Single standalone underscore _ & Single leading underscore _var & Single trailing underscore var_. Patterns with a single underscore are basically naming conventions. Python interpreter doesn’t prevent them from being imported and used outside the module/class. 2. Double leading underscores __var & Double leading and trailing underscores __var__. Patterns with double underscores are more strict. They are either not allowed to be overwritten or need a good reason to do so. Please notice that there is no special meaning for double trailing underscores var__. I hope you enjoyed this article! Leave your comments below if you have any thoughts.
[ { "code": null, "e": 480, "s": 171, "text": "If you are a Python programmer, you are probably familiar with underscores. Python works with two types of underscore: single underscore _ and double underscores __. Don’t underestimate the underscore in Python, it’s a very powerful syntax. In this article, I will talk about 5 different underscore patterns." }, { "code": null, "e": 595, "s": 480, "text": "Single standalone underscore _ is a valid character for a Python identifier, so it can be used as a variable name." }, { "code": null, "e": 644, "s": 595, "text": "Represent the last expression in the interpreter" }, { "code": null, "e": 693, "s": 644, "text": "Represent the last expression in the interpreter" }, { "code": null, "e": 862, "s": 693, "text": "According to Python doc, the special identifier _ is used in the interactive interpreter to store the result of the last evaluation. It is stored in the builtin module." }, { "code": null, "e": 1109, "s": 862, "text": "Here is an example. At first, we check that _ is not stored in the builtin module, then we write a single expression without a variable name. If we check the builtin module again, we will find _ in the module and the value is the last evaluation." }, { "code": null, "e": 1189, "s": 1109, "text": ">>> '_' in dir(__builtins__)False>>> 1+12>>> '_' in dir(__builtins__)True>>> _2" }, { "code": null, "e": 1232, "s": 1189, "text": "2. Represent the values that we don’t care" }, { "code": null, "e": 1578, "s": 1232, "text": "Another use case of single underscore _ is to represent the value that you don’t care or will not be used later in the program. If you apply a linter like Flake8 to your program, you will get an error from the linter (F841) if you have a variable name assigned but never used. Assigning variables that you don’t care to _ can solve this problem." }, { "code": null, "e": 1857, "s": 1578, "text": "Let’s see some code. Example1 uses _ to represent the index of each element in a list. In Example2, we only care about year, month and day from the tuple, so we assign _ to the rest (hour, minute, second). But if we print out _, we will only get the last expression which is 59." }, { "code": null, "e": 2046, "s": 1857, "text": "From Python 3.*, it supports extended iterable unpacking which means we can use *_ to represent multiple values. In Example3, _ actually represents a list of values that we want to ignore." }, { "code": null, "e": 2257, "s": 2046, "text": "Lambda function also supports _. In Example4, lambda function is used to monkeypatch function random.randint, and will always generate the same output. In this case, the input argument is not important anymore." }, { "code": null, "e": 2305, "s": 2257, "text": "3. Visual separator for digit grouping purposes" }, { "code": null, "e": 2492, "s": 2305, "text": "From Python 3.6, underscore _ can also be used as a visual separator for digit grouping purposes. As stated in PEP515, it works for integers, floating-point, and complex number literals." }, { "code": null, "e": 2635, "s": 2492, "text": "integer = 1_000amount = 1_000_000.1binary = 0b_0100_1110hex = 0xCAFE_F00D>>> print(amount)1000000.1>>> print(binary)78>>> print(hex)3405705229" }, { "code": null, "e": 2792, "s": 2635, "text": "According to PEP8, single leading underscore _var is intended for internal use. from M import * doesn’t import objects whose names start with an underscore." }, { "code": null, "e": 3062, "s": 2792, "text": "_ in front of a variable or method name is a weak internal use indicator. It warns the developer that this variable, method, or function is not supposed to be imported and used publicly. Nevertheless, Python doesn’t completely prevent them from being imported and used." }, { "code": null, "e": 3341, "s": 3062, "text": "In the following example, we have a public variable external and a private variable _internal. If we do wildcard import from m import *, it doesn’t include _internal variable (main1.py). But it works if we import _internal explicitly (main2.py) or use regular import (main3.py)." }, { "code": null, "e": 3543, "s": 3341, "text": "Single leading underscore is used a lot in classes. Programmers can create private variables and methods, but like the previous examples, these variables and methods can still be used from the outside." }, { "code": null, "e": 3738, "s": 3543, "text": "In general, the single leading underscore is only a naming convention to indicate the variable or function is for internal use. Programmers are still able to import the name if they really want." }, { "code": null, "e": 3879, "s": 3738, "text": "There is only one reason to use single trailing underscore which is to avoid conflicts with Python keywords. This is also mentioned in PEP8." }, { "code": null, "e": 4030, "s": 3879, "text": "We can use keyword module to check the list of keywords in Python. If you want to have a variable name called global, then you should name it gloabl_." }, { "code": null, "e": 4189, "s": 4030, "text": "The patterns we’ve discussed so far are basically different naming conventions, but with a double leading underscore, Python will behave somewhat differently." }, { "code": null, "e": 4415, "s": 4189, "text": "Python interpreter will do name mangling to identifiers with leading underscores. Name mangling is the process to overwrite such identifiers in a class to avoid conflicts of names between the current class and its subclasses." }, { "code": null, "e": 4747, "s": 4415, "text": "In summary, __var will have a different name in the class. Let’s look at the following example. The example uses built-in function dir to return the list of names in the current local scope. At the end of the list, we see _hour, day, month and year, which means we can directly retrieve these attributes by time._hour or time.year." }, { "code": null, "e": 4834, "s": 4747, "text": "However, for __minute, it has another story. Its name is overwritten to _Time__minute." }, { "code": null, "e": 4865, "s": 4834, "text": "This will have 2 consequences:" }, { "code": null, "e": 5014, "s": 4865, "text": "Attribute __day is not accessible outside class Time. As you can see, __day is not recognized by the class Time, and it is replaced with _Time__day." }, { "code": null, "e": 5163, "s": 5014, "text": "Attribute __day is not accessible outside class Time. As you can see, __day is not recognized by the class Time, and it is replaced with _Time__day." }, { "code": null, "e": 5263, "s": 5163, "text": "print(time.__day)# AttributeError: 'Time' object has no attribute '__day'print(time._Time__day)# 10" }, { "code": null, "e": 5459, "s": 5263, "text": "2. Attribute __day can’t be overwritten in the subclasses of Time. In the example below, we create a subclass TimeSubClass which is extended from class Time, and use dir to check the local names." }, { "code": null, "e": 5624, "s": 5459, "text": "In the output, you can find _TimeSubclass__day, _Time__day, _month and year. It means that _month and year have been overwritten with new values, but not for __day." }, { "code": null, "e": 5744, "s": 5624, "text": "Let’s check the values. _TimeSubclass__day is assigned with the new value, and _Time__day still has the original value." }, { "code": null, "e": 5822, "s": 5744, "text": "print(time_subclass._TimeSubclass__day)# 30print(time_subclass._Time__day)# 1" }, { "code": null, "e": 5987, "s": 5822, "text": "Although you can’t get the value via direct access, you can still get the value via a method, and in the method, you return self.__day. It also works for @property." }, { "code": null, "e": 6140, "s": 5987, "text": "Unlike single trailing underscore, there is no special meaning for double trailing underscores. You can probably think of var__ as an extension of var_." }, { "code": null, "e": 6573, "s": 6140, "text": "However, double leading and trailing underscore __var__ is completely different and it’s a very important pattern in Python. Python doesn’t apply name mangling to such attributes, but names with double leading and trailing underscores are reserved for special use in Python. They are called Magic Names. You can check Python documentation to get a list of magic names. Names like __init__, __call__, __slots__ are all magic methods." }, { "code": null, "e": 6937, "s": 6573, "text": "These magic attributes and magic methods are allowed to be overwritten, but you need to know what you are doing. Let’s look at an example. __str__ is a method that returns the string representation of the object. This method is called when you do print() or str(). In the example, we overwrite the string presentation, then we will get a new format in the output." }, { "code": null, "e": 7214, "s": 6937, "text": "You are allowed to have a customized name with double leading and trailing underscore like __day__. Python will just take it as a regular attribute name and will not apply name mangling on it. However, it’s not a good practice to have a name like this without a strong reason." }, { "code": null, "e": 7313, "s": 7214, "text": "In this article, we’ve discussed 5 different patterns of underscore in Python. Let’s summarize it." }, { "code": null, "e": 7412, "s": 7313, "text": "Single standalone underscore _ & Single leading underscore _var & Single trailing underscore var_." }, { "code": null, "e": 7511, "s": 7412, "text": "Single standalone underscore _ & Single leading underscore _var & Single trailing underscore var_." }, { "code": null, "e": 7674, "s": 7511, "text": "Patterns with a single underscore are basically naming conventions. Python interpreter doesn’t prevent them from being imported and used outside the module/class." }, { "code": null, "e": 7761, "s": 7674, "text": "2. Double leading underscores __var & Double leading and trailing underscores __var__." }, { "code": null, "e": 7975, "s": 7761, "text": "Patterns with double underscores are more strict. They are either not allowed to be overwritten or need a good reason to do so. Please notice that there is no special meaning for double trailing underscores var__." } ]
How to Create an Image Overlay Icon using HTML and CSS ? - GeeksforGeeks
01 Apr, 2020 Image overlay Icon can be an impressive addition to interactive detail or a set of features for your website. This article content will divide the task into two sections, the first section creating the structure and attach the link for the icon. In the second section, we will design the structure using CSS. Creating Structure: In this section, we will create a basic structure and also attach the CDN link of the Font-Awesome for the icons which will be used as an icon on hover. CDN links for the Icons from the Font Awesome:<link rel=”stylesheet” href= “https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”> <link rel=”stylesheet” href= “https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”> HTML code:<!DOCTYPE html><html> <head> <title> Image Overlay Icon using HTML and CSS </title> <link rel="stylesheet" href= "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></head><body> <div class="container"> <h1>GeeksforGeeks</h1> <b>Image Overlay Icon using HTML and CSS</b> <div class="img"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png" alt="Geeksforgeeks"> <div class="overlay"> <a href="#" class="icon"> <i class="fa fa-user"></i> </a> </div> </div> </div></body> </html> <!DOCTYPE html><html> <head> <title> Image Overlay Icon using HTML and CSS </title> <link rel="stylesheet" href= "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></head><body> <div class="container"> <h1>GeeksforGeeks</h1> <b>Image Overlay Icon using HTML and CSS</b> <div class="img"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png" alt="Geeksforgeeks"> <div class="overlay"> <a href="#" class="icon"> <i class="fa fa-user"></i> </a> </div> </div> </div></body> </html> Designing Structure: In the previous section, we have created the structure of the basic website where we are going to use as an image overlay icon. In this section, we will design the structure for the image overlay icon. CSS code:<style> body { text-align: center; } h1 { color: green; } /* Image styling */ img { padding: 5px; height: 225px; width: 225px; border: 2px solid gray; box-shadow: 2px 4px #888888; } /* Overlay styling */ .overlay { position: absolute; top: 23.5%; left: 32.8%; transition: .3s ease; background-color: gray; width: 225px; height: 225px; opacity: 0; } /* Overlay hover */ .container:hover .overlay { opacity: 1; } /* Icon styling */ .icon { color: white; font-size: 92px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }</style> <style> body { text-align: center; } h1 { color: green; } /* Image styling */ img { padding: 5px; height: 225px; width: 225px; border: 2px solid gray; box-shadow: 2px 4px #888888; } /* Overlay styling */ .overlay { position: absolute; top: 23.5%; left: 32.8%; transition: .3s ease; background-color: gray; width: 225px; height: 225px; opacity: 0; } /* Overlay hover */ .container:hover .overlay { opacity: 1; } /* Icon styling */ .icon { color: white; font-size: 92px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }</style> Final Solution: This is the final code after combining the above two sections. It will display the image overlay icon. <!DOCTYPE html><html> <head> <title> Image Overlay Icon using HTML and CSS </title> <link rel="stylesheet" href= "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body { text-align: center; } h1 { color: green; } /* Image styling */ img { padding: 5px; height: 225px; width: 225px; border: 2px solid gray; box-shadow: 2px 4px #888888; } /* Overlay styling */ .overlay { position: absolute; top: 23.5%; left: 32.8%; transition: .3s ease; background-color: gray; width: 225px; height: 225px; opacity: 0; } /* Overlay hover */ .container:hover .overlay { opacity: 1; } /* Icon styling */ .icon { color: white; font-size: 92px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <b>Image Overlay Icon using HTML and CSS</b> <div class="img"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png" alt="Geeksforgeeks"> <div class="overlay"> <a href="#" class="icon"> <i class="fa fa-user"></i> </a> </div> </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 29963, "s": 29935, "text": "\n01 Apr, 2020" }, { "code": null, "e": 30272, "s": 29963, "text": "Image overlay Icon can be an impressive addition to interactive detail or a set of features for your website. This article content will divide the task into two sections, the first section creating the structure and attach the link for the icon. In the second section, we will design the structure using CSS." }, { "code": null, "e": 30445, "s": 30272, "text": "Creating Structure: In this section, we will create a basic structure and also attach the CDN link of the Font-Awesome for the icons which will be used as an icon on hover." }, { "code": null, "e": 30606, "s": 30445, "text": "CDN links for the Icons from the Font Awesome:<link rel=”stylesheet” href= “https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>" }, { "code": null, "e": 30721, "s": 30606, "text": "<link rel=”stylesheet” href= “https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>" }, { "code": null, "e": 31433, "s": 30721, "text": "HTML code:<!DOCTYPE html><html> <head> <title> Image Overlay Icon using HTML and CSS </title> <link rel=\"stylesheet\" href= \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"></head><body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <b>Image Overlay Icon using HTML and CSS</b> <div class=\"img\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png\" alt=\"Geeksforgeeks\"> <div class=\"overlay\"> <a href=\"#\" class=\"icon\"> <i class=\"fa fa-user\"></i> </a> </div> </div> </div></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> Image Overlay Icon using HTML and CSS </title> <link rel=\"stylesheet\" href= \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"></head><body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <b>Image Overlay Icon using HTML and CSS</b> <div class=\"img\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png\" alt=\"Geeksforgeeks\"> <div class=\"overlay\"> <a href=\"#\" class=\"icon\"> <i class=\"fa fa-user\"></i> </a> </div> </div> </div></body> </html>", "e": 32135, "s": 31433, "text": null }, { "code": null, "e": 32358, "s": 32135, "text": "Designing Structure: In the previous section, we have created the structure of the basic website where we are going to use as an image overlay icon. In this section, we will design the structure for the image overlay icon." }, { "code": null, "e": 33191, "s": 32358, "text": "CSS code:<style> body { text-align: center; } h1 { color: green; } /* Image styling */ img { padding: 5px; height: 225px; width: 225px; border: 2px solid gray; box-shadow: 2px 4px #888888; } /* Overlay styling */ .overlay { position: absolute; top: 23.5%; left: 32.8%; transition: .3s ease; background-color: gray; width: 225px; height: 225px; opacity: 0; } /* Overlay hover */ .container:hover .overlay { opacity: 1; } /* Icon styling */ .icon { color: white; font-size: 92px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }</style>" }, { "code": "<style> body { text-align: center; } h1 { color: green; } /* Image styling */ img { padding: 5px; height: 225px; width: 225px; border: 2px solid gray; box-shadow: 2px 4px #888888; } /* Overlay styling */ .overlay { position: absolute; top: 23.5%; left: 32.8%; transition: .3s ease; background-color: gray; width: 225px; height: 225px; opacity: 0; } /* Overlay hover */ .container:hover .overlay { opacity: 1; } /* Icon styling */ .icon { color: white; font-size: 92px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }</style>", "e": 34015, "s": 33191, "text": null }, { "code": null, "e": 34134, "s": 34015, "text": "Final Solution: This is the final code after combining the above two sections. It will display the image overlay icon." }, { "code": "<!DOCTYPE html><html> <head> <title> Image Overlay Icon using HTML and CSS </title> <link rel=\"stylesheet\" href= \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> body { text-align: center; } h1 { color: green; } /* Image styling */ img { padding: 5px; height: 225px; width: 225px; border: 2px solid gray; box-shadow: 2px 4px #888888; } /* Overlay styling */ .overlay { position: absolute; top: 23.5%; left: 32.8%; transition: .3s ease; background-color: gray; width: 225px; height: 225px; opacity: 0; } /* Overlay hover */ .container:hover .overlay { opacity: 1; } /* Icon styling */ .icon { color: white; font-size: 92px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <b>Image Overlay Icon using HTML and CSS</b> <div class=\"img\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png\" alt=\"Geeksforgeeks\"> <div class=\"overlay\"> <a href=\"#\" class=\"icon\"> <i class=\"fa fa-user\"></i> </a> </div> </div> </div></body> </html>", "e": 35834, "s": 34134, "text": null }, { "code": null, "e": 35842, "s": 35834, "text": "Output:" }, { "code": null, "e": 35979, "s": 35842, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 35988, "s": 35979, "text": "CSS-Misc" }, { "code": null, "e": 35998, "s": 35988, "text": "HTML-Misc" }, { "code": null, "e": 36002, "s": 35998, "text": "CSS" }, { "code": null, "e": 36007, "s": 36002, "text": "HTML" }, { "code": null, "e": 36024, "s": 36007, "text": "Web Technologies" }, { "code": null, "e": 36051, "s": 36024, "text": "Web technologies Questions" }, { "code": null, "e": 36056, "s": 36051, "text": "HTML" }, { "code": null, "e": 36154, "s": 36056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36163, "s": 36154, "text": "Comments" }, { "code": null, "e": 36176, "s": 36163, "text": "Old Comments" }, { "code": null, "e": 36238, "s": 36176, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36288, "s": 36238, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 36346, "s": 36288, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 36394, "s": 36346, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 36431, "s": 36394, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 36493, "s": 36431, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36543, "s": 36493, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 36603, "s": 36543, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 36651, "s": 36603, "text": "How to update Node.js and NPM to next version ?" } ]
Add two numbers represented by two arrays | Practice | GeeksforGeeks
Given two array A[0....N-1] and B[0....M-1] of size N and M respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the numbers. Example 1: Input : A[] = {1, 2}, B[] = {2, 1} Output : 33 Explanation: N=2, and A[]={1,2} M=2, and B[]={2,1} Number represented by first array is 12. Number represented by second array is 21 Sum=12+21=33 Example 2: Input : A[] = {9, 5, 4, 9}, B[] = {2, 1, 4} Output : 9763 Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function calc_Sum() that takes an array (a), sizeOfArray (n), an array (b), sizeOfArray (m), and return the sum . The driver code takes care of the printing. Expected Time Complexity: O(N + M). Expected Auxiliary Space: O(N + M). Constraints: 2 ≤ N ≤ 105 2 ≤ M ≤ 105 0 rajubugude2 months ago PYTHON CODE class Solution: def helperAdd(self,a,b,n,m): sum = '' i = n - 1 j = m - 1 carry = 0 while j >= 0: s = a[i] + b[j] + carry sum += str(s % 10) carry = s // 10 i -= 1 j -= 1 while i >= 0: s = a[i] + carry sum += str(s % 10) carry = s // 10 i -= 1 if carry == 1: sum += str(carry) return int(sum[::-1]) def calc_Sum (self, a1, n1, a2, n2): if n1 < n2: return self.helperAdd(a2,a1,n2,n1) return self.helperAdd(a1,a2,n1,n2) +1 prasadchaskar2 months ago Python Code: def calc_Sum (self, arr, n, brr, m) : #Complete the function f = "" s = "" for i in arr: f += str(i) for i in brr: s += str(i) return int(f) + int(s) 0 sagrikasoni3 months ago Java Code class Solution{ String calc_Sum(int a[], int n, int b[], int m) { int i = a.length-1, j = b.length-1; int sum =0, carry =0; String ans = ""; while(i>=0 || j>=0){ int x = (i>=0?a[i]:0); int y = (j>=0?b[j]:0); sum = carry + x+y; carry = sum>=10 ? 1:0; sum = sum%10; ans = ans + Integer.toString(sum); i--; j--; } if(carry>0){ ans= ans + Integer.toString(carry); } StringBuffer s = new StringBuffer(ans); s.reverse(); String res = s.toString(); int curr =0; while(curr<res.length()&&res.charAt(curr)=='0'){ curr++; } return res.substring(curr); } } 0 yashpatil710973 months ago int size=Math.max(n,m); int []c= new int[size+1]; Arrays.fill(c,-1); int sizea=0; int sizeb=0; for(int p=0;p<n;p++) { if(a[p]!=0) { sizea=p; break; } } for(int p=0;p<m;p++) { if(b[p]!=0) { sizeb=p; break; } } int i=n-1; int j=m-1; int count=c.length-1; int carry=0; while(i>=sizea&&j>=sizeb) { int temp=(a[i]+b[j]+carry); c[count]=(temp%10); carry=(temp/10); count--; i--; j--; } while(i>=sizea) { int temp=(a[i]+carry); c[count]=(temp%10); carry=(temp/10); count--; i--; } while(j>=sizeb) { int temp=(b[j]+carry); c[count]=(temp%10); carry=(temp/10); count--; j--; } while(carry!=0) { int temp=(carry%10); c[count]=temp; count--; carry=(carry/10); } String ans=""; for(int k=0;k<c.length;k++) { if(c[k]!=-1) { ans+=(c[k]); } } return ans; +1 afridikingkhan20175 months ago //solve in java int as = 0; for (int i = 0; i < a.length; i++) { if (a[as] != 0) { break; } as++; } int bs = 0; for (int i = 0; i < b.length; i++) { if (b[bs] != 0) { break; } bs++; } int ai = a.length - 1; int bi = b.length - 1; String sum = ""; int carry = 0; while (ai >= as && bi >= bs) { int currSum = a[ai] + b[bi] + carry; carry = currSum / 10; sum = (currSum % 10) + sum; ai--; bi--; } while (ai >= as) { int currSum = a[ai] + carry; carry = currSum / 10; sum = (currSum % 10) + sum; ai--; } while (bi >= bs) { int currSum = b[bi] + carry; carry = currSum / 10; sum = (currSum % 10) + sum; bi--; } if (carry != 0) sum = carry + sum; return sum; } } 0 afridikingkhan2017 This comment was deleted. 0 Imran Wahid7 months ago Imran Wahid Easy C++ solution class Solution{ public: string calc_Sum(int *a,int n,int *b,int m) { int i=n-1,j=m-1,carry=0; string ans=""; while(i>=0 || j>=0) { int sum=(i>=0?a[i--]:0)+(j>=0?b[j--]:0)+carry; carry=sum/10; ans+=to_string(sum%10); } if(carry) { ans+=to_string(carry); } reverse(ans.begin(),ans.end()); while(!ans.empty() && ans[0]=='0') { ans.erase(ans.begin()); } return ans; }}; https://uploads.disquscdn.c... 0 Debojyoti Sinha11 months ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.28 class Solution{ public: string calc_Sum(int A[], int N, int B[], int M) { string res; int carry = 0; int i = N - 1; int j = M - 1; while(i >= 0 and j >= 0) { int sum = A[i] + B[j] + carry; res += (sum % 10) + '0'; carry = sum / 10; i--; j--; } while(i >= 0) { int sum = A[i] + carry; res += (sum % 10) + '0'; carry = sum / 10; i--; } while(j >= 0) { int sum = B[j] + carry; res += (sum % 10) + '0'; carry = sum / 10; j--; } if(carry) { res += carry + '0'; } reverse(res.begin(), res.end()); int curr = 0; while(curr < res.size() and res[curr] == '0') { curr++; } return res.substr(curr); }}; 0 Ashish Agrawal11 months ago Ashish Agrawal Here is my solution, na=''.join(map(str,arr)) nb=''.join(map(str,brr)) return (int(na)+int(nb)) 0 pratyush shekhar1 year ago pratyush shekhar PYTHON SOLUTIONdef calc_Sum (arr, n, brr, m) : str1="" str2="" for i in arr: str1=str1+str(i) for j in brr: str2=str2+str(j) sumi=int(str1)+int(str2) return sumi 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": 527, "s": 238, "text": "Given two array A[0....N-1] and B[0....M-1] of size N and M respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the numbers." }, { "code": null, "e": 538, "s": 527, "text": "Example 1:" }, { "code": null, "e": 731, "s": 538, "text": "Input : A[] = {1, 2}, B[] = {2, 1}\nOutput : 33\nExplanation:\nN=2, and A[]={1,2}\nM=2, and B[]={2,1}\nNumber represented by first array is 12.\nNumber represented by second array is 21\nSum=12+21=33" }, { "code": null, "e": 744, "s": 733, "text": "Example 2:" }, { "code": null, "e": 805, "s": 744, "text": "Input : A[] = {9, 5, 4, 9}, B[] = {2, 1, 4} \nOutput : 9763 \n" }, { "code": null, "e": 1087, "s": 805, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function calc_Sum() that takes an array (a), sizeOfArray (n), an array (b), sizeOfArray (m), and return the sum . The driver code takes care of the printing." }, { "code": null, "e": 1159, "s": 1087, "text": "Expected Time Complexity: O(N + M).\nExpected Auxiliary Space: O(N + M)." }, { "code": null, "e": 1198, "s": 1161, "text": "Constraints:\n2 ≤ N ≤ 105\n2 ≤ M ≤ 105" }, { "code": null, "e": 1200, "s": 1198, "text": "0" }, { "code": null, "e": 1223, "s": 1200, "text": "rajubugude2 months ago" }, { "code": null, "e": 1235, "s": 1223, "text": "PYTHON CODE" }, { "code": null, "e": 1903, "s": 1235, "text": "class Solution:\n def helperAdd(self,a,b,n,m):\n sum = ''\n i = n - 1\n j = m - 1\n carry = 0\n while j >= 0:\n s = a[i] + b[j] + carry\n sum += str(s % 10)\n carry = s // 10\n i -= 1\n j -= 1\n \n while i >= 0:\n s = a[i] + carry\n sum += str(s % 10)\n carry = s // 10\n i -= 1\n \n if carry == 1:\n sum += str(carry)\n return int(sum[::-1])\n \n \n def calc_Sum (self, a1, n1, a2, n2): \n if n1 < n2:\n return self.helperAdd(a2,a1,n2,n1)\n return self.helperAdd(a1,a2,n1,n2)" }, { "code": null, "e": 1906, "s": 1903, "text": "+1" }, { "code": null, "e": 1932, "s": 1906, "text": "prasadchaskar2 months ago" }, { "code": null, "e": 1945, "s": 1932, "text": "Python Code:" }, { "code": null, "e": 2169, "s": 1945, "text": "def calc_Sum (self, arr, n, brr, m) : \n #Complete the function\n f = \"\"\n s = \"\"\n for i in arr:\n f += str(i)\n for i in brr:\n s += str(i)\n return int(f) + int(s)" }, { "code": null, "e": 2171, "s": 2169, "text": "0" }, { "code": null, "e": 2195, "s": 2171, "text": "sagrikasoni3 months ago" }, { "code": null, "e": 2205, "s": 2195, "text": "Java Code" }, { "code": null, "e": 2987, "s": 2205, "text": "class Solution{\n \n \n String calc_Sum(int a[], int n, int b[], int m)\n {\n int i = a.length-1, j = b.length-1; int sum =0, carry =0; String ans = \"\";\n while(i>=0 || j>=0){\n int x = (i>=0?a[i]:0);\n int y = (j>=0?b[j]:0);\n sum = carry + x+y;\n carry = sum>=10 ? 1:0;\n sum = sum%10;\n ans = ans + Integer.toString(sum);\n i--;\n j--;\n }\n if(carry>0){\n ans= ans + Integer.toString(carry);\n }\n StringBuffer s = new StringBuffer(ans);\n s.reverse();\n String res = s.toString();\n int curr =0;\n while(curr<res.length()&&res.charAt(curr)=='0'){\n curr++;\n }\n return res.substring(curr);\n }\n \n \n}" }, { "code": null, "e": 2989, "s": 2987, "text": "0" }, { "code": null, "e": 3016, "s": 2989, "text": "yashpatil710973 months ago" }, { "code": null, "e": 4369, "s": 3016, "text": "int size=Math.max(n,m); int []c= new int[size+1]; Arrays.fill(c,-1); int sizea=0; int sizeb=0; for(int p=0;p<n;p++) { if(a[p]!=0) { sizea=p; break; } } for(int p=0;p<m;p++) { if(b[p]!=0) { sizeb=p; break; } } int i=n-1; int j=m-1; int count=c.length-1; int carry=0; while(i>=sizea&&j>=sizeb) { int temp=(a[i]+b[j]+carry); c[count]=(temp%10); carry=(temp/10); count--; i--; j--; } while(i>=sizea) { int temp=(a[i]+carry); c[count]=(temp%10); carry=(temp/10); count--; i--; } while(j>=sizeb) { int temp=(b[j]+carry); c[count]=(temp%10); carry=(temp/10); count--; j--; } while(carry!=0) { int temp=(carry%10); c[count]=temp; count--; carry=(carry/10); } String ans=\"\"; for(int k=0;k<c.length;k++) { if(c[k]!=-1) { ans+=(c[k]); } } return ans;" }, { "code": null, "e": 4372, "s": 4369, "text": "+1" }, { "code": null, "e": 4403, "s": 4372, "text": "afridikingkhan20175 months ago" }, { "code": null, "e": 4429, "s": 4403, "text": "//solve in java " }, { "code": null, "e": 4569, "s": 4429, "text": "int as = 0; for (int i = 0; i < a.length; i++) { if (a[as] != 0) { break; } as++; }" }, { "code": null, "e": 5395, "s": 4569, "text": " int bs = 0; for (int i = 0; i < b.length; i++) { if (b[bs] != 0) { break; } bs++; } int ai = a.length - 1; int bi = b.length - 1; String sum = \"\"; int carry = 0; while (ai >= as && bi >= bs) { int currSum = a[ai] + b[bi] + carry; carry = currSum / 10; sum = (currSum % 10) + sum; ai--; bi--; } while (ai >= as) { int currSum = a[ai] + carry; carry = currSum / 10; sum = (currSum % 10) + sum; ai--; } while (bi >= bs) { int currSum = b[bi] + carry; carry = currSum / 10; sum = (currSum % 10) + sum; bi--; } if (carry != 0) sum = carry + sum; return sum; } }" }, { "code": null, "e": 5397, "s": 5395, "text": "0" }, { "code": null, "e": 5416, "s": 5397, "text": "afridikingkhan2017" }, { "code": null, "e": 5442, "s": 5416, "text": "This comment was deleted." }, { "code": null, "e": 5444, "s": 5442, "text": "0" }, { "code": null, "e": 5468, "s": 5444, "text": "Imran Wahid7 months ago" }, { "code": null, "e": 5480, "s": 5468, "text": "Imran Wahid" }, { "code": null, "e": 5498, "s": 5480, "text": "Easy C++ solution" }, { "code": null, "e": 6022, "s": 5498, "text": "class Solution{ public: string calc_Sum(int *a,int n,int *b,int m) { int i=n-1,j=m-1,carry=0; string ans=\"\"; while(i>=0 || j>=0) { int sum=(i>=0?a[i--]:0)+(j>=0?b[j--]:0)+carry; carry=sum/10; ans+=to_string(sum%10); } if(carry) { ans+=to_string(carry); } reverse(ans.begin(),ans.end()); while(!ans.empty() && ans[0]=='0') { ans.erase(ans.begin()); } return ans; }};" }, { "code": null, "e": 6054, "s": 6022, "text": " https://uploads.disquscdn.c..." }, { "code": null, "e": 6056, "s": 6054, "text": "0" }, { "code": null, "e": 6085, "s": 6056, "text": "Debojyoti Sinha11 months ago" }, { "code": null, "e": 6101, "s": 6085, "text": "Debojyoti Sinha" }, { "code": null, "e": 6150, "s": 6101, "text": "Correct Answer.Correct AnswerExecution Time:0.28" }, { "code": null, "e": 7217, "s": 6150, "text": "class Solution{ public: string calc_Sum(int A[], int N, int B[], int M) { string res; int carry = 0; int i = N - 1; int j = M - 1; while(i >= 0 and j >= 0) { int sum = A[i] + B[j] + carry; res += (sum % 10) + '0'; carry = sum / 10; i--; j--; } while(i >= 0) { int sum = A[i] + carry; res += (sum % 10) + '0'; carry = sum / 10; i--; } while(j >= 0) { int sum = B[j] + carry; res += (sum % 10) + '0'; carry = sum / 10; j--; } if(carry) { res += carry + '0'; } reverse(res.begin(), res.end()); int curr = 0; while(curr < res.size() and res[curr] == '0') { curr++; } return res.substr(curr); }};" }, { "code": null, "e": 7219, "s": 7217, "text": "0" }, { "code": null, "e": 7247, "s": 7219, "text": "Ashish Agrawal11 months ago" }, { "code": null, "e": 7262, "s": 7247, "text": "Ashish Agrawal" }, { "code": null, "e": 7348, "s": 7262, "text": "Here is my solution, na=''.join(map(str,arr)) nb=''.join(map(str,brr))" }, { "code": null, "e": 7381, "s": 7348, "text": " return (int(na)+int(nb))" }, { "code": null, "e": 7383, "s": 7381, "text": "0" }, { "code": null, "e": 7410, "s": 7383, "text": "pratyush shekhar1 year ago" }, { "code": null, "e": 7427, "s": 7410, "text": "pratyush shekhar" }, { "code": null, "e": 7623, "s": 7427, "text": "PYTHON SOLUTIONdef calc_Sum (arr, n, brr, m) : str1=\"\" str2=\"\" for i in arr: str1=str1+str(i) for j in brr: str2=str2+str(j) sumi=int(str1)+int(str2) return sumi" }, { "code": null, "e": 7769, "s": 7623, "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": 7805, "s": 7769, "text": " Login to access your submissions. " }, { "code": null, "e": 7815, "s": 7805, "text": "\nProblem\n" }, { "code": null, "e": 7825, "s": 7815, "text": "\nContest\n" }, { "code": null, "e": 7888, "s": 7825, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8036, "s": 7888, "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": 8244, "s": 8036, "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": 8350, "s": 8244, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
HSQLDB - Connect
In the installation chapter, we discussed how to connect the database manually. In this chapter, we will discuss how to connect the database programmatically (using Java programming). Take a look at the following program, which will start the server and create a connection between the Java application and the database. import java.sql.Connection; import java.sql.DriverManager; public class ConnectDatabase { public static void main(String[] args) { Connection con = null; try { //Registering the HSQLDB JDBC driver Class.forName("org.hsqldb.jdbc.JDBCDriver"); //Creating the connection with HSQLDB con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", ""); if (con!= null){ System.out.println("Connection created successfully"); }else{ System.out.println("Problem with creating connection"); } } catch (Exception e) { e.printStackTrace(System.out); } } } Save this code into ConnectDatabase.java file. You will have to start the database using the following command. \>cd C:\hsqldb-2.3.4\hsqldb hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:hsqldb/demodb --dbname.0 testdb You can use the following command to compile and execute the code. \>javac ConnectDatabase.java \>java ConnectDatabase After execution of the above command, you will receive the following output − Connection created successfully Print Add Notes Bookmark this page
[ { "code": null, "e": 2166, "s": 1982, "text": "In the installation chapter, we discussed how to connect the database manually. In this chapter, we will discuss how to connect the database programmatically (using Java programming)." }, { "code": null, "e": 2303, "s": 2166, "text": "Take a look at the following program, which will start the server and create a connection between the Java application and the database." }, { "code": null, "e": 3020, "s": 2303, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\n\npublic class ConnectDatabase {\n public static void main(String[] args) {\n Connection con = null;\n \n try {\n //Registering the HSQLDB JDBC driver\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n //Creating the connection with HSQLDB\n con = DriverManager.getConnection(\"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n if (con!= null){\n System.out.println(\"Connection created successfully\");\n \n }else{\n System.out.println(\"Problem with creating connection\");\n }\n \n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n}" }, { "code": null, "e": 3132, "s": 3020, "text": "Save this code into ConnectDatabase.java file. You will have to start the database using the following command." }, { "code": null, "e": 3274, "s": 3132, "text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n" }, { "code": null, "e": 3341, "s": 3274, "text": "You can use the following command to compile and execute the code." }, { "code": null, "e": 3394, "s": 3341, "text": "\\>javac ConnectDatabase.java\n\\>java ConnectDatabase\n" }, { "code": null, "e": 3472, "s": 3394, "text": "After execution of the above command, you will receive the following output −" }, { "code": null, "e": 3505, "s": 3472, "text": "Connection created successfully\n" }, { "code": null, "e": 3512, "s": 3505, "text": " Print" }, { "code": null, "e": 3523, "s": 3512, "text": " Add Notes" } ]
How to Join Computer to the AD domain using PowerShell?
To join any workgroup computer in the domain using PowerShell, we can use the Add-Computer command but before that, there are a few Windows prerequisite that DNS must be configured properly and the domain controller should be reachable and others should suffice then only PowerShell can use the command to join computer into a domain. Add-Computer -ComputerName Test1-win2k16 ` -DomainCredential Labdomain\Administrator ` -DomainName Labdomain.local -Restart -Force -PassThru Once you run the above command, it will ask you for the credential for the user you entered. In the above example, we are joining a remote computer to the domain LabDomain.Local and it will restart the remote system. If the users are logged in on the remote system, it might not restart but the system will connect to the domain. You can restart later forcefully. We need to make sure that the username used in the -DomainCredential parameter, should have proper privileges like DomainAdmin, EnterpriseAdmin. To Join the computer in the Different OU, you need to provide the OU path Add-Computer -ComputerName Test1-win2k16 ` -DomainCredential Labdomain\Administrator ` -DomainName Labdomain.local ` -OuPath 'OU=Prod,OU=Servers,DC=labdomain,DC=local' ` -Restart -Force -PassThru Here the computer Name parameter is String[] so you can use multiple computers. For example, Add-Computer -ComputerName Test1-win2k16, Test1-Win2k12, Test2-Win2k12 ` -DomainCredential Labdomain\Administrator ` -DomainName Labdomain.local ` -OuPath 'OU=Prod,OU=Servers,DC=labdomain,DC=local' ` -Restart -Force -PassThru You can also use the foreach loop and the list of computers from the CSV file to join multiple computers if the OU path is different.
[ { "code": null, "e": 1397, "s": 1062, "text": "To join any workgroup computer in the domain using PowerShell, we can use the Add-Computer command but before that, there are a few Windows prerequisite that DNS must be configured properly and the domain controller should be reachable and others should suffice then only PowerShell can use the command to join computer into a domain." }, { "code": null, "e": 1564, "s": 1397, "text": "Add-Computer -ComputerName Test1-win2k16 `\n -DomainCredential Labdomain\\Administrator `\n -DomainName Labdomain.local -Restart -Force -PassThru" }, { "code": null, "e": 1928, "s": 1564, "text": "Once you run the above command, it will ask you for the credential for the user you entered. In the above example, we are joining a remote computer to the domain LabDomain.Local and it will restart the remote system. If the users are logged in on the remote system, it might not restart but the system will connect to the domain. You can restart later forcefully." }, { "code": null, "e": 2073, "s": 1928, "text": "We need to make sure that the username used in the -DomainCredential parameter, should have proper privileges like DomainAdmin, EnterpriseAdmin." }, { "code": null, "e": 2147, "s": 2073, "text": "To Join the computer in the Different OU, you need to provide the OU path" }, { "code": null, "e": 2395, "s": 2147, "text": "Add-Computer -ComputerName Test1-win2k16 `\n -DomainCredential Labdomain\\Administrator `\n -DomainName Labdomain.local `\n -OuPath 'OU=Prod,OU=Servers,DC=labdomain,DC=local' `\n -Restart -Force -PassThru" }, { "code": null, "e": 2489, "s": 2395, "text": "Here the computer Name parameter is String[] so you can use multiple computers. For example," }, { "code": null, "e": 2767, "s": 2489, "text": "Add-Computer -ComputerName Test1-win2k16, Test1-Win2k12, Test2-Win2k12 `\n -DomainCredential Labdomain\\Administrator `\n -DomainName Labdomain.local `\n -OuPath 'OU=Prod,OU=Servers,DC=labdomain,DC=local' `\n -Restart -Force -PassThru" }, { "code": null, "e": 2901, "s": 2767, "text": "You can also use the foreach loop and the list of computers from the CSV file to join multiple computers if the OU path is different." } ]
DateTime.AddDays() Method in C#
The DateTime.AddDays() method in C# is used to add the specified number of days to the value of this instance. This method returns a new DateTime. Following is the syntax − public DateTime AddDays (double days); Above, the parameter days are the number of days to be added. To subtract, add a negative value. Let us now see an example to implement the DateTime.AddDays() method − using System; public class Demo { public static void Main(){ DateTime d1 = new DateTime(2019, 11, 2, 8, 0, 15); DateTime d2 = d1.AddDays(25); System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1); System.Console.WriteLine("\nNew DateTime (After adding days) = {0:y} {0:dd}", d2); } } This will produce the following output − Initial DateTime = November 2019 02 New DateTime (After adding days) = November 2019 27 Let us now see another example to implement the DateTime.AddDays() method − using System; public class Demo { public static void Main(){ DateTime d1 = DateTime.MinValue; DateTime d2 = d1.AddDays(150); System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1); System.Console.WriteLine("\nNew DateTime (After adding days) = {0:y} {0:dd}", d2); } } This will produce the following output − Initial DateTime = January 0001 01 New DateTime (After adding days) = May 0001 31
[ { "code": null, "e": 1209, "s": 1062, "text": "The DateTime.AddDays() method in C# is used to add the specified number of days to the value of this instance. This method returns a new DateTime." }, { "code": null, "e": 1235, "s": 1209, "text": "Following is the syntax −" }, { "code": null, "e": 1274, "s": 1235, "text": "public DateTime AddDays (double days);" }, { "code": null, "e": 1371, "s": 1274, "text": "Above, the parameter days are the number of days to be added. To subtract, add a negative value." }, { "code": null, "e": 1442, "s": 1371, "text": "Let us now see an example to implement the DateTime.AddDays() method −" }, { "code": null, "e": 1766, "s": 1442, "text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime d1 = new DateTime(2019, 11, 2, 8, 0, 15);\n DateTime d2 = d1.AddDays(25);\n System.Console.WriteLine(\"Initial DateTime = {0:y} {0:dd}\", d1);\n System.Console.WriteLine(\"\\nNew DateTime (After adding days) = {0:y} {0:dd}\", d2);\n }\n}" }, { "code": null, "e": 1807, "s": 1766, "text": "This will produce the following output −" }, { "code": null, "e": 1895, "s": 1807, "text": "Initial DateTime = November 2019 02\nNew DateTime (After adding days) = November 2019 27" }, { "code": null, "e": 1971, "s": 1895, "text": "Let us now see another example to implement the DateTime.AddDays() method −" }, { "code": null, "e": 2278, "s": 1971, "text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime d1 = DateTime.MinValue;\n DateTime d2 = d1.AddDays(150);\n System.Console.WriteLine(\"Initial DateTime = {0:y} {0:dd}\", d1);\n System.Console.WriteLine(\"\\nNew DateTime (After adding days) = {0:y} {0:dd}\", d2);\n }\n}" }, { "code": null, "e": 2319, "s": 2278, "text": "This will produce the following output −" }, { "code": null, "e": 2401, "s": 2319, "text": "Initial DateTime = January 0001 01\nNew DateTime (After adding days) = May 0001 31" } ]
Python Traceback - GeeksforGeeks
23 Jul, 2020 In Python, A traceback is a report containing the function calls made in your code at a specific point i.e when you get an error it is recommended that you should trace it backward(traceback). Whenever the code gets an exception, the traceback will give the information about what went wrong in the code.The Python traceback contains great information that can help you find what is going wrong in the code. These tracebacks can look a little wearisome, but once you break it down to see what it’s trying to show you, they can be very helpful. Consider following example... # Python program to demonstrate# traceback mylist = [1, 2, 3]print(mylist[10]) In this example, we are trying to access the 10th element of the list. With only 3 elements present in the list it will give Runtime error. When this program is executed you will get the following traceback. Traceback (most recent call last): File "", line 2, in print(mylist[10]) IndexError: list index out of range This traceback error has all the information about why this runtime error occurred. Last line of the traceback tells you about what type of error occurred along with relevant information. Previous lines of traceback points to the code in which error occurred. In the above example, the last line indicates the index occurred and the previous two lines show the exact location where the exception has occurred. let us now see, How to read traceback.. Python traceback contains lots of helpful information about what exception is raised. Going through a few tracebacks line by line will give you a better understanding of the information they contain and help you get the most out of them, in this section we will see how to read a particular exception. In python it is best to read traceback from bottom to top. GREEN BOX shows the what type of error occurred . BLUE BOX shows the relevant information about error ORANGE BOX shows traceback statement for recent calls, below The firstRuntime Error:Traceback (most recent call last):File “”, line 1, inModuleNotFoundError: No module named ‘asdf’ line of each call contains information like the file name, line number, and module name RED underlined part shows exact line where exception occurred. Some of the common traceback errors are: NameError IndexError KeyError TypeError valueError ImportError /ModuleNotFound Let’s go through each error one by one: NameError: NameError occurs when you try to reference some variable which hasn’t been defined in the code.Example:number = 1 # since no numb variable is# defined it will give NameError.print(numb) Output:Traceback (most recent call last): File "gfg.py", line 5, in print(numb) NameError: name 'numb' is not defined IndexError: An IndexError is raised when a sequence is referenced which is out of range.Example:mylist = [1, 2, 3] # Accessing the index out# of range will raise IndexErrorprint(mylist[10])Output:Traceback (most recent call last): File "gfg.py", line 5, in print(mylist[10]) IndexError: list index out of range KeyError: Similar to the IndexError, the KeyError is raised when you attempt to access a key that isn’t in the mapping, usually in the case of Python dict. Think of this as the IndexError but for dictionaries.Example:DICT ={ "a" :25, "b" :65 } # A is not mapped in dict# will raise KeyErrorprint(DICT["A"])Output:Traceback (most recent call last): File "gfg.py", line 5, in print(DICT["A"]) KeyError: 'A' TypeError: TypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example:c = 'b'+3print(c)Output:Traceback (most recent call last): File "gfg.py", line 1, in c = 'b'+3 TypeError: must be str, not int ValueError: A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example:print(int('xyz'))Traceback (most recent call last): File "gfg.py", line 1, in print(int('xyz')) ValueError: invalid literal for int() with base 10: 'xyz' ImportError: The ImportError is raised when something goes wrong with an import statement. You’ll get this exception, or its subclass ModuleNotFoundError, if the module you are trying to import can’t be found or if you try to import something from a module that doesn’t exist in the module.Example:import module_does_not_exist Traceback (most recent call last): File "gfg.py", line 1, in import module_does_not_exist ModuleNotFoundError: No module named 'module_does_not_exist' NameError: NameError occurs when you try to reference some variable which hasn’t been defined in the code.Example:number = 1 # since no numb variable is# defined it will give NameError.print(numb) Output:Traceback (most recent call last): File "gfg.py", line 5, in print(numb) NameError: name 'numb' is not defined Example: number = 1 # since no numb variable is# defined it will give NameError.print(numb) Output: Traceback (most recent call last): File "gfg.py", line 5, in print(numb) NameError: name 'numb' is not defined IndexError: An IndexError is raised when a sequence is referenced which is out of range.Example:mylist = [1, 2, 3] # Accessing the index out# of range will raise IndexErrorprint(mylist[10])Output:Traceback (most recent call last): File "gfg.py", line 5, in print(mylist[10]) IndexError: list index out of range Example: mylist = [1, 2, 3] # Accessing the index out# of range will raise IndexErrorprint(mylist[10]) Output: Traceback (most recent call last): File "gfg.py", line 5, in print(mylist[10]) IndexError: list index out of range KeyError: Similar to the IndexError, the KeyError is raised when you attempt to access a key that isn’t in the mapping, usually in the case of Python dict. Think of this as the IndexError but for dictionaries.Example:DICT ={ "a" :25, "b" :65 } # A is not mapped in dict# will raise KeyErrorprint(DICT["A"])Output:Traceback (most recent call last): File "gfg.py", line 5, in print(DICT["A"]) KeyError: 'A' Example: DICT ={ "a" :25, "b" :65 } # A is not mapped in dict# will raise KeyErrorprint(DICT["A"]) Output: Traceback (most recent call last): File "gfg.py", line 5, in print(DICT["A"]) KeyError: 'A' TypeError: TypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example:c = 'b'+3print(c)Output:Traceback (most recent call last): File "gfg.py", line 1, in c = 'b'+3 TypeError: must be str, not int Example: c = 'b'+3print(c) Output: Traceback (most recent call last): File "gfg.py", line 1, in c = 'b'+3 TypeError: must be str, not int ValueError: A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example:print(int('xyz'))Traceback (most recent call last): File "gfg.py", line 1, in print(int('xyz')) ValueError: invalid literal for int() with base 10: 'xyz' Example: print(int('xyz')) Traceback (most recent call last): File "gfg.py", line 1, in print(int('xyz')) ValueError: invalid literal for int() with base 10: 'xyz' ImportError: The ImportError is raised when something goes wrong with an import statement. You’ll get this exception, or its subclass ModuleNotFoundError, if the module you are trying to import can’t be found or if you try to import something from a module that doesn’t exist in the module.Example:import module_does_not_exist Traceback (most recent call last): File "gfg.py", line 1, in import module_does_not_exist ModuleNotFoundError: No module named 'module_does_not_exist' Example: import module_does_not_exist Traceback (most recent call last): File "gfg.py", line 1, in import module_does_not_exist ModuleNotFoundError: No module named 'module_does_not_exist' Akanksha_Rai Python-exceptions Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24163, "s": 24135, "text": "\n23 Jul, 2020" }, { "code": null, "e": 24707, "s": 24163, "text": "In Python, A traceback is a report containing the function calls made in your code at a specific point i.e when you get an error it is recommended that you should trace it backward(traceback). Whenever the code gets an exception, the traceback will give the information about what went wrong in the code.The Python traceback contains great information that can help you find what is going wrong in the code. These tracebacks can look a little wearisome, but once you break it down to see what it’s trying to show you, they can be very helpful." }, { "code": null, "e": 24737, "s": 24707, "text": "Consider following example..." }, { "code": "# Python program to demonstrate# traceback mylist = [1, 2, 3]print(mylist[10])", "e": 24819, "s": 24737, "text": null }, { "code": null, "e": 25027, "s": 24819, "text": "In this example, we are trying to access the 10th element of the list. With only 3 elements present in the list it will give Runtime error. When this program is executed you will get the following traceback." }, { "code": null, "e": 25140, "s": 25027, "text": "Traceback (most recent call last):\n File \"\", line 2, in \nprint(mylist[10])\nIndexError: list index out of range\n" }, { "code": null, "e": 25590, "s": 25140, "text": "This traceback error has all the information about why this runtime error occurred. Last line of the traceback tells you about what type of error occurred along with relevant information. Previous lines of traceback points to the code in which error occurred. In the above example, the last line indicates the index occurred and the previous two lines show the exact location where the exception has occurred. let us now see, How to read traceback.." }, { "code": null, "e": 25892, "s": 25590, "text": "Python traceback contains lots of helpful information about what exception is raised. Going through a few tracebacks line by line will give you a better understanding of the information they contain and help you get the most out of them, in this section we will see how to read a particular exception." }, { "code": null, "e": 25951, "s": 25892, "text": "In python it is best to read traceback from bottom to top." }, { "code": null, "e": 26001, "s": 25951, "text": "GREEN BOX shows the what type of error occurred ." }, { "code": null, "e": 26053, "s": 26001, "text": "BLUE BOX shows the relevant information about error" }, { "code": null, "e": 26322, "s": 26053, "text": "ORANGE BOX shows traceback statement for recent calls, below The firstRuntime Error:Traceback (most recent call last):File “”, line 1, inModuleNotFoundError: No module named ‘asdf’ line of each call contains information like the file name, line number, and module name" }, { "code": null, "e": 26385, "s": 26322, "text": "RED underlined part shows exact line where exception occurred." }, { "code": null, "e": 26426, "s": 26385, "text": "Some of the common traceback errors are:" }, { "code": null, "e": 26436, "s": 26426, "text": "NameError" }, { "code": null, "e": 26447, "s": 26436, "text": "IndexError" }, { "code": null, "e": 26456, "s": 26447, "text": "KeyError" }, { "code": null, "e": 26466, "s": 26456, "text": "TypeError" }, { "code": null, "e": 26477, "s": 26466, "text": "valueError" }, { "code": null, "e": 26505, "s": 26477, "text": "ImportError /ModuleNotFound" }, { "code": null, "e": 26545, "s": 26505, "text": "Let’s go through each error one by one:" }, { "code": null, "e": 28720, "s": 26545, "text": "NameError: NameError occurs when you try to reference some variable which hasn’t been defined in the code.Example:number = 1 # since no numb variable is# defined it will give NameError.print(numb) Output:Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(numb) \nNameError: name 'numb' is not defined\nIndexError: An IndexError is raised when a sequence is referenced which is out of range.Example:mylist = [1, 2, 3] # Accessing the index out# of range will raise IndexErrorprint(mylist[10])Output:Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(mylist[10])\nIndexError: list index out of range\nKeyError: Similar to the IndexError, the KeyError is raised when you attempt to access a key that isn’t in the mapping, usually in the case of Python dict. Think of this as the IndexError but for dictionaries.Example:DICT ={ \"a\" :25, \"b\" :65 } # A is not mapped in dict# will raise KeyErrorprint(DICT[\"A\"])Output:Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(DICT[\"A\"])\nKeyError: 'A'\nTypeError: TypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example:c = 'b'+3print(c)Output:Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n c = 'b'+3\nTypeError: must be str, not int\nValueError: A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example:print(int('xyz'))Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n print(int('xyz'))\nValueError: invalid literal for int() with base 10: 'xyz'\nImportError: The ImportError is raised when something goes wrong with an import statement. You’ll get this exception, or its subclass ModuleNotFoundError, if the module you are trying to import can’t be found or if you try to import something from a module that doesn’t exist in the module.Example:import module_does_not_exist Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n import module_does_not_exist\nModuleNotFoundError: No module named 'module_does_not_exist'\n" }, { "code": null, "e": 29048, "s": 28720, "text": "NameError: NameError occurs when you try to reference some variable which hasn’t been defined in the code.Example:number = 1 # since no numb variable is# defined it will give NameError.print(numb) Output:Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(numb) \nNameError: name 'numb' is not defined\n" }, { "code": null, "e": 29057, "s": 29048, "text": "Example:" }, { "code": "number = 1 # since no numb variable is# defined it will give NameError.print(numb) ", "e": 29144, "s": 29057, "text": null }, { "code": null, "e": 29152, "s": 29144, "text": "Output:" }, { "code": null, "e": 29273, "s": 29152, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(numb) \nNameError: name 'numb' is not defined\n" }, { "code": null, "e": 29593, "s": 29273, "text": "IndexError: An IndexError is raised when a sequence is referenced which is out of range.Example:mylist = [1, 2, 3] # Accessing the index out# of range will raise IndexErrorprint(mylist[10])Output:Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(mylist[10])\nIndexError: list index out of range\n" }, { "code": null, "e": 29602, "s": 29593, "text": "Example:" }, { "code": "mylist = [1, 2, 3] # Accessing the index out# of range will raise IndexErrorprint(mylist[10])", "e": 29697, "s": 29602, "text": null }, { "code": null, "e": 29705, "s": 29697, "text": "Output:" }, { "code": null, "e": 29828, "s": 29705, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(mylist[10])\nIndexError: list index out of range\n" }, { "code": null, "e": 30242, "s": 29828, "text": "KeyError: Similar to the IndexError, the KeyError is raised when you attempt to access a key that isn’t in the mapping, usually in the case of Python dict. Think of this as the IndexError but for dictionaries.Example:DICT ={ \"a\" :25, \"b\" :65 } # A is not mapped in dict# will raise KeyErrorprint(DICT[\"A\"])Output:Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(DICT[\"A\"])\nKeyError: 'A'\n" }, { "code": null, "e": 30251, "s": 30242, "text": "Example:" }, { "code": "DICT ={ \"a\" :25, \"b\" :65 } # A is not mapped in dict# will raise KeyErrorprint(DICT[\"A\"])", "e": 30342, "s": 30251, "text": null }, { "code": null, "e": 30350, "s": 30342, "text": "Output:" }, { "code": null, "e": 30450, "s": 30350, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 5, in \n print(DICT[\"A\"])\nKeyError: 'A'\n" }, { "code": null, "e": 30772, "s": 30450, "text": "TypeError: TypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example:c = 'b'+3print(c)Output:Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n c = 'b'+3\nTypeError: must be str, not int\n" }, { "code": null, "e": 30781, "s": 30772, "text": "Example:" }, { "code": "c = 'b'+3print(c)", "e": 30799, "s": 30781, "text": null }, { "code": null, "e": 30807, "s": 30799, "text": "Output:" }, { "code": null, "e": 30918, "s": 30807, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n c = 'b'+3\nTypeError: must be str, not int\n" }, { "code": null, "e": 31227, "s": 30918, "text": "ValueError: A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example:print(int('xyz'))Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n print(int('xyz'))\nValueError: invalid literal for int() with base 10: 'xyz'\n" }, { "code": null, "e": 31236, "s": 31227, "text": "Example:" }, { "code": "print(int('xyz'))", "e": 31254, "s": 31236, "text": null }, { "code": null, "e": 31399, "s": 31254, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n print(int('xyz'))\nValueError: invalid literal for int() with base 10: 'xyz'\n" }, { "code": null, "e": 31886, "s": 31399, "text": "ImportError: The ImportError is raised when something goes wrong with an import statement. You’ll get this exception, or its subclass ModuleNotFoundError, if the module you are trying to import can’t be found or if you try to import something from a module that doesn’t exist in the module.Example:import module_does_not_exist Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n import module_does_not_exist\nModuleNotFoundError: No module named 'module_does_not_exist'\n" }, { "code": null, "e": 31895, "s": 31886, "text": "Example:" }, { "code": "import module_does_not_exist ", "e": 31926, "s": 31895, "text": null }, { "code": null, "e": 32085, "s": 31926, "text": "Traceback (most recent call last):\n File \"gfg.py\", line 1, in \n import module_does_not_exist\nModuleNotFoundError: No module named 'module_does_not_exist'\n" }, { "code": null, "e": 32098, "s": 32085, "text": "Akanksha_Rai" }, { "code": null, "e": 32116, "s": 32098, "text": "Python-exceptions" }, { "code": null, "e": 32123, "s": 32116, "text": "Python" }, { "code": null, "e": 32142, "s": 32123, "text": "Technical Scripter" }, { "code": null, "e": 32240, "s": 32142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32249, "s": 32240, "text": "Comments" }, { "code": null, "e": 32262, "s": 32249, "text": "Old Comments" }, { "code": null, "e": 32280, "s": 32262, "text": "Python Dictionary" }, { "code": null, "e": 32315, "s": 32280, "text": "Read a file line by line in Python" }, { "code": null, "e": 32337, "s": 32315, "text": "Enumerate() in Python" }, { "code": null, "e": 32369, "s": 32337, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32399, "s": 32369, "text": "Iterate over a list in Python" }, { "code": null, "e": 32441, "s": 32399, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32467, "s": 32441, "text": "Python String | replace()" }, { "code": null, "e": 32510, "s": 32467, "text": "Python program to convert a list to string" }, { "code": null, "e": 32554, "s": 32510, "text": "Reading and Writing to text files in Python" } ]
Check if a large number is divisible by 8 or not in C++
Here we will see how to check a number is divisible by 8 or not. In this case the number is very large number. So we put the number as string. A number will be divisible by 8, if the number formed by last three digits are divisible by 8. Live Demo #include <bits/stdc++.h> using namespace std; bool isDiv8(string num){ int n = num.length(); int last_three_digit_val = (num[n-3] - '0') * 100 + (num[n-2] - '0') * 10 + ((num[n-1] - '0')); if(last_three_digit_val % 8 == 0) return true; return false; } int main() { string num = "1754586672360"; if(isDiv8(num)){ cout << "Divisible"; }else{ cout << "Not Divisible"; } } Divisible
[ { "code": null, "e": 1205, "s": 1062, "text": "Here we will see how to check a number is divisible by 8 or not. In this case the number is very large number. So we put the number as string." }, { "code": null, "e": 1300, "s": 1205, "text": "A number will be divisible by 8, if the number formed by last three digits are divisible by 8." }, { "code": null, "e": 1311, "s": 1300, "text": " Live Demo" }, { "code": null, "e": 1725, "s": 1311, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isDiv8(string num){\n int n = num.length();\n int last_three_digit_val = (num[n-3] - '0') * 100 + (num[n-2] - '0') * 10 + ((num[n-1] - '0'));\n if(last_three_digit_val % 8 == 0)\n return true;\n return false;\n}\nint main() {\n string num = \"1754586672360\";\n if(isDiv8(num)){\n cout << \"Divisible\";\n }else{\n cout << \"Not Divisible\";\n }\n}" }, { "code": null, "e": 1735, "s": 1725, "text": "Divisible" } ]
Python - Data Science Environment Setup
To successfully create and run the example code in this tutorial we will need an environment set up which will have both general-purpose python as well as the special packages required for Data science. We will first look as installing the general-purpose python which can be python 2 or python 3. But we will prefer python 2 for this tutorial mainly because of its maturity and wider support of external packages. The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/ You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats. Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Python on various platforms − Here are the simple steps to install Python on Unix/Linux machine. Open a Web browser and go to https://www.python.org/downloads/. Open a Web browser and go to https://www.python.org/downloads/. Follow the link to download zipped source code available for Unix/Linux. Follow the link to download zipped source code available for Unix/Linux. Download and extract files. Download and extract files. Editing the Modules/Setup file if you want to customize some options. Editing the Modules/Setup file if you want to customize some options. run ./configure script run ./configure script make make make install make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python. Here are the steps to install Python on Windows machine. Open a Web browser and go to https://www.python.org/downloads/. Open a Web browser and go to https://www.python.org/downloads/. Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available. Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation. Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables. The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs. The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not). In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path. To add the Python directory to the path for a particular session in Unix − In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter. In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter. In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter. In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter. In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter. In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter. Note − /usr/local/bin/python is the path of the Python directory Note − /usr/local/bin/python is the path of the Python directory To add the Python directory to the path for a particular session in Windows − At the command prompt − type path %path%;C:\Python and press Enter. Note − C:\Python is the path of the Python directory Here are important environment variables, which can be recognized by Python − PYTHONPATH It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer. PYTHONSTARTUP It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH. PYTHONCASEOK It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it. PYTHONHOME It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. There are three different ways to start Python − You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. Enter python the command line. Start coding right away in the interactive interpreter. $python # Unix/Linux or python% # Unix/Linux or C:> python # Windows/DOS Here is the list of all the available command line options − -d It provides debug output. -O It generates optimized bytecode (resulting in .pyo files). -S Do not run import site to look for Python paths on startup. -v verbose output (detailed trace on import statements). -X disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6. -c cmd run Python script sent in as cmd string file run Python script from given file A Python script can be executed at command line by invoking the interpreter on your application, as in the following − $python script.py # Unix/Linux or python% script.py # Unix/Linux or C: >python script.py # Windows/DOS Note − Be sure the file permission mode allows execution. You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python. Unix − IDLE is the very first Unix IDE for Python. Unix − IDLE is the very first Unix IDE for Python. Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI. Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI. Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. The best way to enable the required packs is to use an installable binary package specific to your operating system. These binaries contain full SciPy stack (inclusive of NumPy, SciPy, matplotlib, IPython, SymPy and nose packages along with core Python). Anaconda (from www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac. Canopy (www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac. Python (x,y): It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from www.python-xy.github.io/) Package managers of respective Linux distributions are used to install one or more packages in SciPy stack. sudo apt-get install python-numpy python-scipy python-matplotlibipythonipythonnotebook python-pandas python-sympy python-nose sudo yum install numpyscipy python-matplotlibipython python-pandas sympy python-nose atlas-devel Core Python (2.6.x, 2.7.x and 3.2.x onwards) must be installed with distutils and zlib module should be enabled. GNU gcc (4.2 and above) C compiler must be available. To install NumPy, run the following command. Python setup.py install Let us test whether NumPy module is properly installed, try to import it from Python prompt. If it is not installed, the following error message will be displayed. Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import numpy ImportError: No module named 'numpy' Similarly we can check for the installation of all the required Data Science packages shown in the next chapters. 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": 2944, "s": 2529, "text": "To successfully create and run the example code in this tutorial we will need an environment set up which will have both general-purpose python as well as the special packages required for Data science. We will first look as installing the general-purpose python which can be python 2 or python 3. But we will prefer python 2 for this tutorial mainly because of its maturity and wider support of external packages." }, { "code": null, "e": 3097, "s": 2944, "text": "The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/" }, { "code": null, "e": 3238, "s": 3097, "text": "You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats." }, { "code": null, "e": 3395, "s": 3238, "text": "Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python." }, { "code": null, "e": 3629, "s": 3395, "text": "If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation." }, { "code": null, "e": 3698, "s": 3629, "text": "Here is a quick overview of installing Python on various platforms −" }, { "code": null, "e": 3765, "s": 3698, "text": "Here are the simple steps to install Python on Unix/Linux machine." }, { "code": null, "e": 3829, "s": 3765, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 3893, "s": 3829, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 3966, "s": 3893, "text": "Follow the link to download zipped source code available for Unix/Linux." }, { "code": null, "e": 4039, "s": 3966, "text": "Follow the link to download zipped source code available for Unix/Linux." }, { "code": null, "e": 4067, "s": 4039, "text": "Download and extract files." }, { "code": null, "e": 4095, "s": 4067, "text": "Download and extract files." }, { "code": null, "e": 4165, "s": 4095, "text": "Editing the Modules/Setup file if you want to customize some options." }, { "code": null, "e": 4235, "s": 4165, "text": "Editing the Modules/Setup file if you want to customize some options." }, { "code": null, "e": 4258, "s": 4235, "text": "run ./configure script" }, { "code": null, "e": 4281, "s": 4258, "text": "run ./configure script" }, { "code": null, "e": 4286, "s": 4281, "text": "make" }, { "code": null, "e": 4291, "s": 4286, "text": "make" }, { "code": null, "e": 4304, "s": 4291, "text": "make install" }, { "code": null, "e": 4317, "s": 4304, "text": "make install" }, { "code": null, "e": 4454, "s": 4317, "text": "This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python." }, { "code": null, "e": 4511, "s": 4454, "text": "Here are the steps to install Python on Windows machine." }, { "code": null, "e": 4575, "s": 4511, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 4639, "s": 4575, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 4747, "s": 4639, "text": "Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install." }, { "code": null, "e": 4855, "s": 4747, "text": "Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install." }, { "code": null, "e": 5054, "s": 4855, "text": "To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI." }, { "code": null, "e": 5253, "s": 5054, "text": "To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI." }, { "code": null, "e": 5437, "s": 5253, "text": "Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done." }, { "code": null, "e": 5621, "s": 5437, "text": "Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done." }, { "code": null, "e": 5932, "s": 5621, "text": "Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available." }, { "code": null, "e": 6139, "s": 5932, "text": "Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation." }, { "code": null, "e": 6311, "s": 6139, "text": "Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables." }, { "code": null, "e": 6504, "s": 6311, "text": "The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs." }, { "code": null, "e": 6608, "s": 6504, "text": "The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not)." }, { "code": null, "e": 6771, "s": 6608, "text": "In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path." }, { "code": null, "e": 6846, "s": 6771, "text": "To add the Python directory to the path for a particular session in Unix −" }, { "code": null, "e": 6929, "s": 6846, "text": "In the csh shell − type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7012, "s": 6929, "text": "In the csh shell − type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7103, "s": 7012, "text": "In the bash shell (Linux) − type export ATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7194, "s": 7103, "text": "In the bash shell (Linux) − type export ATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7276, "s": 7194, "text": "In the sh or ksh shell − type PATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7358, "s": 7276, "text": "In the sh or ksh shell − type PATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7423, "s": 7358, "text": "Note − /usr/local/bin/python is the path of the Python directory" }, { "code": null, "e": 7488, "s": 7423, "text": "Note − /usr/local/bin/python is the path of the Python directory" }, { "code": null, "e": 7566, "s": 7488, "text": "To add the Python directory to the path for a particular session in Windows −" }, { "code": null, "e": 7634, "s": 7566, "text": "At the command prompt − type path %path%;C:\\Python and press Enter." }, { "code": null, "e": 7688, "s": 7634, "text": "Note − C:\\Python is the path of the Python directory" }, { "code": null, "e": 7766, "s": 7688, "text": "Here are important environment variables, which can be recognized by Python −" }, { "code": null, "e": 7777, "s": 7766, "text": "PYTHONPATH" }, { "code": null, "e": 8070, "s": 7777, "text": "It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer." }, { "code": null, "e": 8084, "s": 8070, "text": "PYTHONSTARTUP" }, { "code": null, "e": 8318, "s": 8084, "text": "It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it\ncontains commands that load utilities or modify PYTHONPATH." }, { "code": null, "e": 8331, "s": 8318, "text": "PYTHONCASEOK" }, { "code": null, "e": 8484, "s": 8331, "text": "It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it." }, { "code": null, "e": 8495, "s": 8484, "text": "PYTHONHOME" }, { "code": null, "e": 8647, "s": 8495, "text": "It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy." }, { "code": null, "e": 8696, "s": 8647, "text": "There are three different ways to start Python −" }, { "code": null, "e": 8815, "s": 8696, "text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window." }, { "code": null, "e": 8846, "s": 8815, "text": "Enter python the command line." }, { "code": null, "e": 8902, "s": 8846, "text": "Start coding right away in the interactive interpreter." }, { "code": null, "e": 8976, "s": 8902, "text": "$python # Unix/Linux\nor\npython% # Unix/Linux\nor\nC:> python # Windows/DOS\n" }, { "code": null, "e": 9037, "s": 8976, "text": "Here is the list of all the available command line options −" }, { "code": null, "e": 9040, "s": 9037, "text": "-d" }, { "code": null, "e": 9066, "s": 9040, "text": "It provides debug output." }, { "code": null, "e": 9069, "s": 9066, "text": "-O" }, { "code": null, "e": 9128, "s": 9069, "text": "It generates optimized bytecode (resulting in .pyo files)." }, { "code": null, "e": 9131, "s": 9128, "text": "-S" }, { "code": null, "e": 9191, "s": 9131, "text": "Do not run import site to look for Python paths on startup." }, { "code": null, "e": 9194, "s": 9191, "text": "-v" }, { "code": null, "e": 9248, "s": 9194, "text": "verbose output (detailed trace on import statements)." }, { "code": null, "e": 9251, "s": 9248, "text": "-X" }, { "code": null, "e": 9347, "s": 9251, "text": "disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6." }, { "code": null, "e": 9354, "s": 9347, "text": "-c cmd" }, { "code": null, "e": 9394, "s": 9354, "text": "run Python script sent in as cmd string" }, { "code": null, "e": 9399, "s": 9394, "text": "file" }, { "code": null, "e": 9433, "s": 9399, "text": "run Python script from given file" }, { "code": null, "e": 9552, "s": 9433, "text": "A Python script can be executed at command line by invoking the interpreter on your application, as in the following −" }, { "code": null, "e": 9661, "s": 9552, "text": "$python script.py # Unix/Linux\n\nor\n\npython% script.py # Unix/Linux\n\nor \n\nC: >python script.py # Windows/DOS\n" }, { "code": null, "e": 9719, "s": 9661, "text": "Note − Be sure the file permission mode allows execution." }, { "code": null, "e": 9864, "s": 9719, "text": "You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python." }, { "code": null, "e": 9915, "s": 9864, "text": "Unix − IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 9966, "s": 9915, "text": "Unix − IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 10054, "s": 9966, "text": "Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 10142, "s": 10054, "text": "Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 10299, "s": 10142, "text": "Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 10456, "s": 10299, "text": "Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 10711, "s": 10456, "text": "The best way to enable the required packs is to use an installable binary package specific to your operating system. These binaries contain full SciPy stack (inclusive of NumPy, SciPy, matplotlib, IPython, SymPy and nose packages along with core Python)." }, { "code": null, "e": 10831, "s": 10711, "text": "Anaconda (from www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac." }, { "code": null, "e": 10981, "s": 10831, "text": "Canopy (www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac." }, { "code": null, "e": 11121, "s": 10981, "text": "Python (x,y): It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from www.python-xy.github.io/)" }, { "code": null, "e": 11229, "s": 11121, "text": "Package managers of respective Linux distributions are used to install one or more packages in SciPy stack." }, { "code": null, "e": 11358, "s": 11229, "text": "sudo apt-get install python-numpy \npython-scipy python-matplotlibipythonipythonnotebook python-pandas \npython-sympy python-nose\n" }, { "code": null, "e": 11457, "s": 11358, "text": "sudo yum install numpyscipy python-matplotlibipython \npython-pandas sympy python-nose atlas-devel\n" }, { "code": null, "e": 11570, "s": 11457, "text": "Core Python (2.6.x, 2.7.x and 3.2.x onwards) must be installed with distutils and zlib module should be enabled." }, { "code": null, "e": 11624, "s": 11570, "text": "GNU gcc (4.2 and above) C compiler must be available." }, { "code": null, "e": 11669, "s": 11624, "text": "To install NumPy, run the following command." }, { "code": null, "e": 11694, "s": 11669, "text": "Python setup.py install\n" }, { "code": null, "e": 11787, "s": 11694, "text": "Let us test whether NumPy module is properly installed, try to import it from Python prompt." }, { "code": null, "e": 11858, "s": 11787, "text": "If it is not installed, the following error message will be displayed." }, { "code": null, "e": 11996, "s": 11858, "text": "Traceback (most recent call last): \n File \"<pyshell#0>\", line 1, in <module> \n import numpy \nImportError: No module named 'numpy'\n" }, { "code": null, "e": 12110, "s": 11996, "text": "Similarly we can check for the installation of all the required Data Science packages shown in the next chapters." }, { "code": null, "e": 12147, "s": 12110, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 12163, "s": 12147, "text": " Malhar Lathkar" }, { "code": null, "e": 12196, "s": 12163, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 12215, "s": 12196, "text": " Arnab Chakraborty" }, { "code": null, "e": 12250, "s": 12215, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 12272, "s": 12250, "text": " In28Minutes Official" }, { "code": null, "e": 12306, "s": 12272, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 12334, "s": 12306, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12369, "s": 12334, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 12383, "s": 12369, "text": " Lets Kode It" }, { "code": null, "e": 12416, "s": 12383, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 12433, "s": 12416, "text": " Abhilash Nelson" }, { "code": null, "e": 12440, "s": 12433, "text": " Print" }, { "code": null, "e": 12451, "s": 12440, "text": " Add Notes" } ]
How can I scroll a web page using selenium webdriver in python?
Sometimes we need to perform action on an element which is not present in the viewable area of the page. We need to scroll down to the page in order to reach that element. Selenium cannot perform scrolling action directly. This can be achieved with the help of Javascript Executor and Actions class in Selenium. DOM can work on all elements on the web page with the help of Javascript. Selenium can execute commands in Javascript with the help of the execute_script() method. For the Javascript solution, we have to pass true value to the method scrollIntoView() to identify the object below our current location on the page. We can execute mouse movement with the help of the Actions class in Selenium. Code Implementation with Javascript Executor. import time from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") driver.get("https://www.tutorialspoint.com/index.htm") # identify element l= driver.find_element_by_xpath("//*[text()='About Us']") # Javascript Executor driver.execute_script("arguments[0].scrollIntoView(true);", l) time.sleep(0.4) driver.close While working with Actions class to scroll to view, we have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element. Code Implementation with Actions. from selenium.webdriver import ActionChains from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") driver.get("https://www.tutorialspoint.com/index.htm") # identify element I=driver.find_element_by_xpath("//*[text()='About Us']") # action object creation to scroll a = ActionChains(driver) a.move_to_element(l).perform()
[ { "code": null, "e": 1234, "s": 1062, "text": "Sometimes we need to perform action on an element which is not present in the viewable area of the page. We need to scroll down to the page in order to reach that element." }, { "code": null, "e": 1448, "s": 1234, "text": "Selenium cannot perform scrolling action directly. This can be achieved with the help of Javascript Executor and Actions class in Selenium. DOM can work on all elements on the web page with the help of Javascript." }, { "code": null, "e": 1766, "s": 1448, "text": "Selenium can execute commands in Javascript with the help of the execute_script() method. For the Javascript solution, we have to pass true value to the method scrollIntoView() to identify the object below our current location on the page. We can execute mouse movement with the help of the Actions class in Selenium." }, { "code": null, "e": 1812, "s": 1766, "text": "Code Implementation with Javascript Executor." }, { "code": null, "e": 2168, "s": 1812, "text": "import time\nfrom selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n# identify element\nl= driver.find_element_by_xpath(\"//*[text()='About Us']\")\n# Javascript Executor\ndriver.execute_script(\"arguments[0].scrollIntoView(true);\", l)\ntime.sleep(0.4)\ndriver.close" }, { "code": null, "e": 2336, "s": 2168, "text": "While working with Actions class to scroll to view, we have to use the moveToElement() method. This method shall perform mouse movement till the middle of the element." }, { "code": null, "e": 2370, "s": 2336, "text": "Code Implementation with Actions." }, { "code": null, "e": 2734, "s": 2370, "text": "from selenium.webdriver import ActionChains\nfrom selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n# identify element\nI=driver.find_element_by_xpath(\"//*[text()='About Us']\")\n# action object creation to scroll\na = ActionChains(driver)\na.move_to_element(l).perform()" } ]
Belady’s Anomaly in Page Replacement Algorithms
06 May, 2022 Prerequisite – Page Replacement Algorithms In Operating System, process data is loaded in fixed-sized chunks and each chunk is referred to as a page. The processor loads these pages in the fixed-sized chunks of memory called frames. Typically the size of each page is always equal to the frame size. A page fault occurs when a page is not found in the memory and needs to be loaded from the disk. If a page fault occurs and all memory frames have been already allocated, then replacement of a page in memory is required on the request of a new page. This is referred to as demand-paging. The choice of which page to replace is specified by page replacement algorithms. The commonly used page replacement algorithms are FIFO, LRU, optimal page replacement algorithms, etc. Generally, on increasing the number of frames to a process’ virtual memory, its execution becomes faster as fewer page faults occur. Sometimes the reverse happens, i.e. more page faults occur when more frames are allocated to a process. This most unexpected result is termed Belady’s Anomaly. Bélády’s anomaly is the name given to the phenomenon where increasing the number of page frames results in an increase in the number of page faults for a given memory access pattern. This phenomenon is commonly experienced in the following page replacement algorithms: First in first out (FIFO) Second chance algorithm Random page replacement algorithm First in first out (FIFO) Second chance algorithm Random page replacement algorithm Reason for Belady’s Anomaly – The other two commonly used page replacement algorithms are Optimal and LRU, but Belady’s Anomaly can never occur in these algorithms for any reference string as they belong to a class of stack-based page replacement algorithms. A stack-based algorithm is one for which it can be shown that the set of pages in memory for N frames is always a subset of the set of pages that would be in memory with N + 1 frames. For LRU replacement, the set of pages in memory would be the n most recently referenced pages. If the number of frames increases then these n pages will still be the most recently referenced and so, will still be in the memory. While in FIFO, if a page named b came into physical memory before a page – a then priority of replacement of b is greater than that of a, but this is not independent of the number of page frames and hence, FIFO does not follow a stack page replacement policy and therefore suffers Belady’s Anomaly. Example: Consider the following diagram to understand the behavior of a stack-based page replacement algorithm The diagram illustrates that given the set of pages i.e. {0, 1, 2} in 3 frames of memory is not a subset of the pages in memory – {0, 1, 4, 5} with 4 frames and it is a violation in the property of stack based algorithms. This situation can be frequently seen in FIFO algorithm. Belady’s Anomaly in FIFO – Assuming a system that has no pages loaded in the memory and uses the FIFO Page replacement algorithm. Consider the following reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 Case-1: If the system has 3 frames, the given reference string the using FIFO page replacement algorithm yields a total of 9 page faults. The diagram below illustrates the pattern of the page faults occurring in the example. Case-2: If the system has 4 frames, the given reference string using the FIFO page replacement algorithm yields a total of 10 page faults. The diagram below illustrates the pattern of the page faults occurring in the example. It can be seen from the above example that on increasing the number of frames while using the FIFO page replacement algorithm, the number of page faults increased from 9 to 10. Note – It is not necessary that every string reference pattern cause Belady anomaly in FIFO but there is certain kind of string references that worsen the FIFO performance on increasing the number of frames. Why Stack based algorithms do not suffer Anomaly – All the stack based algorithms never suffer Belady Anomaly because these type of algorithms assigns a priority to a page (for replacement) that is independent of the number of page frames. Examples of such policies are Optimal, LRU and LFU. Additionally these algorithms also have a good property for simulation, i.e. the miss (or hit) ratio can be computed for any number of page frames with a single pass through the reference string. In LRU algorithm every time a page is referenced it is moved at the top of the stack, so, the top n pages of the stack are the n most recently used pages. Even if the number of frames is incremented to n+1, top of the stack will have n+1 most recently used pages. Similar example can be used to calculate the number of page faults in LRU algorithm. Assuming a system that has no pages loaded in the memory and uses the LRU Page replacement algorithm. Consider the following reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 Case-1: If the system has 3 frames, the given reference string using the LRU page replacement algorithm yields a total of 10 page faults. The diagram below illustrates the pattern of the page faults occurring in the example. Case-2: If the system has 4 frames, the given reference string on using LRU page replacement algorithm, then total 8 page faults occur. The diagram shows the pattern of the page faults in the example. Conclusion – Various factors substantially affect the number of page faults, such as reference string length and the number of free page frames available. Anomalies also occur due to the small cache size as well as the reckless rate of change of the contents of the cache. Also, the situation of a fixed number of page faults even after increasing the number of frames can also be seen as an anomaly. Often algorithms like Random page replacement algorithm are also susceptible to Belady’s Anomaly, because it may behave like first in first out (FIFO) page replacement algorithm. But Stack based algorithms are generally immune to all such situations as they are guaranteed to give better page hits when the frames are incremented. GATE CS Corner questions – Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. GATE-CS-2001 | Question 21GATE-CS-2009 | Question 8ISRO CS 2011 | Question 73GATE-CS-2016 (Set 2) | Question 30ISRO CS 2016 | Question 48GATE CS Mock 2018 | Question 63 GATE-CS-2001 | Question 21 GATE-CS-2009 | Question 8 ISRO CS 2011 | Question 73 GATE-CS-2016 (Set 2) | Question 30 ISRO CS 2016 | Question 48 GATE CS Mock 2018 | Question 63 Pushpender007 rkbhola5 GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 May, 2022" }, { "code": null, "e": 353, "s": 52, "text": "Prerequisite – Page Replacement Algorithms In Operating System, process data is loaded in fixed-sized chunks and each chunk is referred to as a page. The processor loads these pages in the fixed-sized chunks of memory called frames. Typically the size of each page is always equal to the frame size. " }, { "code": null, "e": 826, "s": 353, "text": "A page fault occurs when a page is not found in the memory and needs to be loaded from the disk. If a page fault occurs and all memory frames have been already allocated, then replacement of a page in memory is required on the request of a new page. This is referred to as demand-paging. The choice of which page to replace is specified by page replacement algorithms. The commonly used page replacement algorithms are FIFO, LRU, optimal page replacement algorithms, etc. " }, { "code": null, "e": 1120, "s": 826, "text": "Generally, on increasing the number of frames to a process’ virtual memory, its execution becomes faster as fewer page faults occur. Sometimes the reverse happens, i.e. more page faults occur when more frames are allocated to a process. This most unexpected result is termed Belady’s Anomaly. " }, { "code": null, "e": 1306, "s": 1120, "text": "Bélády’s anomaly is the name given to the phenomenon where increasing the number of page frames results in an increase in the number of page faults for a given memory access pattern. " }, { "code": null, "e": 1393, "s": 1306, "text": "This phenomenon is commonly experienced in the following page replacement algorithms: " }, { "code": null, "e": 1478, "s": 1393, "text": "First in first out (FIFO) Second chance algorithm Random page replacement algorithm " }, { "code": null, "e": 1505, "s": 1478, "text": "First in first out (FIFO) " }, { "code": null, "e": 1530, "s": 1505, "text": "Second chance algorithm " }, { "code": null, "e": 1565, "s": 1530, "text": "Random page replacement algorithm " }, { "code": null, "e": 1825, "s": 1565, "text": "Reason for Belady’s Anomaly – The other two commonly used page replacement algorithms are Optimal and LRU, but Belady’s Anomaly can never occur in these algorithms for any reference string as they belong to a class of stack-based page replacement algorithms. " }, { "code": null, "e": 2537, "s": 1825, "text": "A stack-based algorithm is one for which it can be shown that the set of pages in memory for N frames is always a subset of the set of pages that would be in memory with N + 1 frames. For LRU replacement, the set of pages in memory would be the n most recently referenced pages. If the number of frames increases then these n pages will still be the most recently referenced and so, will still be in the memory. While in FIFO, if a page named b came into physical memory before a page – a then priority of replacement of b is greater than that of a, but this is not independent of the number of page frames and hence, FIFO does not follow a stack page replacement policy and therefore suffers Belady’s Anomaly. " }, { "code": null, "e": 2649, "s": 2537, "text": "Example: Consider the following diagram to understand the behavior of a stack-based page replacement algorithm " }, { "code": null, "e": 2929, "s": 2649, "text": "The diagram illustrates that given the set of pages i.e. {0, 1, 2} in 3 frames of memory is not a subset of the pages in memory – {0, 1, 4, 5} with 4 frames and it is a violation in the property of stack based algorithms. This situation can be frequently seen in FIFO algorithm. " }, { "code": null, "e": 3101, "s": 2929, "text": "Belady’s Anomaly in FIFO – Assuming a system that has no pages loaded in the memory and uses the FIFO Page replacement algorithm. Consider the following reference string: " }, { "code": null, "e": 3137, "s": 3101, "text": "1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 " }, { "code": null, "e": 3363, "s": 3137, "text": "Case-1: If the system has 3 frames, the given reference string the using FIFO page replacement algorithm yields a total of 9 page faults. The diagram below illustrates the pattern of the page faults occurring in the example. " }, { "code": null, "e": 3590, "s": 3363, "text": "Case-2: If the system has 4 frames, the given reference string using the FIFO page replacement algorithm yields a total of 10 page faults. The diagram below illustrates the pattern of the page faults occurring in the example. " }, { "code": null, "e": 3768, "s": 3590, "text": "It can be seen from the above example that on increasing the number of frames while using the FIFO page replacement algorithm, the number of page faults increased from 9 to 10. " }, { "code": null, "e": 3977, "s": 3768, "text": "Note – It is not necessary that every string reference pattern cause Belady anomaly in FIFO but there is certain kind of string references that worsen the FIFO performance on increasing the number of frames. " }, { "code": null, "e": 4466, "s": 3977, "text": "Why Stack based algorithms do not suffer Anomaly – All the stack based algorithms never suffer Belady Anomaly because these type of algorithms assigns a priority to a page (for replacement) that is independent of the number of page frames. Examples of such policies are Optimal, LRU and LFU. Additionally these algorithms also have a good property for simulation, i.e. the miss (or hit) ratio can be computed for any number of page frames with a single pass through the reference string. " }, { "code": null, "e": 4731, "s": 4466, "text": "In LRU algorithm every time a page is referenced it is moved at the top of the stack, so, the top n pages of the stack are the n most recently used pages. Even if the number of frames is incremented to n+1, top of the stack will have n+1 most recently used pages. " }, { "code": null, "e": 4960, "s": 4731, "text": "Similar example can be used to calculate the number of page faults in LRU algorithm. Assuming a system that has no pages loaded in the memory and uses the LRU Page replacement algorithm. Consider the following reference string: " }, { "code": null, "e": 4997, "s": 4960, "text": "1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 " }, { "code": null, "e": 5223, "s": 4997, "text": "Case-1: If the system has 3 frames, the given reference string using the LRU page replacement algorithm yields a total of 10 page faults. The diagram below illustrates the pattern of the page faults occurring in the example. " }, { "code": null, "e": 5425, "s": 5223, "text": "Case-2: If the system has 4 frames, the given reference string on using LRU page replacement algorithm, then total 8 page faults occur. The diagram shows the pattern of the page faults in the example. " }, { "code": null, "e": 6158, "s": 5425, "text": "Conclusion – Various factors substantially affect the number of page faults, such as reference string length and the number of free page frames available. Anomalies also occur due to the small cache size as well as the reckless rate of change of the contents of the cache. Also, the situation of a fixed number of page faults even after increasing the number of frames can also be seen as an anomaly. Often algorithms like Random page replacement algorithm are also susceptible to Belady’s Anomaly, because it may behave like first in first out (FIFO) page replacement algorithm. But Stack based algorithms are generally immune to all such situations as they are guaranteed to give better page hits when the frames are incremented. " }, { "code": null, "e": 6384, "s": 6158, "text": "GATE CS Corner questions – Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. " }, { "code": null, "e": 6553, "s": 6384, "text": "GATE-CS-2001 | Question 21GATE-CS-2009 | Question 8ISRO CS 2011 | Question 73GATE-CS-2016 (Set 2) | Question 30ISRO CS 2016 | Question 48GATE CS Mock 2018 | Question 63" }, { "code": null, "e": 6580, "s": 6553, "text": "GATE-CS-2001 | Question 21" }, { "code": null, "e": 6606, "s": 6580, "text": "GATE-CS-2009 | Question 8" }, { "code": null, "e": 6633, "s": 6606, "text": "ISRO CS 2011 | Question 73" }, { "code": null, "e": 6668, "s": 6633, "text": "GATE-CS-2016 (Set 2) | Question 30" }, { "code": null, "e": 6695, "s": 6668, "text": "ISRO CS 2016 | Question 48" }, { "code": null, "e": 6727, "s": 6695, "text": "GATE CS Mock 2018 | Question 63" }, { "code": null, "e": 6743, "s": 6729, "text": "Pushpender007" }, { "code": null, "e": 6752, "s": 6743, "text": "rkbhola5" }, { "code": null, "e": 6760, "s": 6752, "text": "GATE CS" }, { "code": null, "e": 6778, "s": 6760, "text": "Operating Systems" }, { "code": null, "e": 6796, "s": 6778, "text": "Operating Systems" } ]
Sum of the sequence 2, 22, 222, .........
15 Jun, 2022 Find the sum of the following sequence : 2, 22, 222, ......... to n terms. Examples : Input : 2 Output: 1.9926 Input : 3 Output: 23.9112 A simple solution is to compute terms one by one and add to the result.The above problem can be efficiently solved using the following formula: C++ Java Python3 C# PHP Javascript // CPP program to find sum of series// 2, 22, 222, ..#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesfloat sumOfSeries(int n){ return 0.0246 * (pow(10, n) - 1 - (9 * n));} // driver codeint main(){ int n = 3; cout << sumOfSeries(n); return 0;} // JAVA Code for Sum of the// sequence 2, 22, 222,...import java.util.*; class GFG { // function which return the // the sum of series static double sumOfSeries(int n) { return 0.0246 * (Math.pow(10, n) - 1 - (9 * n)); } /* Driver program */ public static void main(String[] args) { int n = 3; System.out.println(sumOfSeries(n)); }} // This code is contributed by Arnav Kr. Mandal. # Python3 code to find# sum of series# 2, 22, 222, ..import math # function which return# the sum of seriesdef sumOfSeries( n ): return 0.0246 * (math.pow(10, n) - 1 - (9 * n)) # driver coden = 3print( sumOfSeries(n)) # This code is contributed by "Sharad_Bhardwaj". // C# Code for Sum of the// sequence 2, 22, 222,...using System; class GFG { // Function which return the // the sum of series static double sumOfSeries(int n) { return 0.0246 * (Math.Pow(10, n) - 1 - (9 * n)); } // Driver Code public static void Main() { int n = 3; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m. <?php// PHP program to find sum// of series 2, 22, 222, .. // function which return the// the sum of seriesfunction sumOfSeries($n){ return 0.0246 * (pow(10, $n) - 1 - (9 * $n));} // Driver Code$n = 3;echo(sumOfSeries($n)); // This code is contributed by Ajit.?> <script> // JavaScript program for Sum of the// sequence 2, 22, 222,... // function which return the // the sum of series function sumOfSeries(n) { return 0.0246 * (Math.pow(10, n) - 1 - (9 * n)); } // Driver code let n = 3; document.write(sumOfSeries(n)); </script> Output : 23.9112 Time complexity: O(log n) since using inbuilt power function. Auxiliary Space: O(1) jit_t splevel62 technophpfij series series-sum Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Fizz Buzz Implementation Count ways to reach the n'th stair Product of Array except itself Median of two sorted arrays of same size Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2022" }, { "code": null, "e": 142, "s": 54, "text": "Find the sum of the following sequence : 2, 22, 222, ......... to n terms. Examples : " }, { "code": null, "e": 194, "s": 142, "text": "Input : 2\nOutput: 1.9926\n\nInput : 3\nOutput: 23.9112" }, { "code": null, "e": 341, "s": 196, "text": "A simple solution is to compute terms one by one and add to the result.The above problem can be efficiently solved using the following formula: " }, { "code": null, "e": 347, "s": 343, "text": "C++" }, { "code": null, "e": 352, "s": 347, "text": "Java" }, { "code": null, "e": 360, "s": 352, "text": "Python3" }, { "code": null, "e": 363, "s": 360, "text": "C#" }, { "code": null, "e": 367, "s": 363, "text": "PHP" }, { "code": null, "e": 378, "s": 367, "text": "Javascript" }, { "code": "// CPP program to find sum of series// 2, 22, 222, ..#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesfloat sumOfSeries(int n){ return 0.0246 * (pow(10, n) - 1 - (9 * n));} // driver codeint main(){ int n = 3; cout << sumOfSeries(n); return 0;}", "e": 679, "s": 378, "text": null }, { "code": "// JAVA Code for Sum of the// sequence 2, 22, 222,...import java.util.*; class GFG { // function which return the // the sum of series static double sumOfSeries(int n) { return 0.0246 * (Math.pow(10, n) - 1 - (9 * n)); } /* Driver program */ public static void main(String[] args) { int n = 3; System.out.println(sumOfSeries(n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 1148, "s": 679, "text": null }, { "code": "# Python3 code to find# sum of series# 2, 22, 222, ..import math # function which return# the sum of seriesdef sumOfSeries( n ): return 0.0246 * (math.pow(10, n) - 1 - (9 * n)) # driver coden = 3print( sumOfSeries(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 1422, "s": 1148, "text": null }, { "code": "// C# Code for Sum of the// sequence 2, 22, 222,...using System; class GFG { // Function which return the // the sum of series static double sumOfSeries(int n) { return 0.0246 * (Math.Pow(10, n) - 1 - (9 * n)); } // Driver Code public static void Main() { int n = 3; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m.", "e": 1844, "s": 1422, "text": null }, { "code": "<?php// PHP program to find sum// of series 2, 22, 222, .. // function which return the// the sum of seriesfunction sumOfSeries($n){ return 0.0246 * (pow(10, $n) - 1 - (9 * $n));} // Driver Code$n = 3;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>", "e": 2130, "s": 1844, "text": null }, { "code": "<script> // JavaScript program for Sum of the// sequence 2, 22, 222,... // function which return the // the sum of series function sumOfSeries(n) { return 0.0246 * (Math.pow(10, n) - 1 - (9 * n)); } // Driver code let n = 3; document.write(sumOfSeries(n)); </script>", "e": 2486, "s": 2130, "text": null }, { "code": null, "e": 2496, "s": 2486, "text": "Output : " }, { "code": null, "e": 2504, "s": 2496, "text": "23.9112" }, { "code": null, "e": 2588, "s": 2504, "text": "Time complexity: O(log n) since using inbuilt power function. Auxiliary Space: O(1)" }, { "code": null, "e": 2594, "s": 2588, "text": "jit_t" }, { "code": null, "e": 2604, "s": 2594, "text": "splevel62" }, { "code": null, "e": 2617, "s": 2604, "text": "technophpfij" }, { "code": null, "e": 2624, "s": 2617, "text": "series" }, { "code": null, "e": 2635, "s": 2624, "text": "series-sum" }, { "code": null, "e": 2648, "s": 2635, "text": "Mathematical" }, { "code": null, "e": 2661, "s": 2648, "text": "Mathematical" }, { "code": null, "e": 2668, "s": 2661, "text": "series" }, { "code": null, "e": 2766, "s": 2668, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2798, "s": 2766, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 2844, "s": 2798, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 2888, "s": 2844, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 2930, "s": 2888, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 2962, "s": 2930, "text": "Check if a number is Palindrome" }, { "code": null, "e": 2987, "s": 2962, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 3022, "s": 2987, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 3053, "s": 3022, "text": "Product of Array except itself" }, { "code": null, "e": 3094, "s": 3053, "text": "Median of two sorted arrays of same size" } ]
How to remove all items in a Qlistwidget in PyQt5?
25 Feb, 2021 Prerequisite: PyQt5 QListWidget There are so many options provided by Python to develop GUI applications and PyQt5 is one of them. PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. In this article, we will learn how to remove all items from QlistWidget in PyQt5. To achieve the required functionality i.e. to cleaning the window or deleting all elements using Qlistwidget in Python, its clear() method is used. Syntax: clear() Import module Create QListWidget Add title and button Add mechanism to delete all items of the list when the button is pressed Display window Program: Python3 # Import Moduleimport sysfrom PyQt5.QtWidgets import * class ListBox(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # Vertical box layout vbox = QVBoxLayout(self) # Horizontal box layout hbox = QHBoxLayout() # Create QlistWidget Object self.listWidget = QListWidget(self) # Add Items to QlistWidget self.listWidget.addItems( ['python', 'c++', 'java', 'pyqt5', 'javascript', 'geeksforgeeks']) # Add Push Button clear_btn = QPushButton('Clear', self) clear_btn.clicked.connect(self.clearListWidget) vbox.addWidget(self.listWidget) hbox.addWidget(clear_btn) vbox.addLayout(hbox) self.setLayout(vbox) # Set geometry self.setGeometry(300, 300, 350, 250) # Set window title self.setWindowTitle('QListWidget') # Display QlistWidget self.show() def clearListWidget(self): self.listWidget.clear() if __name__ == '__main__': app = QApplication(sys.argv) # Call ListBox Class ex = ListBox() # Close the window sys.exit(app.exec_()) Output: Picked PyQt5-Widget Python-gui Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2021" }, { "code": null, "e": 42, "s": 28, "text": "Prerequisite:" }, { "code": null, "e": 48, "s": 42, "text": "PyQt5" }, { "code": null, "e": 60, "s": 48, "text": "QListWidget" }, { "code": null, "e": 365, "s": 60, "text": "There are so many options provided by Python to develop GUI applications and PyQt5 is one of them. PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library." }, { "code": null, "e": 595, "s": 365, "text": "In this article, we will learn how to remove all items from QlistWidget in PyQt5. To achieve the required functionality i.e. to cleaning the window or deleting all elements using Qlistwidget in Python, its clear() method is used." }, { "code": null, "e": 603, "s": 595, "text": "Syntax:" }, { "code": null, "e": 611, "s": 603, "text": "clear()" }, { "code": null, "e": 625, "s": 611, "text": "Import module" }, { "code": null, "e": 644, "s": 625, "text": "Create QListWidget" }, { "code": null, "e": 665, "s": 644, "text": "Add title and button" }, { "code": null, "e": 738, "s": 665, "text": "Add mechanism to delete all items of the list when the button is pressed" }, { "code": null, "e": 753, "s": 738, "text": "Display window" }, { "code": null, "e": 762, "s": 753, "text": "Program:" }, { "code": null, "e": 770, "s": 762, "text": "Python3" }, { "code": "# Import Moduleimport sysfrom PyQt5.QtWidgets import * class ListBox(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # Vertical box layout vbox = QVBoxLayout(self) # Horizontal box layout hbox = QHBoxLayout() # Create QlistWidget Object self.listWidget = QListWidget(self) # Add Items to QlistWidget self.listWidget.addItems( ['python', 'c++', 'java', 'pyqt5', 'javascript', 'geeksforgeeks']) # Add Push Button clear_btn = QPushButton('Clear', self) clear_btn.clicked.connect(self.clearListWidget) vbox.addWidget(self.listWidget) hbox.addWidget(clear_btn) vbox.addLayout(hbox) self.setLayout(vbox) # Set geometry self.setGeometry(300, 300, 350, 250) # Set window title self.setWindowTitle('QListWidget') # Display QlistWidget self.show() def clearListWidget(self): self.listWidget.clear() if __name__ == '__main__': app = QApplication(sys.argv) # Call ListBox Class ex = ListBox() # Close the window sys.exit(app.exec_())", "e": 1964, "s": 770, "text": null }, { "code": null, "e": 1972, "s": 1964, "text": "Output:" }, { "code": null, "e": 1979, "s": 1972, "text": "Picked" }, { "code": null, "e": 1992, "s": 1979, "text": "PyQt5-Widget" }, { "code": null, "e": 2003, "s": 1992, "text": "Python-gui" }, { "code": null, "e": 2010, "s": 2003, "text": "Python" }, { "code": null, "e": 2108, "s": 2010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2140, "s": 2108, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2167, "s": 2140, "text": "Python Classes and Objects" }, { "code": null, "e": 2198, "s": 2167, "text": "Python | os.path.join() method" }, { "code": null, "e": 2221, "s": 2198, "text": "Introduction To PYTHON" }, { "code": null, "e": 2242, "s": 2221, "text": "Python OOPs Concepts" }, { "code": null, "e": 2298, "s": 2242, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2340, "s": 2298, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2382, "s": 2340, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2421, "s": 2382, "text": "Python | Get unique values from a list" } ]
response.iter_content() – Python requests
01 Mar, 2020 response.iter_content() iterates over the response.content. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.iter_content() out of a response object. To illustrate use of response.iter_content(), let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC. Download and Install Python 3 Latest Version How to install requests in Python – For windows, linux, mac # import requests moduleimport requests # Making a get requestresponse = requests.get('https://geeksforgeeks.org') # print responseprint(response) # print iter_content dataprint(response.iter_content()) # iterates over the listfor i in response.iter_content(): print(i) Save above file as request.py and run using Python request.py Check that iterator object and iterators at the start of the output, it shows the iterator object and iteration elements in bytes respectively. There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. requests.status_code If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Mar, 2020" }, { "code": null, "e": 462, "s": 28, "text": "response.iter_content() iterates over the response.content. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.iter_content() out of a response object." }, { "code": null, "e": 617, "s": 462, "text": "To illustrate use of response.iter_content(), let’s ping geeksforgeeks.org. To run this script, you need to have Python and requests installed on your PC." }, { "code": null, "e": 662, "s": 617, "text": "Download and Install Python 3 Latest Version" }, { "code": null, "e": 722, "s": 662, "text": "How to install requests in Python – For windows, linux, mac" }, { "code": "# import requests moduleimport requests # Making a get requestresponse = requests.get('https://geeksforgeeks.org') # print responseprint(response) # print iter_content dataprint(response.iter_content()) # iterates over the listfor i in response.iter_content(): print(i)", "e": 999, "s": 722, "text": null }, { "code": null, "e": 1043, "s": 999, "text": "Save above file as request.py and run using" }, { "code": null, "e": 1062, "s": 1043, "text": "Python request.py\n" }, { "code": null, "e": 1206, "s": 1062, "text": "Check that iterator object and iterators at the start of the output, it shows the iterator object and iteration elements in bytes respectively." }, { "code": null, "e": 1457, "s": 1206, "text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute." }, { "code": null, "e": 1478, "s": 1457, "text": "requests.status_code" }, { "code": null, "e": 1635, "s": 1478, "text": "If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources." }, { "code": null, "e": 1651, "s": 1635, "text": "Python-requests" }, { "code": null, "e": 1658, "s": 1651, "text": "Python" }, { "code": null, "e": 1756, "s": 1658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1788, "s": 1756, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1815, "s": 1788, "text": "Python Classes and Objects" }, { "code": null, "e": 1836, "s": 1815, "text": "Python OOPs Concepts" }, { "code": null, "e": 1859, "s": 1836, "text": "Introduction To PYTHON" }, { "code": null, "e": 1890, "s": 1859, "text": "Python | os.path.join() method" }, { "code": null, "e": 1946, "s": 1890, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1988, "s": 1946, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2030, "s": 1988, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2069, "s": 2030, "text": "Python | Get unique values from a list" } ]
Mongoose | findOneAndRemove() Function
20 May, 2020 The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter 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 You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose 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 node index.js Filename: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find only one document matching the// condition(age>=5) and remove itUser.findOneAndRemove({age: {$gte:5} }, function (err, docs) { if (err){ console.log(err) } else{ console.log("Removed User : ", docs); }}); Steps to run the program: The project structure will look like this:Make sure you have installed mongoose module using the following command:npm install mongooseBelow is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see the database as shown below: The project structure will look like this: Make sure you have installed mongoose module using the following command:npm install mongoose npm install mongoose Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js After the function is executed, You can see the database as shown below: So this is how you can use the mongoose findOneAndRemove() function which finds the document according to the condition and then removes the first matched document. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2020" }, { "code": null, "e": 158, "s": 28, "text": "The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element." }, { "code": null, "e": 191, "s": 158, "text": "Installation of mongoose module:" }, { "code": null, "e": 587, "s": 191, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter 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" }, { "code": null, "e": 710, "s": 587, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 731, "s": 710, "text": "npm install mongoose" }, { "code": null, "e": 858, "s": 731, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 879, "s": 858, "text": "npm version mongoose" }, { "code": null, "e": 1027, "s": 879, "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.node index.js" }, { "code": null, "e": 1041, "s": 1027, "text": "node index.js" }, { "code": null, "e": 1060, "s": 1041, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find only one document matching the// condition(age>=5) and remove itUser.findOneAndRemove({age: {$gte:5} }, function (err, docs) { if (err){ console.log(err) } else{ console.log(\"Removed User : \", docs); }});", "e": 1655, "s": 1060, "text": null }, { "code": null, "e": 1681, "s": 1655, "text": "Steps to run the program:" }, { "code": null, "e": 2121, "s": 1681, "text": "The project structure will look like this:Make sure you have installed mongoose module using the following command:npm install mongooseBelow is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see the database as shown below:" }, { "code": null, "e": 2164, "s": 2121, "text": "The project structure will look like this:" }, { "code": null, "e": 2258, "s": 2164, "text": "Make sure you have installed mongoose module using the following command:npm install mongoose" }, { "code": null, "e": 2279, "s": 2258, "text": "npm install mongoose" }, { "code": null, "e": 2461, "s": 2279, "text": "Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 2513, "s": 2461, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2527, "s": 2513, "text": "node index.js" }, { "code": null, "e": 2600, "s": 2527, "text": "After the function is executed, You can see the database as shown below:" }, { "code": null, "e": 2765, "s": 2600, "text": "So this is how you can use the mongoose findOneAndRemove() function which finds the document according to the condition and then removes the first matched document." }, { "code": null, "e": 2774, "s": 2765, "text": "Mongoose" }, { "code": null, "e": 2782, "s": 2774, "text": "MongoDB" }, { "code": null, "e": 2790, "s": 2782, "text": "Node.js" }, { "code": null, "e": 2807, "s": 2790, "text": "Web Technologies" } ]
HTML Entity Parser in C++
Suppose we have a string; we have to design one HTML parser that will replace the special character of HTML syntax into normal character. The HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. These are the special characters and their entities for HTML − Quotation Mark − the entity is " and symbol character is ". Quotation Mark − the entity is " and symbol character is ". Single Quote Mark − the entity is ' and symbol character is '. Single Quote Mark − the entity is ' and symbol character is '. Ampersand − the entity is & and symbol character is &. Ampersand − the entity is & and symbol character is &. Greater Than Sign − the entity is > and symbol character is >. Greater Than Sign − the entity is > and symbol character is >. Less Than Sign − the entity is < and symbol character is <. Less Than Sign − the entity is < and symbol character is <. Slash − the entity is ⁄ and symbol character is /. Slash − the entity is ⁄ and symbol character is /. So, if the input is like "& is changed but &ambassador; is not.", then the output will be "& is changed but &ambassador; is not." To solve this, we will follow these steps − Define an array v = initialize v by splitting string using space Define an array v = initialize v by splitting string using space ret := empty string ret := empty string Define one map m, this will hold all HTML symbol as key and corresponding special character as value Define one map m, this will hold all HTML symbol as key and corresponding special character as value for initialize i := 0, when i < size of v, update (increase i by 1), do −s := v[i]temp := empty stringn := size of v[i]k := 0while k < n, do −if v[i, k] is same as '&', then −temp := temp + v[i, k](increase k by 1)while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1)temp := temp + v[i, k](increase k by 1)if temp is member of m, then −ret := ret + m[temp]Otherwiseret := ret + temptemp := empty stringOtherwiseret := ret + v[i, k](increase k by 1)if size of temp is not 0 and temp is member of m, then −ret := ret concatenate m[temp]otherwise when size of temp, then −ret := ret concatenate tempif i is not equal to size of v, then −ret := ret concatenate blank space for initialize i := 0, when i < size of v, update (increase i by 1), do − s := v[i] s := v[i] temp := empty string temp := empty string n := size of v[i] n := size of v[i] k := 0 k := 0 while k < n, do −if v[i, k] is same as '&', then −temp := temp + v[i, k](increase k by 1)while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1)temp := temp + v[i, k](increase k by 1)if temp is member of m, then −ret := ret + m[temp]Otherwiseret := ret + temptemp := empty stringOtherwiseret := ret + v[i, k](increase k by 1) while k < n, do − if v[i, k] is same as '&', then −temp := temp + v[i, k](increase k by 1)while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1)temp := temp + v[i, k](increase k by 1)if temp is member of m, then −ret := ret + m[temp]Otherwiseret := ret + temptemp := empty string if v[i, k] is same as '&', then − temp := temp + v[i, k] temp := temp + v[i, k] (increase k by 1) (increase k by 1) while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1) while (k < n and v[i, k] is not equal to ';'), do − temp := temp + v[i, k] temp := temp + v[i, k] (increase k by 1) (increase k by 1) temp := temp + v[i, k] temp := temp + v[i, k] (increase k by 1) (increase k by 1) if temp is member of m, then −ret := ret + m[temp] if temp is member of m, then − ret := ret + m[temp] ret := ret + m[temp] Otherwiseret := ret + temp Otherwise ret := ret + temp ret := ret + temp temp := empty string temp := empty string Otherwiseret := ret + v[i, k](increase k by 1) Otherwise ret := ret + v[i, k] ret := ret + v[i, k] (increase k by 1) (increase k by 1) if size of temp is not 0 and temp is member of m, then −ret := ret concatenate m[temp] if size of temp is not 0 and temp is member of m, then − ret := ret concatenate m[temp] ret := ret concatenate m[temp] otherwise when size of temp, then −ret := ret concatenate temp otherwise when size of temp, then − ret := ret concatenate temp ret := ret concatenate temp if i is not equal to size of v, then −ret := ret concatenate blank space if i is not equal to size of v, then − ret := ret concatenate blank space ret := ret concatenate blank space return ret return ret Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: vector <string> split(string& s, char delimiter){ vector <string> tokens; string token; istringstream tokenStream(s); while(getline(tokenStream, token, delimiter)){ tokens.push_back(token); } return tokens; } void out(vector <string> v){ for(string s : v) cout << s << endl; } string entityParser(string text) { vector<string> v = split(text, ' '); string ret = ""; map<string, string> m; m["""] = "\""; m["'"] = "\'"; m["&"] = "&"; m[">"] = ">"; m["<"] = "<"; m["⁄"] = "/"; for (int i = 0; i < v.size(); i++) { string s = v[i]; string temp = ""; int n = v[i].size(); int k = 0; while (k < n) { if (v[i][k] == '&') { temp += v[i][k]; k++; while (k < n && v[i][k] != ';') { temp += v[i][k]; k++; } temp += v[i][k]; k++; if (m.count(temp)) ret += m[temp]; else ret += temp; temp = ""; } else { ret += v[i][k]; k++; } } if (temp.size() && m.count(temp)) { ret += m[temp]; } else if (temp.size()) ret += temp; if (i != v.size() - 1) ret += " "; } return ret; } }; main(){ Solution ob; cout << (ob.entityParser("& is changed but &ambassador; is not.")); } "& is changed but &ambassador; is not." & is changed but &ambassador; is not.
[ { "code": null, "e": 1411, "s": 1062, "text": "Suppose we have a string; we have to design one HTML parser that will replace the special character of HTML syntax into normal character. The HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. These are the special characters and their entities for HTML −" }, { "code": null, "e": 1471, "s": 1411, "text": "Quotation Mark − the entity is \" and symbol character is \"." }, { "code": null, "e": 1531, "s": 1471, "text": "Quotation Mark − the entity is \" and symbol character is \"." }, { "code": null, "e": 1594, "s": 1531, "text": "Single Quote Mark − the entity is ' and symbol character is '." }, { "code": null, "e": 1657, "s": 1594, "text": "Single Quote Mark − the entity is ' and symbol character is '." }, { "code": null, "e": 1712, "s": 1657, "text": "Ampersand − the entity is & and symbol character is &." }, { "code": null, "e": 1767, "s": 1712, "text": "Ampersand − the entity is & and symbol character is &." }, { "code": null, "e": 1830, "s": 1767, "text": "Greater Than Sign − the entity is > and symbol character is >." }, { "code": null, "e": 1893, "s": 1830, "text": "Greater Than Sign − the entity is > and symbol character is >." }, { "code": null, "e": 1953, "s": 1893, "text": "Less Than Sign − the entity is < and symbol character is <." }, { "code": null, "e": 2013, "s": 1953, "text": "Less Than Sign − the entity is < and symbol character is <." }, { "code": null, "e": 2064, "s": 2013, "text": "Slash − the entity is ⁄ and symbol character is /." }, { "code": null, "e": 2115, "s": 2064, "text": "Slash − the entity is ⁄ and symbol character is /." }, { "code": null, "e": 2245, "s": 2115, "text": "So, if the input is like \"& is changed but &ambassador; is not.\", then the output will be \"& is changed but &ambassador; is not.\"" }, { "code": null, "e": 2289, "s": 2245, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2354, "s": 2289, "text": "Define an array v = initialize v by splitting string using space" }, { "code": null, "e": 2419, "s": 2354, "text": "Define an array v = initialize v by splitting string using space" }, { "code": null, "e": 2439, "s": 2419, "text": "ret := empty string" }, { "code": null, "e": 2459, "s": 2439, "text": "ret := empty string" }, { "code": null, "e": 2560, "s": 2459, "text": "Define one map m, this will hold all HTML symbol as key and corresponding special character as value" }, { "code": null, "e": 2661, "s": 2560, "text": "Define one map m, this will hold all HTML symbol as key and corresponding special character as value" }, { "code": null, "e": 3367, "s": 2661, "text": "for initialize i := 0, when i < size of v, update (increase i by 1), do −s := v[i]temp := empty stringn := size of v[i]k := 0while k < n, do −if v[i, k] is same as '&', then −temp := temp + v[i, k](increase k by 1)while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1)temp := temp + v[i, k](increase k by 1)if temp is member of m, then −ret := ret + m[temp]Otherwiseret := ret + temptemp := empty stringOtherwiseret := ret + v[i, k](increase k by 1)if size of temp is not 0 and temp is member of m, then −ret := ret concatenate m[temp]otherwise when size of temp, then −ret := ret concatenate tempif i is not equal to size of v, then −ret := ret concatenate blank space" }, { "code": null, "e": 3441, "s": 3367, "text": "for initialize i := 0, when i < size of v, update (increase i by 1), do −" }, { "code": null, "e": 3451, "s": 3441, "text": "s := v[i]" }, { "code": null, "e": 3461, "s": 3451, "text": "s := v[i]" }, { "code": null, "e": 3482, "s": 3461, "text": "temp := empty string" }, { "code": null, "e": 3503, "s": 3482, "text": "temp := empty string" }, { "code": null, "e": 3521, "s": 3503, "text": "n := size of v[i]" }, { "code": null, "e": 3539, "s": 3521, "text": "n := size of v[i]" }, { "code": null, "e": 3546, "s": 3539, "text": "k := 0" }, { "code": null, "e": 3553, "s": 3546, "text": "k := 0" }, { "code": null, "e": 3914, "s": 3553, "text": "while k < n, do −if v[i, k] is same as '&', then −temp := temp + v[i, k](increase k by 1)while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1)temp := temp + v[i, k](increase k by 1)if temp is member of m, then −ret := ret + m[temp]Otherwiseret := ret + temptemp := empty stringOtherwiseret := ret + v[i, k](increase k by 1)" }, { "code": null, "e": 3932, "s": 3914, "text": "while k < n, do −" }, { "code": null, "e": 4230, "s": 3932, "text": "if v[i, k] is same as '&', then −temp := temp + v[i, k](increase k by 1)while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1)temp := temp + v[i, k](increase k by 1)if temp is member of m, then −ret := ret + m[temp]Otherwiseret := ret + temptemp := empty string" }, { "code": null, "e": 4264, "s": 4230, "text": "if v[i, k] is same as '&', then −" }, { "code": null, "e": 4287, "s": 4264, "text": "temp := temp + v[i, k]" }, { "code": null, "e": 4310, "s": 4287, "text": "temp := temp + v[i, k]" }, { "code": null, "e": 4328, "s": 4310, "text": "(increase k by 1)" }, { "code": null, "e": 4346, "s": 4328, "text": "(increase k by 1)" }, { "code": null, "e": 4437, "s": 4346, "text": "while (k < n and v[i, k] is not equal to ';'), do −temp := temp + v[i, k](increase k by 1)" }, { "code": null, "e": 4489, "s": 4437, "text": "while (k < n and v[i, k] is not equal to ';'), do −" }, { "code": null, "e": 4512, "s": 4489, "text": "temp := temp + v[i, k]" }, { "code": null, "e": 4535, "s": 4512, "text": "temp := temp + v[i, k]" }, { "code": null, "e": 4553, "s": 4535, "text": "(increase k by 1)" }, { "code": null, "e": 4571, "s": 4553, "text": "(increase k by 1)" }, { "code": null, "e": 4594, "s": 4571, "text": "temp := temp + v[i, k]" }, { "code": null, "e": 4617, "s": 4594, "text": "temp := temp + v[i, k]" }, { "code": null, "e": 4635, "s": 4617, "text": "(increase k by 1)" }, { "code": null, "e": 4653, "s": 4635, "text": "(increase k by 1)" }, { "code": null, "e": 4704, "s": 4653, "text": "if temp is member of m, then −ret := ret + m[temp]" }, { "code": null, "e": 4735, "s": 4704, "text": "if temp is member of m, then −" }, { "code": null, "e": 4756, "s": 4735, "text": "ret := ret + m[temp]" }, { "code": null, "e": 4777, "s": 4756, "text": "ret := ret + m[temp]" }, { "code": null, "e": 4804, "s": 4777, "text": "Otherwiseret := ret + temp" }, { "code": null, "e": 4814, "s": 4804, "text": "Otherwise" }, { "code": null, "e": 4832, "s": 4814, "text": "ret := ret + temp" }, { "code": null, "e": 4850, "s": 4832, "text": "ret := ret + temp" }, { "code": null, "e": 4871, "s": 4850, "text": "temp := empty string" }, { "code": null, "e": 4892, "s": 4871, "text": "temp := empty string" }, { "code": null, "e": 4939, "s": 4892, "text": "Otherwiseret := ret + v[i, k](increase k by 1)" }, { "code": null, "e": 4949, "s": 4939, "text": "Otherwise" }, { "code": null, "e": 4970, "s": 4949, "text": "ret := ret + v[i, k]" }, { "code": null, "e": 4991, "s": 4970, "text": "ret := ret + v[i, k]" }, { "code": null, "e": 5009, "s": 4991, "text": "(increase k by 1)" }, { "code": null, "e": 5027, "s": 5009, "text": "(increase k by 1)" }, { "code": null, "e": 5114, "s": 5027, "text": "if size of temp is not 0 and temp is member of m, then −ret := ret concatenate m[temp]" }, { "code": null, "e": 5171, "s": 5114, "text": "if size of temp is not 0 and temp is member of m, then −" }, { "code": null, "e": 5202, "s": 5171, "text": "ret := ret concatenate m[temp]" }, { "code": null, "e": 5233, "s": 5202, "text": "ret := ret concatenate m[temp]" }, { "code": null, "e": 5296, "s": 5233, "text": "otherwise when size of temp, then −ret := ret concatenate temp" }, { "code": null, "e": 5332, "s": 5296, "text": "otherwise when size of temp, then −" }, { "code": null, "e": 5360, "s": 5332, "text": "ret := ret concatenate temp" }, { "code": null, "e": 5388, "s": 5360, "text": "ret := ret concatenate temp" }, { "code": null, "e": 5461, "s": 5388, "text": "if i is not equal to size of v, then −ret := ret concatenate blank space" }, { "code": null, "e": 5500, "s": 5461, "text": "if i is not equal to size of v, then −" }, { "code": null, "e": 5535, "s": 5500, "text": "ret := ret concatenate blank space" }, { "code": null, "e": 5570, "s": 5535, "text": "ret := ret concatenate blank space" }, { "code": null, "e": 5581, "s": 5570, "text": "return ret" }, { "code": null, "e": 5592, "s": 5581, "text": "return ret" }, { "code": null, "e": 5664, "s": 5592, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 5675, "s": 5664, "text": " Live Demo" }, { "code": null, "e": 7355, "s": 5675, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n vector <string> split(string& s, char delimiter){\n vector <string> tokens;\n string token;\n istringstream tokenStream(s);\n while(getline(tokenStream, token, delimiter)){\n tokens.push_back(token);\n }\n return tokens;\n }\n void out(vector <string> v){\n for(string s : v) cout << s << endl;\n }\n string entityParser(string text) {\n vector<string> v = split(text, ' ');\n string ret = \"\";\n map<string, string> m;\n m[\"\"\"] = \"\\\"\";\n m[\"'\"] = \"\\'\";\n m[\"&\"] = \"&\";\n m[\">\"] = \">\";\n m[\"<\"] = \"<\";\n m[\"⁄\"] = \"/\";\n for (int i = 0; i < v.size(); i++) {\n string s = v[i];\n string temp = \"\";\n int n = v[i].size();\n int k = 0;\n while (k < n) {\n if (v[i][k] == '&') {\n temp += v[i][k];\n k++;\n while (k < n && v[i][k] != ';') {\n temp += v[i][k];\n k++;\n }\n temp += v[i][k];\n k++;\n if (m.count(temp))\n ret += m[temp];\n else\n ret += temp;\n temp = \"\";\n }\n else {\n ret += v[i][k];\n k++;\n }\n }\n if (temp.size() && m.count(temp)) {\n ret += m[temp];\n }\n else if (temp.size())\n ret += temp;\n if (i != v.size() - 1)\n ret += \" \";\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.entityParser(\"& is changed but &ambassador; is not.\"));\n}" }, { "code": null, "e": 7395, "s": 7355, "text": "\"& is changed but &ambassador; is not.\"" }, { "code": null, "e": 7433, "s": 7395, "text": "& is changed but &ambassador; is not." } ]
What are the differences between printStackTrace() method and getMessage() method in Java?
There are two ways to find the details of the exception, one is the printStackTrace() method and another is the getMessage() method. This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class. This method will display the name of the exception and nature of the message and line number where an exception has occurred. public class PrintStackTraceMethod { public static void main(String[] args) { try { int a[]= new int[5]; a[5]=20; } catch (Exception e) { e.printStackTrace(); } } } java.lang.ArrayIndexOutOfBoundsException: 5 at PrintStackTraceMethod.main(PrintStackTraceMethod.java:5) This is a method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error and java.lang.Exception classes. This method will display the only exception message. public class GetMessageMethod { public static void main(String[] args) { try { int x=1/0; } catch (Exception e) { System.out.println(e.getMessage()); } } } / by zero
[ { "code": null, "e": 1195, "s": 1062, "text": "There are two ways to find the details of the exception, one is the printStackTrace() method and another is the getMessage() method." }, { "code": null, "e": 1338, "s": 1195, "text": "This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class." }, { "code": null, "e": 1464, "s": 1338, "text": "This method will display the name of the exception and nature of the message and line number where an exception has occurred." }, { "code": null, "e": 1680, "s": 1464, "text": "public class PrintStackTraceMethod {\n public static void main(String[] args) {\n try {\n int a[]= new int[5];\n a[5]=20;\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 1792, "s": 1680, "text": "java.lang.ArrayIndexOutOfBoundsException: 5\n at PrintStackTraceMethod.main(PrintStackTraceMethod.java:5)" }, { "code": null, "e": 1929, "s": 1792, "text": "This is a method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error and java.lang.Exception classes." }, { "code": null, "e": 1982, "s": 1929, "text": "This method will display the only exception message." }, { "code": null, "e": 2180, "s": 1982, "text": "public class GetMessageMethod {\n public static void main(String[] args) {\n try {\n int x=1/0;\n } catch (Exception e) {\n System.out.println(e.getMessage());\n }\n }\n}" }, { "code": null, "e": 2190, "s": 2180, "text": "/ by zero" } ]
Word Clouds in Tableau: Quick & Easy. | by Parul Pandey | Towards Data Science
A Word cloud, also known as a Tag cloud, is a visual representation of text data, typically used to depict keyword metadata (tags) on websites or to visualize free form text[Wikipedia]. Word clouds are a popular typeof infographic with the help of which we can show the relative frequency of words in our data. This can be depicted either by the size or the color of the chosen fields in the data. They are a pretty powerful feature to draw attention to your presentation or story Tableau is a data analytics and a visualization tool widely used in the industry today. Tableau provides a native feature to create Word Clouds with a few mouse clicks. This is going to be a pretty short article emphasizing on the steps required to create a word cloud in Tableau. In case you want a more detailed article to begin with Tableau, make sure you go through my article Data Visualisation with Tableau first. Even though this article is focussed on word clouds, I would also be mentioning some visual best practices with respect to using word clouds. Word clouds look cool but there are some better substitutes that convey the same message but in a more clear and accurate way. The data pertains to the top 20 movies of 2018 in the US having been ranked by domestic box office earnings in billions of dollars. The data also contains the Metacritic scores for each movie. Metacritic is a website that aggregates reviews of media products including movies. All the worksheets and Tableau Workbooks can be accessed from its associated repository here. Open the Tableau Desktop and connect to the data source. You can choose any data format but here we are using an excel file which has the desired data.Drag the desired dimension to Text on the Marks card. Here I am going to drag the Movie Title to the Text since I want to know which movie performed well in terms of the Box office collections.Drag the Domestic Gross earnings on to the Size on the Marks card.Now drag the Domestic Gross earnings on to the Color on the Marks card since we want the color to reflect the earning pattern.Change the Mark type from Automatic to Text.Next, you can hide the title, change the view and the background as per your likings and you have your word cloud ready. Open the Tableau Desktop and connect to the data source. You can choose any data format but here we are using an excel file which has the desired data. Drag the desired dimension to Text on the Marks card. Here I am going to drag the Movie Title to the Text since I want to know which movie performed well in terms of the Box office collections. Drag the Domestic Gross earnings on to the Size on the Marks card. Now drag the Domestic Gross earnings on to the Color on the Marks card since we want the color to reflect the earning pattern. Change the Mark type from Automatic to Text. Next, you can hide the title, change the view and the background as per your likings and you have your word cloud ready. The steps remain the same as above except that we use the Metacritic Score instead of the earnings. The above examples deal with a simple and refined dataset having limited fields. What if the data contained a paragraph or some passage from a book and we were required to create a word cloud for that. Let’s see an example of such an instance. For the demonstration purpose, I have taken the entire passage from one of my medium articles. I copied the entire text irrespective of the content and placed it in a text.txt file. Then I ran a small python script to save the words and their frequencies into a CSV file. You can use any dataset of your choice. from collections import Counterdef word(fname): with open(fname) as f: return Counter(f.read().split())print(word_count("text.txt")) import csvmy_dict = word_count("text.txt")with open('test.csv', 'w') as f: for key in my_dict.keys(): f.write("%s,%s\n"%(key,my_dict[key])) text.csv is the file that contains our dataset and will appear like this: Now switch to Tableau. Create a word cloud as explained above using the words in the text.csv file. If you want to limit the number of entries, you can use the word count as a filter and show only the words with minimum frequency. Remove the most common words — Even after filtering by the word count, we see that there are words like ‘the’, ‘in’ etc which do not hold much significance but are appearing all over the worksheet. Let’s get rid of them. We will begin by creating a list of common words in English which can be accessed from here. The list contains words having a rank associated with them which we will use as a measure for filtering. Now let’s add this sheet into our workbook. The two sheets will be blended against the Words column since that is common to both sources. Create a new parameter and name it as “Words to be excluded” with the following settings: Show the Parameter Control and exclude the most common words from the cloud by filtering. Now adjust the settings and you can have a better-looking word cloud with filter options. Marti A. Hearst’s guest post “What’s up with Tag Clouds” is worth a read when discussing about word clouds. Word clouds are definitely eye-catching and provide a sort of overview or first insight and since they are quite popular, people usually have one or two in their presentations. On the other hand, word clouds do not provide a clear differentiation between words of similar sizes, unlike a bar chart. Also, words belonging to the same category may lie far apart from each other and the smaller ones may be overlooked. TreeMap A Treemap may provide a better, but not the best, idea when compared to a word cloud. Treemaps are sometimes regarded as rectangular cousins of Pie Chart and may not be ideal when displaying detailed information. Bar Chart A sorted Bar Chart definitely provides better and more accurate information since it gives a baseline for comparison. Word Clouds are surely catchy and help the presentation to shine out but when it comes to serious data analysis there are better tools that can be tried out. However, the main aim of this article was to show how to create word clouds in Tableau with minimalistic effort. So you can try out building your own word clouds with data of your choice.
[ { "code": null, "e": 653, "s": 172, "text": "A Word cloud, also known as a Tag cloud, is a visual representation of text data, typically used to depict keyword metadata (tags) on websites or to visualize free form text[Wikipedia]. Word clouds are a popular typeof infographic with the help of which we can show the relative frequency of words in our data. This can be depicted either by the size or the color of the chosen fields in the data. They are a pretty powerful feature to draw attention to your presentation or story" }, { "code": null, "e": 1073, "s": 653, "text": "Tableau is a data analytics and a visualization tool widely used in the industry today. Tableau provides a native feature to create Word Clouds with a few mouse clicks. This is going to be a pretty short article emphasizing on the steps required to create a word cloud in Tableau. In case you want a more detailed article to begin with Tableau, make sure you go through my article Data Visualisation with Tableau first." }, { "code": null, "e": 1342, "s": 1073, "text": "Even though this article is focussed on word clouds, I would also be mentioning some visual best practices with respect to using word clouds. Word clouds look cool but there are some better substitutes that convey the same message but in a more clear and accurate way." }, { "code": null, "e": 1619, "s": 1342, "text": "The data pertains to the top 20 movies of 2018 in the US having been ranked by domestic box office earnings in billions of dollars. The data also contains the Metacritic scores for each movie. Metacritic is a website that aggregates reviews of media products including movies." }, { "code": null, "e": 1713, "s": 1619, "text": "All the worksheets and Tableau Workbooks can be accessed from its associated repository here." }, { "code": null, "e": 2414, "s": 1713, "text": "Open the Tableau Desktop and connect to the data source. You can choose any data format but here we are using an excel file which has the desired data.Drag the desired dimension to Text on the Marks card. Here I am going to drag the Movie Title to the Text since I want to know which movie performed well in terms of the Box office collections.Drag the Domestic Gross earnings on to the Size on the Marks card.Now drag the Domestic Gross earnings on to the Color on the Marks card since we want the color to reflect the earning pattern.Change the Mark type from Automatic to Text.Next, you can hide the title, change the view and the background as per your likings and you have your word cloud ready." }, { "code": null, "e": 2566, "s": 2414, "text": "Open the Tableau Desktop and connect to the data source. You can choose any data format but here we are using an excel file which has the desired data." }, { "code": null, "e": 2760, "s": 2566, "text": "Drag the desired dimension to Text on the Marks card. Here I am going to drag the Movie Title to the Text since I want to know which movie performed well in terms of the Box office collections." }, { "code": null, "e": 2827, "s": 2760, "text": "Drag the Domestic Gross earnings on to the Size on the Marks card." }, { "code": null, "e": 2954, "s": 2827, "text": "Now drag the Domestic Gross earnings on to the Color on the Marks card since we want the color to reflect the earning pattern." }, { "code": null, "e": 2999, "s": 2954, "text": "Change the Mark type from Automatic to Text." }, { "code": null, "e": 3120, "s": 2999, "text": "Next, you can hide the title, change the view and the background as per your likings and you have your word cloud ready." }, { "code": null, "e": 3220, "s": 3120, "text": "The steps remain the same as above except that we use the Metacritic Score instead of the earnings." }, { "code": null, "e": 3464, "s": 3220, "text": "The above examples deal with a simple and refined dataset having limited fields. What if the data contained a paragraph or some passage from a book and we were required to create a word cloud for that. Let’s see an example of such an instance." }, { "code": null, "e": 3776, "s": 3464, "text": "For the demonstration purpose, I have taken the entire passage from one of my medium articles. I copied the entire text irrespective of the content and placed it in a text.txt file. Then I ran a small python script to save the words and their frequencies into a CSV file. You can use any dataset of your choice." }, { "code": null, "e": 3931, "s": 3776, "text": "from collections import Counterdef word(fname): with open(fname) as f: return Counter(f.read().split())print(word_count(\"text.txt\"))" }, { "code": null, "e": 4081, "s": 3931, "text": "import csvmy_dict = word_count(\"text.txt\")with open('test.csv', 'w') as f: for key in my_dict.keys(): f.write(\"%s,%s\\n\"%(key,my_dict[key]))" }, { "code": null, "e": 4155, "s": 4081, "text": "text.csv is the file that contains our dataset and will appear like this:" }, { "code": null, "e": 4178, "s": 4155, "text": "Now switch to Tableau." }, { "code": null, "e": 4255, "s": 4178, "text": "Create a word cloud as explained above using the words in the text.csv file." }, { "code": null, "e": 4386, "s": 4255, "text": "If you want to limit the number of entries, you can use the word count as a filter and show only the words with minimum frequency." }, { "code": null, "e": 4805, "s": 4386, "text": "Remove the most common words — Even after filtering by the word count, we see that there are words like ‘the’, ‘in’ etc which do not hold much significance but are appearing all over the worksheet. Let’s get rid of them. We will begin by creating a list of common words in English which can be accessed from here. The list contains words having a rank associated with them which we will use as a measure for filtering." }, { "code": null, "e": 4943, "s": 4805, "text": "Now let’s add this sheet into our workbook. The two sheets will be blended against the Words column since that is common to both sources." }, { "code": null, "e": 5033, "s": 4943, "text": "Create a new parameter and name it as “Words to be excluded” with the following settings:" }, { "code": null, "e": 5123, "s": 5033, "text": "Show the Parameter Control and exclude the most common words from the cloud by filtering." }, { "code": null, "e": 5213, "s": 5123, "text": "Now adjust the settings and you can have a better-looking word cloud with filter options." }, { "code": null, "e": 5498, "s": 5213, "text": "Marti A. Hearst’s guest post “What’s up with Tag Clouds” is worth a read when discussing about word clouds. Word clouds are definitely eye-catching and provide a sort of overview or first insight and since they are quite popular, people usually have one or two in their presentations." }, { "code": null, "e": 5737, "s": 5498, "text": "On the other hand, word clouds do not provide a clear differentiation between words of similar sizes, unlike a bar chart. Also, words belonging to the same category may lie far apart from each other and the smaller ones may be overlooked." }, { "code": null, "e": 5745, "s": 5737, "text": "TreeMap" }, { "code": null, "e": 5958, "s": 5745, "text": "A Treemap may provide a better, but not the best, idea when compared to a word cloud. Treemaps are sometimes regarded as rectangular cousins of Pie Chart and may not be ideal when displaying detailed information." }, { "code": null, "e": 5968, "s": 5958, "text": "Bar Chart" }, { "code": null, "e": 6086, "s": 5968, "text": "A sorted Bar Chart definitely provides better and more accurate information since it gives a baseline for comparison." } ]
cin get() in C++ with Examples - GeeksforGeeks
17 Jan, 2020 cin.get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (>>) terminates when whitespace is found. However, cin.get() reads a string with the whitespace. Syntax: cin.get(string_name, size); Example 1: // C++ program to demonstrate cin.get() #include <iostream>using namespace std; int main(){ char name[25]; cin.get(name, 25); cout << name; return 0;} Input: Geeks for Geeks Output: Geeks for Geeks Example 2: // C++ program to demonstrate cin.get() #include <iostream>using namespace std; int main(){ char name[100]; cin.get(name, 3); cout << name; return 0;} Input: GFG Output: GF CPP-Functions C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Classes and Objects Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Virtual Function in C++ Constructors in C++ Copy Constructor in C++ Templates in C++ with Examples C++ Data Types unordered_map in C++ STL
[ { "code": null, "e": 24739, "s": 24711, "text": "\n17 Jan, 2020" }, { "code": null, "e": 24964, "s": 24739, "text": "cin.get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (>>) terminates when whitespace is found. However, cin.get() reads a string with the whitespace." }, { "code": null, "e": 24972, "s": 24964, "text": "Syntax:" }, { "code": null, "e": 25000, "s": 24972, "text": "cin.get(string_name, size);" }, { "code": null, "e": 25011, "s": 25000, "text": "Example 1:" }, { "code": "// C++ program to demonstrate cin.get() #include <iostream>using namespace std; int main(){ char name[25]; cin.get(name, 25); cout << name; return 0;}", "e": 25178, "s": 25011, "text": null }, { "code": null, "e": 25185, "s": 25178, "text": "Input:" }, { "code": null, "e": 25201, "s": 25185, "text": "Geeks for Geeks" }, { "code": null, "e": 25209, "s": 25201, "text": "Output:" }, { "code": null, "e": 25225, "s": 25209, "text": "Geeks for Geeks" }, { "code": null, "e": 25236, "s": 25225, "text": "Example 2:" }, { "code": "// C++ program to demonstrate cin.get() #include <iostream>using namespace std; int main(){ char name[100]; cin.get(name, 3); cout << name; return 0;}", "e": 25403, "s": 25236, "text": null }, { "code": null, "e": 25410, "s": 25403, "text": "Input:" }, { "code": null, "e": 25414, "s": 25410, "text": "GFG" }, { "code": null, "e": 25422, "s": 25414, "text": "Output:" }, { "code": null, "e": 25425, "s": 25422, "text": "GF" }, { "code": null, "e": 25439, "s": 25425, "text": "CPP-Functions" }, { "code": null, "e": 25443, "s": 25439, "text": "C++" }, { "code": null, "e": 25462, "s": 25443, "text": "Technical Scripter" }, { "code": null, "e": 25466, "s": 25462, "text": "CPP" }, { "code": null, "e": 25564, "s": 25466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25573, "s": 25564, "text": "Comments" }, { "code": null, "e": 25586, "s": 25573, "text": "Old Comments" }, { "code": null, "e": 25610, "s": 25586, "text": "C++ Classes and Objects" }, { "code": null, "e": 25638, "s": 25610, "text": "Socket Programming in C/C++" }, { "code": null, "e": 25666, "s": 25638, "text": "Operator Overloading in C++" }, { "code": null, "e": 25701, "s": 25666, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25725, "s": 25701, "text": "Virtual Function in C++" }, { "code": null, "e": 25745, "s": 25725, "text": "Constructors in C++" }, { "code": null, "e": 25769, "s": 25745, "text": "Copy Constructor in C++" }, { "code": null, "e": 25800, "s": 25769, "text": "Templates in C++ with Examples" }, { "code": null, "e": 25815, "s": 25800, "text": "C++ Data Types" } ]
How to create hidden form element on the fly using jQuery ? - GeeksforGeeks
31 Oct, 2019 JQuery is the library that makes the use of JavaScript easy. Inserting the <input type=’hidden’> can also be done using jQuery. The append() and appendTo() inbuilt function can be used to add the hidden form element but they are not only limited to the <input type=’hidden’> but we can also add other html elements. Note: They both perform pretty much the same. The major difference is only about the syntax and that is explained below. Using appendTo() method: In the appendTo() method, the content comes before the method like $(content).appendTo(selector). Below examples illustrates the appendTo() method to create hidden form element: Example 1: If only one attribute is to be added, then it can be given by passing two arguments in attr() method. First argument is the name of attribute, and the second argument is the value of the attribute. <!DOCTYPE html> <html> <head> <title>GeeksforGeeks </title> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script></head> <body> <script> $(document).ready(function() { $("<input>").attr("type", "hidden").appendTo("form"); }) </script> <form> Name: <input type="text"> <br> Hidden: </form> </body> </html> Output: The output can be seen in the browser using Inspect Element feature (e.g. ctrl + shift + i in Google Chrome). Example 2: Multiple attributes can also be given by passing them as an object of attributes in the attr() method. <!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script> </head> <body> <script> $(document).ready(function() { $("<input>").attr({ name: "hiddenField", id: "hiddenId", type: "hidden", value: 10 }).appendTo("form"); }) </script> <form> Name: <input type="text"> <br> Hidden: </form> </body> </html> Output: The output can be seen in the browser using Inspect Element feature (e.g. ctrl + shift + i in Google Chrome). Using append() method: In the append() method, the content comes after the method like $(selector).append(content) . Below example illustrates the append() method to create hidden form element: Example: <!DOCTYPE html> <html> <head> <title>GeeksforGeeks</title> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> </head> <body> <script> $(document).ready(function() { $("form").append("<input type='hidden' name='hidField' value='111'>") }) </script> <form> Name: <input type="text"> <br> Hidden: </form> </body> </html> Output: The output can be seen in the browser using Inspect Element feature (e.g. ctrl + shift + i in Google Chrome). jQuery-Misc Picked JQuery Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method How to get the value in an input text box using jQuery ? Difference Between JavaScript and jQuery QR Code Generator using HTML, CSS and jQuery Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25779, "s": 25751, "text": "\n31 Oct, 2019" }, { "code": null, "e": 26095, "s": 25779, "text": "JQuery is the library that makes the use of JavaScript easy. Inserting the <input type=’hidden’> can also be done using jQuery. The append() and appendTo() inbuilt function can be used to add the hidden form element but they are not only limited to the <input type=’hidden’> but we can also add other html elements." }, { "code": null, "e": 26216, "s": 26095, "text": "Note: They both perform pretty much the same. The major difference is only about the syntax and that is explained below." }, { "code": null, "e": 26339, "s": 26216, "text": "Using appendTo() method: In the appendTo() method, the content comes before the method like $(content).appendTo(selector)." }, { "code": null, "e": 26419, "s": 26339, "text": "Below examples illustrates the appendTo() method to create hidden form element:" }, { "code": null, "e": 26628, "s": 26419, "text": "Example 1: If only one attribute is to be added, then it can be given by passing two arguments in attr() method. First argument is the name of attribute, and the second argument is the value of the attribute." }, { "code": "<!DOCTYPE html> <html> <head> <title>GeeksforGeeks </title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity=\"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"> </script></head> <body> <script> $(document).ready(function() { $(\"<input>\").attr(\"type\", \"hidden\").appendTo(\"form\"); }) </script> <form> Name: <input type=\"text\"> <br> Hidden: </form> </body> </html>", "e": 27124, "s": 26628, "text": null }, { "code": null, "e": 27242, "s": 27124, "text": "Output: The output can be seen in the browser using Inspect Element feature (e.g. ctrl + shift + i in Google Chrome)." }, { "code": null, "e": 27356, "s": 27242, "text": "Example 2: Multiple attributes can also be given by passing them as an object of attributes in the attr() method." }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity=\"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"> </script> </head> <body> <script> $(document).ready(function() { $(\"<input>\").attr({ name: \"hiddenField\", id: \"hiddenId\", type: \"hidden\", value: 10 }).appendTo(\"form\"); }) </script> <form> Name: <input type=\"text\"> <br> Hidden: </form> </body> </html>", "e": 27974, "s": 27356, "text": null }, { "code": null, "e": 28092, "s": 27974, "text": "Output: The output can be seen in the browser using Inspect Element feature (e.g. ctrl + shift + i in Google Chrome)." }, { "code": null, "e": 28209, "s": 28092, "text": "Using append() method: In the append() method, the content comes after the method like $(selector).append(content) ." }, { "code": null, "e": 28286, "s": 28209, "text": "Below example illustrates the append() method to create hidden form element:" }, { "code": null, "e": 28295, "s": 28286, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>GeeksforGeeks</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity=\"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"></script> </head> <body> <script> $(document).ready(function() { $(\"form\").append(\"<input type='hidden' name='hidField' value='111'>\") }) </script> <form> Name: <input type=\"text\"> <br> Hidden: </form> </body> </html>", "e": 28823, "s": 28295, "text": null }, { "code": null, "e": 28941, "s": 28823, "text": "Output: The output can be seen in the browser using Inspect Element feature (e.g. ctrl + shift + i in Google Chrome)." }, { "code": null, "e": 28953, "s": 28941, "text": "jQuery-Misc" }, { "code": null, "e": 28960, "s": 28953, "text": "Picked" }, { "code": null, "e": 28967, "s": 28960, "text": "JQuery" }, { "code": null, "e": 28986, "s": 28967, "text": "Technical Scripter" }, { "code": null, "e": 29003, "s": 28986, "text": "Web Technologies" }, { "code": null, "e": 29030, "s": 29003, "text": "Web technologies Questions" }, { "code": null, "e": 29128, "s": 29030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29201, "s": 29128, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 29224, "s": 29201, "text": "jQuery | ajax() Method" }, { "code": null, "e": 29281, "s": 29224, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 29322, "s": 29281, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 29367, "s": 29322, "text": "QR Code Generator using HTML, CSS and jQuery" }, { "code": null, "e": 29409, "s": 29367, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29442, "s": 29409, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29485, "s": 29442, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29547, "s": 29485, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Let’s Talk About Graph Neural Network Python Libraries! | by Rohith Teja | Towards Data Science
The growing popularity of Graph Neural Network (GNNs) gave us a bunch of python libraries to work with. As I was dealing with GNNs for quite a while, I have secured hands-on experience on some popular GNN python libraries and thought of making a small comparison between them. In this article, we will pick a Node Classification task (a simple one of course!) and use 3 different python libraries to formulate and solve the problem. The libraries that we are going to use: Deep Graph Library (DGL) — built on PyTorch, TensorFlow and MXNetPyTorch Geometric (PyG) — built on PyTorchSpektral — built on Keras/ TensorFlow 2 Deep Graph Library (DGL) — built on PyTorch, TensorFlow and MXNet PyTorch Geometric (PyG) — built on PyTorch Spektral — built on Keras/ TensorFlow 2 Please refer to the installation guides in the official websites of these libraries. Since I want to keep it simple, I will use the popular Zachary’s Karate Club graph dataset. Here, the nodes represent 34 students who were involved in the club and the links represent 78 different interactions between pairs of members outside the club. There are two different types of labels i.e, the two factions. Node Classification: In this task, our aim is to build a model to predict the labels of the nodes i.e, the factions joined by the students. We divide the graph into train and test sets (in the ratio 70:30) using a specific seed value. The same train and test splits will be used to build predictive models with different libraries so that we can have a comparison. Once we have chosen the task, there are 6 simple steps to build a predictive model: Data preparationBuild the custom datasetChoose a GNN methodTrain the modelPerform hyperparameter tuningPredict the node labels on test data Data preparation Build the custom dataset Choose a GNN method Train the model Perform hyperparameter tuning Predict the node labels on test data All three python libraries have an implementation where we can transform our graph into the library’s custom dataset and use it to train the Graph Neural Network model. Firstly, we will generate some node embeddings that can be used as input to the Graph Neural Network. I chose DeepWalk node embedding technique which is based on the Random Walk concept. Graph Embedding python library will be used to build the DeepWalk model. Firstly, install the Graph Embedding library and run the setup: !git clone https://github.com/shenweichen/GraphEmbedding.gitcd GraphEmbedding/!python setup.py install The embeddings are saved in the embeddings dictionary variable. Now we have a job of creating the custom datasets for the libraries. I have already explained the process for PyTorch Geometric library in this Medium article that I published. Feel free to check it! towardsdatascience.com In this article, I will focus on DGL and Spektral. In the custom dataset, we add the graph information such as node embeddings, edges, train and test masks. As the Spektral library is based on Keras, we need to convert the labels into one-hot vectors. The rest of the process of including graph information in the custom dataset and also the train and test masks are similar. For this experiment. I am choosing Graph Convolutional Network (GCN) which is popular among GNNs. Let us create the GCN model using both libraries. For the GCN model, I used the number of neurons in the hidden layer to be 16. Since there are only two factions/ labels, we use the binary cross-entropy as the loss function. We created the custom datasets for both libraries and also instantiated the GCN models, so now we can start training the model and predict the labels of the test set. After training the model for 100 epochs, the test labels were predicted and the metrics were calculated. We obtained the following scores: Train Accuracy: 1.0 Test Accuracy: 0.90 Since we used the same dataset, model and hyperparameters, we obtained the same results with both libraries. The core implementation of GCN in these libraries is the same! Train Accuracy: 1.0 Test Accuracy: 0.90 This is a toy example so I did not go much in detail with hyperparameter tuning. If you are using a bigger graph with multiple labels for nodes, then you need to perform hyperparameter tuning to find the best model which fits your graph data. You just need to add a validation set and create the corresponding validation mask in the custom dataset. Then, train the model on the training set and using the validation metrics, tune the hyperparameters. Select the best model based on the model corresponding to the highest validation metric (like accuracy score/ F1 score). This selected model will be used to predict the labels on the test set and final metrics will be calculated. All three libraries are good but I prefer PyTorch Geometric to model the Graph Neural Networks. I might be biased with the choice of the library as I worked extensively with PyG but this library has a good collection of GNN models, which the other libraries are lacking on. So my ranking of these libraries is as follows: PyTorch GeometricDeep Graph LibrarySpektral PyTorch Geometric Deep Graph Library Spektral Again, I am a bit biased to using PyTorch to train neural networks. If you are someone who likes to work with Keras and TensorFlow to construct neural networks, then looking into Spektral might be a good idea. Also, keep in mind that DGL offers other backend support such as MXNet and TensorFlow in addition to the PyTorch. The code that I used to formulate the Node Classification task is taken from the examples present in the repositories/ websites of the libraries. I took enough liberty to modify the code to make it useable for the Karate Club dataset. Below you will find the links for examples that will be useful for your reference: DGL Custom Dataset — https://docs.dgl.ai/en/0.6.x/new-tutorial/6_load_data.htmlDGL GCN — https://docs.dgl.ai/tutorials/blitz/1_introduction.html.Spektral Custom Dataset — https://graphneural.network/creating-dataset/Spektral GCN — https://github.com/danielegrattarola/spektral/blob/master/examples/node_prediction/citation_gcn.pyDeepWalk embeddings — https://github.com/shenweichen/GraphEmbedding/blob/master/examples/deepwalk_wiki.py DGL Custom Dataset — https://docs.dgl.ai/en/0.6.x/new-tutorial/6_load_data.html DGL GCN — https://docs.dgl.ai/tutorials/blitz/1_introduction.html. Spektral Custom Dataset — https://graphneural.network/creating-dataset/ Spektral GCN — https://github.com/danielegrattarola/spektral/blob/master/examples/node_prediction/citation_gcn.py DeepWalk embeddings — https://github.com/shenweichen/GraphEmbedding/blob/master/examples/deepwalk_wiki.py Note: Some part of my DGL code was influenced by the PyTorch Geometric library as both libraries use PyTorch as backend. If you have reached this part of the post, thank you for reading and also your attention. I hope you found the post informative and if you have any questions feel free to reach me on LinkedIn, Twitter or GitHub.
[ { "code": null, "e": 276, "s": 172, "text": "The growing popularity of Graph Neural Network (GNNs) gave us a bunch of python libraries to work with." }, { "code": null, "e": 449, "s": 276, "text": "As I was dealing with GNNs for quite a while, I have secured hands-on experience on some popular GNN python libraries and thought of making a small comparison between them." }, { "code": null, "e": 605, "s": 449, "text": "In this article, we will pick a Node Classification task (a simple one of course!) and use 3 different python libraries to formulate and solve the problem." }, { "code": null, "e": 645, "s": 605, "text": "The libraries that we are going to use:" }, { "code": null, "e": 792, "s": 645, "text": "Deep Graph Library (DGL) — built on PyTorch, TensorFlow and MXNetPyTorch Geometric (PyG) — built on PyTorchSpektral — built on Keras/ TensorFlow 2" }, { "code": null, "e": 858, "s": 792, "text": "Deep Graph Library (DGL) — built on PyTorch, TensorFlow and MXNet" }, { "code": null, "e": 901, "s": 858, "text": "PyTorch Geometric (PyG) — built on PyTorch" }, { "code": null, "e": 941, "s": 901, "text": "Spektral — built on Keras/ TensorFlow 2" }, { "code": null, "e": 1026, "s": 941, "text": "Please refer to the installation guides in the official websites of these libraries." }, { "code": null, "e": 1342, "s": 1026, "text": "Since I want to keep it simple, I will use the popular Zachary’s Karate Club graph dataset. Here, the nodes represent 34 students who were involved in the club and the links represent 78 different interactions between pairs of members outside the club. There are two different types of labels i.e, the two factions." }, { "code": null, "e": 1482, "s": 1342, "text": "Node Classification: In this task, our aim is to build a model to predict the labels of the nodes i.e, the factions joined by the students." }, { "code": null, "e": 1707, "s": 1482, "text": "We divide the graph into train and test sets (in the ratio 70:30) using a specific seed value. The same train and test splits will be used to build predictive models with different libraries so that we can have a comparison." }, { "code": null, "e": 1791, "s": 1707, "text": "Once we have chosen the task, there are 6 simple steps to build a predictive model:" }, { "code": null, "e": 1931, "s": 1791, "text": "Data preparationBuild the custom datasetChoose a GNN methodTrain the modelPerform hyperparameter tuningPredict the node labels on test data" }, { "code": null, "e": 1948, "s": 1931, "text": "Data preparation" }, { "code": null, "e": 1973, "s": 1948, "text": "Build the custom dataset" }, { "code": null, "e": 1993, "s": 1973, "text": "Choose a GNN method" }, { "code": null, "e": 2009, "s": 1993, "text": "Train the model" }, { "code": null, "e": 2039, "s": 2009, "text": "Perform hyperparameter tuning" }, { "code": null, "e": 2076, "s": 2039, "text": "Predict the node labels on test data" }, { "code": null, "e": 2245, "s": 2076, "text": "All three python libraries have an implementation where we can transform our graph into the library’s custom dataset and use it to train the Graph Neural Network model." }, { "code": null, "e": 2347, "s": 2245, "text": "Firstly, we will generate some node embeddings that can be used as input to the Graph Neural Network." }, { "code": null, "e": 2505, "s": 2347, "text": "I chose DeepWalk node embedding technique which is based on the Random Walk concept. Graph Embedding python library will be used to build the DeepWalk model." }, { "code": null, "e": 2569, "s": 2505, "text": "Firstly, install the Graph Embedding library and run the setup:" }, { "code": null, "e": 2672, "s": 2569, "text": "!git clone https://github.com/shenweichen/GraphEmbedding.gitcd GraphEmbedding/!python setup.py install" }, { "code": null, "e": 2805, "s": 2672, "text": "The embeddings are saved in the embeddings dictionary variable. Now we have a job of creating the custom datasets for the libraries." }, { "code": null, "e": 2936, "s": 2805, "text": "I have already explained the process for PyTorch Geometric library in this Medium article that I published. Feel free to check it!" }, { "code": null, "e": 2959, "s": 2936, "text": "towardsdatascience.com" }, { "code": null, "e": 3010, "s": 2959, "text": "In this article, I will focus on DGL and Spektral." }, { "code": null, "e": 3116, "s": 3010, "text": "In the custom dataset, we add the graph information such as node embeddings, edges, train and test masks." }, { "code": null, "e": 3335, "s": 3116, "text": "As the Spektral library is based on Keras, we need to convert the labels into one-hot vectors. The rest of the process of including graph information in the custom dataset and also the train and test masks are similar." }, { "code": null, "e": 3433, "s": 3335, "text": "For this experiment. I am choosing Graph Convolutional Network (GCN) which is popular among GNNs." }, { "code": null, "e": 3483, "s": 3433, "text": "Let us create the GCN model using both libraries." }, { "code": null, "e": 3561, "s": 3483, "text": "For the GCN model, I used the number of neurons in the hidden layer to be 16." }, { "code": null, "e": 3658, "s": 3561, "text": "Since there are only two factions/ labels, we use the binary cross-entropy as the loss function." }, { "code": null, "e": 3825, "s": 3658, "text": "We created the custom datasets for both libraries and also instantiated the GCN models, so now we can start training the model and predict the labels of the test set." }, { "code": null, "e": 3964, "s": 3825, "text": "After training the model for 100 epochs, the test labels were predicted and the metrics were calculated. We obtained the following scores:" }, { "code": null, "e": 4004, "s": 3964, "text": "Train Accuracy: 1.0 Test Accuracy: 0.90" }, { "code": null, "e": 4113, "s": 4004, "text": "Since we used the same dataset, model and hyperparameters, we obtained the same results with both libraries." }, { "code": null, "e": 4176, "s": 4113, "text": "The core implementation of GCN in these libraries is the same!" }, { "code": null, "e": 4216, "s": 4176, "text": "Train Accuracy: 1.0 Test Accuracy: 0.90" }, { "code": null, "e": 4459, "s": 4216, "text": "This is a toy example so I did not go much in detail with hyperparameter tuning. If you are using a bigger graph with multiple labels for nodes, then you need to perform hyperparameter tuning to find the best model which fits your graph data." }, { "code": null, "e": 4897, "s": 4459, "text": "You just need to add a validation set and create the corresponding validation mask in the custom dataset. Then, train the model on the training set and using the validation metrics, tune the hyperparameters. Select the best model based on the model corresponding to the highest validation metric (like accuracy score/ F1 score). This selected model will be used to predict the labels on the test set and final metrics will be calculated." }, { "code": null, "e": 5171, "s": 4897, "text": "All three libraries are good but I prefer PyTorch Geometric to model the Graph Neural Networks. I might be biased with the choice of the library as I worked extensively with PyG but this library has a good collection of GNN models, which the other libraries are lacking on." }, { "code": null, "e": 5219, "s": 5171, "text": "So my ranking of these libraries is as follows:" }, { "code": null, "e": 5263, "s": 5219, "text": "PyTorch GeometricDeep Graph LibrarySpektral" }, { "code": null, "e": 5281, "s": 5263, "text": "PyTorch Geometric" }, { "code": null, "e": 5300, "s": 5281, "text": "Deep Graph Library" }, { "code": null, "e": 5309, "s": 5300, "text": "Spektral" }, { "code": null, "e": 5519, "s": 5309, "text": "Again, I am a bit biased to using PyTorch to train neural networks. If you are someone who likes to work with Keras and TensorFlow to construct neural networks, then looking into Spektral might be a good idea." }, { "code": null, "e": 5633, "s": 5519, "text": "Also, keep in mind that DGL offers other backend support such as MXNet and TensorFlow in addition to the PyTorch." }, { "code": null, "e": 5951, "s": 5633, "text": "The code that I used to formulate the Node Classification task is taken from the examples present in the repositories/ websites of the libraries. I took enough liberty to modify the code to make it useable for the Karate Club dataset. Below you will find the links for examples that will be useful for your reference:" }, { "code": null, "e": 6386, "s": 5951, "text": "DGL Custom Dataset — https://docs.dgl.ai/en/0.6.x/new-tutorial/6_load_data.htmlDGL GCN — https://docs.dgl.ai/tutorials/blitz/1_introduction.html.Spektral Custom Dataset — https://graphneural.network/creating-dataset/Spektral GCN — https://github.com/danielegrattarola/spektral/blob/master/examples/node_prediction/citation_gcn.pyDeepWalk embeddings — https://github.com/shenweichen/GraphEmbedding/blob/master/examples/deepwalk_wiki.py" }, { "code": null, "e": 6466, "s": 6386, "text": "DGL Custom Dataset — https://docs.dgl.ai/en/0.6.x/new-tutorial/6_load_data.html" }, { "code": null, "e": 6533, "s": 6466, "text": "DGL GCN — https://docs.dgl.ai/tutorials/blitz/1_introduction.html." }, { "code": null, "e": 6605, "s": 6533, "text": "Spektral Custom Dataset — https://graphneural.network/creating-dataset/" }, { "code": null, "e": 6719, "s": 6605, "text": "Spektral GCN — https://github.com/danielegrattarola/spektral/blob/master/examples/node_prediction/citation_gcn.py" }, { "code": null, "e": 6825, "s": 6719, "text": "DeepWalk embeddings — https://github.com/shenweichen/GraphEmbedding/blob/master/examples/deepwalk_wiki.py" }, { "code": null, "e": 6946, "s": 6825, "text": "Note: Some part of my DGL code was influenced by the PyTorch Geometric library as both libraries use PyTorch as backend." } ]
What is XLNet and why it outperforms BERT | by Xu LIANG | Towards Data Science
Not less a week after the release, it seems everyone around me in the NLP field is talking about XLNet. Yes, the “improves upon BERT on 20 tasks” did attract our eyes. But the more important thing is to understand how it works and why it outperforms BERT. So I write this blog to share my thoughts after reading the paper. The content is structured as follows. What is XLNet? What are the differences between XLNet and BERT? How XLNet works? If you are interested in the Two-Stream Self-Attention in XLNet, you can look up my another post, What is Two-Stream Self-Attention in XLNet. First of all, XLNet is a BERT-like model instead of a totally different one. But it is a very promising and potential one. In one word, XLNet is a generalized autoregressive pretraining method. So what is the autoregressive(AR) language model? AR language model is a kind of model that using the context word to predict the next word. But here the context word is constrained to two directions, either forward or backward. The GPT and GPT-2 are both AR language model. The advantages of AR language model are good at generative NLP tasks. Because when generating context, usually is the forward direction. AR language model naturally works well on such NLP tasks. But AR language model has some disadvantages, it only can use forward context or backward context, which means it can't use forward and backward context at the same time. Unlike the AR language model, BERT is categorized as autoencoder(AE) language model. The AE language model aims to reconstruct the original data from corrupted input. The corrupted input means we use [MASK] to replace the original token into in the pre-train phase. And the objective is to predict into to get the original sentence. The advantages of AE language model is that it can see the context on both forward and backward direction. But the AE language model also has its disadvantages. It uses the [MASK] in the pretraining, but this kind of artificial symbols are absent from the real data at finetuning time, resulting in a pretrain-finetune discrepancy. Another disadvantage of [MASK] is that it assumes the predicted (masked) tokens are independent of each other given the unmasked tokens. For example, we have a sentence “It shows that the housing crisis was turned into a banking crisis”. We mask “banking” and “crisis”. Attention here, we know the masked “banking” and “crisis” contains implicit relation to each other. But AE model is trying to predict “banking” given unmasked tokens, and predict “crisis” given unmasked tokens separately. It ignores the relation between “banking” and “crisis”. In other words, it assumes the predicted (masked) tokens are independent of each other. But we know the model should learn such correlation among the predicted (masked) tokens to predict one of the tokens. What the author wants to emphasize is that the XLNet propose a new way to let the AR language model learn from bi-directional context to avoid the disadvantages brought by the MASK method in AE language model. The AR language model only can use the context either forward or backward, so how to let it learn from bi-directional context? Language model consists of two phases, the pre-train phase, and fine-tune phase. XLNet focus on pre-train phase. In the pre-train phase, it proposed a new objective called Permutation Language Modeling. We can know the basic idea from this name, it uses permutation. Here we take an example to explain. The sequence order is [x1, x2, x3, x4]. All permutations of such sequence are below. So for this 4 tokens (N) sentence, there are 24 (N!) permutations. The scenario is that we want to predict the x3. So there are 4 patterns in the 24 permutations, x3 is at the 1st position, 2nd position, 3rd position, 4th position. [x3, xx, xx, xx][xx, x3, xx, xx][xx, xx, x3, xx][xx, xx, xx, x3] Here we set the position of x3 ast-th position and t-1 tokens are the context words for predicting x3. The words before x3 have every possible words and length in the sequence. Intuitively, the model will learn to gather information from all positions on both sides. The implementation is far complicated than the above explanation, I won’t talk it here. But you should get the most basic and most important idea about XLNet. If you are interested in the Two-Stream Self-Attention in XLNet, you can look up my another post, What is Two-Stream Self-Attention in XLNet. Like BERT brought the MASK method to the public, XLNet showed permutation method is a good choice as the language model objective. It is predictable that there are more works to explore the language model objective in the future. Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu paper: https://arxiv.org/abs/1906.08237 code: pytorch_transformers/modeling_xlnet.py What is Two-Stream Self-Attention in XLNet
[ { "code": null, "e": 151, "s": 47, "text": "Not less a week after the release, it seems everyone around me in the NLP field is talking about XLNet." }, { "code": null, "e": 370, "s": 151, "text": "Yes, the “improves upon BERT on 20 tasks” did attract our eyes. But the more important thing is to understand how it works and why it outperforms BERT. So I write this blog to share my thoughts after reading the paper." }, { "code": null, "e": 408, "s": 370, "text": "The content is structured as follows." }, { "code": null, "e": 423, "s": 408, "text": "What is XLNet?" }, { "code": null, "e": 472, "s": 423, "text": "What are the differences between XLNet and BERT?" }, { "code": null, "e": 489, "s": 472, "text": "How XLNet works?" }, { "code": null, "e": 631, "s": 489, "text": "If you are interested in the Two-Stream Self-Attention in XLNet, you can look up my another post, What is Two-Stream Self-Attention in XLNet." }, { "code": null, "e": 825, "s": 631, "text": "First of all, XLNet is a BERT-like model instead of a totally different one. But it is a very promising and potential one. In one word, XLNet is a generalized autoregressive pretraining method." }, { "code": null, "e": 875, "s": 825, "text": "So what is the autoregressive(AR) language model?" }, { "code": null, "e": 1054, "s": 875, "text": "AR language model is a kind of model that using the context word to predict the next word. But here the context word is constrained to two directions, either forward or backward." }, { "code": null, "e": 1100, "s": 1054, "text": "The GPT and GPT-2 are both AR language model." }, { "code": null, "e": 1295, "s": 1100, "text": "The advantages of AR language model are good at generative NLP tasks. Because when generating context, usually is the forward direction. AR language model naturally works well on such NLP tasks." }, { "code": null, "e": 1466, "s": 1295, "text": "But AR language model has some disadvantages, it only can use forward context or backward context, which means it can't use forward and backward context at the same time." }, { "code": null, "e": 1551, "s": 1466, "text": "Unlike the AR language model, BERT is categorized as autoencoder(AE) language model." }, { "code": null, "e": 1633, "s": 1551, "text": "The AE language model aims to reconstruct the original data from corrupted input." }, { "code": null, "e": 1799, "s": 1633, "text": "The corrupted input means we use [MASK] to replace the original token into in the pre-train phase. And the objective is to predict into to get the original sentence." }, { "code": null, "e": 1906, "s": 1799, "text": "The advantages of AE language model is that it can see the context on both forward and backward direction." }, { "code": null, "e": 2885, "s": 1906, "text": "But the AE language model also has its disadvantages. It uses the [MASK] in the pretraining, but this kind of artificial symbols are absent from the real data at finetuning time, resulting in a pretrain-finetune discrepancy. Another disadvantage of [MASK] is that it assumes the predicted (masked) tokens are independent of each other given the unmasked tokens. For example, we have a sentence “It shows that the housing crisis was turned into a banking crisis”. We mask “banking” and “crisis”. Attention here, we know the masked “banking” and “crisis” contains implicit relation to each other. But AE model is trying to predict “banking” given unmasked tokens, and predict “crisis” given unmasked tokens separately. It ignores the relation between “banking” and “crisis”. In other words, it assumes the predicted (masked) tokens are independent of each other. But we know the model should learn such correlation among the predicted (masked) tokens to predict one of the tokens." }, { "code": null, "e": 3095, "s": 2885, "text": "What the author wants to emphasize is that the XLNet propose a new way to let the AR language model learn from bi-directional context to avoid the disadvantages brought by the MASK method in AE language model." }, { "code": null, "e": 3222, "s": 3095, "text": "The AR language model only can use the context either forward or backward, so how to let it learn from bi-directional context?" }, { "code": null, "e": 3489, "s": 3222, "text": "Language model consists of two phases, the pre-train phase, and fine-tune phase. XLNet focus on pre-train phase. In the pre-train phase, it proposed a new objective called Permutation Language Modeling. We can know the basic idea from this name, it uses permutation." }, { "code": null, "e": 3610, "s": 3489, "text": "Here we take an example to explain. The sequence order is [x1, x2, x3, x4]. All permutations of such sequence are below." }, { "code": null, "e": 3677, "s": 3610, "text": "So for this 4 tokens (N) sentence, there are 24 (N!) permutations." }, { "code": null, "e": 3842, "s": 3677, "text": "The scenario is that we want to predict the x3. So there are 4 patterns in the 24 permutations, x3 is at the 1st position, 2nd position, 3rd position, 4th position." }, { "code": null, "e": 3907, "s": 3842, "text": "[x3, xx, xx, xx][xx, x3, xx, xx][xx, xx, x3, xx][xx, xx, xx, x3]" }, { "code": null, "e": 4010, "s": 3907, "text": "Here we set the position of x3 ast-th position and t-1 tokens are the context words for predicting x3." }, { "code": null, "e": 4174, "s": 4010, "text": "The words before x3 have every possible words and length in the sequence. Intuitively, the model will learn to gather information from all positions on both sides." }, { "code": null, "e": 4475, "s": 4174, "text": "The implementation is far complicated than the above explanation, I won’t talk it here. But you should get the most basic and most important idea about XLNet. If you are interested in the Two-Stream Self-Attention in XLNet, you can look up my another post, What is Two-Stream Self-Attention in XLNet." }, { "code": null, "e": 4705, "s": 4475, "text": "Like BERT brought the MASK method to the public, XLNet showed permutation method is a good choice as the language model objective. It is predictable that there are more works to explore the language model objective in the future." }, { "code": null, "e": 4815, "s": 4705, "text": "Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu" }, { "code": null, "e": 4855, "s": 4815, "text": "paper: https://arxiv.org/abs/1906.08237" }, { "code": null, "e": 4900, "s": 4855, "text": "code: pytorch_transformers/modeling_xlnet.py" } ]
How to insert an item into a C# list by using an index?
Firstly, set a list − List<int> list = new List<int>(); list.Add(456); list.Add(321); list.Add(123); list.Add(877); list.Add(588); list.Add(459); Now, to add an item at index 5, let say; for that, use the Insert() method − list.Insert(5, 999); Let us see the complete example − using System; using System.Collections.Generic; namespace Demo { public class Program { public static void Main(string[] args) { List<int> list = new List<int>(); list.Add(456); list.Add(321); list.Add(123); list.Add(877); list.Add(588); list.Add(459); Console.Write("List: "); foreach (int i in list) { Console.Write(i + " "); } Console.WriteLine("\nCount: {0}", list.Count); // inserting element at index 5 list.Insert(5, 999); Console.Write("\nList after inserting a new element: "); foreach (int i in list) { Console.Write(i + " "); } Console.WriteLine("\nCount: {0}", list.Count); } } }
[ { "code": null, "e": 1084, "s": 1062, "text": "Firstly, set a list −" }, { "code": null, "e": 1208, "s": 1084, "text": "List<int> list = new List<int>();\nlist.Add(456);\nlist.Add(321);\nlist.Add(123);\nlist.Add(877);\nlist.Add(588);\nlist.Add(459);" }, { "code": null, "e": 1285, "s": 1208, "text": "Now, to add an item at index 5, let say; for that, use the Insert() method −" }, { "code": null, "e": 1306, "s": 1285, "text": "list.Insert(5, 999);" }, { "code": null, "e": 1340, "s": 1306, "text": "Let us see the complete example −" }, { "code": null, "e": 2131, "s": 1340, "text": "using System;\nusing System.Collections.Generic;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n List<int> list = new List<int>();\n list.Add(456);\n list.Add(321);\n list.Add(123);\n list.Add(877);\n list.Add(588);\n list.Add(459);\n Console.Write(\"List: \");\n\n foreach (int i in list) {\n Console.Write(i + \" \");\n }\n Console.WriteLine(\"\\nCount: {0}\", list.Count);\n\n // inserting element at index 5\n list.Insert(5, 999);\n Console.Write(\"\\nList after inserting a new element: \");\n\n foreach (int i in list) {\n Console.Write(i + \" \");\n }\n Console.WriteLine(\"\\nCount: {0}\", list.Count);\n }\n }\n}" } ]
Content Providers in Android with Example - GeeksforGeeks
17 Sep, 2020 In Android, Content Providers are a very important component that serves the purpose of a relational database to store the data of applications. The role of the content provider in the android system is like a central repository in which data of the applications are stored, and it facilitates other applications to securely access and modifies that data based on the user requirements. Android system allows the content provider to store the application data in several ways. Users can manage to store the application data like images, audio, videos, and personal contact information by storing them in SQLite Database, in files, or even on a network. In order to share the data, content providers have certain permissions that are used to grant or restrict the rights to other applications to interfere with the data. Content URI(Uniform Resource Identifier) is the key concept of Content providers. To access the data from a content provider, URI is used as a query string. Structure of a Content URI: content://authority/optionalPath/optionalID Details of different parts of Content URI: content:// – Mandatory part of the URI as it represents that the given URI is a Content URI. authority – Signifies the name of the content provider like contacts, browser, etc. This part must be unique for every content provider. optionalPath – Specifies the type of data provided by the content provider. It is essential as this part helps content providers to support different types of data that are not related to each other like audio and video files. optionalID – It is a numeric value that is used when there is a need to access a particular record. If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based URI. Four fundamental operations are possible in Content Provider namely Create, Read, Update, and Delete. These operations are often termed as CRUD operations. Create: Operation to create data in a content provider. Read: Used to fetch data from a content provider. Update: To modify existing data. Delete: To remove existing data from the storage. UI components of android applications like Activity and Fragments use an object CursorLoader to send query requests to ContentResolver. The ContentResolver object sends requests (like create, read, update, and delete) to the ContentProvider as a client. After receiving a request, ContentProvider process it and returns the desired result. Below is a diagram to represent these processes in pictorial form. Following are the steps which are essential to follow in order to create a Content Provider: Create a class in the same directory where the that MainActivity file resides and this class must extend the ContentProvider base class. To access the content, define a content provider URI address. Create a database to store the application data. Implement the six abstract methods of ContentProvider class. Register the content provider in AndroidManifest.xml file using <provider> tag. Following are the six abstract methods and their description which are essential to override as the part of ContenProvider class: Abstract Method Description A method that accepts arguments and fetches the data from the desired table. Data is retired as a cursor object. To insert a new row in the database of the content provider. It returns the content URI of the inserted row. This method is used to update the fields of an existing row. It returns the number of rows updated. This method is used to delete the existing rows. It returns the number of rows deleted. This method returns the Multipurpose Internet Mail Extension(MIME) type of data to the given Content URI. As the content provider is created, the android system calls this method immediately to initialise the provider. The prime purpose of a content provider is to serve as a central repository of data where users can store and can fetch the data. The access of this repository is given to other applications also but in a safe manner in order to serve the different requirements of the user. The following are the steps involved in implementing a content provider. In this content provider, the user can store the name of persons and can fetch the stored data. Moreover, another application can also access the stored data and can display the data. Note: Following steps are performed on Android Studio version 4.0 Creating a Content Provider: Step 1: Create a new project Click on File, then New => New Project.Select language as Java/Kotlin.Choose empty activity as a templateSelect the minimum SDK as per your need. Click on File, then New => New Project. Select language as Java/Kotlin. Choose empty activity as a template Select the minimum SDK as per your need. Step 2: Modify the strings.xml file All the strings used in the activity are stored here. XML <resources> <string name="app_name">Content_Provider_In_Android</string> <string name="hintText">Enter User Name</string> <string name="heading">Content Provider In Android</string> <string name="insertButtontext">Insert Data</string> <string name="loadButtonText">Load Data</string></resources> Step 3: Creating the Content Provider class Click on File, then New => Other => ContentProvider.Name the ContentProviderDefine authority (it can be anything for example “com.demo.user.provider”)Select Exported and Enabled optionChoose the language as Java/Kotlin Click on File, then New => Other => ContentProvider. Name the ContentProvider Define authority (it can be anything for example “com.demo.user.provider”) Select Exported and Enabled option Choose the language as Java/Kotlin This class extends the ContentProvider base class and override the six abstract methods. Below is the complete code to define a content provider. Java Kotlin package com.example.contentprovidersinandroid; import android.content.ContentProvider;import android.content.ContentUris;import android.content.ContentValues;import android.content.Context;import android.content.UriMatcher;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteQueryBuilder;import android.net.Uri;import java.util.HashMap; public class MyContentProvider extends ContentProvider { public MyContentProvider() { } // defining authority so that other application can access it static final String PROVIDER_NAME = "com.demo.user.provider"; // defining content URI static final String URL = "content://" + PROVIDER_NAME + "/users"; // parsing the content URI static final Uri CONTENT_URI = Uri.parse(URL); static final String id = "id"; static final String name = "name"; static final int uriCode = 1; static final UriMatcher uriMatcher; private static HashMap<String, String> values; static { // to match the content URI // every time user access table under content provider uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); // to access whole table uriMatcher.addURI(PROVIDER_NAME, "users", uriCode); // to access a particular row // of the table uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode); } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case uriCode: return "vnd.android.cursor.dir/users"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } // creating the database @Override public boolean onCreate() { Context context = getContext(); DatabaseHelper dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); if (db != null) { return true; } return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(TABLE_NAME); switch (uriMatcher.match(uri)) { case uriCode: qb.setProjectionMap(values); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (sortOrder == null || sortOrder == "") { sortOrder = id; } Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } // adding data to the database @Override public Uri insert(Uri uri, ContentValues values) { long rowID = db.insert(TABLE_NAME, "", values); if (rowID > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLiteException("Failed to add a record into " + uri); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)) { case uriCode: count = db.update(TABLE_NAME, values, selection, selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)) { case uriCode: count = db.delete(TABLE_NAME, selection, selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } // creating object of database // to perform query private SQLiteDatabase db; // declaring name of the database static final String DATABASE_NAME = "UserDB"; // declaring table name of the database static final String TABLE_NAME = "Users"; // declaring version of the database static final int DATABASE_VERSION = 1; // sql query to create the table static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, " + " name TEXT NOT NULL);"; // creating a database private static class DatabaseHelper extends SQLiteOpenHelper { // defining a constructor DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // creating a table in the database @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_DB_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // sql query to drop a table // having similar name db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } }} package com.example.contentprovidersinandroid import android.content.*import android.database.Cursorimport android.database.sqlite.SQLiteDatabaseimport android.database.sqlite.SQLiteExceptionimport android.database.sqlite.SQLiteOpenHelperimport android.database.sqlite.SQLiteQueryBuilderimport android.net.Uri class MyContentProvider : ContentProvider() { companion object { // defining authority so that other application can access it const val PROVIDER_NAME = "com.demo.user.provider" // defining content URI const val URL = "content://$PROVIDER_NAME/users" // parsing the content URI val CONTENT_URI = Uri.parse(URL) const val id = "id" const val name = "name" const val uriCode = 1 var uriMatcher: UriMatcher? = null private val values: HashMap<String, String>? = null // declaring name of the database const val DATABASE_NAME = "UserDB" // declaring table name of the database const val TABLE_NAME = "Users" // declaring version of the database const val DATABASE_VERSION = 1 // sql query to create the table const val CREATE_DB_TABLE = (" CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, " + " name TEXT NOT NULL);") init { // to match the content URI // every time user access table under content provider uriMatcher = UriMatcher(UriMatcher.NO_MATCH) // to access whole table uriMatcher!!.addURI( PROVIDER_NAME, "users", uriCode ) // to access a particular row // of the table uriMatcher!!.addURI( PROVIDER_NAME, "users/*", uriCode ) } } override fun getType(uri: Uri): String? { return when (uriMatcher!!.match(uri)) { uriCode -> "vnd.android.cursor.dir/users" else -> throw IllegalArgumentException("Unsupported URI: $uri") } } // creating the database override fun onCreate(): Boolean { val context = context val dbHelper = DatabaseHelper(context) db = dbHelper.writableDatabase return if (db != null) { true } else false } override fun query( uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String? ): Cursor? { var sortOrder = sortOrder val qb = SQLiteQueryBuilder() qb.tables = TABLE_NAME when (uriMatcher!!.match(uri)) { uriCode -> qb.projectionMap = values else -> throw IllegalArgumentException("Unknown URI $uri") } if (sortOrder == null || sortOrder === "") { sortOrder = id } val c = qb.query( db, projection, selection, selectionArgs, null, null, sortOrder ) c.setNotificationUri(context!!.contentResolver, uri) return c } // adding data to the database override fun insert(uri: Uri, values: ContentValues?): Uri? { val rowID = db!!.insert(TABLE_NAME, "", values) if (rowID > 0) { val _uri = ContentUris.withAppendedId(CONTENT_URI, rowID) context!!.contentResolver.notifyChange(_uri, null) return _uri } throw SQLiteException("Failed to add a record into $uri") } override fun update( uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>? ): Int { var count = 0 count = when (uriMatcher!!.match(uri)) { uriCode -> db!!.update(TABLE_NAME, values, selection, selectionArgs) else -> throw IllegalArgumentException("Unknown URI $uri") } context!!.contentResolver.notifyChange(uri, null) return count } override fun delete( uri: Uri, selection: String?, selectionArgs: Array<String>? ): Int { var count = 0 count = when (uriMatcher!!.match(uri)) { uriCode -> db!!.delete(TABLE_NAME, selection, selectionArgs) else -> throw IllegalArgumentException("Unknown URI $uri") } context!!.contentResolver.notifyChange(uri, null) return count } // creating object of database // to perform query private var db: SQLiteDatabase? = null // creating a database private class DatabaseHelper // defining a constructor internal constructor(context: Context?) : SQLiteOpenHelper( context, DATABASE_NAME, null, DATABASE_VERSION ) { // creating a table in the database override fun onCreate(db: SQLiteDatabase) { db.execSQL(CREATE_DB_TABLE) } override fun onUpgrade( db: SQLiteDatabase, oldVersion: Int, newVersion: Int ) { // sql query to drop a table // having similar name db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME") onCreate(db) } }} Step 4: Design the activity_main.xml layout One Textview, EditText field, two Buttons, and a Textview to display the stored data will be added in the activity using the below code. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" app:layout_constraintBottom_toTopOf="@+id/imageView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.13" tools:ignore="MissingConstraints"> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_marginBottom="70dp" android:fontFamily="@font/roboto" android:text="@string/heading" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textColor="@android:color/holo_green_dark" android:textSize="36sp" android:textStyle="bold" /> <EditText android:id="@+id/textName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:layout_marginBottom="40dp" android:fontFamily="@font/roboto" android:hint="@string/hintText" /> <Button android:id="@+id/insertButton" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:onClick="onClickAddDetails" android:text="@string/insertButtontext" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textColor="#FFFFFF" android:textStyle="bold" /> <Button android:id="@+id/loadButton" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:onClick="onClickShowDetails" android:text="@string/loadButtonText" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textColor="#FFFFFF" android:textStyle="bold" /> <TextView android:id="@+id/res" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:clickable="false" android:ems="10" android:fontFamily="@font/roboto" android:textColor="@android:color/holo_green_dark" android:textSize="18sp" android:textStyle="bold" /> </LinearLayout> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:srcCompat="@drawable/banner" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 5: Modify the MainActivity file Button functionalities will be defined in this file. Moreover, the query to be performed while inserting and fetching the data is mentioned here. Below is the complete code. Java Kotlin package com.example.contentprovidersinandroid; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.inputmethod.InputMethodManager;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onTouchEvent(MotionEvent event) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); return true; } public void onClickAddDetails(View view) { // class to add values in the database ContentValues values = new ContentValues(); // fetching text from user values.put(MyContentProvider.name, ((EditText) findViewById(R.id.textName)).getText().toString()); // inserting into database through content URI getContentResolver().insert(MyContentProvider.CONTENT_URI, values); // displaying a toast message Toast.makeText(getBaseContext(), "New Record Inserted", Toast.LENGTH_LONG).show(); } public void onClickShowDetails(View view) { // inserting complete table details in this text field TextView resultView= (TextView) findViewById(R.id.res); // creating a cursor object of the // content URI Cursor cursor = getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null, null, null); // iteration of the cursor // to print whole table if(cursor.moveToFirst()) { StringBuilder strBuild=new StringBuilder(); while (!cursor.isAfterLast()) { strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+ cursor.getString(cursor.getColumnIndex("name"))); cursor.moveToNext(); } resultView.setText(strBuild); } else { resultView.setText("No Records Found"); } }} package com.example.content_provider_in_android import android.content.ContentValuesimport android.content.Contextimport android.net.Uriimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.view.inputmethod.InputMethodManagerimport android.widget.EditTextimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport com.example.contentprovidersinandroid.MyContentProvider class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onTouchEvent(event: MotionEvent?): Boolean { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0) return true } fun onClickAddDetails(view: View?) { // class to add values in the database val values = ContentValues() // fetching text from user values.put(MyContentProvider.name, (findViewById<View>(R.id.textName) as EditText).text.toString()) // inserting into database through content URI contentResolver.insert(MyContentProvider.CONTENT_URI, values) // displaying a toast message Toast.makeText(baseContext, "New Record Inserted", Toast.LENGTH_LONG).show() } fun onClickShowDetails(view: View?) { // inserting complete table details in this text field val resultView = findViewById<View>(R.id.res) as TextView // creating a cursor object of the // content URI val cursor = contentResolver.query(Uri.parse("content://com.demo.user.provider/users"), null, null, null, null) // iteration of the cursor // to print whole table if (cursor!!.moveToFirst()) { val strBuild = StringBuilder() while (!cursor.isAfterLast) { strBuild.append(""" ${cursor.getString(cursor.getColumnIndex("id"))}-${cursor.getString(cursor.getColumnIndex("name"))} """.trimIndent()) cursor.moveToNext() } resultView.text = strBuild } else { resultView.text = "No Records Found" } }} Step 6: Modify the AndroidManifest file The AndroidManifest file must contain the content provider name, authorities, and permissions which enables the content provider to be accessed by other applications. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.content_provider_in_android"> <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"> <provider android:name="com.example.contentprovidersinandroid.MyContentProvider" android:authorities="com.demo.user.provider" android:enabled="true" android:exported="true"></provider> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="preloaded_fonts" android:resource="@array/preloaded_fonts" /> </application> </manifest> Creating another application to access the Content Provider: Step 1: Create a new Project Click on File, then New => New Project.Select language as Java/Kotlin.Choose empty activity as a templateSelect the minimum SDK as per your need. Click on File, then New => New Project. Select language as Java/Kotlin. Choose empty activity as a template Select the minimum SDK as per your need. Step 2: Modify strings.xml file All the strings used in the activity are stored in this file. XML <resources> <string name="app_name">Accessing_Content_Provider</string> <string name="heading">Accessing data of Content Provider</string> <string name="loadButtonText">Load Data</string></resources> Step 3: Designing the ctivity_main.xml layout Two TextView is added in the activity, one for heading and one to display the stored data in a content provider. One Button is also added to receive the command to display data. Below is the code to implement this design. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" app:layout_constraintBottom_toTopOf="@+id/imageView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.13" tools:ignore="MissingConstraints"> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_marginBottom="70dp" android:fontFamily="@font/roboto" android:text="@string/heading" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textColor="@android:color/holo_green_dark" android:textSize="36sp" android:textStyle="bold" /> <Button android:id="@+id/loadButton" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:onClick="onClickShowDetails" android:text="@string/loadButtonText" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textColor="#FFFFFF" android:textStyle="bold" /> <TextView android:id="@+id/res" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:clickable="false" android:ems="10" android:fontFamily="@font/roboto" android:textColor="@android:color/holo_green_dark" android:textSize="18sp" android:textStyle="bold" /> </LinearLayout> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:srcCompat="@drawable/banner" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Modify the MainActivity file The ContentURI of the previous application is mentioned here and the same functions which were used in the previous app to display the records will also be used here. Below is the complete code: Java Kotlin package com.example.accessingcontentprovider; import androidx.appcompat.app.AppCompatActivity;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.TextView; public class MainActivity extends AppCompatActivity { Uri CONTENT_URI = Uri.parse("content://com.demo.user.provider/users"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClickShowDetails(View view) { // inserting complete table details in this text field TextView resultView= (TextView) findViewById(R.id.res); // creating a cursor object of the // content URI Cursor cursor = getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null, null, null); // iteration of the cursor // to print whole table if(cursor.moveToFirst()) { StringBuilder strBuild=new StringBuilder(); while (!cursor.isAfterLast()) { strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+ cursor.getString(cursor.getColumnIndex("name"))); cursor.moveToNext(); } resultView.setText(strBuild); } else { resultView.setText("No Records Found"); } }} package com.example.accessing_content_provider import android.net.Uriimport android.os.Bundleimport android.view.Viewimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { var CONTENT_URI = Uri.parse("content://com.demo.user.provider/users") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun onClickShowDetails(view: View?) { // inserting complete table details in this text field val resultView = findViewById<View>(R.id.res) as TextView // creating a cursor object of the // content URI val cursor = contentResolver.query(Uri.parse("content://com.demo.user.provider/users"), null, null, null, null) // iteration of the cursor // to print whole table if (cursor!!.moveToFirst()) { val strBuild = StringBuilder() while (!cursor.isAfterLast) { strBuild.append(""" ${cursor.getString(cursor.getColumnIndex("id"))}-${cursor.getString(cursor.getColumnIndex("name"))} """.trimIndent()) cursor.moveToNext() } resultView.text = strBuild } else { resultView.text = "No Records Found" } }} android Android Java Kotlin Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Services in Android with Example Android RecyclerView in Kotlin Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24724, "s": 24696, "text": "\n17 Sep, 2020" }, { "code": null, "e": 25544, "s": 24724, "text": "In Android, Content Providers are a very important component that serves the purpose of a relational database to store the data of applications. The role of the content provider in the android system is like a central repository in which data of the applications are stored, and it facilitates other applications to securely access and modifies that data based on the user requirements. Android system allows the content provider to store the application data in several ways. Users can manage to store the application data like images, audio, videos, and personal contact information by storing them in SQLite Database, in files, or even on a network. In order to share the data, content providers have certain permissions that are used to grant or restrict the rights to other applications to interfere with the data." }, { "code": null, "e": 25702, "s": 25544, "text": "Content URI(Uniform Resource Identifier) is the key concept of Content providers. To access the data from a content provider, URI is used as a query string. " }, { "code": null, "e": 25774, "s": 25702, "text": "Structure of a Content URI: content://authority/optionalPath/optionalID" }, { "code": null, "e": 25817, "s": 25774, "text": "Details of different parts of Content URI:" }, { "code": null, "e": 25910, "s": 25817, "text": "content:// – Mandatory part of the URI as it represents that the given URI is a Content URI." }, { "code": null, "e": 26047, "s": 25910, "text": "authority – Signifies the name of the content provider like contacts, browser, etc. This part must be unique for every content provider." }, { "code": null, "e": 26274, "s": 26047, "text": "optionalPath – Specifies the type of data provided by the content provider. It is essential as this part helps content providers to support different types of data that are not related to each other like audio and video files." }, { "code": null, "e": 26374, "s": 26274, "text": "optionalID – It is a numeric value that is used when there is a need to access a particular record." }, { "code": null, "e": 26465, "s": 26374, "text": "If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based URI." }, { "code": null, "e": 26622, "s": 26465, "text": "Four fundamental operations are possible in Content Provider namely Create, Read, Update, and Delete. These operations are often termed as CRUD operations. " }, { "code": null, "e": 26678, "s": 26622, "text": "Create: Operation to create data in a content provider." }, { "code": null, "e": 26728, "s": 26678, "text": "Read: Used to fetch data from a content provider." }, { "code": null, "e": 26761, "s": 26728, "text": "Update: To modify existing data." }, { "code": null, "e": 26811, "s": 26761, "text": "Delete: To remove existing data from the storage." }, { "code": null, "e": 27218, "s": 26811, "text": "UI components of android applications like Activity and Fragments use an object CursorLoader to send query requests to ContentResolver. The ContentResolver object sends requests (like create, read, update, and delete) to the ContentProvider as a client. After receiving a request, ContentProvider process it and returns the desired result. Below is a diagram to represent these processes in pictorial form." }, { "code": null, "e": 27311, "s": 27218, "text": "Following are the steps which are essential to follow in order to create a Content Provider:" }, { "code": null, "e": 27448, "s": 27311, "text": "Create a class in the same directory where the that MainActivity file resides and this class must extend the ContentProvider base class." }, { "code": null, "e": 27510, "s": 27448, "text": "To access the content, define a content provider URI address." }, { "code": null, "e": 27559, "s": 27510, "text": "Create a database to store the application data." }, { "code": null, "e": 27620, "s": 27559, "text": "Implement the six abstract methods of ContentProvider class." }, { "code": null, "e": 27700, "s": 27620, "text": "Register the content provider in AndroidManifest.xml file using <provider> tag." }, { "code": null, "e": 27830, "s": 27700, "text": "Following are the six abstract methods and their description which are essential to override as the part of ContenProvider class:" }, { "code": null, "e": 27846, "s": 27830, "text": "Abstract Method" }, { "code": null, "e": 27858, "s": 27846, "text": "Description" }, { "code": null, "e": 27921, "s": 27858, "text": "A method that accepts arguments and fetches the data from the " }, { "code": null, "e": 27972, "s": 27921, "text": "desired table. Data is retired as a cursor object." }, { "code": null, "e": 28034, "s": 27972, "text": "To insert a new row in the database of the content provider. " }, { "code": null, "e": 28083, "s": 28034, "text": "It returns the content URI of the inserted row. " }, { "code": null, "e": 28145, "s": 28083, "text": "This method is used to update the fields of an existing row. " }, { "code": null, "e": 28184, "s": 28145, "text": "It returns the number of rows updated." }, { "code": null, "e": 28234, "s": 28184, "text": "This method is used to delete the existing rows. " }, { "code": null, "e": 28273, "s": 28234, "text": "It returns the number of rows deleted." }, { "code": null, "e": 28341, "s": 28273, "text": "This method returns the Multipurpose Internet Mail Extension(MIME) " }, { "code": null, "e": 28380, "s": 28341, "text": "type of data to the given Content URI." }, { "code": null, "e": 28442, "s": 28380, "text": "As the content provider is created, the android system calls " }, { "code": null, "e": 28494, "s": 28442, "text": "this method immediately to initialise the provider." }, { "code": null, "e": 29026, "s": 28494, "text": "The prime purpose of a content provider is to serve as a central repository of data where users can store and can fetch the data. The access of this repository is given to other applications also but in a safe manner in order to serve the different requirements of the user. The following are the steps involved in implementing a content provider. In this content provider, the user can store the name of persons and can fetch the stored data. Moreover, another application can also access the stored data and can display the data." }, { "code": null, "e": 29092, "s": 29026, "text": "Note: Following steps are performed on Android Studio version 4.0" }, { "code": null, "e": 29121, "s": 29092, "text": "Creating a Content Provider:" }, { "code": null, "e": 29150, "s": 29121, "text": "Step 1: Create a new project" }, { "code": null, "e": 29296, "s": 29150, "text": "Click on File, then New => New Project.Select language as Java/Kotlin.Choose empty activity as a templateSelect the minimum SDK as per your need." }, { "code": null, "e": 29336, "s": 29296, "text": "Click on File, then New => New Project." }, { "code": null, "e": 29368, "s": 29336, "text": "Select language as Java/Kotlin." }, { "code": null, "e": 29404, "s": 29368, "text": "Choose empty activity as a template" }, { "code": null, "e": 29445, "s": 29404, "text": "Select the minimum SDK as per your need." }, { "code": null, "e": 29481, "s": 29445, "text": "Step 2: Modify the strings.xml file" }, { "code": null, "e": 29535, "s": 29481, "text": "All the strings used in the activity are stored here." }, { "code": null, "e": 29539, "s": 29535, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">Content_Provider_In_Android</string> <string name=\"hintText\">Enter User Name</string> <string name=\"heading\">Content Provider In Android</string> <string name=\"insertButtontext\">Insert Data</string> <string name=\"loadButtonText\">Load Data</string></resources>", "e": 29850, "s": 29539, "text": null }, { "code": null, "e": 29894, "s": 29850, "text": "Step 3: Creating the Content Provider class" }, { "code": null, "e": 30113, "s": 29894, "text": "Click on File, then New => Other => ContentProvider.Name the ContentProviderDefine authority (it can be anything for example “com.demo.user.provider”)Select Exported and Enabled optionChoose the language as Java/Kotlin" }, { "code": null, "e": 30166, "s": 30113, "text": "Click on File, then New => Other => ContentProvider." }, { "code": null, "e": 30191, "s": 30166, "text": "Name the ContentProvider" }, { "code": null, "e": 30266, "s": 30191, "text": "Define authority (it can be anything for example “com.demo.user.provider”)" }, { "code": null, "e": 30301, "s": 30266, "text": "Select Exported and Enabled option" }, { "code": null, "e": 30336, "s": 30301, "text": "Choose the language as Java/Kotlin" }, { "code": null, "e": 30482, "s": 30336, "text": "This class extends the ContentProvider base class and override the six abstract methods. Below is the complete code to define a content provider." }, { "code": null, "e": 30487, "s": 30482, "text": "Java" }, { "code": null, "e": 30494, "s": 30487, "text": "Kotlin" }, { "code": "package com.example.contentprovidersinandroid; import android.content.ContentProvider;import android.content.ContentUris;import android.content.ContentValues;import android.content.Context;import android.content.UriMatcher;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteQueryBuilder;import android.net.Uri;import java.util.HashMap; public class MyContentProvider extends ContentProvider { public MyContentProvider() { } // defining authority so that other application can access it static final String PROVIDER_NAME = \"com.demo.user.provider\"; // defining content URI static final String URL = \"content://\" + PROVIDER_NAME + \"/users\"; // parsing the content URI static final Uri CONTENT_URI = Uri.parse(URL); static final String id = \"id\"; static final String name = \"name\"; static final int uriCode = 1; static final UriMatcher uriMatcher; private static HashMap<String, String> values; static { // to match the content URI // every time user access table under content provider uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); // to access whole table uriMatcher.addURI(PROVIDER_NAME, \"users\", uriCode); // to access a particular row // of the table uriMatcher.addURI(PROVIDER_NAME, \"users/*\", uriCode); } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case uriCode: return \"vnd.android.cursor.dir/users\"; default: throw new IllegalArgumentException(\"Unsupported URI: \" + uri); } } // creating the database @Override public boolean onCreate() { Context context = getContext(); DatabaseHelper dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); if (db != null) { return true; } return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(TABLE_NAME); switch (uriMatcher.match(uri)) { case uriCode: qb.setProjectionMap(values); break; default: throw new IllegalArgumentException(\"Unknown URI \" + uri); } if (sortOrder == null || sortOrder == \"\") { sortOrder = id; } Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } // adding data to the database @Override public Uri insert(Uri uri, ContentValues values) { long rowID = db.insert(TABLE_NAME, \"\", values); if (rowID > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLiteException(\"Failed to add a record into \" + uri); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)) { case uriCode: count = db.update(TABLE_NAME, values, selection, selectionArgs); break; default: throw new IllegalArgumentException(\"Unknown URI \" + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; switch (uriMatcher.match(uri)) { case uriCode: count = db.delete(TABLE_NAME, selection, selectionArgs); break; default: throw new IllegalArgumentException(\"Unknown URI \" + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } // creating object of database // to perform query private SQLiteDatabase db; // declaring name of the database static final String DATABASE_NAME = \"UserDB\"; // declaring table name of the database static final String TABLE_NAME = \"Users\"; // declaring version of the database static final int DATABASE_VERSION = 1; // sql query to create the table static final String CREATE_DB_TABLE = \" CREATE TABLE \" + TABLE_NAME + \" (id INTEGER PRIMARY KEY AUTOINCREMENT, \" + \" name TEXT NOT NULL);\"; // creating a database private static class DatabaseHelper extends SQLiteOpenHelper { // defining a constructor DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // creating a table in the database @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_DB_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // sql query to drop a table // having similar name db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME); onCreate(db); } }}", "e": 35985, "s": 30494, "text": null }, { "code": "package com.example.contentprovidersinandroid import android.content.*import android.database.Cursorimport android.database.sqlite.SQLiteDatabaseimport android.database.sqlite.SQLiteExceptionimport android.database.sqlite.SQLiteOpenHelperimport android.database.sqlite.SQLiteQueryBuilderimport android.net.Uri class MyContentProvider : ContentProvider() { companion object { // defining authority so that other application can access it const val PROVIDER_NAME = \"com.demo.user.provider\" // defining content URI const val URL = \"content://$PROVIDER_NAME/users\" // parsing the content URI val CONTENT_URI = Uri.parse(URL) const val id = \"id\" const val name = \"name\" const val uriCode = 1 var uriMatcher: UriMatcher? = null private val values: HashMap<String, String>? = null // declaring name of the database const val DATABASE_NAME = \"UserDB\" // declaring table name of the database const val TABLE_NAME = \"Users\" // declaring version of the database const val DATABASE_VERSION = 1 // sql query to create the table const val CREATE_DB_TABLE = (\" CREATE TABLE \" + TABLE_NAME + \" (id INTEGER PRIMARY KEY AUTOINCREMENT, \" + \" name TEXT NOT NULL);\") init { // to match the content URI // every time user access table under content provider uriMatcher = UriMatcher(UriMatcher.NO_MATCH) // to access whole table uriMatcher!!.addURI( PROVIDER_NAME, \"users\", uriCode ) // to access a particular row // of the table uriMatcher!!.addURI( PROVIDER_NAME, \"users/*\", uriCode ) } } override fun getType(uri: Uri): String? { return when (uriMatcher!!.match(uri)) { uriCode -> \"vnd.android.cursor.dir/users\" else -> throw IllegalArgumentException(\"Unsupported URI: $uri\") } } // creating the database override fun onCreate(): Boolean { val context = context val dbHelper = DatabaseHelper(context) db = dbHelper.writableDatabase return if (db != null) { true } else false } override fun query( uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String? ): Cursor? { var sortOrder = sortOrder val qb = SQLiteQueryBuilder() qb.tables = TABLE_NAME when (uriMatcher!!.match(uri)) { uriCode -> qb.projectionMap = values else -> throw IllegalArgumentException(\"Unknown URI $uri\") } if (sortOrder == null || sortOrder === \"\") { sortOrder = id } val c = qb.query( db, projection, selection, selectionArgs, null, null, sortOrder ) c.setNotificationUri(context!!.contentResolver, uri) return c } // adding data to the database override fun insert(uri: Uri, values: ContentValues?): Uri? { val rowID = db!!.insert(TABLE_NAME, \"\", values) if (rowID > 0) { val _uri = ContentUris.withAppendedId(CONTENT_URI, rowID) context!!.contentResolver.notifyChange(_uri, null) return _uri } throw SQLiteException(\"Failed to add a record into $uri\") } override fun update( uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>? ): Int { var count = 0 count = when (uriMatcher!!.match(uri)) { uriCode -> db!!.update(TABLE_NAME, values, selection, selectionArgs) else -> throw IllegalArgumentException(\"Unknown URI $uri\") } context!!.contentResolver.notifyChange(uri, null) return count } override fun delete( uri: Uri, selection: String?, selectionArgs: Array<String>? ): Int { var count = 0 count = when (uriMatcher!!.match(uri)) { uriCode -> db!!.delete(TABLE_NAME, selection, selectionArgs) else -> throw IllegalArgumentException(\"Unknown URI $uri\") } context!!.contentResolver.notifyChange(uri, null) return count } // creating object of database // to perform query private var db: SQLiteDatabase? = null // creating a database private class DatabaseHelper // defining a constructor internal constructor(context: Context?) : SQLiteOpenHelper( context, DATABASE_NAME, null, DATABASE_VERSION ) { // creating a table in the database override fun onCreate(db: SQLiteDatabase) { db.execSQL(CREATE_DB_TABLE) } override fun onUpgrade( db: SQLiteDatabase, oldVersion: Int, newVersion: Int ) { // sql query to drop a table // having similar name db.execSQL(\"DROP TABLE IF EXISTS $TABLE_NAME\") onCreate(db) } }}", "e": 41171, "s": 35985, "text": null }, { "code": null, "e": 41215, "s": 41171, "text": "Step 4: Design the activity_main.xml layout" }, { "code": null, "e": 41352, "s": 41215, "text": "One Textview, EditText field, two Buttons, and a Textview to display the stored data will be added in the activity using the below code." }, { "code": null, "e": 41356, "s": 41352, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\"> <LinearLayout android:id=\"@+id/linearLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerVertical=\"true\" android:orientation=\"vertical\" app:layout_constraintBottom_toTopOf=\"@+id/imageView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.13\" tools:ignore=\"MissingConstraints\"> <TextView android:id=\"@+id/textView1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"40dp\" android:layout_marginBottom=\"70dp\" android:fontFamily=\"@font/roboto\" android:text=\"@string/heading\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Large\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"36sp\" android:textStyle=\"bold\" /> <EditText android:id=\"@+id/textName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"40dp\" android:fontFamily=\"@font/roboto\" android:hint=\"@string/hintText\" /> <Button android:id=\"@+id/insertButton\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:onClick=\"onClickAddDetails\" android:text=\"@string/insertButtontext\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Display1\" android:textColor=\"#FFFFFF\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/loadButton\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:onClick=\"onClickShowDetails\" android:text=\"@string/loadButtonText\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Display1\" android:textColor=\"#FFFFFF\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/res\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginEnd=\"20dp\" android:clickable=\"false\" android:ems=\"10\" android:fontFamily=\"@font/roboto\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> </LinearLayout> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:srcCompat=\"@drawable/banner\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 45558, "s": 41356, "text": null }, { "code": null, "e": 45595, "s": 45558, "text": "Step 5: Modify the MainActivity file" }, { "code": null, "e": 45769, "s": 45595, "text": "Button functionalities will be defined in this file. Moreover, the query to be performed while inserting and fetching the data is mentioned here. Below is the complete code." }, { "code": null, "e": 45774, "s": 45769, "text": "Java" }, { "code": null, "e": 45781, "s": 45774, "text": "Kotlin" }, { "code": "package com.example.contentprovidersinandroid; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.inputmethod.InputMethodManager;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onTouchEvent(MotionEvent event) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); return true; } public void onClickAddDetails(View view) { // class to add values in the database ContentValues values = new ContentValues(); // fetching text from user values.put(MyContentProvider.name, ((EditText) findViewById(R.id.textName)).getText().toString()); // inserting into database through content URI getContentResolver().insert(MyContentProvider.CONTENT_URI, values); // displaying a toast message Toast.makeText(getBaseContext(), \"New Record Inserted\", Toast.LENGTH_LONG).show(); } public void onClickShowDetails(View view) { // inserting complete table details in this text field TextView resultView= (TextView) findViewById(R.id.res); // creating a cursor object of the // content URI Cursor cursor = getContentResolver().query(Uri.parse(\"content://com.demo.user.provider/users\"), null, null, null, null); // iteration of the cursor // to print whole table if(cursor.moveToFirst()) { StringBuilder strBuild=new StringBuilder(); while (!cursor.isAfterLast()) { strBuild.append(\"\\n\"+cursor.getString(cursor.getColumnIndex(\"id\"))+ \"-\"+ cursor.getString(cursor.getColumnIndex(\"name\"))); cursor.moveToNext(); } resultView.setText(strBuild); } else { resultView.setText(\"No Records Found\"); } }}", "e": 48149, "s": 45781, "text": null }, { "code": "package com.example.content_provider_in_android import android.content.ContentValuesimport android.content.Contextimport android.net.Uriimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.view.inputmethod.InputMethodManagerimport android.widget.EditTextimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport com.example.contentprovidersinandroid.MyContentProvider class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onTouchEvent(event: MotionEvent?): Boolean { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0) return true } fun onClickAddDetails(view: View?) { // class to add values in the database val values = ContentValues() // fetching text from user values.put(MyContentProvider.name, (findViewById<View>(R.id.textName) as EditText).text.toString()) // inserting into database through content URI contentResolver.insert(MyContentProvider.CONTENT_URI, values) // displaying a toast message Toast.makeText(baseContext, \"New Record Inserted\", Toast.LENGTH_LONG).show() } fun onClickShowDetails(view: View?) { // inserting complete table details in this text field val resultView = findViewById<View>(R.id.res) as TextView // creating a cursor object of the // content URI val cursor = contentResolver.query(Uri.parse(\"content://com.demo.user.provider/users\"), null, null, null, null) // iteration of the cursor // to print whole table if (cursor!!.moveToFirst()) { val strBuild = StringBuilder() while (!cursor.isAfterLast) { strBuild.append(\"\"\" ${cursor.getString(cursor.getColumnIndex(\"id\"))}-${cursor.getString(cursor.getColumnIndex(\"name\"))} \"\"\".trimIndent()) cursor.moveToNext() } resultView.text = strBuild } else { resultView.text = \"No Records Found\" } }}", "e": 50440, "s": 48149, "text": null }, { "code": null, "e": 50480, "s": 50440, "text": "Step 6: Modify the AndroidManifest file" }, { "code": null, "e": 50647, "s": 50480, "text": "The AndroidManifest file must contain the content provider name, authorities, and permissions which enables the content provider to be accessed by other applications." }, { "code": null, "e": 50651, "s": 50647, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.content_provider_in_android\"> <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\"> <provider android:name=\"com.example.contentprovidersinandroid.MyContentProvider\" android:authorities=\"com.demo.user.provider\" android:enabled=\"true\" android:exported=\"true\"></provider> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <meta-data android:name=\"preloaded_fonts\" android:resource=\"@array/preloaded_fonts\" /> </application> </manifest>", "e": 51725, "s": 50651, "text": null }, { "code": null, "e": 51786, "s": 51725, "text": "Creating another application to access the Content Provider:" }, { "code": null, "e": 51815, "s": 51786, "text": "Step 1: Create a new Project" }, { "code": null, "e": 51961, "s": 51815, "text": "Click on File, then New => New Project.Select language as Java/Kotlin.Choose empty activity as a templateSelect the minimum SDK as per your need." }, { "code": null, "e": 52001, "s": 51961, "text": "Click on File, then New => New Project." }, { "code": null, "e": 52033, "s": 52001, "text": "Select language as Java/Kotlin." }, { "code": null, "e": 52069, "s": 52033, "text": "Choose empty activity as a template" }, { "code": null, "e": 52110, "s": 52069, "text": "Select the minimum SDK as per your need." }, { "code": null, "e": 52142, "s": 52110, "text": "Step 2: Modify strings.xml file" }, { "code": null, "e": 52204, "s": 52142, "text": "All the strings used in the activity are stored in this file." }, { "code": null, "e": 52208, "s": 52204, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">Accessing_Content_Provider</string> <string name=\"heading\">Accessing data of Content Provider</string> <string name=\"loadButtonText\">Load Data</string></resources>", "e": 52417, "s": 52208, "text": null }, { "code": null, "e": 52463, "s": 52417, "text": "Step 3: Designing the ctivity_main.xml layout" }, { "code": null, "e": 52685, "s": 52463, "text": "Two TextView is added in the activity, one for heading and one to display the stored data in a content provider. One Button is also added to receive the command to display data. Below is the code to implement this design." }, { "code": null, "e": 52689, "s": 52685, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\"> <LinearLayout android:id=\"@+id/linearLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerVertical=\"true\" android:orientation=\"vertical\" app:layout_constraintBottom_toTopOf=\"@+id/imageView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.13\" tools:ignore=\"MissingConstraints\"> <TextView android:id=\"@+id/textView1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"40dp\" android:layout_marginBottom=\"70dp\" android:fontFamily=\"@font/roboto\" android:text=\"@string/heading\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Large\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"36sp\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/loadButton\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:onClick=\"onClickShowDetails\" android:text=\"@string/loadButtonText\" android:textAlignment=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Display1\" android:textColor=\"#FFFFFF\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/res\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginEnd=\"20dp\" android:clickable=\"false\" android:ems=\"10\" android:fontFamily=\"@font/roboto\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> </LinearLayout> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:srcCompat=\"@drawable/banner\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 55805, "s": 52689, "text": null }, { "code": null, "e": 55842, "s": 55805, "text": "Step 4: Modify the MainActivity file" }, { "code": null, "e": 56037, "s": 55842, "text": "The ContentURI of the previous application is mentioned here and the same functions which were used in the previous app to display the records will also be used here. Below is the complete code:" }, { "code": null, "e": 56042, "s": 56037, "text": "Java" }, { "code": null, "e": 56049, "s": 56042, "text": "Kotlin" }, { "code": "package com.example.accessingcontentprovider; import androidx.appcompat.app.AppCompatActivity;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.TextView; public class MainActivity extends AppCompatActivity { Uri CONTENT_URI = Uri.parse(\"content://com.demo.user.provider/users\"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClickShowDetails(View view) { // inserting complete table details in this text field TextView resultView= (TextView) findViewById(R.id.res); // creating a cursor object of the // content URI Cursor cursor = getContentResolver().query(Uri.parse(\"content://com.demo.user.provider/users\"), null, null, null, null); // iteration of the cursor // to print whole table if(cursor.moveToFirst()) { StringBuilder strBuild=new StringBuilder(); while (!cursor.isAfterLast()) { strBuild.append(\"\\n\"+cursor.getString(cursor.getColumnIndex(\"id\"))+ \"-\"+ cursor.getString(cursor.getColumnIndex(\"name\"))); cursor.moveToNext(); } resultView.setText(strBuild); } else { resultView.setText(\"No Records Found\"); } }}", "e": 57465, "s": 56049, "text": null }, { "code": "package com.example.accessing_content_provider import android.net.Uriimport android.os.Bundleimport android.view.Viewimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { var CONTENT_URI = Uri.parse(\"content://com.demo.user.provider/users\") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun onClickShowDetails(view: View?) { // inserting complete table details in this text field val resultView = findViewById<View>(R.id.res) as TextView // creating a cursor object of the // content URI val cursor = contentResolver.query(Uri.parse(\"content://com.demo.user.provider/users\"), null, null, null, null) // iteration of the cursor // to print whole table if (cursor!!.moveToFirst()) { val strBuild = StringBuilder() while (!cursor.isAfterLast) { strBuild.append(\"\"\" ${cursor.getString(cursor.getColumnIndex(\"id\"))}-${cursor.getString(cursor.getColumnIndex(\"name\"))} \"\"\".trimIndent()) cursor.moveToNext() } resultView.text = strBuild } else { resultView.text = \"No Records Found\" } }}", "e": 58803, "s": 57465, "text": null }, { "code": null, "e": 58811, "s": 58803, "text": "android" }, { "code": null, "e": 58819, "s": 58811, "text": "Android" }, { "code": null, "e": 58824, "s": 58819, "text": "Java" }, { "code": null, "e": 58831, "s": 58824, "text": "Kotlin" }, { "code": null, "e": 58836, "s": 58831, "text": "Java" }, { "code": null, "e": 58844, "s": 58836, "text": "Android" }, { "code": null, "e": 58942, "s": 58844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 58951, "s": 58942, "text": "Comments" }, { "code": null, "e": 58964, "s": 58951, "text": "Old Comments" }, { "code": null, "e": 59007, "s": 58964, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 59065, "s": 59007, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 59098, "s": 59065, "text": "Services in Android with Example" }, { "code": null, "e": 59129, "s": 59098, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 59168, "s": 59129, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 59183, "s": 59168, "text": "Arrays in Java" }, { "code": null, "e": 59227, "s": 59183, "text": "Split() String method in Java with examples" }, { "code": null, "e": 59249, "s": 59227, "text": "For-each loop in Java" }, { "code": null, "e": 59285, "s": 59249, "text": "Arrays.sort() in Java with examples" } ]
Flexbox - Align Self
This property is similar to align-items, but here, it is applied to individual flex items. Usage − align-self: auto | flex-start | flex-end | center | baseline | stretch; This property accepts the following values − flex-start − The flex item will be aligned vertically at the top of the container. flex-start − The flex item will be aligned vertically at the top of the container. flex-end − The flex item will be aligned vertically at the bottom of the container. flex-end − The flex item will be aligned vertically at the bottom of the container. flex-center − The flex item will be aligned vertically at the center of the container. flex-center − The flex item will be aligned vertically at the center of the container. Stretch − The flex item will be aligned vertically such that it fills up the whole vertical space of the container. Stretch − The flex item will be aligned vertically such that it fills up the whole vertical space of the container. baseline − The flex item will be aligned at the base line of the cross axis. baseline − The flex item will be aligned at the base line of the cross axis. On passing this value to the property align-self, a particular flex-item will be aligned vertically at the top of the container. The following example demonstrates the result of passing the value flex-start to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:start;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-self, a particular flex-item will be aligned vertically at the bottom of the container. The following example demonstrates the result of passing the value flex-end to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:flex-end;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing the value center to the property align-self, a particular flex-item will be aligned vertically at the center of the container. The following example demonstrates the result of passing the value center to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:center;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − On passing this value to the property align-self, a particular flex item it will be aligned vertically such that it fills up the whole vertical space of the container. The following example demonstrates the result of passing the value stretch to the align-self property. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta; align-self:stretch;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:flex; height:100vh; border:3px solid black; align-items:flex-start; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 87 Lectures 11 hours Code And Create 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 1902, "s": 1811, "text": "This property is similar to align-items, but here, it is applied to individual flex items." }, { "code": null, "e": 1910, "s": 1902, "text": "Usage −" }, { "code": null, "e": 1983, "s": 1910, "text": "align-self: auto | flex-start | flex-end | center | baseline | stretch;\n" }, { "code": null, "e": 2028, "s": 1983, "text": "This property accepts the following values −" }, { "code": null, "e": 2111, "s": 2028, "text": "flex-start − The flex item will be aligned vertically at the top of the container." }, { "code": null, "e": 2194, "s": 2111, "text": "flex-start − The flex item will be aligned vertically at the top of the container." }, { "code": null, "e": 2278, "s": 2194, "text": "flex-end − The flex item will be aligned vertically at the bottom of the container." }, { "code": null, "e": 2362, "s": 2278, "text": "flex-end − The flex item will be aligned vertically at the bottom of the container." }, { "code": null, "e": 2449, "s": 2362, "text": "flex-center − The flex item will be aligned vertically at the center of the container." }, { "code": null, "e": 2536, "s": 2449, "text": "flex-center − The flex item will be aligned vertically at the center of the container." }, { "code": null, "e": 2652, "s": 2536, "text": "Stretch − The flex item will be aligned vertically such that it fills up the whole vertical space of the container." }, { "code": null, "e": 2768, "s": 2652, "text": "Stretch − The flex item will be aligned vertically such that it fills up the whole vertical space of the container." }, { "code": null, "e": 2845, "s": 2768, "text": "baseline − The flex item will be aligned at the base line of the cross axis." }, { "code": null, "e": 2922, "s": 2845, "text": "baseline − The flex item will be aligned at the base line of the cross axis." }, { "code": null, "e": 3051, "s": 2922, "text": "On passing this value to the property align-self, a particular flex-item will be aligned vertically at the top of the container." }, { "code": null, "e": 3157, "s": 3051, "text": "The following example demonstrates the result of passing the value flex-start to the align-self property." }, { "code": null, "e": 3964, "s": 3157, "text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta; align-self:start;}\n .box5{background:yellow;}\n .box6{background:pink;}\n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n height:100vh;\n border:3px solid black;\n align-items:flex-start;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4003, "s": 3964, "text": "It will produce the following result −" }, { "code": null, "e": 4135, "s": 4003, "text": "On passing this value to the property align-self, a particular flex-item will be aligned vertically at the bottom of the container." }, { "code": null, "e": 4239, "s": 4135, "text": "The following example demonstrates the result of passing the value flex-end to the align-self property." }, { "code": null, "e": 5049, "s": 4239, "text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta; align-self:flex-end;}\n .box5{background:yellow;}\n .box6{background:pink;}\n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n height:100vh;\n border:3px solid black;\n align-items:flex-start;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 5088, "s": 5049, "text": "It will produce the following result −" }, { "code": null, "e": 5226, "s": 5088, "text": "On passing the value center to the property align-self, a particular flex-item will be aligned vertically at the center of the container." }, { "code": null, "e": 5328, "s": 5226, "text": "The following example demonstrates the result of passing the value center to the align-self property." }, { "code": null, "e": 6136, "s": 5328, "text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta; align-self:center;}\n .box5{background:yellow;}\n .box6{background:pink;}\n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n height:100vh;\n border:3px solid black;\n align-items:flex-start;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 6175, "s": 6136, "text": "It will produce the following result −" }, { "code": null, "e": 6343, "s": 6175, "text": "On passing this value to the property align-self, a particular flex item it will be aligned vertically such that it fills up the whole vertical space of the container." }, { "code": null, "e": 6446, "s": 6343, "text": "The following example demonstrates the result of passing the value stretch to the align-self property." }, { "code": null, "e": 7255, "s": 6446, "text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta; align-self:stretch;}\n .box5{background:yellow;}\n .box6{background:pink;}\n .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:flex;\n height:100vh;\n border:3px solid black;\n align-items:flex-start;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 7294, "s": 7255, "text": "It will produce the following result −" }, { "code": null, "e": 7329, "s": 7294, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7360, "s": 7329, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7394, "s": 7360, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 7411, "s": 7394, "text": " Code And Create" }, { "code": null, "e": 7448, "s": 7411, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 7464, "s": 7448, "text": " Muslim Helalee" }, { "code": null, "e": 7471, "s": 7464, "text": " Print" }, { "code": null, "e": 7482, "s": 7471, "text": " Add Notes" } ]
Pure Component in React.js
We have a lifecycle method called shouldComponentUpdate which by default returns true (Boolean) value. The purpose of the shouldComponentUpdate is we can custom implement the default behavior and decide when react should update or re-render the component. Generally we use state or props value to decide the update cycle. React has now provided us a PureComponent which does the comparison of state and props to decide the update cycle. We don’t need to override shouldComponentUpdate if we extend class with PureComponent. React does the shallow comparisons of current state and props with new props and state to decide whether to continue with next update cycle or not. This helps in improving the performance of the application. But we should extend the class with PureComponent only when it makes sense comparing every state and props. Else we can implement the shouldCompnentUpdate at our own if all state and props comparison is not required. This extend PureComponent applies to only stateful class based compnents. For functional components we can use pure function as shown below − import { pure } from ‘recompose’; export default pure ( (props) => { //custom code return ‘something useful’ ;// your code }) import React, {PureComponent} from ‘react’; export default class Test extends PureComponent{ render(){ return ‘’; } } As PureComponent does shallow comparison of state and props objects and so there is a possibility that if these objects contains nested data structure then PureComponent’s implemented shouldComponentUpdate will return false . It can even skip the update of whole subtree of children of this component. In this scenario, child elements should also be Pure then. So nested data structure comparison does not works well with PureComponent. It works only if the state and props are simple objects. Components can be termed as pure if they return same output for same input values at any point of time. If state or props references new object, PureComponent will re-render every time. Objects should be modified immutably to make update successfully using PureComponent We can use forceUpdate to manually re-render even if shouldComponentUpdate fails. Use imutable.js if we have nested objects in shallow comparison . class Test extends React.PureComponent { constructor(props) { super(props); this.state = { taskList: [ { title: 'excercise'}, { title: 'cooking'}, { title: 'Reacting'}, ] }; } componentDidMount() { setInterval(() => { this.setState((oldState) => { return { taskList: [...oldState.taskList] } }); }, 1000); } render() { console.log(“taskList render called”); return (<div> {this.state.taskList.map((task, i) => { return (<Task key={i} title={task.title} />); })} </div>); } } class Task extends React.Component { render() { console.log(“task added”); return (<div> {this.props.title} </div>); } } ReactDOM.render(<Test />, document.getElementById('app')); We have manually triggered a prop change call from componentDidMount after every second just to showcase how each task gets rendered every time. Please check console log in browser. Because Task component is not extending the PureComponent. React does not know what is changed so its rendering the Task every time. So now just change Task component with below line Export default class task extends PureComponent => It solves the multiple rendering of Task and prevents unnecessary render if no new task is added.
[ { "code": null, "e": 1165, "s": 1062, "text": "We have a lifecycle method called shouldComponentUpdate which by default returns true (Boolean) value." }, { "code": null, "e": 1318, "s": 1165, "text": "The purpose of the shouldComponentUpdate is we can custom implement the default behavior and decide when react should update or re-render the component." }, { "code": null, "e": 1586, "s": 1318, "text": "Generally we use state or props value to decide the update cycle. React has now provided us a PureComponent which does the comparison of state and props to decide the update cycle. We don’t need to override shouldComponentUpdate if we extend class with PureComponent." }, { "code": null, "e": 1734, "s": 1586, "text": "React does the shallow comparisons of current state and props with new props and state to decide whether to continue with next update cycle or not." }, { "code": null, "e": 2011, "s": 1734, "text": "This helps in improving the performance of the application. But we should extend the class with PureComponent only when it makes sense comparing every state and props. Else we can implement the shouldCompnentUpdate at our own if all state and props comparison is not required." }, { "code": null, "e": 2153, "s": 2011, "text": "This extend PureComponent applies to only stateful class based compnents. For functional components we can use pure function as shown below −" }, { "code": null, "e": 2285, "s": 2153, "text": "import { pure } from ‘recompose’;\nexport default pure ( (props) => {\n //custom code\n return ‘something useful’ ;// your code\n})" }, { "code": null, "e": 2415, "s": 2285, "text": "import React, {PureComponent} from ‘react’;\nexport default class Test extends PureComponent{\n render(){\n return ‘’;\n }\n}" }, { "code": null, "e": 2717, "s": 2415, "text": "As PureComponent does shallow comparison of state and props objects and so there is a possibility that if these objects contains nested data structure then PureComponent’s implemented shouldComponentUpdate will return false . It can even skip the update of whole subtree of children of this component." }, { "code": null, "e": 2776, "s": 2717, "text": "In this scenario, child elements should also be Pure then." }, { "code": null, "e": 2909, "s": 2776, "text": "So nested data structure comparison does not works well with PureComponent. It works only if the state and props are simple objects." }, { "code": null, "e": 3013, "s": 2909, "text": "Components can be termed as pure if they return same output for same input values at any point of time." }, { "code": null, "e": 3095, "s": 3013, "text": "If state or props references new object, PureComponent will re-render every time." }, { "code": null, "e": 3180, "s": 3095, "text": "Objects should be modified immutably to make update successfully using PureComponent" }, { "code": null, "e": 3328, "s": 3180, "text": "We can use forceUpdate to manually re-render even if shouldComponentUpdate fails. Use imutable.js if we have nested objects in shallow comparison ." }, { "code": null, "e": 4238, "s": 3328, "text": "class Test extends React.PureComponent {\n constructor(props) {\n super(props);\n this.state = {\n taskList: [\n { title: 'excercise'},\n { title: 'cooking'},\n { title: 'Reacting'},\n ]\n };\n }\n componentDidMount() {\n setInterval(() => {\n this.setState((oldState) => {\n return { taskList: [...oldState.taskList] }\n });\n }, 1000);\n }\n render() {\n console.log(“taskList render called”);\n return (<div>\n {this.state.taskList.map((task, i) => {\n return (<Task\n key={i}\n title={task.title}\n />);\n })}\n </div>);\n }\n}\nclass Task extends React.Component {\n render() {\n console.log(“task added”);\n return (<div>\n {this.props.title}\n </div>);\n }\n}\nReactDOM.render(<Test />, document.getElementById('app'));" }, { "code": null, "e": 4383, "s": 4238, "text": "We have manually triggered a prop change call from componentDidMount after every second just to showcase how each task gets rendered every time." }, { "code": null, "e": 4420, "s": 4383, "text": "Please check console log in browser." }, { "code": null, "e": 4553, "s": 4420, "text": "Because Task component is not extending the PureComponent. React does not know what is changed so its rendering the Task every time." }, { "code": null, "e": 4603, "s": 4553, "text": "So now just change Task component with below line" }, { "code": null, "e": 4752, "s": 4603, "text": "Export default class task extends PureComponent => It solves the multiple rendering of Task and prevents unnecessary render if no new task is added." } ]
Tryit Editor v3.6 - Show React
import React from 'react'; import ReactDOM from 'react-dom/client'; const Header = () => { return ( <> <h1 style={{color: "red"}}>Hello Style!</h1> <p>Add a little style!</p> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Header />); <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>React App</title> </head> <body> <div id="root"></div> </body> </html> Add a little style!
[ { "code": null, "e": 305, "s": 0, "text": "\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\n\nconst Header = () => {\n return (\n <>\n <h1 style={{color: \"red\"}}>Hello Style!</h1>\n <p>Add a little style!</p>\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Header />);\n\n" }, { "code": null, "e": 555, "s": 305, "text": "\n\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\"\n content=\"width=device-width, initial-scale=1\" />\n <title>React App</title>\n </head>\n <body>\n\n <div id=\"root\"></div>\n\n </body>\n</html>\n\n" } ]
Count Triplets such that one of the numbers can be written as sum of the other two in C++
We are given an array Arr[] of integers with length n. The goal is to find the number of triplets (Arr[i],Arr[j],Arr[k]) such that the sum of any two numbers is equal to the third number. a+b=c, where a,b,c are elements of Arr[] with indexes i,j,k such that 0<=i<j<k<n We will do this by using three for loops. Increment count if arr[x]+arr[y]=arr[z] and x!=y!=z. Let’s understand with examples. arr[]= { 1,2,2,3,4 }, N=5 Number of triplets: 4 Triplets with arr[x]+arr[y]=arr[z]. Arr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3 Arr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3 Arr{}=[ 1,2,2,3,4 ] =(1,3,4) → 1+3=4 Arr{}=[ 1,2,2,3,4 ] =(2,2,4) → 2+2=4 Total triplets: 4 arr[]= {2,2,2,2,2}, N=5 Number of triplets: 0 Every two numbers have sum=4 which is not equal to third=2. Total triplets: 0 We take an integer array Arr[] initialized with random numbers. We take an integer array Arr[] initialized with random numbers. Variable N stores the length of Arr[]. Variable N stores the length of Arr[]. Function countTriplets(int arr[],int n) takes an array, its length returns the triplets in which one of the numbers can be written as sum of the other two Function countTriplets(int arr[],int n) takes an array, its length returns the triplets in which one of the numbers can be written as sum of the other two Take the initial variable count as 0 for the number of triplets. Take the initial variable count as 0 for the number of triplets. Traverse array using three for loops for each element of the triplet. Traverse array using three for loops for each element of the triplet. Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n. Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n. Check if arr[i]+arr[j]==arr[k] or arr[i]+arr[k]==arr[j] or arr[k]+arr[j]==arr[i] If true then increment count. Check if arr[i]+arr[j]==arr[k] or arr[i]+arr[k]==arr[j] or arr[k]+arr[j]==arr[i] If true then increment count. At the end of all loops count will have a total number of triplets that meet the condition. At the end of all loops count will have a total number of triplets that meet the condition. Return the count as result. Return the count as result. Live Demo #include <bits/stdc++.h> using namespace std; int countTriplets(int arr[], int n){ int count = 0; for (int i = 0; i < n-2; i++){ for (int j = i+1; j < n-1; j++){ for (int k = j+1; k < n; k++){ if(arr[i]+arr[j]==arr[k] || arr[j]+arr[k]==arr[i] || arr[k]+arr[i]==arr[j]){ count++; } } } } return count; } int main(){ int Arr[]={ 1,2,2,3,4 }; int N=5; //length of array cout <<endl<< "Number of triplets : "<<countTriplets(Arr,N); return 0; } Number of triplets : 4
[ { "code": null, "e": 1250, "s": 1062, "text": "We are given an array Arr[] of integers with length n. The goal is to find the number of triplets\n(Arr[i],Arr[j],Arr[k]) such that the sum of any two numbers is equal to the third number." }, { "code": null, "e": 1458, "s": 1250, "text": "a+b=c, where a,b,c are elements of Arr[] with indexes i,j,k such that 0<=i<j<k<n\nWe will do this by using three for loops. Increment count if arr[x]+arr[y]=arr[z] and x!=y!=z.\nLet’s understand with examples." }, { "code": null, "e": 1484, "s": 1458, "text": "arr[]= { 1,2,2,3,4 }, N=5" }, { "code": null, "e": 1506, "s": 1484, "text": "Number of triplets: 4" }, { "code": null, "e": 1542, "s": 1506, "text": "Triplets with arr[x]+arr[y]=arr[z]." }, { "code": null, "e": 1690, "s": 1542, "text": "Arr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3\nArr{}=[ 1,2,2,3,4 ] =(1,2,3) → 1+2=3\nArr{}=[ 1,2,2,3,4 ] =(1,3,4) → 1+3=4\nArr{}=[ 1,2,2,3,4 ] =(2,2,4) → 2+2=4" }, { "code": null, "e": 1708, "s": 1690, "text": "Total triplets: 4" }, { "code": null, "e": 1732, "s": 1708, "text": "arr[]= {2,2,2,2,2}, N=5" }, { "code": null, "e": 1754, "s": 1732, "text": "Number of triplets: 0" }, { "code": null, "e": 1814, "s": 1754, "text": "Every two numbers have sum=4 which is not equal to third=2." }, { "code": null, "e": 1832, "s": 1814, "text": "Total triplets: 0" }, { "code": null, "e": 1896, "s": 1832, "text": "We take an integer array Arr[] initialized with random numbers." }, { "code": null, "e": 1960, "s": 1896, "text": "We take an integer array Arr[] initialized with random numbers." }, { "code": null, "e": 1999, "s": 1960, "text": "Variable N stores the length of Arr[]." }, { "code": null, "e": 2038, "s": 1999, "text": "Variable N stores the length of Arr[]." }, { "code": null, "e": 2193, "s": 2038, "text": "Function countTriplets(int arr[],int n) takes an array, its length returns the triplets in\nwhich one of the numbers can be written as sum of the other two" }, { "code": null, "e": 2348, "s": 2193, "text": "Function countTriplets(int arr[],int n) takes an array, its length returns the triplets in\nwhich one of the numbers can be written as sum of the other two" }, { "code": null, "e": 2413, "s": 2348, "text": "Take the initial variable count as 0 for the number of triplets." }, { "code": null, "e": 2478, "s": 2413, "text": "Take the initial variable count as 0 for the number of triplets." }, { "code": null, "e": 2548, "s": 2478, "text": "Traverse array using three for loops for each element of the triplet." }, { "code": null, "e": 2618, "s": 2548, "text": "Traverse array using three for loops for each element of the triplet." }, { "code": null, "e": 2685, "s": 2618, "text": "Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n." }, { "code": null, "e": 2752, "s": 2685, "text": "Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n." }, { "code": null, "e": 2863, "s": 2752, "text": "Check if arr[i]+arr[j]==arr[k] or arr[i]+arr[k]==arr[j] or arr[k]+arr[j]==arr[i] If true then\nincrement count." }, { "code": null, "e": 2974, "s": 2863, "text": "Check if arr[i]+arr[j]==arr[k] or arr[i]+arr[k]==arr[j] or arr[k]+arr[j]==arr[i] If true then\nincrement count." }, { "code": null, "e": 3066, "s": 2974, "text": "At the end of all loops count will have a total number of triplets that meet the condition." }, { "code": null, "e": 3158, "s": 3066, "text": "At the end of all loops count will have a total number of triplets that meet the condition." }, { "code": null, "e": 3186, "s": 3158, "text": "Return the count as result." }, { "code": null, "e": 3214, "s": 3186, "text": "Return the count as result." }, { "code": null, "e": 3225, "s": 3214, "text": " Live Demo" }, { "code": null, "e": 3762, "s": 3225, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint countTriplets(int arr[], int n){\n int count = 0;\n for (int i = 0; i < n-2; i++){\n for (int j = i+1; j < n-1; j++){\n for (int k = j+1; k < n; k++){\n if(arr[i]+arr[j]==arr[k] || arr[j]+arr[k]==arr[i] || arr[k]+arr[i]==arr[j]){ count++;\n }\n }\n }\n }\n return count;\n}\nint main(){\n int Arr[]={ 1,2,2,3,4 };\n int N=5; //length of array\n cout <<endl<< \"Number of triplets : \"<<countTriplets(Arr,N);\n return 0;\n}" }, { "code": null, "e": 3785, "s": 3762, "text": "Number of triplets : 4" } ]
Schedule elevator to reduce the total time taken
01 Jun, 2022 Given an integer k and an array arr[] representing the destination floors for N people waiting currently at the ground floor and k is the capacity of the elevator i.e. maximum number of people it can hold at the same time. It takes 1 unit time for the elevator to reach any consecutive floor from the current floor. The task is to schedule the elevator in a way to minimize the total time taken to get all the people to their destination floor and then return back to the ground floor.Examples: Input: arr[] = {2, 3, 4}, k = 2 Output: 12 Second and the third persons (destination floors 3 and 4) shall go in the first turn taking 8 (4 + 4) unit time. The only person left will take 2 unit time to get to the destination And then the elevator will take another 2 unit time to get back to the ground floor. Total time taken = 8 + 2 + 2 = 12Input: arr[] = {5, 5, 4}, k = 3 Output: 10 Every person can get on the elevator at the same time Time required will be 10 (5 + 5). Approach: Sort the given array in decreasing order of destination. Create groups of K (starting from the highest floor), the cost for each group will be 2 * (max(Elements in current group)). The summation across all groups will be the answer.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum time taken// by the elevator when operating optimallyint minTime(int n, int k, int a[]){ // Sort in descending order sort(a, a + n, greater<int>()); int minTime = 0; // Iterate through the groups for (int i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codeint main(){ int k = 2; int arr[] = { 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minTime(n, k, arr); return 0;} // Java implementation of the approachimport java.util.*; class GFG{// Function to return the minimum time taken// by the elevator when operating optimallypublic static int minTime(int n, int k, Integer a[]){ // Sort in descending order Arrays.sort(a , Collections.reverseOrder()); int minTime = 0; // Iterate through the groups for (int i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codepublic static void main(String args[]){ int k = 2; Integer arr[] = { 2, 3, 4 }; int n = arr.length; System.out.println(minTime(n, k, arr));}} // This code is contributed by Pushpesh Raj. # Python3 implementation of the approach # Function to return the minimum time taken# by the elevator when operating optimallydef minTime(n, k, a) : # Sort in descending order a.sort(reverse = True); minTime = 0; # Iterate through the groups for i in range(0, n, k) : # Update the time taken for # each group minTime += (2 * a[i]); # Return the total time taken return minTime; # Driver codeif __name__ == "__main__" : k = 2; arr = [ 2, 3, 4 ]; n = len(arr) ; print(minTime(n, k, arr)); # This code is contributed by Ryuga // C# implementation of the approachusing System; class GFG{ // Function to return the minimum time taken// by the elevator when operating optimallystatic int minTime(int n, int k, int []a){ // Sort in descending order int temp; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if(a[i] < a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } int minTime = 0; // Iterate through the groups for (int i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codepublic static void Main(String []args){ int k = 2; int []arr = { 2, 3, 4 }; int n = arr.Length; Console.Write(minTime(n, k, arr));}} // This code is contributed by Arnab Kundu <script> // JavaScript implementation of the approach // Function to return the minimum time taken// by the elevator when operating optimallyfunction minTime(n , k , a){ // Sort in descending order var temp; for(var i = 0; i < n; i++) { for(var j = i + 1; j < n; j++) { if(a[i] < a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } var minTime = 0; // Iterate through the groups for (var i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codevar k = 2;var arr = [ 2, 3, 4 ];var n = arr.length;document.write(minTime(n, k, arr)); // This code is contributed by Amit Katiyar </script> 12 Time Complexity: O(N * log(N))Auxiliary Space: O(1) ankthon SURENDRA_GANGWAR andrew1234 amit143katiyar pankajsharmagfg pushpeshrajdx01 Arrays Sorting Quiz Algorithms Arrays Algorithms 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, 2022" }, { "code": null, "e": 549, "s": 52, "text": "Given an integer k and an array arr[] representing the destination floors for N people waiting currently at the ground floor and k is the capacity of the elevator i.e. maximum number of people it can hold at the same time. It takes 1 unit time for the elevator to reach any consecutive floor from the current floor. The task is to schedule the elevator in a way to minimize the total time taken to get all the people to their destination floor and then return back to the ground floor.Examples: " }, { "code": null, "e": 1025, "s": 549, "text": "Input: arr[] = {2, 3, 4}, k = 2 Output: 12 Second and the third persons (destination floors 3 and 4) shall go in the first turn taking 8 (4 + 4) unit time. The only person left will take 2 unit time to get to the destination And then the elevator will take another 2 unit time to get back to the ground floor. Total time taken = 8 + 2 + 2 = 12Input: arr[] = {5, 5, 4}, k = 3 Output: 10 Every person can get on the elevator at the same time Time required will be 10 (5 + 5). " }, { "code": null, "e": 1322, "s": 1027, "text": "Approach: Sort the given array in decreasing order of destination. Create groups of K (starting from the highest floor), the cost for each group will be 2 * (max(Elements in current group)). The summation across all groups will be the answer.Below is the implementation of the above approach: " }, { "code": null, "e": 1326, "s": 1322, "text": "C++" }, { "code": null, "e": 1331, "s": 1326, "text": "Java" }, { "code": null, "e": 1339, "s": 1331, "text": "Python3" }, { "code": null, "e": 1342, "s": 1339, "text": "C#" }, { "code": null, "e": 1353, "s": 1342, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum time taken// by the elevator when operating optimallyint minTime(int n, int k, int a[]){ // Sort in descending order sort(a, a + n, greater<int>()); int minTime = 0; // Iterate through the groups for (int i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codeint main(){ int k = 2; int arr[] = { 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minTime(n, k, arr); return 0;}", "e": 2000, "s": 1353, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{// Function to return the minimum time taken// by the elevator when operating optimallypublic static int minTime(int n, int k, Integer a[]){ // Sort in descending order Arrays.sort(a , Collections.reverseOrder()); int minTime = 0; // Iterate through the groups for (int i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codepublic static void main(String args[]){ int k = 2; Integer arr[] = { 2, 3, 4 }; int n = arr.length; System.out.println(minTime(n, k, arr));}} // This code is contributed by Pushpesh Raj.", "e": 2723, "s": 2000, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the minimum time taken# by the elevator when operating optimallydef minTime(n, k, a) : # Sort in descending order a.sort(reverse = True); minTime = 0; # Iterate through the groups for i in range(0, n, k) : # Update the time taken for # each group minTime += (2 * a[i]); # Return the total time taken return minTime; # Driver codeif __name__ == \"__main__\" : k = 2; arr = [ 2, 3, 4 ]; n = len(arr) ; print(minTime(n, k, arr)); # This code is contributed by Ryuga", "e": 3322, "s": 2723, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimum time taken// by the elevator when operating optimallystatic int minTime(int n, int k, int []a){ // Sort in descending order int temp; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { if(a[i] < a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } int minTime = 0; // Iterate through the groups for (int i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codepublic static void Main(String []args){ int k = 2; int []arr = { 2, 3, 4 }; int n = arr.Length; Console.Write(minTime(n, k, arr));}} // This code is contributed by Arnab Kundu", "e": 4215, "s": 3322, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the minimum time taken// by the elevator when operating optimallyfunction minTime(n , k , a){ // Sort in descending order var temp; for(var i = 0; i < n; i++) { for(var j = i + 1; j < n; j++) { if(a[i] < a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } var minTime = 0; // Iterate through the groups for (var i = 0; i < n; i += k) // Update the time taken for each group minTime += (2 * a[i]); // Return the total time taken return minTime;} // Driver codevar k = 2;var arr = [ 2, 3, 4 ];var n = arr.length;document.write(minTime(n, k, arr)); // This code is contributed by Amit Katiyar </script>", "e": 5041, "s": 4215, "text": null }, { "code": null, "e": 5044, "s": 5041, "text": "12" }, { "code": null, "e": 5096, "s": 5044, "text": "Time Complexity: O(N * log(N))Auxiliary Space: O(1)" }, { "code": null, "e": 5104, "s": 5096, "text": "ankthon" }, { "code": null, "e": 5121, "s": 5104, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5132, "s": 5121, "text": "andrew1234" }, { "code": null, "e": 5147, "s": 5132, "text": "amit143katiyar" }, { "code": null, "e": 5163, "s": 5147, "text": "pankajsharmagfg" }, { "code": null, "e": 5179, "s": 5163, "text": "pushpeshrajdx01" }, { "code": null, "e": 5186, "s": 5179, "text": "Arrays" }, { "code": null, "e": 5199, "s": 5186, "text": "Sorting Quiz" }, { "code": null, "e": 5210, "s": 5199, "text": "Algorithms" }, { "code": null, "e": 5217, "s": 5210, "text": "Arrays" }, { "code": null, "e": 5228, "s": 5217, "text": "Algorithms" } ]
send_keys() element method – Selenium Python
27 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies This article revolves around how to use send_keys method in Selenium. send_keys method is used to send text to any field, such as input field of a form or even to anchor tag paragraph, etc. It replaces its contents on the webpage in your browser. element.send_keys("some text") Example – <input type="text" name="passwd" id="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id") element = driver.find_element_by_name("passwd") element = driver.find_element_by_xpath("//input[@id='passwd-id']") Also, to find multiple elements, we can use – elements = driver.find_elements_by_name("passwd") To enter text into a field, for example, element.send_keys("some text") One can simulate pressing the arrow keys by using the “Keys” class: element.send_keys(" and some", Keys.ARROW_DOWN) Also note, it is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail.One can easily clear the contents of a text field or textarea with the clear method: Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python. Here we get element of search and enter “Arrays” in the same.Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_id("gsc-i-id2") # send keys element.send_keys("Arrays") Output- Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Apr, 2020" }, { "code": null, "e": 611, "s": 54, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies" }, { "code": null, "e": 858, "s": 611, "text": "This article revolves around how to use send_keys method in Selenium. send_keys method is used to send text to any field, such as input field of a form or even to anchor tag paragraph, etc. It replaces its contents on the webpage in your browser." }, { "code": null, "e": 889, "s": 858, "text": "element.send_keys(\"some text\")" }, { "code": null, "e": 899, "s": 889, "text": "Example –" }, { "code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />", "e": 950, "s": 899, "text": null }, { "code": null, "e": 1031, "s": 950, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": null, "e": 1195, "s": 1031, "text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")" }, { "code": null, "e": 1241, "s": 1195, "text": "Also, to find multiple elements, we can use –" }, { "code": null, "e": 1291, "s": 1241, "text": "elements = driver.find_elements_by_name(\"passwd\")" }, { "code": null, "e": 1332, "s": 1291, "text": "To enter text into a field, for example," }, { "code": null, "e": 1363, "s": 1332, "text": "element.send_keys(\"some text\")" }, { "code": null, "e": 1431, "s": 1363, "text": "One can simulate pressing the arrow keys by using the “Keys” class:" }, { "code": null, "e": 1479, "s": 1431, "text": "element.send_keys(\" and some\", Keys.ARROW_DOWN)" }, { "code": null, "e": 1703, "s": 1479, "text": "Also note, it is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail.One can easily clear the contents of a text field or textarea with the clear method:" }, { "code": null, "e": 1861, "s": 1703, "text": "Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python. Here we get element of search and enter “Arrays” in the same.Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_id(\"gsc-i-id2\") # send keys element.send_keys(\"Arrays\")", "e": 2139, "s": 1861, "text": null }, { "code": null, "e": 2147, "s": 2139, "text": "Output-" }, { "code": null, "e": 2163, "s": 2147, "text": "Python-selenium" }, { "code": null, "e": 2172, "s": 2163, "text": "selenium" }, { "code": null, "e": 2179, "s": 2172, "text": "Python" } ]
Program to build a DFA that accepts strings starting and ending with different character
07 Jun, 2021 Prerequisite: Deterministic Finite Automata Given string, str consists of characters ‘a’ & ‘b’. The task is to check whether string str starts and ends with different characters or not. If it does, print ‘YES’ with state transitions, else print ‘NO’. Examples: Input: ababab Output: YES Explanation: The string “ababab” is starting with ‘a’ and ends with ‘b’Input : ababa Output : NO Explanation: The string “ababab” is starting with ‘a’ and ends with ‘a’ In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {a, b}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state.DFA Machine: For the above problem statement build a DFA machine. It is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q2 and Q4 are the final states: Explanation: Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine. Now, it is defined that the string must not end with an ‘a’ to be accepted. At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string. If it gets a ‘b’, then it can go to the final state, since a string ending in ‘b’ is acceptable in this case, so it moves to state Q2. Here, if it gets an ‘a’, it again enters the non-final state else for consecutive ‘b’s, it keeps circling in the final state. The same is in the case when the first character is detected as ‘b’.Approach: Define the minimum number of states required to make the state diagram. Use functions to various states.List all the valid transitions. Each state must have a transition for every valid symbol.Define the final states by applying the base condition.Define all the state transitions using state function calls.Define a returning condition for the end of the string. Define the minimum number of states required to make the state diagram. Use functions to various states. List all the valid transitions. Each state must have a transition for every valid symbol. Define the final states by applying the base condition. Define all the state transitions using state function calls. Define a returning condition for the end of the string. For the given DFA Machine, the specifications are as follows: Q0, Q1, Q2, Q3, Q4 are the defined states.a and b are valid symbols. Each state has a transition defined for a and b.Q2 and Q4 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected.Suppose at state Q0, if ‘a’ comes, the function call is made to Q1. If ‘b’ comes, the function call is made to Q3.If by following the process, the program reaches the end of the string, the output is made according to the state the program is at. Q0, Q1, Q2, Q3, Q4 are the defined states. a and b are valid symbols. Each state has a transition defined for a and b. Q2 and Q4 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected. Suppose at state Q0, if ‘a’ comes, the function call is made to Q1. If ‘b’ comes, the function call is made to Q3. If by following the process, the program reaches the end of the string, the output is made according to the state the program is at. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP Program to DFA that accepts// string if it starts and end with// same character#include <bits/stdc++.h>using namespace std; // various states of DFA machine// are defined using functions.bool q1(string, int);bool q2(string, int);bool q3(string, int);bool q4(string, int); // vector to store state transitionvector<string> state_transition; // end position is checked using string// length value.// q0 is the starting state.// q2 and q4 are intermediate states.// q1 and q3 are final states. bool q1(string s, int i){ state_transition.push_back("q1"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} bool q2(string s, int i){ state_transition.push_back("q2"); if (i == s.length()) { return true; } // state transitions // a takes to q1, b takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} bool q3(string s, int i){ state_transition.push_back("q3"); if (i == s.length()) { return false; } // state transitions // a takes to q4, 1 takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} bool q4(string s, int i){ state_transition.push_back("q4"); if (i == s.length()) { return true; } // state transitions // a takes to q4, b takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} bool q0(string s, int i){ state_transition.push_back("q0"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q3 if (s[i] == 'a') return q1(s, i + 1); else return q3(s, i + 1);} int main(){ string s = "ababab"; // all state transitions are printed. // if string is acceptable, print YES. // else NO is printed bool ans = q0(s, 0); if (ans) { cout << "YES" << endl; // print transition state of given // string str for (auto& it : state_transition) { cout << it << ' '; } } else cout << "NO" << endl; return 0;} // Java Program to DFA that accepts// string if it starts and end with// same characterimport java.util.*; class GFG{ // vector to store state transition static Vector state_transition = new Vector(); // end position is checked using string // length value. // q0 is the starting state. // q2 and q4 are intermediate states. // q1 and q3 are final states. static boolean q1(String s, int i) { state_transition.add("q1"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q2 if (s.charAt(i) == 'a') return q1(s, i + 1); else return q2(s, i + 1); } static boolean q2(String s, int i) { state_transition.add("q2"); if (i == s.length()) { return true; } // state transitions // a takes to q1, b takes to q2 if (s.charAt(i) == 'a') return q1(s, i + 1); else return q2(s, i + 1); } static boolean q3(String s, int i) { state_transition.add("q3"); if (i == s.length()) { return false; } // state transitions // a takes to q4, 1 takes to q3 if (s.charAt(i) == 'a') return q4(s, i + 1); else return q3(s, i + 1); } static boolean q4(String s, int i) { state_transition.add("q4"); if (i == s.length()) { return true; } // state transitions // a takes to q4, b takes to q3 if (s.charAt(i) == 'a') return q4(s, i + 1); else return q3(s, i + 1); } static boolean q0(String s, int i) { state_transition.add("q0"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q3 if (s.charAt(i) == 'a') return q1(s, i + 1); else return q3(s, i + 1); } // Driver code public static void main (String[] args) { String s = "ababab"; // all state transitions are printed. // if string is acceptable, print YES. // else NO is printed boolean ans = q0(s, 0); if (ans == true) { System.out.println("YES"); // print transition state of given // string str for(int index = 0; index < state_transition.size(); index++) { //(auto& it : ) { System.out.print((String)state_transition.get(index) + ' '); } } else System.out.println("NO"); }} // This code is contributed by AnkitRai01 # Python3 Program to DFA that accepts# if it starts and end with# same character # vector to store state transitionstate_transition = [] # end position is checked using string# length value.# q0 is the starting state.# q2 and q4 are intermediate states.# q1 and q3 are final states.def q1(s, i): state_transition.append("q1") if (i == len(s)): return False # state transitions # a takes to q1, b takes to q2 if (s[i] == 'a'): return q1(s, i + 1) else: return q2(s, i + 1) def q2(s, i): state_transition.append("q2") if (i == len(s)): return True # state transitions # a takes to q1, b takes to q2 if (s[i] == 'a'): return q1(s, i + 1) else: return q2(s, i + 1) def q3(s, i): state_transition.append("q3") if (i == len(s)): return False # state transitions # a takes to q4, 1 takes to q3 if (s[i] == 'a'): return q4(s, i + 1) else: return q3(s, i + 1) def q4(s, i): state_transition.append("q4") if (i == len(s)): return True # state transitions # a takes to q4, b takes to q3 if (s[i] == 'a'): return q4(s, i + 1) else: return q3(s, i + 1) def q0(s, i): state_transition.append("q0") if (i == len(s)): return False # state transitions # a takes to q1, b takes to q3 if (s[i] == 'a'): return q1(s, i + 1) else: return q3(s, i + 1) s = "ababab" # all state transitions are printed.# if is acceptable, print YES.# else NO is printedans = q0(s, 0)if (ans): print("YES") # print transition state of given # str for it in state_transition: print(it, end = " ") else: print("NO") # This code is contributed by mohit kumar 29 // C# Program to DFA that accepts// string if it starts and end with// same characterusing System;using System.Collections;class GFG{ // vector to store state transitionstatic ArrayList state_transition = new ArrayList(); // end position is checked using// string length value.// q0 is the starting state.// q2 and q4 are intermediate// states. q1 and q3 are final// states. static bool q1(string s, int i){ state_transition.Add("q1"); if (i == s.Length) { return false; } // state transitions // a takes to q1, b // takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} static bool q2(string s, int i){ state_transition.Add("q2"); if (i == s.Length) { return true; } // state transitions // a takes to q1, b takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} static bool q3(string s, int i){ state_transition.Add("q3"); if (i == s.Length) { return false; } // state transitions // a takes to q4, 1 // takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} static bool q4(string s, int i){ state_transition.Add("q4"); if (i == s.Length) { return true; } // state transitions // a takes to q4, b // takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} static bool q0(string s, int i){ state_transition.Add("q0"); if (i == s.Length) { return false; } // state transitions // a takes to q1, b // takes to q3 if (s[i] == 'a') return q1(s, i + 1); else return q3(s, i + 1);} // Driver codepublic static void Main (string[] args){ string s = "ababab"; // all state transitions are // printed. If string is // acceptable, print YES. // else NO is printed bool ans = q0(s, 0); if (ans == true) { Console.Write("YES\n"); // print transition state // of given string str for(int index = 0; index < state_transition.Count; index++) { //(auto& it : ) { Console.Write( (string)state_transition[index] + ' '); } } else Console.Write("NO");}} // This code is contributed bt rutvik_56 <script> // JavaScript Program to DFA that accepts // string if it starts and end with // same character // vector to store state transition var state_transition = []; // end position is checked using // string length value. // q0 is the starting state. // q2 and q4 are intermediate // states. q1 and q3 are final // states. function q1(s, i) { state_transition.push("q1"); if (i === s.length) { return false; } // state transitions // a takes to q1, b // takes to q2 if (s[i] === "a") return q1(s, i + 1); else return q2(s, i + 1); } function q2(s, i) { state_transition.push("q2"); if (i === s.length) { return true; } // state transitions // a takes to q1, b takes to q2 if (s[i] === "a") return q1(s, i + 1); else return q2(s, i + 1); } function q3(s, i) { state_transition.push("q3"); if (i === s.length) { return false; } // state transitions // a takes to q4, 1 // takes to q3 if (s[i] === "a") return q4(s, i + 1); else return q3(s, i + 1); } function q4(s, i) { state_transition.push("q4"); if (i === s.length) { return true; } // state transitions // a takes to q4, b // takes to q3 if (s[i] === "a") return q4(s, i + 1); else return q3(s, i + 1); } function q0(s, i) { state_transition.push("q0"); if (i === s.length) { return false; } // state transitions // a takes to q1, b // takes to q3 if (s[i] === "a") return q1(s, i + 1); else return q3(s, i + 1); } // Driver code var s = "ababab"; // all state transitions are // printed. If string is // acceptable, print YES. // else NO is printed var ans = q0(s, 0); if (ans === true) { document.write("YES <br>"); // print transition state // of given string str for (var index = 0; index < state_transition.length; index++) { //(auto& it : ) { document.write(state_transition[index] + " "); } } else document.write("NO"); // This code is contributed by rdtank. </script> YES q0 q1 q2 q1 q2 q1 q2 Time Complexity: O(n) where a string of length n requires traversal through n states. mohit kumar 29 ankthon rutvik_56 rdtank Pattern Searching Strings Theory of Computation & Automata Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jun, 2021" }, { "code": null, "e": 290, "s": 28, "text": "Prerequisite: Deterministic Finite Automata Given string, str consists of characters ‘a’ & ‘b’. The task is to check whether string str starts and ends with different characters or not. If it does, print ‘YES’ with state transitions, else print ‘NO’. Examples: " }, { "code": null, "e": 486, "s": 290, "text": "Input: ababab Output: YES Explanation: The string “ababab” is starting with ‘a’ and ends with ‘b’Input : ababa Output : NO Explanation: The string “ababab” is starting with ‘a’ and ends with ‘a’ " }, { "code": null, "e": 1030, "s": 486, "text": "In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {a, b}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state.DFA Machine: For the above problem statement build a DFA machine. It is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q2 and Q4 are the final states: " }, { "code": null, "e": 1755, "s": 1030, "text": "Explanation: Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine. Now, it is defined that the string must not end with an ‘a’ to be accepted. At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string. If it gets a ‘b’, then it can go to the final state, since a string ending in ‘b’ is acceptable in this case, so it moves to state Q2. Here, if it gets an ‘a’, it again enters the non-final state else for consecutive ‘b’s, it keeps circling in the final state. The same is in the case when the first character is detected as ‘b’.Approach: " }, { "code": null, "e": 2119, "s": 1755, "text": "Define the minimum number of states required to make the state diagram. Use functions to various states.List all the valid transitions. Each state must have a transition for every valid symbol.Define the final states by applying the base condition.Define all the state transitions using state function calls.Define a returning condition for the end of the string." }, { "code": null, "e": 2224, "s": 2119, "text": "Define the minimum number of states required to make the state diagram. Use functions to various states." }, { "code": null, "e": 2314, "s": 2224, "text": "List all the valid transitions. Each state must have a transition for every valid symbol." }, { "code": null, "e": 2370, "s": 2314, "text": "Define the final states by applying the base condition." }, { "code": null, "e": 2431, "s": 2370, "text": "Define all the state transitions using state function calls." }, { "code": null, "e": 2487, "s": 2431, "text": "Define a returning condition for the end of the string." }, { "code": null, "e": 2550, "s": 2487, "text": "For the given DFA Machine, the specifications are as follows: " }, { "code": null, "e": 3034, "s": 2550, "text": "Q0, Q1, Q2, Q3, Q4 are the defined states.a and b are valid symbols. Each state has a transition defined for a and b.Q2 and Q4 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected.Suppose at state Q0, if ‘a’ comes, the function call is made to Q1. If ‘b’ comes, the function call is made to Q3.If by following the process, the program reaches the end of the string, the output is made according to the state the program is at." }, { "code": null, "e": 3077, "s": 3034, "text": "Q0, Q1, Q2, Q3, Q4 are the defined states." }, { "code": null, "e": 3153, "s": 3077, "text": "a and b are valid symbols. Each state has a transition defined for a and b." }, { "code": null, "e": 3274, "s": 3153, "text": "Q2 and Q4 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected." }, { "code": null, "e": 3389, "s": 3274, "text": "Suppose at state Q0, if ‘a’ comes, the function call is made to Q1. If ‘b’ comes, the function call is made to Q3." }, { "code": null, "e": 3522, "s": 3389, "text": "If by following the process, the program reaches the end of the string, the output is made according to the state the program is at." }, { "code": null, "e": 3575, "s": 3522, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 3579, "s": 3575, "text": "C++" }, { "code": null, "e": 3584, "s": 3579, "text": "Java" }, { "code": null, "e": 3592, "s": 3584, "text": "Python3" }, { "code": null, "e": 3595, "s": 3592, "text": "C#" }, { "code": null, "e": 3606, "s": 3595, "text": "Javascript" }, { "code": "// CPP Program to DFA that accepts// string if it starts and end with// same character#include <bits/stdc++.h>using namespace std; // various states of DFA machine// are defined using functions.bool q1(string, int);bool q2(string, int);bool q3(string, int);bool q4(string, int); // vector to store state transitionvector<string> state_transition; // end position is checked using string// length value.// q0 is the starting state.// q2 and q4 are intermediate states.// q1 and q3 are final states. bool q1(string s, int i){ state_transition.push_back(\"q1\"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} bool q2(string s, int i){ state_transition.push_back(\"q2\"); if (i == s.length()) { return true; } // state transitions // a takes to q1, b takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} bool q3(string s, int i){ state_transition.push_back(\"q3\"); if (i == s.length()) { return false; } // state transitions // a takes to q4, 1 takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} bool q4(string s, int i){ state_transition.push_back(\"q4\"); if (i == s.length()) { return true; } // state transitions // a takes to q4, b takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} bool q0(string s, int i){ state_transition.push_back(\"q0\"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q3 if (s[i] == 'a') return q1(s, i + 1); else return q3(s, i + 1);} int main(){ string s = \"ababab\"; // all state transitions are printed. // if string is acceptable, print YES. // else NO is printed bool ans = q0(s, 0); if (ans) { cout << \"YES\" << endl; // print transition state of given // string str for (auto& it : state_transition) { cout << it << ' '; } } else cout << \"NO\" << endl; return 0;}", "e": 5817, "s": 3606, "text": null }, { "code": "// Java Program to DFA that accepts// string if it starts and end with// same characterimport java.util.*; class GFG{ // vector to store state transition static Vector state_transition = new Vector(); // end position is checked using string // length value. // q0 is the starting state. // q2 and q4 are intermediate states. // q1 and q3 are final states. static boolean q1(String s, int i) { state_transition.add(\"q1\"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q2 if (s.charAt(i) == 'a') return q1(s, i + 1); else return q2(s, i + 1); } static boolean q2(String s, int i) { state_transition.add(\"q2\"); if (i == s.length()) { return true; } // state transitions // a takes to q1, b takes to q2 if (s.charAt(i) == 'a') return q1(s, i + 1); else return q2(s, i + 1); } static boolean q3(String s, int i) { state_transition.add(\"q3\"); if (i == s.length()) { return false; } // state transitions // a takes to q4, 1 takes to q3 if (s.charAt(i) == 'a') return q4(s, i + 1); else return q3(s, i + 1); } static boolean q4(String s, int i) { state_transition.add(\"q4\"); if (i == s.length()) { return true; } // state transitions // a takes to q4, b takes to q3 if (s.charAt(i) == 'a') return q4(s, i + 1); else return q3(s, i + 1); } static boolean q0(String s, int i) { state_transition.add(\"q0\"); if (i == s.length()) { return false; } // state transitions // a takes to q1, b takes to q3 if (s.charAt(i) == 'a') return q1(s, i + 1); else return q3(s, i + 1); } // Driver code public static void main (String[] args) { String s = \"ababab\"; // all state transitions are printed. // if string is acceptable, print YES. // else NO is printed boolean ans = q0(s, 0); if (ans == true) { System.out.println(\"YES\"); // print transition state of given // string str for(int index = 0; index < state_transition.size(); index++) { //(auto& it : ) { System.out.print((String)state_transition.get(index) + ' '); } } else System.out.println(\"NO\"); }} // This code is contributed by AnkitRai01", "e": 8592, "s": 5817, "text": null }, { "code": "# Python3 Program to DFA that accepts# if it starts and end with# same character # vector to store state transitionstate_transition = [] # end position is checked using string# length value.# q0 is the starting state.# q2 and q4 are intermediate states.# q1 and q3 are final states.def q1(s, i): state_transition.append(\"q1\") if (i == len(s)): return False # state transitions # a takes to q1, b takes to q2 if (s[i] == 'a'): return q1(s, i + 1) else: return q2(s, i + 1) def q2(s, i): state_transition.append(\"q2\") if (i == len(s)): return True # state transitions # a takes to q1, b takes to q2 if (s[i] == 'a'): return q1(s, i + 1) else: return q2(s, i + 1) def q3(s, i): state_transition.append(\"q3\") if (i == len(s)): return False # state transitions # a takes to q4, 1 takes to q3 if (s[i] == 'a'): return q4(s, i + 1) else: return q3(s, i + 1) def q4(s, i): state_transition.append(\"q4\") if (i == len(s)): return True # state transitions # a takes to q4, b takes to q3 if (s[i] == 'a'): return q4(s, i + 1) else: return q3(s, i + 1) def q0(s, i): state_transition.append(\"q0\") if (i == len(s)): return False # state transitions # a takes to q1, b takes to q3 if (s[i] == 'a'): return q1(s, i + 1) else: return q3(s, i + 1) s = \"ababab\" # all state transitions are printed.# if is acceptable, print YES.# else NO is printedans = q0(s, 0)if (ans): print(\"YES\") # print transition state of given # str for it in state_transition: print(it, end = \" \") else: print(\"NO\") # This code is contributed by mohit kumar 29", "e": 10339, "s": 8592, "text": null }, { "code": "// C# Program to DFA that accepts// string if it starts and end with// same characterusing System;using System.Collections;class GFG{ // vector to store state transitionstatic ArrayList state_transition = new ArrayList(); // end position is checked using// string length value.// q0 is the starting state.// q2 and q4 are intermediate// states. q1 and q3 are final// states. static bool q1(string s, int i){ state_transition.Add(\"q1\"); if (i == s.Length) { return false; } // state transitions // a takes to q1, b // takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} static bool q2(string s, int i){ state_transition.Add(\"q2\"); if (i == s.Length) { return true; } // state transitions // a takes to q1, b takes to q2 if (s[i] == 'a') return q1(s, i + 1); else return q2(s, i + 1);} static bool q3(string s, int i){ state_transition.Add(\"q3\"); if (i == s.Length) { return false; } // state transitions // a takes to q4, 1 // takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} static bool q4(string s, int i){ state_transition.Add(\"q4\"); if (i == s.Length) { return true; } // state transitions // a takes to q4, b // takes to q3 if (s[i] == 'a') return q4(s, i + 1); else return q3(s, i + 1);} static bool q0(string s, int i){ state_transition.Add(\"q0\"); if (i == s.Length) { return false; } // state transitions // a takes to q1, b // takes to q3 if (s[i] == 'a') return q1(s, i + 1); else return q3(s, i + 1);} // Driver codepublic static void Main (string[] args){ string s = \"ababab\"; // all state transitions are // printed. If string is // acceptable, print YES. // else NO is printed bool ans = q0(s, 0); if (ans == true) { Console.Write(\"YES\\n\"); // print transition state // of given string str for(int index = 0; index < state_transition.Count; index++) { //(auto& it : ) { Console.Write( (string)state_transition[index] + ' '); } } else Console.Write(\"NO\");}} // This code is contributed bt rutvik_56", "e": 12518, "s": 10339, "text": null }, { "code": "<script> // JavaScript Program to DFA that accepts // string if it starts and end with // same character // vector to store state transition var state_transition = []; // end position is checked using // string length value. // q0 is the starting state. // q2 and q4 are intermediate // states. q1 and q3 are final // states. function q1(s, i) { state_transition.push(\"q1\"); if (i === s.length) { return false; } // state transitions // a takes to q1, b // takes to q2 if (s[i] === \"a\") return q1(s, i + 1); else return q2(s, i + 1); } function q2(s, i) { state_transition.push(\"q2\"); if (i === s.length) { return true; } // state transitions // a takes to q1, b takes to q2 if (s[i] === \"a\") return q1(s, i + 1); else return q2(s, i + 1); } function q3(s, i) { state_transition.push(\"q3\"); if (i === s.length) { return false; } // state transitions // a takes to q4, 1 // takes to q3 if (s[i] === \"a\") return q4(s, i + 1); else return q3(s, i + 1); } function q4(s, i) { state_transition.push(\"q4\"); if (i === s.length) { return true; } // state transitions // a takes to q4, b // takes to q3 if (s[i] === \"a\") return q4(s, i + 1); else return q3(s, i + 1); } function q0(s, i) { state_transition.push(\"q0\"); if (i === s.length) { return false; } // state transitions // a takes to q1, b // takes to q3 if (s[i] === \"a\") return q1(s, i + 1); else return q3(s, i + 1); } // Driver code var s = \"ababab\"; // all state transitions are // printed. If string is // acceptable, print YES. // else NO is printed var ans = q0(s, 0); if (ans === true) { document.write(\"YES <br>\"); // print transition state // of given string str for (var index = 0; index < state_transition.length; index++) { //(auto& it : ) { document.write(state_transition[index] + \" \"); } } else document.write(\"NO\"); // This code is contributed by rdtank. </script>", "e": 14900, "s": 12518, "text": null }, { "code": null, "e": 14925, "s": 14900, "text": "YES\nq0 q1 q2 q1 q2 q1 q2" }, { "code": null, "e": 15014, "s": 14927, "text": "Time Complexity: O(n) where a string of length n requires traversal through n states. " }, { "code": null, "e": 15029, "s": 15014, "text": "mohit kumar 29" }, { "code": null, "e": 15037, "s": 15029, "text": "ankthon" }, { "code": null, "e": 15047, "s": 15037, "text": "rutvik_56" }, { "code": null, "e": 15054, "s": 15047, "text": "rdtank" }, { "code": null, "e": 15072, "s": 15054, "text": "Pattern Searching" }, { "code": null, "e": 15080, "s": 15072, "text": "Strings" }, { "code": null, "e": 15113, "s": 15080, "text": "Theory of Computation & Automata" }, { "code": null, "e": 15121, "s": 15113, "text": "Strings" }, { "code": null, "e": 15139, "s": 15121, "text": "Pattern Searching" } ]
How to remove CSS style of <style> tag using JavaScript/jQuery ?
11 Oct, 2019 Given an HTML document containing inline and internal CSS and the task is to remove the style of <style> tag. The internal or embedded CSS is used within the head section of the HTML document. It is enclosed within <style> tag. Approach: The jQuery remove() and empty() methods are used to remove the CSS style of <style> element. Example 1: This example uses remove() method to remove the CSS style of <style> element. <!DOCTYPE HTML> <html> <head> <title> How to remove CSS style of style tag using JavaScript/jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .parent { background: green; } .child { background: blue; margin: 10px; } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <div class="parent" id = "parent" style = "color: red; font-size: 22px"> Parent <div class="child"> Child </div> </div> <br> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var parent = document.getElementById('parent'); up.innerHTML = "Click on the button to remove " + "the CSS from the < style > tag only."; function GFG_Fun() { $('style').remove(); down.innerHTML = "Style tag has been removed."; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example uses jQuery empty() method to remove the CSS style of <style> element. <!DOCTYPE HTML> <html> <head> <title> How to remove CSS style of style tag using JavaScript/jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .parent { background: green; } .child { background: blue; margin: 10px; } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <div class="parent" id = "parent" style = "color: red; font-size: 22px"> Parent <div class="child"> Child </div> </div> <br> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var parent = document.getElementById('parent'); up.innerHTML = "Click on the button to remove the" + " CSS from the < style > tag only."; function GFG_Fun() { $('style').empty(); down.innerHTML = "Style tag has been removed."; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 256, "s": 28, "text": "Given an HTML document containing inline and internal CSS and the task is to remove the style of <style> tag. The internal or embedded CSS is used within the head section of the HTML document. It is enclosed within <style> tag." }, { "code": null, "e": 359, "s": 256, "text": "Approach: The jQuery remove() and empty() methods are used to remove the CSS style of <style> element." }, { "code": null, "e": 448, "s": 359, "text": "Example 1: This example uses remove() method to remove the CSS style of <style> element." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to remove CSS style of style tag using JavaScript/jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .parent { background: green; } .child { background: blue; margin: 10px; } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <div class=\"parent\" id = \"parent\" style = \"color: red; font-size: 22px\"> Parent <div class=\"child\"> Child </div> </div> <br> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var parent = document.getElementById('parent'); up.innerHTML = \"Click on the button to remove \" + \"the CSS from the < style > tag only.\"; function GFG_Fun() { $('style').remove(); down.innerHTML = \"Style tag has been removed.\"; } </script> </body> </html>", "e": 1896, "s": 448, "text": null }, { "code": null, "e": 1904, "s": 1896, "text": "Output:" }, { "code": null, "e": 1935, "s": 1904, "text": "Before clicking on the button:" }, { "code": null, "e": 1965, "s": 1935, "text": "After clicking on the button:" }, { "code": null, "e": 2060, "s": 1965, "text": "Example 2: This example uses jQuery empty() method to remove the CSS style of <style> element." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to remove CSS style of style tag using JavaScript/jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .parent { background: green; } .child { background: blue; margin: 10px; } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <div class=\"parent\" id = \"parent\" style = \"color: red; font-size: 22px\"> Parent <div class=\"child\"> Child </div> </div> <br> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var parent = document.getElementById('parent'); up.innerHTML = \"Click on the button to remove the\" + \" CSS from the < style > tag only.\"; function GFG_Fun() { $('style').empty(); down.innerHTML = \"Style tag has been removed.\"; } </script> </body> </html>", "e": 3507, "s": 2060, "text": null }, { "code": null, "e": 3515, "s": 3507, "text": "Output:" }, { "code": null, "e": 3546, "s": 3515, "text": "Before clicking on the button:" }, { "code": null, "e": 3576, "s": 3546, "text": "After clicking on the button:" }, { "code": null, "e": 3587, "s": 3576, "text": "JavaScript" }, { "code": null, "e": 3604, "s": 3587, "text": "Web Technologies" }, { "code": null, "e": 3631, "s": 3604, "text": "Web technologies Questions" } ]
Sum of two numbers is 20 and their difference is 4. Find the numbers
17 Aug, 2021 Arithmetic is the branch of mathematics that deals with the properties and manipulation of numbers including basic operations of maths like addition, subtraction, etc. These kinds of problems basically give a few conditions and equations are required to obtain from them such that the number of unknown variables is equal to the number of equations which will make sure that the values can be found of the variables by using some basic arithmetic operations on those equations. Look at the problem statement below for a better understanding The problem given says that 2 unknown numbers are given, whose sum is equal to 20 and the difference is 4. The first requirement is to create two equations based on the information provided, two equations will contain two unknowns and they can be easily solved either by substitution method or by elimination method, lets do a step by step solution of the problem statement, Step-by-step explanation Since the 2 numbers are unknown, assume them to be two natural numbers x and y Given: Sum of x and y=20 Therefore, it can be written as, x+y = 20 ⇢ (1) Given, Difference of x and y = 4 which can be written as x−y = 4 ⇢ (2) Now it can be observed that 2 equations are formed and there are 2 unknown variables, which implies that on performing arithmetic operations on these 2 equations, the value of the unknown variables can be easily found. Hence, on Adding equation (1) & equation (2) we get, 2x = 24 which implies x = 12 Since, the value of x is there, put x =12 in equation (1) and get y = 8 Therefore, we have obtained the 2 numbers ⇢ The first number is 12 and the second number is 8. Question 1: Given two numbers whose difference is 6 and the sum is 10. Find the 2 numbers. Solution: Step-by-step explanation: Since the 2 numbers are unknown, assume them to be two natural numbers x and y Given: Difference of x and y = 6 Therefore, x-y = 6 ⇢ (1) Given: Sum of x and y = 10 which can be written as x+y = 10 ⇢ (2) Now it can be observed that 2 equations are formed and 2 unknown variables are obtained, which implies that on performing arithmetic operations on these 2 equations the value of the unknown variables can be obtained. Hence, on Adding equation (1) & equation (2), 2x = 16 which implies x = 8 Since value of x is known, put x = 8 in equation (1) and get y = 2 Therefore, the 2 numbers ⇢ The first number is 8 and the second number is 2. Question 2: Given two numbers whose difference is 50 and the sum is 100. Find the 2 numbers. Solution: Step-by-step explanation: Since the 2 numbers are unknown, assume them to be two natural numbers x and y Given: Difference of x and y=50 Therefore, x-y = 50 ⇢ (1) Given: Sum of x and y=100 which can be written as x+y = 100 ⇢ (2) Now it can be observed that 2 equations are formed and 2 unknown variables are obtained, which implies that on performing arithmetic operations on these 2 equations the value of the unknown variables can be obtained. Hence, on Adding equation (1) & equation (2), 2x = 150 which implies x = 75 Since value of x is known put x=75 in equation (1) and get y=25 Therefore, the 2 numbers ⇢ The first number is 75 and the second number is 25. Question 3: Given two integer numbers whose difference is 100 and the sum is 30. Find the 2 numbers. Solution: Step-by-step explanation: Since the 2 numbers are unknown, assume them to be two natural numbers x and y Given: Difference of x and y=100 Therefore, x-y = 100 ⇢ (1) Given: Sum of x and y = 30 which can be written as x+y = 30 ⇢ (2) Now it can be observed that 2 equations are formed and 2 unknown variables are obtained, which implies that on performing arithmetic operations on these 2 equations the value of the unknown variables can be obtained. Hence, on Adding equation (1) & equation (2), 2x = 130 which implies x = 65 Since value of x is known put x = 65 in equation (1) and get y = -35 Therefore, the 2 numbers ⇢ The first number is 65 and the second number is -35. Picked Maths MAQ School Learning School Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Aug, 2021" }, { "code": null, "e": 506, "s": 28, "text": "Arithmetic is the branch of mathematics that deals with the properties and manipulation of numbers including basic operations of maths like addition, subtraction, etc. These kinds of problems basically give a few conditions and equations are required to obtain from them such that the number of unknown variables is equal to the number of equations which will make sure that the values can be found of the variables by using some basic arithmetic operations on those equations." }, { "code": null, "e": 569, "s": 506, "text": "Look at the problem statement below for a better understanding" }, { "code": null, "e": 944, "s": 569, "text": "The problem given says that 2 unknown numbers are given, whose sum is equal to 20 and the difference is 4. The first requirement is to create two equations based on the information provided, two equations will contain two unknowns and they can be easily solved either by substitution method or by elimination method, lets do a step by step solution of the problem statement," }, { "code": null, "e": 969, "s": 944, "text": "Step-by-step explanation" }, { "code": null, "e": 1049, "s": 969, "text": "Since the 2 numbers are unknown, assume them to be two natural numbers x and y" }, { "code": null, "e": 1074, "s": 1049, "text": "Given: Sum of x and y=20" }, { "code": null, "e": 1107, "s": 1074, "text": "Therefore, it can be written as," }, { "code": null, "e": 1124, "s": 1107, "text": "x+y = 20 ⇢ (1)" }, { "code": null, "e": 1157, "s": 1124, "text": "Given, Difference of x and y = 4" }, { "code": null, "e": 1181, "s": 1157, "text": "which can be written as" }, { "code": null, "e": 1197, "s": 1181, "text": "x−y = 4 ⇢ (2)" }, { "code": null, "e": 1416, "s": 1197, "text": "Now it can be observed that 2 equations are formed and there are 2 unknown variables, which implies that on performing arithmetic operations on these 2 equations, the value of the unknown variables can be easily found." }, { "code": null, "e": 1469, "s": 1416, "text": "Hence, on Adding equation (1) & equation (2) we get," }, { "code": null, "e": 1477, "s": 1469, "text": "2x = 24" }, { "code": null, "e": 1498, "s": 1477, "text": "which implies x = 12" }, { "code": null, "e": 1570, "s": 1498, "text": "Since, the value of x is there, put x =12 in equation (1) and get y = 8" }, { "code": null, "e": 1666, "s": 1570, "text": "Therefore, we have obtained the 2 numbers ⇢ The first number is 12 and the second number is 8." }, { "code": null, "e": 1757, "s": 1666, "text": "Question 1: Given two numbers whose difference is 6 and the sum is 10. Find the 2 numbers." }, { "code": null, "e": 1767, "s": 1757, "text": "Solution:" }, { "code": null, "e": 1793, "s": 1767, "text": "Step-by-step explanation:" }, { "code": null, "e": 1873, "s": 1793, "text": "Since the 2 numbers are unknown, assume them to be two natural numbers x and y" }, { "code": null, "e": 1906, "s": 1873, "text": "Given: Difference of x and y = 6" }, { "code": null, "e": 1917, "s": 1906, "text": "Therefore," }, { "code": null, "e": 1933, "s": 1917, "text": "x-y = 6 ⇢ (1)" }, { "code": null, "e": 1960, "s": 1933, "text": "Given: Sum of x and y = 10" }, { "code": null, "e": 1984, "s": 1960, "text": "which can be written as" }, { "code": null, "e": 2001, "s": 1984, "text": "x+y = 10 ⇢ (2)" }, { "code": null, "e": 2218, "s": 2001, "text": "Now it can be observed that 2 equations are formed and 2 unknown variables are obtained, which implies that on performing arithmetic operations on these 2 equations the value of the unknown variables can be obtained." }, { "code": null, "e": 2264, "s": 2218, "text": "Hence, on Adding equation (1) & equation (2)," }, { "code": null, "e": 2272, "s": 2264, "text": "2x = 16" }, { "code": null, "e": 2292, "s": 2272, "text": "which implies x = 8" }, { "code": null, "e": 2359, "s": 2292, "text": "Since value of x is known, put x = 8 in equation (1) and get y = 2" }, { "code": null, "e": 2437, "s": 2359, "text": "Therefore, the 2 numbers ⇢ The first number is 8 and the second number is 2." }, { "code": null, "e": 2530, "s": 2437, "text": "Question 2: Given two numbers whose difference is 50 and the sum is 100. Find the 2 numbers." }, { "code": null, "e": 2540, "s": 2530, "text": "Solution:" }, { "code": null, "e": 2566, "s": 2540, "text": "Step-by-step explanation:" }, { "code": null, "e": 2646, "s": 2566, "text": "Since the 2 numbers are unknown, assume them to be two natural numbers x and y" }, { "code": null, "e": 2678, "s": 2646, "text": "Given: Difference of x and y=50" }, { "code": null, "e": 2689, "s": 2678, "text": "Therefore," }, { "code": null, "e": 2706, "s": 2689, "text": "x-y = 50 ⇢ (1)" }, { "code": null, "e": 2732, "s": 2706, "text": "Given: Sum of x and y=100" }, { "code": null, "e": 2756, "s": 2732, "text": "which can be written as" }, { "code": null, "e": 2774, "s": 2756, "text": "x+y = 100 ⇢ (2)" }, { "code": null, "e": 2991, "s": 2774, "text": "Now it can be observed that 2 equations are formed and 2 unknown variables are obtained, which implies that on performing arithmetic operations on these 2 equations the value of the unknown variables can be obtained." }, { "code": null, "e": 3037, "s": 2991, "text": "Hence, on Adding equation (1) & equation (2)," }, { "code": null, "e": 3046, "s": 3037, "text": "2x = 150" }, { "code": null, "e": 3067, "s": 3046, "text": "which implies x = 75" }, { "code": null, "e": 3131, "s": 3067, "text": "Since value of x is known put x=75 in equation (1) and get y=25" }, { "code": null, "e": 3210, "s": 3131, "text": "Therefore, the 2 numbers ⇢ The first number is 75 and the second number is 25." }, { "code": null, "e": 3311, "s": 3210, "text": "Question 3: Given two integer numbers whose difference is 100 and the sum is 30. Find the 2 numbers." }, { "code": null, "e": 3321, "s": 3311, "text": "Solution:" }, { "code": null, "e": 3347, "s": 3321, "text": "Step-by-step explanation:" }, { "code": null, "e": 3427, "s": 3347, "text": "Since the 2 numbers are unknown, assume them to be two natural numbers x and y" }, { "code": null, "e": 3460, "s": 3427, "text": "Given: Difference of x and y=100" }, { "code": null, "e": 3472, "s": 3460, "text": "Therefore, " }, { "code": null, "e": 3490, "s": 3472, "text": "x-y = 100 ⇢ (1)" }, { "code": null, "e": 3517, "s": 3490, "text": "Given: Sum of x and y = 30" }, { "code": null, "e": 3541, "s": 3517, "text": "which can be written as" }, { "code": null, "e": 3558, "s": 3541, "text": "x+y = 30 ⇢ (2)" }, { "code": null, "e": 3775, "s": 3558, "text": "Now it can be observed that 2 equations are formed and 2 unknown variables are obtained, which implies that on performing arithmetic operations on these 2 equations the value of the unknown variables can be obtained." }, { "code": null, "e": 3821, "s": 3775, "text": "Hence, on Adding equation (1) & equation (2)," }, { "code": null, "e": 3830, "s": 3821, "text": "2x = 130" }, { "code": null, "e": 3851, "s": 3830, "text": "which implies x = 65" }, { "code": null, "e": 3920, "s": 3851, "text": "Since value of x is known put x = 65 in equation (1) and get y = -35" }, { "code": null, "e": 4000, "s": 3920, "text": "Therefore, the 2 numbers ⇢ The first number is 65 and the second number is -35." }, { "code": null, "e": 4007, "s": 4000, "text": "Picked" }, { "code": null, "e": 4017, "s": 4007, "text": "Maths MAQ" }, { "code": null, "e": 4033, "s": 4017, "text": "School Learning" }, { "code": null, "e": 4052, "s": 4033, "text": "School Mathematics" } ]
Python | Index specific cyclic iteration in list
21 Feb, 2019 The problem of cyclic iteration is quite common, but sometimes, we come through the issue in which we require to process the list in a way in which it is cyclic iterated that too starting from a specific index. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using % operator + loopThe % operator can be used to cycle the out of bound index value to begin from the beginning of list to form a cycle and hence help in the cyclic iteration. # Python3 code to demonstrate # cyclic iteration in list # using % operator and loop # initializing tuple list test_list = [5, 4, 2, 3, 7] # printing original listprint ("The original list is : " + str(test_list)) # starting index K = 3 # using % operator and loop# cyclic iteration in list res = []for i in range(len(test_list)): res.append(test_list[K % len(test_list)]) K = K + 1 # printing result print ("The cycled list is : " + str(res)) The original list is : [5, 4, 2, 3, 7] The cycled list is : [3, 7, 5, 4, 2] Method #2 : Using itertools.cycle() + itertools.islice() + itertools.dropwhile()The itertools library has built in functions that can help achieve to the solution of this particular problem. The cycle function performs the cycling part, dropwhile function brings the cycle to begin of list and islice function specifies the cycle size. # Python3 code to demonstrate # cyclic iteration in list using itertoolsfrom itertools import cycle, islice, dropwhile # initializing tuple list test_list = [5, 4, 2, 3, 7] # printing original listprint ("The original list is : " + str(test_list)) # starting index K = 3 # using itertools methods for# cyclic iteration in list cycling = cycle(test_list) skipping = dropwhile(lambda x: x != K, cycling) slicing = islice(skipping, None, len(test_list))slicing = list(slicing) # printing result print ("The cycled list is : " + str(slicing)) The original list is : [5, 4, 2, 3, 7] The cycled list is : [3, 7, 5, 4, 2] Marketing Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2019" }, { "code": null, "e": 303, "s": 28, "text": "The problem of cyclic iteration is quite common, but sometimes, we come through the issue in which we require to process the list in a way in which it is cyclic iterated that too starting from a specific index. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 495, "s": 303, "text": "Method #1 : Using % operator + loopThe % operator can be used to cycle the out of bound index value to begin from the beginning of list to form a cycle and hence help in the cyclic iteration." }, { "code": "# Python3 code to demonstrate # cyclic iteration in list # using % operator and loop # initializing tuple list test_list = [5, 4, 2, 3, 7] # printing original listprint (\"The original list is : \" + str(test_list)) # starting index K = 3 # using % operator and loop# cyclic iteration in list res = []for i in range(len(test_list)): res.append(test_list[K % len(test_list)]) K = K + 1 # printing result print (\"The cycled list is : \" + str(res))", "e": 951, "s": 495, "text": null }, { "code": null, "e": 1028, "s": 951, "text": "The original list is : [5, 4, 2, 3, 7]\nThe cycled list is : [3, 7, 5, 4, 2]\n" }, { "code": null, "e": 1365, "s": 1028, "text": " Method #2 : Using itertools.cycle() + itertools.islice() + itertools.dropwhile()The itertools library has built in functions that can help achieve to the solution of this particular problem. The cycle function performs the cycling part, dropwhile function brings the cycle to begin of list and islice function specifies the cycle size." }, { "code": "# Python3 code to demonstrate # cyclic iteration in list using itertoolsfrom itertools import cycle, islice, dropwhile # initializing tuple list test_list = [5, 4, 2, 3, 7] # printing original listprint (\"The original list is : \" + str(test_list)) # starting index K = 3 # using itertools methods for# cyclic iteration in list cycling = cycle(test_list) skipping = dropwhile(lambda x: x != K, cycling) slicing = islice(skipping, None, len(test_list))slicing = list(slicing) # printing result print (\"The cycled list is : \" + str(slicing))", "e": 1911, "s": 1365, "text": null }, { "code": null, "e": 1988, "s": 1911, "text": "The original list is : [5, 4, 2, 3, 7]\nThe cycled list is : [3, 7, 5, 4, 2]\n" }, { "code": null, "e": 1998, "s": 1988, "text": "Marketing" }, { "code": null, "e": 2019, "s": 1998, "text": "Python list-programs" }, { "code": null, "e": 2031, "s": 2019, "text": "python-list" }, { "code": null, "e": 2038, "s": 2031, "text": "Python" }, { "code": null, "e": 2054, "s": 2038, "text": "Python Programs" }, { "code": null, "e": 2066, "s": 2054, "text": "python-list" } ]
Sales Forecast Prediction – Python
10 Dec, 2021 Forecast prediction is predicting a future value using past values and many other factors. In this tutorial, we will create a sales forecasting model using the Keras functional API. It is determining present-day or future sales using data like past sales, seasonality, festivities, economic conditions, etc. So, this model will predict sales on a certain day after being provided with a certain set of inputs. In this model 8 parameters were used as input: past seven day salesday of the weekdate – the date was transformed into 3 different inputsseasonFestival or notsales on the same day in the previous year past seven day sales day of the week date – the date was transformed into 3 different inputs season Festival or not sales on the same day in the previous year First, all inputs are preprocessed to be understandable by the machine. This is a linear regression model based on supervised learning, so the output will be provided along with the input. Then inputs are then fed to the model along with desired output. The model will plot(learn) a relation(function) between the input and output. This function or relation is then used to predict the output for a specific set of inputs. In this case, input parameters like date and previous sales are labeled as input, and the amount of sales is marked as output. The model will predict a number between 0 and 1 as a sigmoid function is used in the last layer. This output can be multiplied by a specific number(in this case, maximum sales), this will be our corresponding sales amount for a certain day. This output is then provided as input to calculate sales data for the next day. This cycle of steps will be continued until a certain date arrives. numpypandaskerastensorflowcsvmatplotlib.pyplot numpy pandas keras tensorflow csv matplotlib.pyplot Python3 import pandas as pd # to extract data from dataset(.csv file)import csv #used to read and write to csv filesimport numpy as np #used to convert input into numpy arrays to be fed to the modelimport matplotlib.pyplot as plt #to plot/visualize sales data and sales forecastingimport tensorflow as tf # acts as the framework upon which this model is builtfrom tensorflow import keras #defines layers and functions in the model #here the csv file has been copied into three lists to allow better availabilitylist_row,date,traffic = get_data('/home/abh/Documents/Python/Untitled Folder/Sales_dataset') The use of external libraries has been kept to a minimum to provide a simpler interface, you can replace the functions used in this tutorial with those already existing in established libraries. Sales data from Jan 2015 to Dec 2019 As you can see, the sales data seems to be following a similar kind of pattern for each year and the peak sales value seems to be increasing with time over the 5-year time frame. In this 5-year time frame, the first 4 years will be used to train the model and the last year will be used as a test set. Now, a few helper functions were used for processing the dataset and creating inputs of the required shape and size. They are as follows: get_data – used to load the data set using a path to its location.date_to_day – provides a day to each day. For example — 2/2/16 is Saturday and 9/5/15 is Monday.date_to_enc – Encodes data into one-hot vectors, this provides a better learning opportunity for the model. get_data – used to load the data set using a path to its location. date_to_day – provides a day to each day. For example — 2/2/16 is Saturday and 9/5/15 is Monday. date_to_enc – Encodes data into one-hot vectors, this provides a better learning opportunity for the model. All the properties of these functions and a few other functions cannot be explained here as it would take too much time. Please visit this link if you want to look at the entire code. Initially, the data set had only two columns: date and traffic(sales). After the addition of different columns and processing/normalization of values, the data contained all these values. DateTrafficHoliday or notDay Date Traffic Holiday or not Day All these parameters have to be converted into a form that the machine can understand, which will be done using this function below. Instead of keeping date, month, and year as a single entity, it was broken into three different inputs. The reason is that the year parameter in these inputs will be the same most of the time, this will cause the model to become complacent i.e it will begin to overfit to the current dataset. To increase the variability between different various inputs dates, days and months were labeled separately. The following function conversion() will create six lists and append appropriate input to them. This is how years 2015 to 2019 will look as an encoding: is {2015: array([1., 0., 0., 0., 0.], dtype=float32), 2016: array([0., 1., 0., 0., 0.], dtype=float32), 2017: array([0., 0., 1., 0., 0.], dtype=float32), 2018: array([0., 0., 0., 1., 0.], dtype=float32), 2019: array([0., 0., 0., 0., 1.], dtype=float32) Each of them is a NumPy array of length 5 with 1s and 0s denoting its value Python3 def conversion(week,days,months,years,list_row): #lists have been defined to hold different inputs inp_day = [] inp_mon = [] inp_year = [] inp_week=[] inp_hol=[] out = [] #converts the days of a week(monday,sunday,etc.) into one hot vectors and stores them as a dictionary week1 = number_to_one_hot(week) #list_row contains primary inputs for row in list_row: #Filter out date from list_row d = row[0] #the date was split into three values date, month and year. d_split=d.split('/') if d_split[2]==str(year_all[0]): #prevents use of the first year data to ensure each input contains previous year data as well. continue #encode the three parameters of date into one hot vectors using date_to_enc function. d1,m1,y1 = date_to_enc(d,days,months,years) #days, months and years and dictionaries containing the one hot encoding of each date,month and year. inp_day.append(d1) #append date into date input inp_mon.append(m1) #append month into month input inp_year.append(y1) #append year into year input week2 = week1[row[3]] #the day column from list_is converted into its one-hot representation and saved into week2 variable inp_week.append(week2)# it is now appended into week input. inp_hol.append([row[2]])#specifies whether the day is a holiday or not t1 = row[1] #row[1] contains the traffic/sales value for a specific date out.append(t1) #append t1(traffic value) into a list out return inp_day,inp_mon,inp_year,inp_week,inp_hol,out #all the processed inputs are returned inp_day,inp_mon,inp_year,inp_week,inp_hol,out = conversion(week,days,months,years,list_train)#all of the inputs must be converted into numpy arrays to be fed into the modelinp_day = np.array(inp_day)inp_mon = np.array(inp_mon)inp_year = np.array(inp_year)inp_week = np.array(inp_week)inp_hol = np.array(inp_hol) We will now process some other inputs that were remaining, the reason behind using all these parameters is to increase the efficiency of the model, you can experiment with removing or adding some inputs. Sales data of the past seven days were passed as an input to create a trend in sales data, this will the predicted value will not be completely random similarly, sales data of the same day in the previous year was also provided. The following function(other_inputs) processes three inputs: sales data of past seven days sales data on the same date in the previous year seasonality – seasonality was added to mark trends like summer sales, etc. Python3 def other_inputs(season,list_row): #lists to hold all the inputs inp7=[] inp_prev=[] inp_sess=[] count=0 #count variable will be used to keep track of the index of current row in order to access the traffic values of past seven days. for row in list_row: ind = count count=count+1 d = row[0] #date was copied to variable d d_split=d.split('/') if d_split[2]==str(year_all[0]): #preventing use of the first year in the data continue sess = cur_season(season,d) #assigning a season to to the current date inp_sess.append(sess) #appending sess variable to an input list t7=[] #temporary list to hold seven sales value t_prev=[] #temporary list to hold the previous year sales value t_prev.append(list_row[ind-365][1]) #accessing the sales value from one year back and appending them for j in range(0,7): t7.append(list_row[ind-j-1][1]) #appending the last seven days sales value inp7.append(t7) inp_prev.append(t_prev) return inp7,inp_prev,inp_sess inp7,inp_prev,inp_sess = other_inputs(season,list_train)inp7 = np.array(inp7)inp7= inp7.reshape(inp7.shape[0],inp7.shape[1],1)inp_prev = np.array(inp_prev)inp_sess = np.array(inp_sess) The reason behind so many inputs is that if all of these were combined into a single array, it would have different rows or columns of different lengths. Such an array cannot be fed as an input. Linearly arranging all the values in a single array lead to the model having a high loss. A linear arrangement will cause the model to generalize, as the difference between successive inputs would not be too different, which will lead to limited learning, decreasing the accuracy of the model. Eight separate inputs are processed and concatenated into a single layer and passed to the model. The finalized inputs are as follows: DateMonthYearDayPrevious seven days salessales in the previous yearSeasonHoliday or not Date Month Year Day Previous seven days sales sales in the previous year Season Holiday or not Here in most layers, I have used 5 units as the output shape, you can further experiment with it to increase the efficiency of the model. Python from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Input, Dense,LSTM,Flattenfrom tensorflow.keras.layers import concatenate#an Input variable is made from every input arrayinput_day = Input(shape=(inp_day.shape[1],),name = 'input_day')input_mon = Input(shape=(inp_mon.shape[1],),name = 'input_mon')input_year = Input(shape=(inp_year.shape[1],),name = 'input_year')input_week = Input(shape=(inp_week.shape[1],),name = 'input_week')input_hol = Input(shape=(inp_hol.shape[1],),name = 'input_hol')input_day7 = Input(shape=(inp7.shape[1],inp7.shape[2]),name = 'input_day7')input_day_prev = Input(shape=(inp_prev.shape[1],),name = 'input_day_prev')input_day_sess = Input(shape=(inp_sess.shape[1],),name = 'input_day_sess')# The model is quite straight-forward, all inputs were inserted into a dense layer with 5 units and 'relu' as activation functionx1 = Dense(5, activation='relu')(input_day)x2 = Dense(5, activation='relu')(input_mon)x3 = Dense(5, activation='relu')(input_year)x4 = Dense(5, activation='relu')(input_week)x5 = Dense(5, activation='relu')(input_hol)x_6 = Dense(5, activation='relu')(input_day7)x__6 = LSTM(5,return_sequences=True)(x_6) # LSTM is used to remember the importance of each day from the seven days datax6 = Flatten()(x__10) # done to make the shape compatible to other inputs as LSTM outputs a three dimensional tensorx7 = Dense(5, activation='relu')(input_day_prev)x8 = Dense(5, activation='relu')(input_day_sess)c = concatenate([x1,x2,x3,x4,x5,x6,x7,x8]) # all inputs are concatenated into onelayer1 = Dense(64,activation='relu')(c)outputs = Dense(1, activation='sigmoid')(layer1) # a single output is produced with value ranging between 0-1.# now the model is initialized and created as wellmodel = Model(inputs=[input_day,input_mon,input_year,input_week,input_hol,input_day7,input_day_prev,input_day_sess], outputs=outputs)model.summary() # used to draw a summary(diagram) of the model Model Summary: Compiling the model using RMSprop: RMSprop is great at dealing with random distributions, hence its use here. Python3 from tensorflow.keras.optimizers import RMSprop model.compile(loss=['mean_squared_error'], optimizer = 'adam', metrics = ['acc'] #while accuracy is used as a metrics here it will remain zero as this is no classification model ) # linear regression models are best gauged by their loss value Fitting the model on the dataset: The model will now be fed with the input and output data, this is the final step and now our model will be able to predict sales data. Python3 history = model.fit( x = [inp_day,inp_mon,inp_year,inp_week,inp_hol,inp7,inp_prev,inp_sess], y = out, batch_size=16, steps_per_epoch=50, epochs = 15, verbose=1, shuffle =False )#all the inputs were fed into the model and the training was completed Output: Now, to test the model, input() takes input and transform it into the appropriate form: Python3 def input(date): d1,d2,d3 = date_to_enc(date,days,months,years) #separate date into three parameters print('date=',date) d1 = np.array([d1]) d2 = np.array([d2]) d3 = np.array([d3]) week1 = number_to_one_hot(week) #defining one hot vector to encode days of a week week2 = week1[day[date]] week2=np.array([week2]) //appeding a column for holiday(0-not holiday, 1- holiday) if date in holiday: h=1 #print('holiday') else: h=0 #print("no holiday") h = np.array([h]) sess = cur_season(season,date) #getting seasonality data from cur_season function sess = np.array([sess]) return d1,d2,d3,week2,h,sess Predicting sales data is not what we are here for right, so let’s get on with the forecasting job. Sales Forecasting Defining forecast_testing function to forecast the sales data from one year back from provided date: This function works as follows: A date is required as input to forecast the sales data from one year back till the mentioned date Then, we access the previous year’s sales data on the same day and sales data of 7 days before it. Then, using these as input a new value is predicted, then in the seven days value the first day is removed and the predicted output is added as input for the next prediction For eg: we require forecasting of one year till 31/12/2019 First, the date of 31/12/2018 (one year back) is recorded, and also seven-day sales from (25/12/2018 – 31/12/2018) Then the sales data of one year back i.e 31/12/2017 is collected Using these as inputs with other ones, the first sales data(i.e 1/1/2019) is predicted Then 24/12/2018 sales data is removed and 1/1/2019 predicted sales are added. This cycle is repeated until the sales data for 31/12/2019 is predicted. So, previous outputs are used as inputs. Python3 def forecast_testing(date): maxj = max(traffic) # determines the maximum sales value in order to normalize or return the data to its original form out=[] count=-1 ind=0 for i in list_row: count =count+1 if i[0]==date: #identify the index of the data in list ind = count t7=[] t_prev=[] t_prev.append(list_row[ind-365][1]) #previous year data # for the first input, sales data of last seven days will be taken from training data for j in range(0,7): t7.append(list_row[ind-j-365][1]) result=[] # list to store the output and values count=0 for i in list_date[ind-364:ind+2]: d1,d2,d3,week2,h,sess = input(i) # using input function to process input values into numpy arrays t_7 = np.array([t7]) # converting the data into a numpy array t_7 = t_7.reshape(1,7,1) # extracting and processing the previous year sales value t_prev=[] t_prev.append(list_row[ind-730+count][1]) t_prev = np.array([t_prev]) #predicting value for output y_out = model.predict([d1,d2,d3,week2,h,t_7,t_prev,sess]) #output and multiply the max value to the output value to increase its range from 0-1 print(y_out[0][0]*maxj) t7.pop(0) #delete the first value from the last seven days value t7.append(y_out[0][0]) # append the output as input for the seven days data result.append(y_out[0][0]*maxj) # append the output value to the result list count=count+1 return result Run the forecast test function and a list containing all the sales data for that one year are returned Result = forecast_testing(’31/12/2019′, date) Graphs for both the forecast and actual values to test the performance of the model Python3 plt.plot(result,color='red',label='predicted')plt.plot(test_sales,color='purple',label="actual")plt.xlabel("Date")plt.ylabel("Sales")leg = plt.legend()plt.show() Actual Values from 1/1/2019 to 31/12/2019 Comparison between prediction and actual values As you can see, the predicted and actual values are quite close to each other, this proves the efficiency of our model. If there are any errors or possibilities of improvements in the above article, please feel free to mention them in the comment section. abhinavchaudhary12 arorakashish0911 varshagumber28 ddeevviissaavviittaa Picked Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Dec, 2021" }, { "code": null, "e": 234, "s": 52, "text": "Forecast prediction is predicting a future value using past values and many other factors. In this tutorial, we will create a sales forecasting model using the Keras functional API." }, { "code": null, "e": 360, "s": 234, "text": "It is determining present-day or future sales using data like past sales, seasonality, festivities, economic conditions, etc." }, { "code": null, "e": 462, "s": 360, "text": "So, this model will predict sales on a certain day after being provided with a certain set of inputs." }, { "code": null, "e": 509, "s": 462, "text": "In this model 8 parameters were used as input:" }, { "code": null, "e": 663, "s": 509, "text": "past seven day salesday of the weekdate – the date was transformed into 3 different inputsseasonFestival or notsales on the same day in the previous year" }, { "code": null, "e": 684, "s": 663, "text": "past seven day sales" }, { "code": null, "e": 700, "s": 684, "text": "day of the week" }, { "code": null, "e": 756, "s": 700, "text": "date – the date was transformed into 3 different inputs" }, { "code": null, "e": 763, "s": 756, "text": "season" }, { "code": null, "e": 779, "s": 763, "text": "Festival or not" }, { "code": null, "e": 822, "s": 779, "text": "sales on the same day in the previous year" }, { "code": null, "e": 1761, "s": 822, "text": "First, all inputs are preprocessed to be understandable by the machine. This is a linear regression model based on supervised learning, so the output will be provided along with the input. Then inputs are then fed to the model along with desired output. The model will plot(learn) a relation(function) between the input and output. This function or relation is then used to predict the output for a specific set of inputs. In this case, input parameters like date and previous sales are labeled as input, and the amount of sales is marked as output. The model will predict a number between 0 and 1 as a sigmoid function is used in the last layer. This output can be multiplied by a specific number(in this case, maximum sales), this will be our corresponding sales amount for a certain day. This output is then provided as input to calculate sales data for the next day. This cycle of steps will be continued until a certain date arrives." }, { "code": null, "e": 1808, "s": 1761, "text": "numpypandaskerastensorflowcsvmatplotlib.pyplot" }, { "code": null, "e": 1814, "s": 1808, "text": "numpy" }, { "code": null, "e": 1821, "s": 1814, "text": "pandas" }, { "code": null, "e": 1827, "s": 1821, "text": "keras" }, { "code": null, "e": 1838, "s": 1827, "text": "tensorflow" }, { "code": null, "e": 1842, "s": 1838, "text": "csv" }, { "code": null, "e": 1860, "s": 1842, "text": "matplotlib.pyplot" }, { "code": null, "e": 1868, "s": 1860, "text": "Python3" }, { "code": "import pandas as pd # to extract data from dataset(.csv file)import csv #used to read and write to csv filesimport numpy as np #used to convert input into numpy arrays to be fed to the modelimport matplotlib.pyplot as plt #to plot/visualize sales data and sales forecastingimport tensorflow as tf # acts as the framework upon which this model is builtfrom tensorflow import keras #defines layers and functions in the model #here the csv file has been copied into three lists to allow better availabilitylist_row,date,traffic = get_data('/home/abh/Documents/Python/Untitled Folder/Sales_dataset')", "e": 2569, "s": 1868, "text": null }, { "code": null, "e": 2764, "s": 2569, "text": "The use of external libraries has been kept to a minimum to provide a simpler interface, you can replace the functions used in this tutorial with those already existing in established libraries." }, { "code": null, "e": 2801, "s": 2764, "text": "Sales data from Jan 2015 to Dec 2019" }, { "code": null, "e": 2980, "s": 2801, "text": "As you can see, the sales data seems to be following a similar kind of pattern for each year and the peak sales value seems to be increasing with time over the 5-year time frame." }, { "code": null, "e": 3104, "s": 2980, "text": "In this 5-year time frame, the first 4 years will be used to train the model and the last year will be used as a test set. " }, { "code": null, "e": 3242, "s": 3104, "text": "Now, a few helper functions were used for processing the dataset and creating inputs of the required shape and size. They are as follows:" }, { "code": null, "e": 3512, "s": 3242, "text": "get_data – used to load the data set using a path to its location.date_to_day – provides a day to each day. For example — 2/2/16 is Saturday and 9/5/15 is Monday.date_to_enc – Encodes data into one-hot vectors, this provides a better learning opportunity for the model." }, { "code": null, "e": 3579, "s": 3512, "text": "get_data – used to load the data set using a path to its location." }, { "code": null, "e": 3676, "s": 3579, "text": "date_to_day – provides a day to each day. For example — 2/2/16 is Saturday and 9/5/15 is Monday." }, { "code": null, "e": 3784, "s": 3676, "text": "date_to_enc – Encodes data into one-hot vectors, this provides a better learning opportunity for the model." }, { "code": null, "e": 3968, "s": 3784, "text": "All the properties of these functions and a few other functions cannot be explained here as it would take too much time. Please visit this link if you want to look at the entire code." }, { "code": null, "e": 4039, "s": 3968, "text": "Initially, the data set had only two columns: date and traffic(sales)." }, { "code": null, "e": 4156, "s": 4039, "text": "After the addition of different columns and processing/normalization of values, the data contained all these values." }, { "code": null, "e": 4185, "s": 4156, "text": "DateTrafficHoliday or notDay" }, { "code": null, "e": 4190, "s": 4185, "text": "Date" }, { "code": null, "e": 4198, "s": 4190, "text": "Traffic" }, { "code": null, "e": 4213, "s": 4198, "text": "Holiday or not" }, { "code": null, "e": 4217, "s": 4213, "text": "Day" }, { "code": null, "e": 4350, "s": 4217, "text": "All these parameters have to be converted into a form that the machine can understand, which will be done using this function below." }, { "code": null, "e": 4909, "s": 4350, "text": "Instead of keeping date, month, and year as a single entity, it was broken into three different inputs. The reason is that the year parameter in these inputs will be the same most of the time, this will cause the model to become complacent i.e it will begin to overfit to the current dataset. To increase the variability between different various inputs dates, days and months were labeled separately. The following function conversion() will create six lists and append appropriate input to them. This is how years 2015 to 2019 will look as an encoding: is" }, { "code": null, "e": 5159, "s": 4909, "text": "{2015: array([1., 0., 0., 0., 0.], dtype=float32), 2016: array([0., 1., 0., 0., 0.], dtype=float32), 2017: array([0., 0., 1., 0., 0.], dtype=float32), 2018: array([0., 0., 0., 1., 0.], dtype=float32), 2019: array([0., 0., 0., 0., 1.], dtype=float32)" }, { "code": null, "e": 5235, "s": 5159, "text": "Each of them is a NumPy array of length 5 with 1s and 0s denoting its value" }, { "code": null, "e": 5243, "s": 5235, "text": "Python3" }, { "code": "def conversion(week,days,months,years,list_row): #lists have been defined to hold different inputs inp_day = [] inp_mon = [] inp_year = [] inp_week=[] inp_hol=[] out = [] #converts the days of a week(monday,sunday,etc.) into one hot vectors and stores them as a dictionary week1 = number_to_one_hot(week) #list_row contains primary inputs for row in list_row: #Filter out date from list_row d = row[0] #the date was split into three values date, month and year. d_split=d.split('/') if d_split[2]==str(year_all[0]): #prevents use of the first year data to ensure each input contains previous year data as well. continue #encode the three parameters of date into one hot vectors using date_to_enc function. d1,m1,y1 = date_to_enc(d,days,months,years) #days, months and years and dictionaries containing the one hot encoding of each date,month and year. inp_day.append(d1) #append date into date input inp_mon.append(m1) #append month into month input inp_year.append(y1) #append year into year input week2 = week1[row[3]] #the day column from list_is converted into its one-hot representation and saved into week2 variable inp_week.append(week2)# it is now appended into week input. inp_hol.append([row[2]])#specifies whether the day is a holiday or not t1 = row[1] #row[1] contains the traffic/sales value for a specific date out.append(t1) #append t1(traffic value) into a list out return inp_day,inp_mon,inp_year,inp_week,inp_hol,out #all the processed inputs are returned inp_day,inp_mon,inp_year,inp_week,inp_hol,out = conversion(week,days,months,years,list_train)#all of the inputs must be converted into numpy arrays to be fed into the modelinp_day = np.array(inp_day)inp_mon = np.array(inp_mon)inp_year = np.array(inp_year)inp_week = np.array(inp_week)inp_hol = np.array(inp_hol)", "e": 7165, "s": 5243, "text": null }, { "code": null, "e": 7370, "s": 7165, "text": " We will now process some other inputs that were remaining, the reason behind using all these parameters is to increase the efficiency of the model, you can experiment with removing or adding some inputs." }, { "code": null, "e": 7599, "s": 7370, "text": "Sales data of the past seven days were passed as an input to create a trend in sales data, this will the predicted value will not be completely random similarly, sales data of the same day in the previous year was also provided." }, { "code": null, "e": 7660, "s": 7599, "text": "The following function(other_inputs) processes three inputs:" }, { "code": null, "e": 7690, "s": 7660, "text": "sales data of past seven days" }, { "code": null, "e": 7739, "s": 7690, "text": "sales data on the same date in the previous year" }, { "code": null, "e": 7814, "s": 7739, "text": "seasonality – seasonality was added to mark trends like summer sales, etc." }, { "code": null, "e": 7822, "s": 7814, "text": "Python3" }, { "code": "def other_inputs(season,list_row): #lists to hold all the inputs inp7=[] inp_prev=[] inp_sess=[] count=0 #count variable will be used to keep track of the index of current row in order to access the traffic values of past seven days. for row in list_row: ind = count count=count+1 d = row[0] #date was copied to variable d d_split=d.split('/') if d_split[2]==str(year_all[0]): #preventing use of the first year in the data continue sess = cur_season(season,d) #assigning a season to to the current date inp_sess.append(sess) #appending sess variable to an input list t7=[] #temporary list to hold seven sales value t_prev=[] #temporary list to hold the previous year sales value t_prev.append(list_row[ind-365][1]) #accessing the sales value from one year back and appending them for j in range(0,7): t7.append(list_row[ind-j-1][1]) #appending the last seven days sales value inp7.append(t7) inp_prev.append(t_prev) return inp7,inp_prev,inp_sess inp7,inp_prev,inp_sess = other_inputs(season,list_train)inp7 = np.array(inp7)inp7= inp7.reshape(inp7.shape[0],inp7.shape[1],1)inp_prev = np.array(inp_prev)inp_sess = np.array(inp_sess)", "e": 9016, "s": 7822, "text": null }, { "code": null, "e": 9211, "s": 9016, "text": "The reason behind so many inputs is that if all of these were combined into a single array, it would have different rows or columns of different lengths. Such an array cannot be fed as an input." }, { "code": null, "e": 9302, "s": 9211, "text": "Linearly arranging all the values in a single array lead to the model having a high loss. " }, { "code": null, "e": 9506, "s": 9302, "text": "A linear arrangement will cause the model to generalize, as the difference between successive inputs would not be too different, which will lead to limited learning, decreasing the accuracy of the model." }, { "code": null, "e": 9604, "s": 9506, "text": "Eight separate inputs are processed and concatenated into a single layer and passed to the model." }, { "code": null, "e": 9641, "s": 9604, "text": "The finalized inputs are as follows:" }, { "code": null, "e": 9729, "s": 9641, "text": "DateMonthYearDayPrevious seven days salessales in the previous yearSeasonHoliday or not" }, { "code": null, "e": 9734, "s": 9729, "text": "Date" }, { "code": null, "e": 9740, "s": 9734, "text": "Month" }, { "code": null, "e": 9745, "s": 9740, "text": "Year" }, { "code": null, "e": 9749, "s": 9745, "text": "Day" }, { "code": null, "e": 9775, "s": 9749, "text": "Previous seven days sales" }, { "code": null, "e": 9802, "s": 9775, "text": "sales in the previous year" }, { "code": null, "e": 9809, "s": 9802, "text": "Season" }, { "code": null, "e": 9824, "s": 9809, "text": "Holiday or not" }, { "code": null, "e": 9963, "s": 9824, "text": "Here in most layers, I have used 5 units as the output shape, you can further experiment with it to increase the efficiency of the model. " }, { "code": null, "e": 9970, "s": 9963, "text": "Python" }, { "code": "from tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Input, Dense,LSTM,Flattenfrom tensorflow.keras.layers import concatenate#an Input variable is made from every input arrayinput_day = Input(shape=(inp_day.shape[1],),name = 'input_day')input_mon = Input(shape=(inp_mon.shape[1],),name = 'input_mon')input_year = Input(shape=(inp_year.shape[1],),name = 'input_year')input_week = Input(shape=(inp_week.shape[1],),name = 'input_week')input_hol = Input(shape=(inp_hol.shape[1],),name = 'input_hol')input_day7 = Input(shape=(inp7.shape[1],inp7.shape[2]),name = 'input_day7')input_day_prev = Input(shape=(inp_prev.shape[1],),name = 'input_day_prev')input_day_sess = Input(shape=(inp_sess.shape[1],),name = 'input_day_sess')# The model is quite straight-forward, all inputs were inserted into a dense layer with 5 units and 'relu' as activation functionx1 = Dense(5, activation='relu')(input_day)x2 = Dense(5, activation='relu')(input_mon)x3 = Dense(5, activation='relu')(input_year)x4 = Dense(5, activation='relu')(input_week)x5 = Dense(5, activation='relu')(input_hol)x_6 = Dense(5, activation='relu')(input_day7)x__6 = LSTM(5,return_sequences=True)(x_6) # LSTM is used to remember the importance of each day from the seven days datax6 = Flatten()(x__10) # done to make the shape compatible to other inputs as LSTM outputs a three dimensional tensorx7 = Dense(5, activation='relu')(input_day_prev)x8 = Dense(5, activation='relu')(input_day_sess)c = concatenate([x1,x2,x3,x4,x5,x6,x7,x8]) # all inputs are concatenated into onelayer1 = Dense(64,activation='relu')(c)outputs = Dense(1, activation='sigmoid')(layer1) # a single output is produced with value ranging between 0-1.# now the model is initialized and created as wellmodel = Model(inputs=[input_day,input_mon,input_year,input_week,input_hol,input_day7,input_day_prev,input_day_sess], outputs=outputs)model.summary() # used to draw a summary(diagram) of the model", "e": 11911, "s": 9970, "text": null }, { "code": null, "e": 11926, "s": 11911, "text": "Model Summary:" }, { "code": null, "e": 11961, "s": 11926, "text": "Compiling the model using RMSprop:" }, { "code": null, "e": 12036, "s": 11961, "text": "RMSprop is great at dealing with random distributions, hence its use here." }, { "code": null, "e": 12044, "s": 12036, "text": "Python3" }, { "code": "from tensorflow.keras.optimizers import RMSprop model.compile(loss=['mean_squared_error'], optimizer = 'adam', metrics = ['acc'] #while accuracy is used as a metrics here it will remain zero as this is no classification model ) # linear regression models are best gauged by their loss value", "e": 12391, "s": 12044, "text": null }, { "code": null, "e": 12425, "s": 12391, "text": "Fitting the model on the dataset:" }, { "code": null, "e": 12560, "s": 12425, "text": "The model will now be fed with the input and output data, this is the final step and now our model will be able to predict sales data." }, { "code": null, "e": 12568, "s": 12560, "text": "Python3" }, { "code": "history = model.fit( x = [inp_day,inp_mon,inp_year,inp_week,inp_hol,inp7,inp_prev,inp_sess], y = out, batch_size=16, steps_per_epoch=50, epochs = 15, verbose=1, shuffle =False )#all the inputs were fed into the model and the training was completed", "e": 12896, "s": 12568, "text": null }, { "code": null, "e": 12904, "s": 12896, "text": "Output:" }, { "code": null, "e": 12992, "s": 12904, "text": "Now, to test the model, input() takes input and transform it into the appropriate form:" }, { "code": null, "e": 13000, "s": 12992, "text": "Python3" }, { "code": "def input(date): d1,d2,d3 = date_to_enc(date,days,months,years) #separate date into three parameters print('date=',date) d1 = np.array([d1]) d2 = np.array([d2]) d3 = np.array([d3]) week1 = number_to_one_hot(week) #defining one hot vector to encode days of a week week2 = week1[day[date]] week2=np.array([week2]) //appeding a column for holiday(0-not holiday, 1- holiday) if date in holiday: h=1 #print('holiday') else: h=0 #print(\"no holiday\") h = np.array([h]) sess = cur_season(season,date) #getting seasonality data from cur_season function sess = np.array([sess]) return d1,d2,d3,week2,h,sess", "e": 13738, "s": 13000, "text": null }, { "code": null, "e": 13837, "s": 13738, "text": "Predicting sales data is not what we are here for right, so let’s get on with the forecasting job." }, { "code": null, "e": 13855, "s": 13837, "text": "Sales Forecasting" }, { "code": null, "e": 13956, "s": 13855, "text": "Defining forecast_testing function to forecast the sales data from one year back from provided date:" }, { "code": null, "e": 13988, "s": 13956, "text": "This function works as follows:" }, { "code": null, "e": 14086, "s": 13988, "text": "A date is required as input to forecast the sales data from one year back till the mentioned date" }, { "code": null, "e": 14185, "s": 14086, "text": "Then, we access the previous year’s sales data on the same day and sales data of 7 days before it." }, { "code": null, "e": 14359, "s": 14185, "text": "Then, using these as input a new value is predicted, then in the seven days value the first day is removed and the predicted output is added as input for the next prediction" }, { "code": null, "e": 14418, "s": 14359, "text": "For eg: we require forecasting of one year till 31/12/2019" }, { "code": null, "e": 14533, "s": 14418, "text": "First, the date of 31/12/2018 (one year back) is recorded, and also seven-day sales from (25/12/2018 – 31/12/2018)" }, { "code": null, "e": 14598, "s": 14533, "text": "Then the sales data of one year back i.e 31/12/2017 is collected" }, { "code": null, "e": 14685, "s": 14598, "text": "Using these as inputs with other ones, the first sales data(i.e 1/1/2019) is predicted" }, { "code": null, "e": 14836, "s": 14685, "text": "Then 24/12/2018 sales data is removed and 1/1/2019 predicted sales are added. This cycle is repeated until the sales data for 31/12/2019 is predicted." }, { "code": null, "e": 14877, "s": 14836, "text": "So, previous outputs are used as inputs." }, { "code": null, "e": 14885, "s": 14877, "text": "Python3" }, { "code": "def forecast_testing(date): maxj = max(traffic) # determines the maximum sales value in order to normalize or return the data to its original form out=[] count=-1 ind=0 for i in list_row: count =count+1 if i[0]==date: #identify the index of the data in list ind = count t7=[] t_prev=[] t_prev.append(list_row[ind-365][1]) #previous year data # for the first input, sales data of last seven days will be taken from training data for j in range(0,7): t7.append(list_row[ind-j-365][1]) result=[] # list to store the output and values count=0 for i in list_date[ind-364:ind+2]: d1,d2,d3,week2,h,sess = input(i) # using input function to process input values into numpy arrays t_7 = np.array([t7]) # converting the data into a numpy array t_7 = t_7.reshape(1,7,1) # extracting and processing the previous year sales value t_prev=[] t_prev.append(list_row[ind-730+count][1]) t_prev = np.array([t_prev]) #predicting value for output y_out = model.predict([d1,d2,d3,week2,h,t_7,t_prev,sess]) #output and multiply the max value to the output value to increase its range from 0-1 print(y_out[0][0]*maxj) t7.pop(0) #delete the first value from the last seven days value t7.append(y_out[0][0]) # append the output as input for the seven days data result.append(y_out[0][0]*maxj) # append the output value to the result list count=count+1 return result", "e": 16406, "s": 14885, "text": null }, { "code": null, "e": 16509, "s": 16406, "text": "Run the forecast test function and a list containing all the sales data for that one year are returned" }, { "code": null, "e": 16555, "s": 16509, "text": "Result = forecast_testing(’31/12/2019′, date)" }, { "code": null, "e": 16639, "s": 16555, "text": "Graphs for both the forecast and actual values to test the performance of the model" }, { "code": null, "e": 16647, "s": 16639, "text": "Python3" }, { "code": "plt.plot(result,color='red',label='predicted')plt.plot(test_sales,color='purple',label=\"actual\")plt.xlabel(\"Date\")plt.ylabel(\"Sales\")leg = plt.legend()plt.show()", "e": 16809, "s": 16647, "text": null }, { "code": null, "e": 16854, "s": 16812, "text": "Actual Values from 1/1/2019 to 31/12/2019" }, { "code": null, "e": 16902, "s": 16854, "text": "Comparison between prediction and actual values" }, { "code": null, "e": 17159, "s": 16902, "text": " As you can see, the predicted and actual values are quite close to each other, this proves the efficiency of our model. If there are any errors or possibilities of improvements in the above article, please feel free to mention them in the comment section." }, { "code": null, "e": 17178, "s": 17159, "text": "abhinavchaudhary12" }, { "code": null, "e": 17195, "s": 17178, "text": "arorakashish0911" }, { "code": null, "e": 17210, "s": 17195, "text": "varshagumber28" }, { "code": null, "e": 17231, "s": 17210, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 17238, "s": 17231, "text": "Picked" }, { "code": null, "e": 17245, "s": 17238, "text": "Python" } ]
Role of Operator Precedence Parser
09 Mar, 2021 In this, we will cover the overview of Operator Precedence Parser and mainly focus on the role of Operator Precedence Parser. And will also cover the algorithm for the construction of the Precedence function and finally will discuss error recovery in operator precedence parsing. Let’s discuss it one by one. Introduction :Operator Precedence Parser constructed for operator precedence grammar. Operator precedence grammar is a grammar that doesn’t contain epsilon productions and does not contain two adjacent non-terminals on R.H.S. of any production. Operator precedence grammar is provided with precedence rules. Operator Precedence grammar could be either ambiguous or unambiguous. Operator Precedence Parser Algorithm : 1. If the front of input $ and top of stack both have $, it's done else 2. compare front of input b with ⋗ if b! = '⋗' then push b scan the next input symbol 3. if b == '⋗' then pop till ⋖ and store it in a string S pop ⋖ also reduce the poped string if (top of stack) ⋖ (front of input) then push ⋖ S if (top of stack) ⋗ (front of input) then push S and goto 3 Components Operator Diagram : Components Operator Example –Let’s take an example to understand the role of operator precedence as follows. E-> E+T/T T-> T*V/V V->a/b/c/d string= "a+b*c*d" Implementation of the above algorithm for the string “a+b*c*d” as follows. Algorithm for construction of Precedence function : Generate a function Xa for each grammar terminal a and for the end of the string symbol.Partition the symbol in groups so that Xa and Yb are the same groups if a ≐ b.Generate a directed graph whose nodes are in the groups, for each symbol a and b, do place an edge from the group of Yb to the group of Xa if a ⋖ b, otherwise if a ⋗ b place an edge from the group of Xa to that of Yb.If the constructed graph has a cycle then no procedure functions exist. When there are no cycles collect the length of the longest paths from the groups of Xa and yb respectively. Generate a function Xa for each grammar terminal a and for the end of the string symbol. Partition the symbol in groups so that Xa and Yb are the same groups if a ≐ b. Generate a directed graph whose nodes are in the groups, for each symbol a and b, do place an edge from the group of Yb to the group of Xa if a ⋖ b, otherwise if a ⋗ b place an edge from the group of Xa to that of Yb. If the constructed graph has a cycle then no procedure functions exist. When there are no cycles collect the length of the longest paths from the groups of Xa and yb respectively. Example –Let’s take an example to understand the construction of precedence function as follows. E -> E + E/E * E/( E )/id Here, you will see the Operator precedence relation table and Precedence Relations Graph diagram. Let’s have a look. Operator precedence relation table Precedence Relations Graph As we can see no cycle there is no cycle in the graph, we can make this function table as follows. Function table Columns Representation function : Columns represent function Ya and Rows represent function Xa –It is calculated by taking the longest path from Xid to X$ and Yid to Y$. fid -> g* -> f+ ->g+ -> f$ gid -> f* -> g* ->f+ -> g+ ->f$ The disadvantage of the operator precedence relation table is that if there are ‘n’ numbers of symbols then we require a table of n*n to store them. On other hand, by using the operator function table, to accommodate n number of symbols we require a table of 2*n. Operator Precedence Grammar cannot decide the unary minus(lexical analyzer should handle the unary minus). The advantage of using Operator Precedence Grammar is simple and enough powerful for expression in programming languages. Error Recovery in Operator-Precedence Parsing : Error Cases –1. No relation holds between the terminal on the top of the stack and the next input symbol.2. A handle is found (reduction step), but there is no production with this handle as a right side. Error recovery –1. Each empty entry is filled with a pointer to an error routine.2. Decides the popped handle “looks like” which right-hand side. And tries to recover from that situation. Handling shift/ reduce errors –To take care of such types of errors we must modify the following.1. Stack2. Input3. or Both Technical Scripter 2020 Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Mar, 2021" }, { "code": null, "e": 361, "s": 52, "text": "In this, we will cover the overview of Operator Precedence Parser and mainly focus on the role of Operator Precedence Parser. And will also cover the algorithm for the construction of the Precedence function and finally will discuss error recovery in operator precedence parsing. Let’s discuss it one by one." }, { "code": null, "e": 740, "s": 361, "text": "Introduction :Operator Precedence Parser constructed for operator precedence grammar. Operator precedence grammar is a grammar that doesn’t contain epsilon productions and does not contain two adjacent non-terminals on R.H.S. of any production. Operator precedence grammar is provided with precedence rules. Operator Precedence grammar could be either ambiguous or unambiguous." }, { "code": null, "e": 779, "s": 740, "text": "Operator Precedence Parser Algorithm :" }, { "code": null, "e": 1224, "s": 779, "text": "1. If the front of input $ and top of stack both have $, it's done\n else\n2. compare front of input b with ⋗\n if b! = '⋗'\n then push b\n scan the next input symbol\n3. if b == '⋗'\n then pop till ⋖ and store it in a string S\n pop ⋖ also\n reduce the poped string\n if (top of stack) ⋖ (front of input)\n then push ⋖ S\n if (top of stack) ⋗ (front of input)\n then push S and goto 3 " }, { "code": null, "e": 1254, "s": 1224, "text": "Components Operator Diagram :" }, { "code": null, "e": 1274, "s": 1254, "text": "Components Operator" }, { "code": null, "e": 1363, "s": 1274, "text": "Example –Let’s take an example to understand the role of operator precedence as follows." }, { "code": null, "e": 1412, "s": 1363, "text": "E-> E+T/T\nT-> T*V/V\nV->a/b/c/d\nstring= \"a+b*c*d\"" }, { "code": null, "e": 1487, "s": 1412, "text": "Implementation of the above algorithm for the string “a+b*c*d” as follows." }, { "code": null, "e": 1539, "s": 1487, "text": "Algorithm for construction of Precedence function :" }, { "code": null, "e": 2102, "s": 1539, "text": "Generate a function Xa for each grammar terminal a and for the end of the string symbol.Partition the symbol in groups so that Xa and Yb are the same groups if a ≐ b.Generate a directed graph whose nodes are in the groups, for each symbol a and b, do place an edge from the group of Yb to the group of Xa if a ⋖ b, otherwise if a ⋗ b place an edge from the group of Xa to that of Yb.If the constructed graph has a cycle then no procedure functions exist. When there are no cycles collect the length of the longest paths from the groups of Xa and yb respectively." }, { "code": null, "e": 2191, "s": 2102, "text": "Generate a function Xa for each grammar terminal a and for the end of the string symbol." }, { "code": null, "e": 2270, "s": 2191, "text": "Partition the symbol in groups so that Xa and Yb are the same groups if a ≐ b." }, { "code": null, "e": 2488, "s": 2270, "text": "Generate a directed graph whose nodes are in the groups, for each symbol a and b, do place an edge from the group of Yb to the group of Xa if a ⋖ b, otherwise if a ⋗ b place an edge from the group of Xa to that of Yb." }, { "code": null, "e": 2668, "s": 2488, "text": "If the constructed graph has a cycle then no procedure functions exist. When there are no cycles collect the length of the longest paths from the groups of Xa and yb respectively." }, { "code": null, "e": 2765, "s": 2668, "text": "Example –Let’s take an example to understand the construction of precedence function as follows." }, { "code": null, "e": 2791, "s": 2765, "text": "E -> E + E/E * E/( E )/id" }, { "code": null, "e": 2908, "s": 2791, "text": "Here, you will see the Operator precedence relation table and Precedence Relations Graph diagram. Let’s have a look." }, { "code": null, "e": 2943, "s": 2908, "text": "Operator precedence relation table" }, { "code": null, "e": 2970, "s": 2943, "text": "Precedence Relations Graph" }, { "code": null, "e": 3069, "s": 2970, "text": "As we can see no cycle there is no cycle in the graph, we can make this function table as follows." }, { "code": null, "e": 3084, "s": 3069, "text": "Function table" }, { "code": null, "e": 3118, "s": 3084, "text": "Columns Representation function :" }, { "code": null, "e": 3254, "s": 3118, "text": "Columns represent function Ya and Rows represent function Xa –It is calculated by taking the longest path from Xid to X$ and Yid to Y$." }, { "code": null, "e": 3314, "s": 3254, "text": "fid -> g* -> f+ ->g+ -> f$\ngid -> f* -> g* ->f+ -> g+ ->f$ " }, { "code": null, "e": 3685, "s": 3314, "text": "The disadvantage of the operator precedence relation table is that if there are ‘n’ numbers of symbols then we require a table of n*n to store them. On other hand, by using the operator function table, to accommodate n number of symbols we require a table of 2*n. Operator Precedence Grammar cannot decide the unary minus(lexical analyzer should handle the unary minus)." }, { "code": null, "e": 3807, "s": 3685, "text": "The advantage of using Operator Precedence Grammar is simple and enough powerful for expression in programming languages." }, { "code": null, "e": 3855, "s": 3807, "text": "Error Recovery in Operator-Precedence Parsing :" }, { "code": null, "e": 4061, "s": 3855, "text": "Error Cases –1. No relation holds between the terminal on the top of the stack and the next input symbol.2. A handle is found (reduction step), but there is no production with this handle as a right side. " }, { "code": null, "e": 4250, "s": 4061, "text": "Error recovery –1. Each empty entry is filled with a pointer to an error routine.2. Decides the popped handle “looks like” which right-hand side. And tries to recover from that situation. " }, { "code": null, "e": 4374, "s": 4250, "text": "Handling shift/ reduce errors –To take care of such types of errors we must modify the following.1. Stack2. Input3. or Both" }, { "code": null, "e": 4398, "s": 4374, "text": "Technical Scripter 2020" }, { "code": null, "e": 4414, "s": 4398, "text": "Compiler Design" }, { "code": null, "e": 4422, "s": 4414, "text": "GATE CS" } ]
Instant minus() method in Java with Examples
28 Jan, 2022 In Instant class, there are two types of minus() method depending upon the parameters passed to it. minus() method of a Instant class used to returns a copy of this instant with the specified amount of unit subtracted.If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.Syntax: public Instant minus(long amountToSubtract, TemporalUnit unit) Parameters: This method accepts two parameters: amountToSubtract which is the amount of the unit to subtract to the result, may be negative and unit which is the unit of the amount to subtract, not null. Return value: This method returns Instant based on this instant with the specified amount subtracted.Exception: This method throws following Exceptions: DateTimeException – if the subtraction cannot be made UnsupportedTemporalTypeException – if the unit is not supported ArithmeticException – if numeric overflow occurs Below programs illustrate the minus() method:Program 1: Java // Java program to demonstrate// Instant.minus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create an Instant object Instant instant = Instant.parse("2018-12-30T19:34:50.63Z"); // subtract 20 DAYS to Instant Instant value = instant.minus(20, ChronoUnit.DAYS); // print result System.out.println("Instant after subtracting DAYS: " + value); }} Instant after subtracting DAYS: 2018-12-10T19:34:50.630Z minus() method of a Instant class used to returns a copy of this instant with the specified amount subtracted to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.Syntax: public Instant minus(TemporalAmount amountTosubtract) Parameters: This method accepts one single parameter amountTosubtract which is the amount to subtract, It should not be null.Return value: This method returns Instant based on this date-time with the subtraction made, not null.Exception: This method throws following Exceptions: DateTimeException – if the subtraction cannot be made ArithmeticException – if numeric overflow occurs Below programs illustrate the minus() method: Program 1: Java // Java program to demonstrate// Instant.minus() method import java.time.*;public class GFG { public static void main(String[] args) { // create an Instant object Instant inst = Instant.parse("2018-12-30T19:34:50.63Z"); // subtract 10 Days to Instant Instant value = inst.minus(Period.ofDays(10)); // print result System.out.println("Instant after subtracting Days: " + value); }} Instant after subtracting Days: 2018-12-20T19:34:50.630Z References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minus(java.time.temporal.TemporalAmount) https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minus(long, java.time.temporal.TemporalUnit) saurabh1990aror Java-Functions Java-Instant Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2022" }, { "code": null, "e": 129, "s": 28, "text": "In Instant class, there are two types of minus() method depending upon the parameters passed to it. " }, { "code": null, "e": 386, "s": 129, "text": "minus() method of a Instant class used to returns a copy of this instant with the specified amount of unit subtracted.If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.Syntax: " }, { "code": null, "e": 470, "s": 386, "text": "public Instant minus(long amountToSubtract,\n TemporalUnit unit)" }, { "code": null, "e": 520, "s": 470, "text": "Parameters: This method accepts two parameters: " }, { "code": null, "e": 616, "s": 520, "text": "amountToSubtract which is the amount of the unit to subtract to the result, may be negative and" }, { "code": null, "e": 676, "s": 616, "text": "unit which is the unit of the amount to subtract, not null." }, { "code": null, "e": 831, "s": 676, "text": "Return value: This method returns Instant based on this instant with the specified amount subtracted.Exception: This method throws following Exceptions: " }, { "code": null, "e": 885, "s": 831, "text": "DateTimeException – if the subtraction cannot be made" }, { "code": null, "e": 949, "s": 885, "text": "UnsupportedTemporalTypeException – if the unit is not supported" }, { "code": null, "e": 998, "s": 949, "text": "ArithmeticException – if numeric overflow occurs" }, { "code": null, "e": 1056, "s": 998, "text": "Below programs illustrate the minus() method:Program 1: " }, { "code": null, "e": 1061, "s": 1056, "text": "Java" }, { "code": "// Java program to demonstrate// Instant.minus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create an Instant object Instant instant = Instant.parse(\"2018-12-30T19:34:50.63Z\"); // subtract 20 DAYS to Instant Instant value = instant.minus(20, ChronoUnit.DAYS); // print result System.out.println(\"Instant after subtracting DAYS: \" + value); }}", "e": 1590, "s": 1061, "text": null }, { "code": null, "e": 1647, "s": 1590, "text": "Instant after subtracting DAYS: 2018-12-10T19:34:50.630Z" }, { "code": null, "e": 1893, "s": 1649, "text": "minus() method of a Instant class used to returns a copy of this instant with the specified amount subtracted to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.Syntax: " }, { "code": null, "e": 1947, "s": 1893, "text": "public Instant minus(TemporalAmount amountTosubtract)" }, { "code": null, "e": 2226, "s": 1947, "text": "Parameters: This method accepts one single parameter amountTosubtract which is the amount to subtract, It should not be null.Return value: This method returns Instant based on this date-time with the subtraction made, not null.Exception: This method throws following Exceptions:" }, { "code": null, "e": 2280, "s": 2226, "text": "DateTimeException – if the subtraction cannot be made" }, { "code": null, "e": 2329, "s": 2280, "text": "ArithmeticException – if numeric overflow occurs" }, { "code": null, "e": 2388, "s": 2329, "text": "Below programs illustrate the minus() method: Program 1: " }, { "code": null, "e": 2393, "s": 2388, "text": "Java" }, { "code": "// Java program to demonstrate// Instant.minus() method import java.time.*;public class GFG { public static void main(String[] args) { // create an Instant object Instant inst = Instant.parse(\"2018-12-30T19:34:50.63Z\"); // subtract 10 Days to Instant Instant value = inst.minus(Period.ofDays(10)); // print result System.out.println(\"Instant after subtracting Days: \" + value); }}", "e": 2876, "s": 2393, "text": null }, { "code": null, "e": 2933, "s": 2876, "text": "Instant after subtracting Days: 2018-12-20T19:34:50.630Z" }, { "code": null, "e": 3166, "s": 2935, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minus(java.time.temporal.TemporalAmount) https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minus(long, java.time.temporal.TemporalUnit) " }, { "code": null, "e": 3182, "s": 3166, "text": "saurabh1990aror" }, { "code": null, "e": 3197, "s": 3182, "text": "Java-Functions" }, { "code": null, "e": 3210, "s": 3197, "text": "Java-Instant" }, { "code": null, "e": 3228, "s": 3210, "text": "Java-time package" }, { "code": null, "e": 3233, "s": 3228, "text": "Java" }, { "code": null, "e": 3238, "s": 3233, "text": "Java" } ]
Precision of Floating Point Numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
18 Apr, 2022 The decimal equivalent of 1/3 is 0.33333333333333.... An infinite length number would require infinite memory to store, and we typically have 4 or 8 bytes. Therefore, Floating point numbers store only a certain number of significant digits, and the rest are lost. The precision of a floating-point number defines how many significant digits it can represent without information loss. When outputting floating-point numbers, cout has a default precision of 6 and it truncates anything after that. Below are a few libraries and methods which are used to provide precision to floating-point numbers in C++: Floor rounds off the given value to the closest integer which is less than the given value. It is defined in the <cmath> header file. CPP // C++ program to demonstrate working of floor()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.711; cout << floor(x) << endl; cout << floor(y) << endl; cout << floor(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << floor(a) << endl; cout << floor(b) << endl; cout << floor(c) << endl; return 0;} 1 1 1 -2 -2 -2 Ceil rounds off the given value to the closest integer which is more than the given value. It is defined in the <cmath> header file. CPP // C++ program to demonstrate working of ceil()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.611; cout << ceil(x) << endl; cout << ceil(y) << endl; cout << ceil(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << ceil(a) << endl; cout << ceil(b) << endl; cout << ceil(c) << endl; return 0;} 2 2 2 -1 -1 -1 Trunc rounds remove digits after the decimal point. It is defined in the <cmath> header file. CPP // C++ program to demonstrate working of trunc()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.611; cout << trunc(x) << endl; cout << trunc(y) << endl; cout << trunc(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << trunc(a) << endl; cout << trunc(b) << endl; cout << trunc(c) << endl; return 0;} 1 1 1 -1 -1 -1 Rounds gave numbers to the closest integer. It is defined in the header files: <cmath> and <ctgmath>. CPP // C++ program to demonstrate working of round()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.611; cout << round(x) << endl; cout << round(y) << endl; cout << round(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << round(a) << endl; cout << round(b) << endl; cout << round(c) << endl; return 0;} 1 2 2 -1 -2 -2 Setprecision when used along with ‘fixed’ provides precision to floating-point numbers correct to decimal numbers mentioned in the brackets of the setprecision. It is defined in header file <iomanip>. CPP // C++ program to demonstrate// working of setprecision()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double pi = 3.14159, npi = -3.14159; cout << fixed << setprecision(0) << pi << " " << npi << endl; cout << fixed << setprecision(1) << pi << " " << npi << endl; cout << fixed << setprecision(2) << pi << " " << npi << endl; cout << fixed << setprecision(3) << pi << " " << npi << endl; cout << fixed << setprecision(4) << pi << " " << npi << endl; cout << fixed << setprecision(5) << pi << " " << npi << endl; cout << fixed << setprecision(6) << pi << " " << npi << endl;} 3 -3 3.1 -3.1 3.14 -3.14 3.142 -3.142 3.1416 -3.1416 3.14159 -3.14159 3.141590 -3.141590 Note: When the value mentioned in the setprecision() exceeds the number of floating point digits in the original number then 0 is appended to floating point digit to match the precision mentioned by the user. There exist other methods too to provide precision to floating-point numbers. The above mentioned are a few of the most commonly used methods to provide precision to floating-point numbers during competitive coding.This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 simmytarika5 CPP-Library Data Type Operators C Language C++ Technical Scripter Operators Data Type CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Apr, 2022" }, { "code": null, "e": 656, "s": 52, "text": "The decimal equivalent of 1/3 is 0.33333333333333.... An infinite length number would require infinite memory to store, and we typically have 4 or 8 bytes. Therefore, Floating point numbers store only a certain number of significant digits, and the rest are lost. The precision of a floating-point number defines how many significant digits it can represent without information loss. When outputting floating-point numbers, cout has a default precision of 6 and it truncates anything after that. Below are a few libraries and methods which are used to provide precision to floating-point numbers in C++:" }, { "code": null, "e": 790, "s": 656, "text": "Floor rounds off the given value to the closest integer which is less than the given value. It is defined in the <cmath> header file." }, { "code": null, "e": 794, "s": 790, "text": "CPP" }, { "code": "// C++ program to demonstrate working of floor()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.711; cout << floor(x) << endl; cout << floor(y) << endl; cout << floor(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << floor(a) << endl; cout << floor(b) << endl; cout << floor(c) << endl; return 0;}", "e": 1202, "s": 794, "text": null }, { "code": null, "e": 1217, "s": 1202, "text": "1\n1\n1\n-2\n-2\n-2" }, { "code": null, "e": 1350, "s": 1217, "text": "Ceil rounds off the given value to the closest integer which is more than the given value. It is defined in the <cmath> header file." }, { "code": null, "e": 1354, "s": 1350, "text": "CPP" }, { "code": "// C++ program to demonstrate working of ceil()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.611; cout << ceil(x) << endl; cout << ceil(y) << endl; cout << ceil(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << ceil(a) << endl; cout << ceil(b) << endl; cout << ceil(c) << endl; return 0;}", "e": 1755, "s": 1354, "text": null }, { "code": null, "e": 1770, "s": 1755, "text": "2\n2\n2\n-1\n-1\n-1" }, { "code": null, "e": 1864, "s": 1770, "text": "Trunc rounds remove digits after the decimal point. It is defined in the <cmath> header file." }, { "code": null, "e": 1868, "s": 1864, "text": "CPP" }, { "code": "// C++ program to demonstrate working of trunc()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.611; cout << trunc(x) << endl; cout << trunc(y) << endl; cout << trunc(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << trunc(a) << endl; cout << trunc(b) << endl; cout << trunc(c) << endl; return 0;}", "e": 2276, "s": 1868, "text": null }, { "code": null, "e": 2291, "s": 2276, "text": "1\n1\n1\n-1\n-1\n-1" }, { "code": null, "e": 2393, "s": 2291, "text": "Rounds gave numbers to the closest integer. It is defined in the header files: <cmath> and <ctgmath>." }, { "code": null, "e": 2397, "s": 2393, "text": "CPP" }, { "code": "// C++ program to demonstrate working of round()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double x = 1.411, y = 1.500, z = 1.611; cout << round(x) << endl; cout << round(y) << endl; cout << round(z) << endl; double a = -1.411, b = -1.500, c = -1.611; cout << round(a) << endl; cout << round(b) << endl; cout << round(c) << endl; return 0;}", "e": 2806, "s": 2397, "text": null }, { "code": null, "e": 2821, "s": 2806, "text": "1\n2\n2\n-1\n-2\n-2" }, { "code": null, "e": 3022, "s": 2821, "text": "Setprecision when used along with ‘fixed’ provides precision to floating-point numbers correct to decimal numbers mentioned in the brackets of the setprecision. It is defined in header file <iomanip>." }, { "code": null, "e": 3026, "s": 3022, "text": "CPP" }, { "code": "// C++ program to demonstrate// working of setprecision()// in C/C++#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double pi = 3.14159, npi = -3.14159; cout << fixed << setprecision(0) << pi << \" \" << npi << endl; cout << fixed << setprecision(1) << pi << \" \" << npi << endl; cout << fixed << setprecision(2) << pi << \" \" << npi << endl; cout << fixed << setprecision(3) << pi << \" \" << npi << endl; cout << fixed << setprecision(4) << pi << \" \" << npi << endl; cout << fixed << setprecision(5) << pi << \" \" << npi << endl; cout << fixed << setprecision(6) << pi << \" \" << npi << endl;}", "e": 3717, "s": 3026, "text": null }, { "code": null, "e": 3806, "s": 3717, "text": "3 -3\n3.1 -3.1\n3.14 -3.14\n3.142 -3.142\n3.1416 -3.1416\n3.14159 -3.14159\n3.141590 -3.141590" }, { "code": null, "e": 4015, "s": 3806, "text": "Note: When the value mentioned in the setprecision() exceeds the number of floating point digits in the original number then 0 is appended to floating point digit to match the precision mentioned by the user." }, { "code": null, "e": 4651, "s": 4015, "text": "There exist other methods too to provide precision to floating-point numbers. The above mentioned are a few of the most commonly used methods to provide precision to floating-point numbers during competitive coding.This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4665, "s": 4651, "text": "anshikajain26" }, { "code": null, "e": 4678, "s": 4665, "text": "simmytarika5" }, { "code": null, "e": 4690, "s": 4678, "text": "CPP-Library" }, { "code": null, "e": 4700, "s": 4690, "text": "Data Type" }, { "code": null, "e": 4710, "s": 4700, "text": "Operators" }, { "code": null, "e": 4721, "s": 4710, "text": "C Language" }, { "code": null, "e": 4725, "s": 4721, "text": "C++" }, { "code": null, "e": 4744, "s": 4725, "text": "Technical Scripter" }, { "code": null, "e": 4754, "s": 4744, "text": "Operators" }, { "code": null, "e": 4764, "s": 4754, "text": "Data Type" }, { "code": null, "e": 4768, "s": 4764, "text": "CPP" } ]
Optimal File Merge Patterns
15 Jun, 2022 Given n number of sorted files, the task is to find the minimum computations done to reach the Optimal Merge Pattern. When two or more sorted files are to be merged altogether to form a single file, the minimum computations are done to reach this file are known as Optimal Merge Pattern. If more than 2 files need to be merged then it can be done in pairs. For example, if need to merge 4 files A, B, C, D. First Merge A with B to get X1, merge X1 with C to get X2, merge X2 with D to get X3 as the output file. If we have two files of sizes m and n, the total computation time will be m+n. Here, we use the greedy strategy by merging the two smallest size files among all the files present. Examples: Given 3 files with sizes 2, 3, 4 units. Find an optimal way to combine these files Input: n = 3, size = {2, 3, 4} Output: 14 Explanation: There are different ways to combine these files: Method 1: Optimal method Method 2: Method 3: Input: n = 6, size = {2, 3, 4, 5, 6, 7} Output: 68 Explanation: Optimal way to combine these files Input: n = 5, size = {5,10,20,30,30} Output: 205 Input: n = 5, size = {8,8,8,8,8} Output: 96 Observations: From the above results, we may conclude that for finding the minimum cost of computation we need to have our array always sorted, i.e., add the minimum possible computation cost and remove the files from the array. We can achieve this optimally using a min-heap(priority-queue) data structure.Approach: Node represents a file with a given size also given nodes are greater than 2 Add all the nodes in a priority queue (Min Heap).{pq.poll = file size}Initialize count = 0 // variable to store file computations.Repeat while (size of priority Queue is greater than 1) int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it outweight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it outcount +=weight;pq.add(weight) // add this combined cost to priority queue; count is the final answer Add all the nodes in a priority queue (Min Heap).{pq.poll = file size} Initialize count = 0 // variable to store file computations. Repeat while (size of priority Queue is greater than 1) int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it outweight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it outcount +=weight;pq.add(weight) // add this combined cost to priority queue; int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it outweight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it outcount +=weight;pq.add(weight) // add this combined cost to priority queue; int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it out weight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it out count +=weight; pq.add(weight) // add this combined cost to priority queue; count is the final answer Below is the implementation of the above approach: C++ Java Python3 // C++ program to implement// Optimal File Merge Pattern#include <bits/stdc++.h>using namespace std; // Function to find minimum computationint minComputation(int size, int files[]){ // Create a min heap priority_queue<int, vector<int>, greater<int> > pq; for (int i = 0; i < size; i++) { // Add sizes to priorityQueue pq.push(files[i]); } // Variable to count total Computation int count = 0; while (pq.size() > 1) { // pop two smallest size element // from the min heap int first_smallest = pq.top(); pq.pop(); int second_smallest = pq.top(); pq.pop(); int temp = first_smallest + second_smallest; // Add the current computations // with the previous one's count += temp; // Add new combined file size // to priority queue or min heap pq.push(temp); } return count;} // Driver codeint main(){ // No of files int n = 6; // 6 files with their sizes int files[] = { 2, 3, 4, 5, 6, 7 }; // Total no of computations // do be done final answer cout << "Minimum Computations = " << minComputation(n, files); return 0;} // This code is contributed by jaigoyal1328 // Java program to implement// Optimal File Merge Pattern import java.util.PriorityQueue;import java.util.Scanner; public class OptimalMergePatterns { // Function to find minimum computation static int minComputation(int size, int files[]) { // create a min heap PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int i = 0; i < size; i++) { // add sizes to priorityQueue pq.add(files[i]); } // variable to count total computations int count = 0; while (pq.size() > 1) { // pop two smallest size element // from the min heap int temp = pq.poll() + pq.poll(); // add the current computations // with the previous one's count += temp; // add new combined file size // to priority queue or min heap pq.add(temp); } return count; } public static void main(String[] args) { // no of files int size = 6; // 6 files with their sizes int files[] = new int[] { 2, 3, 4, 5, 6, 7 }; // total no of computations // do be done final answer System.out.println("Minimum Computations = " + minComputation(size, files)); }} # Python Program to implement# Optimal File Merge Pattern class Heap(): # Building own implementation of Min Heap def __init__(self): self.h = [] def parent(self, index): # Returns parent index for given index if index > 0: return (index - 1) // 2 def lchild(self, index): # Returns left child index for given index return (2 * index) + 1 def rchild(self, index): # Returns right child index for given index return (2 * index) + 2 def addItem(self, item): # Function to add an item to heap self.h.append(item) if len(self.h) == 1: # If heap has only one item no need to heapify return index = len(self.h) - 1 parent = self.parent(index) # Moves the item up if it is smaller than the parent while index > 0 and item < self.h[parent]: self.h[index], self.h[parent] = self.h[parent], self.h[parent] index = parent parent = self.parent(index) def deleteItem(self): # Function to add an item to heap length = len(self.h) self.h[0], self.h[length-1] = self.h[length-1], self.h[0] deleted = self.h.pop() # Since root will be violating heap property # Call moveDownHeapify() to restore heap property self.moveDownHeapify(0) return deleted def moveDownHeapify(self, index): # Function to make the items follow Heap property # Compares the value with the children and moves item down lc, rc = self.lchild(index), self.rchild(index) length, smallest = len(self.h), index if lc < length and self.h[lc] <= self.h[smallest]: smallest = lc if rc < length and self.h[rc] <= self.h[smallest]: smallest = rc if smallest != index: # Swaps the parent node with the smaller child self.h[smallest], self.h[index] = self.h[index], self.h[smallest] # Recursive call to compare next subtree self.moveDownHeapify(smallest) def increaseItem(self, index, value): # Increase the value of 'index' to 'value' if value <= self.h[index]: return self.h[index] = value self.moveDownHeapify(index) class OptimalMergePattern(): def __init__(self, n, items): self.n = n self.items = items self.heap = Heap() def optimalMerge(self): # Corner cases if list has no more than 1 item if self.n <= 0: return 0 if self.n == 1: return self.items[0] # Insert items into min heap for _ in self.items: self.heap.addItem(_) count = 0 while len(self.heap.h) != 1: tmp = self.heap.deleteItem() count += (tmp + self.heap.h[0]) self.heap.increaseItem(0, tmp + self.heap.h[0]) return count # Driver Codeif __name__ == '__main__': OMP = OptimalMergePattern(6, [2, 3, 4, 5, 6, 7]) ans = OMP.optimalMerge() print(ans) # This code is contributed by Rajat Gupta Minimum Computations = 68 Time Complexity: O(nlogn)Auxiliary Space: O(n) jaigoyal1328 akshaysingh98088 rajatscientist51 geeky01adarsh sanskar84 java-file-handling Greedy Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2022" }, { "code": null, "e": 342, "s": 54, "text": "Given n number of sorted files, the task is to find the minimum computations done to reach the Optimal Merge Pattern. When two or more sorted files are to be merged altogether to form a single file, the minimum computations are done to reach this file are known as Optimal Merge Pattern." }, { "code": null, "e": 566, "s": 342, "text": "If more than 2 files need to be merged then it can be done in pairs. For example, if need to merge 4 files A, B, C, D. First Merge A with B to get X1, merge X1 with C to get X2, merge X2 with D to get X3 as the output file." }, { "code": null, "e": 746, "s": 566, "text": "If we have two files of sizes m and n, the total computation time will be m+n. Here, we use the greedy strategy by merging the two smallest size files among all the files present." }, { "code": null, "e": 840, "s": 746, "text": "Examples: Given 3 files with sizes 2, 3, 4 units. Find an optimal way to combine these files " }, { "code": null, "e": 971, "s": 840, "text": "Input: n = 3, size = {2, 3, 4} Output: 14 Explanation: There are different ways to combine these files: Method 1: Optimal method " }, { "code": null, "e": 983, "s": 971, "text": "Method 2: " }, { "code": null, "e": 995, "s": 983, "text": "Method 3: " }, { "code": null, "e": 1096, "s": 995, "text": "Input: n = 6, size = {2, 3, 4, 5, 6, 7} Output: 68 Explanation: Optimal way to combine these files " }, { "code": null, "e": 1146, "s": 1096, "text": "Input: n = 5, size = {5,10,20,30,30} Output: 205 " }, { "code": null, "e": 1191, "s": 1146, "text": "Input: n = 5, size = {8,8,8,8,8} Output: 96 " }, { "code": null, "e": 1205, "s": 1191, "text": "Observations:" }, { "code": null, "e": 1510, "s": 1205, "text": "From the above results, we may conclude that for finding the minimum cost of computation we need to have our array always sorted, i.e., add the minimum possible computation cost and remove the files from the array. We can achieve this optimally using a min-heap(priority-queue) data structure.Approach: " }, { "code": null, "e": 1588, "s": 1510, "text": "Node represents a file with a given size also given nodes are greater than 2 " }, { "code": null, "e": 2063, "s": 1588, "text": "Add all the nodes in a priority queue (Min Heap).{pq.poll = file size}Initialize count = 0 // variable to store file computations.Repeat while (size of priority Queue is greater than 1) int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it outweight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it outcount +=weight;pq.add(weight) // add this combined cost to priority queue; count is the final answer" }, { "code": null, "e": 2134, "s": 2063, "text": "Add all the nodes in a priority queue (Min Heap).{pq.poll = file size}" }, { "code": null, "e": 2195, "s": 2134, "text": "Initialize count = 0 // variable to store file computations." }, { "code": null, "e": 2515, "s": 2195, "text": "Repeat while (size of priority Queue is greater than 1) int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it outweight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it outcount +=weight;pq.add(weight) // add this combined cost to priority queue; " }, { "code": null, "e": 2779, "s": 2515, "text": "int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it outweight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it outcount +=weight;pq.add(weight) // add this combined cost to priority queue; " }, { "code": null, "e": 2882, "s": 2779, "text": "int weight = pq.poll(); pq.pop;//pq denotes priority queue, remove 1st smallest and pop(remove) it out" }, { "code": null, "e": 2968, "s": 2882, "text": "weight+=pq.poll() && pq.pop(); // add the second element and then pop(remove) it out" }, { "code": null, "e": 2984, "s": 2968, "text": "count +=weight;" }, { "code": null, "e": 3046, "s": 2984, "text": "pq.add(weight) // add this combined cost to priority queue; " }, { "code": null, "e": 3072, "s": 3046, "text": "count is the final answer" }, { "code": null, "e": 3125, "s": 3072, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 3129, "s": 3125, "text": "C++" }, { "code": null, "e": 3134, "s": 3129, "text": "Java" }, { "code": null, "e": 3142, "s": 3134, "text": "Python3" }, { "code": "// C++ program to implement// Optimal File Merge Pattern#include <bits/stdc++.h>using namespace std; // Function to find minimum computationint minComputation(int size, int files[]){ // Create a min heap priority_queue<int, vector<int>, greater<int> > pq; for (int i = 0; i < size; i++) { // Add sizes to priorityQueue pq.push(files[i]); } // Variable to count total Computation int count = 0; while (pq.size() > 1) { // pop two smallest size element // from the min heap int first_smallest = pq.top(); pq.pop(); int second_smallest = pq.top(); pq.pop(); int temp = first_smallest + second_smallest; // Add the current computations // with the previous one's count += temp; // Add new combined file size // to priority queue or min heap pq.push(temp); } return count;} // Driver codeint main(){ // No of files int n = 6; // 6 files with their sizes int files[] = { 2, 3, 4, 5, 6, 7 }; // Total no of computations // do be done final answer cout << \"Minimum Computations = \" << minComputation(n, files); return 0;} // This code is contributed by jaigoyal1328", "e": 4377, "s": 3142, "text": null }, { "code": "// Java program to implement// Optimal File Merge Pattern import java.util.PriorityQueue;import java.util.Scanner; public class OptimalMergePatterns { // Function to find minimum computation static int minComputation(int size, int files[]) { // create a min heap PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int i = 0; i < size; i++) { // add sizes to priorityQueue pq.add(files[i]); } // variable to count total computations int count = 0; while (pq.size() > 1) { // pop two smallest size element // from the min heap int temp = pq.poll() + pq.poll(); // add the current computations // with the previous one's count += temp; // add new combined file size // to priority queue or min heap pq.add(temp); } return count; } public static void main(String[] args) { // no of files int size = 6; // 6 files with their sizes int files[] = new int[] { 2, 3, 4, 5, 6, 7 }; // total no of computations // do be done final answer System.out.println(\"Minimum Computations = \" + minComputation(size, files)); }}", "e": 5683, "s": 4377, "text": null }, { "code": "# Python Program to implement# Optimal File Merge Pattern class Heap(): # Building own implementation of Min Heap def __init__(self): self.h = [] def parent(self, index): # Returns parent index for given index if index > 0: return (index - 1) // 2 def lchild(self, index): # Returns left child index for given index return (2 * index) + 1 def rchild(self, index): # Returns right child index for given index return (2 * index) + 2 def addItem(self, item): # Function to add an item to heap self.h.append(item) if len(self.h) == 1: # If heap has only one item no need to heapify return index = len(self.h) - 1 parent = self.parent(index) # Moves the item up if it is smaller than the parent while index > 0 and item < self.h[parent]: self.h[index], self.h[parent] = self.h[parent], self.h[parent] index = parent parent = self.parent(index) def deleteItem(self): # Function to add an item to heap length = len(self.h) self.h[0], self.h[length-1] = self.h[length-1], self.h[0] deleted = self.h.pop() # Since root will be violating heap property # Call moveDownHeapify() to restore heap property self.moveDownHeapify(0) return deleted def moveDownHeapify(self, index): # Function to make the items follow Heap property # Compares the value with the children and moves item down lc, rc = self.lchild(index), self.rchild(index) length, smallest = len(self.h), index if lc < length and self.h[lc] <= self.h[smallest]: smallest = lc if rc < length and self.h[rc] <= self.h[smallest]: smallest = rc if smallest != index: # Swaps the parent node with the smaller child self.h[smallest], self.h[index] = self.h[index], self.h[smallest] # Recursive call to compare next subtree self.moveDownHeapify(smallest) def increaseItem(self, index, value): # Increase the value of 'index' to 'value' if value <= self.h[index]: return self.h[index] = value self.moveDownHeapify(index) class OptimalMergePattern(): def __init__(self, n, items): self.n = n self.items = items self.heap = Heap() def optimalMerge(self): # Corner cases if list has no more than 1 item if self.n <= 0: return 0 if self.n == 1: return self.items[0] # Insert items into min heap for _ in self.items: self.heap.addItem(_) count = 0 while len(self.heap.h) != 1: tmp = self.heap.deleteItem() count += (tmp + self.heap.h[0]) self.heap.increaseItem(0, tmp + self.heap.h[0]) return count # Driver Codeif __name__ == '__main__': OMP = OptimalMergePattern(6, [2, 3, 4, 5, 6, 7]) ans = OMP.optimalMerge() print(ans) # This code is contributed by Rajat Gupta", "e": 8781, "s": 5683, "text": null }, { "code": null, "e": 8807, "s": 8781, "text": "Minimum Computations = 68" }, { "code": null, "e": 8854, "s": 8807, "text": "Time Complexity: O(nlogn)Auxiliary Space: O(n)" }, { "code": null, "e": 8867, "s": 8854, "text": "jaigoyal1328" }, { "code": null, "e": 8884, "s": 8867, "text": "akshaysingh98088" }, { "code": null, "e": 8901, "s": 8884, "text": "rajatscientist51" }, { "code": null, "e": 8915, "s": 8901, "text": "geeky01adarsh" }, { "code": null, "e": 8925, "s": 8915, "text": "sanskar84" }, { "code": null, "e": 8944, "s": 8925, "text": "java-file-handling" }, { "code": null, "e": 8951, "s": 8944, "text": "Greedy" }, { "code": null, "e": 8958, "s": 8951, "text": "Greedy" } ]
Perl | ne operator
07 May, 2019 ‘ne‘ operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise not equal to the string to its right. Syntax: String1 ne String2 Returns: 1 if left argument is not equal to the right argument Example 1: #!/usr/local/bin/perl # Initializing Strings$a = "Welcome";$b = "Geeks"; # Comparing the strings using ne operator$c = $a ne $b; if($c == 1){ print"String1 is not equal to String2";}else{ print"String1 is equal to String2";} String1 is not equal to String2 Example 2: #!/usr/local/bin/perl # Initializing Strings$a = "Geeks";$b = "Geeks"; # Comparing the strings using ne operator$c = $a ne $b; if($c == 1){ print"String1 is not equal to String2";}else{ print"String1 is equal to String2";} String1 is equal to String2 perl-operators Perl-String-Operators Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 May, 2019" }, { "code": null, "e": 241, "s": 28, "text": "‘ne‘ operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise not equal to the string to its right." }, { "code": null, "e": 268, "s": 241, "text": "Syntax: String1 ne String2" }, { "code": null, "e": 331, "s": 268, "text": "Returns: 1 if left argument is not equal to the right argument" }, { "code": null, "e": 342, "s": 331, "text": "Example 1:" }, { "code": "#!/usr/local/bin/perl # Initializing Strings$a = \"Welcome\";$b = \"Geeks\"; # Comparing the strings using ne operator$c = $a ne $b; if($c == 1){ print\"String1 is not equal to String2\";}else{ print\"String1 is equal to String2\";}", "e": 576, "s": 342, "text": null }, { "code": null, "e": 609, "s": 576, "text": "String1 is not equal to String2\n" }, { "code": null, "e": 620, "s": 609, "text": "Example 2:" }, { "code": "#!/usr/local/bin/perl # Initializing Strings$a = \"Geeks\";$b = \"Geeks\"; # Comparing the strings using ne operator$c = $a ne $b; if($c == 1){ print\"String1 is not equal to String2\";}else{ print\"String1 is equal to String2\";}", "e": 852, "s": 620, "text": null }, { "code": null, "e": 881, "s": 852, "text": "String1 is equal to String2\n" }, { "code": null, "e": 896, "s": 881, "text": "perl-operators" }, { "code": null, "e": 918, "s": 896, "text": "Perl-String-Operators" }, { "code": null, "e": 923, "s": 918, "text": "Perl" }, { "code": null, "e": 928, "s": 923, "text": "Perl" } ]
Python | Ways to find indices of value in list
30 Nov, 2018 Usually, we require to find the index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list. Let’s discuss certain ways to find indices of value in given list. Method #1 : Naive Method We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. # Python3 code to demonstrate # finding indices of values# using naive method # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print ("Original list : " + str(test_list)) # using naive method# to find indices for 3res_list = []for i in range(0, len(test_list)) : if test_list[i] == 3 : res_list.append(i) # printing resultant list print ("New indices list : " + str(res_list)) Original list : [1, 3, 4, 3, 6, 7] New indices list : [1, 3] Method #2 : Using list comprehension List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time. # Python3 code to demonstrate # finding indices of values# using list comprehension # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print ("Original list : " + str(test_list)) # using list comprehension# to find indices for 3res_list = [i for i in range(len(test_list)) if test_list[i] == 3] # printing resultant list print ("New indices list : " + str(res_list)) Original list : [1, 3, 4, 3, 6, 7] New indices list : [1, 3] Method #3 : Using enumerate()Using enumerate() we can achieve the similar task, this is slightly faster technique than above and hence is recommended to be used over the list comprehension technique. # Python3 code to demonstrate # finding indices of values# using enumerate() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print ("Original list : " + str(test_list)) # using enumerate()# to find indices for 3res_list = [i for i, value in enumerate(test_list) if value == 3] # printing resultant list print ("New indices list : " + str(res_list)) Original list : [1, 3, 4, 3, 6, 7] New indices list : [1, 3] Method #4 : Using filter() This is yet another method that can be employed to achieve this particular task, filter() usually is able to perform the filtering tasks and hence can also be used in this situation to achieve this task. # Python3 code to demonstrate # finding indices of values# using filter() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print ("Original list : " + str(test_list)) # using filter()# to find indices for 3res_list = list(filter(lambda x: test_list[x] == 3, range(len(test_list)))) # printing resultant list print ("New indices list : " + str(res_list)) Original list : [1, 3, 4, 3, 6, 7] New indices list : [1, 3] Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2018" }, { "code": null, "e": 280, "s": 28, "text": "Usually, we require to find the index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list." }, { "code": null, "e": 347, "s": 280, "text": "Let’s discuss certain ways to find indices of value in given list." }, { "code": null, "e": 372, "s": 347, "text": "Method #1 : Naive Method" }, { "code": null, "e": 571, "s": 372, "text": "We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task." }, { "code": "# Python3 code to demonstrate # finding indices of values# using naive method # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using naive method# to find indices for 3res_list = []for i in range(0, len(test_list)) : if test_list[i] == 3 : res_list.append(i) # printing resultant list print (\"New indices list : \" + str(res_list))", "e": 999, "s": 571, "text": null }, { "code": null, "e": 1061, "s": 999, "text": "Original list : [1, 3, 4, 3, 6, 7]\nNew indices list : [1, 3]\n" }, { "code": null, "e": 1099, "s": 1061, "text": " Method #2 : Using list comprehension" }, { "code": null, "e": 1269, "s": 1099, "text": "List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time." }, { "code": "# Python3 code to demonstrate # finding indices of values# using list comprehension # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using list comprehension# to find indices for 3res_list = [i for i in range(len(test_list)) if test_list[i] == 3] # printing resultant list print (\"New indices list : \" + str(res_list))", "e": 1673, "s": 1269, "text": null }, { "code": null, "e": 1735, "s": 1673, "text": "Original list : [1, 3, 4, 3, 6, 7]\nNew indices list : [1, 3]\n" }, { "code": null, "e": 1936, "s": 1735, "text": " Method #3 : Using enumerate()Using enumerate() we can achieve the similar task, this is slightly faster technique than above and hence is recommended to be used over the list comprehension technique." }, { "code": "# Python3 code to demonstrate # finding indices of values# using enumerate() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using enumerate()# to find indices for 3res_list = [i for i, value in enumerate(test_list) if value == 3] # printing resultant list print (\"New indices list : \" + str(res_list))", "e": 2325, "s": 1936, "text": null }, { "code": null, "e": 2387, "s": 2325, "text": "Original list : [1, 3, 4, 3, 6, 7]\nNew indices list : [1, 3]\n" }, { "code": null, "e": 2415, "s": 2387, "text": " Method #4 : Using filter()" }, { "code": null, "e": 2619, "s": 2415, "text": "This is yet another method that can be employed to achieve this particular task, filter() usually is able to perform the filtering tasks and hence can also be used in this situation to achieve this task." }, { "code": "# Python3 code to demonstrate # finding indices of values# using filter() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using filter()# to find indices for 3res_list = list(filter(lambda x: test_list[x] == 3, range(len(test_list)))) # printing resultant list print (\"New indices list : \" + str(res_list))", "e": 3012, "s": 2619, "text": null }, { "code": null, "e": 3074, "s": 3012, "text": "Original list : [1, 3, 4, 3, 6, 7]\nNew indices list : [1, 3]\n" }, { "code": null, "e": 3095, "s": 3074, "text": "Python list-programs" }, { "code": null, "e": 3107, "s": 3095, "text": "python-list" }, { "code": null, "e": 3114, "s": 3107, "text": "Python" }, { "code": null, "e": 3126, "s": 3114, "text": "python-list" } ]
How to Install Boost Library in C++ on Linux?
16 Oct, 2021 Boost is a set of libraries for the C++ programming language. It contains 164 individual libraries. It was initially released on September 1, 1999. Furthermore, it provides support for many tasks such as pseudo-random number generation, linear algebra, multithreading, image processing, regular expressions, and unit testing. In this article, we are going to learn how we can install a boost library in C++ on Linux. To install the boost library on your Linux, run the following command in your Linux terminal. sudo apt-get install libboost-all-dev installing the boost library Confirm the installation by pressing y from the keyword. This will confirm that the user wants to install the above-listed packages. In this sample program, we are going to create an array using the boost library. For that, we have to include the boost’s array header file into our CPP program. Code: C++ #include <boost/array.hpp>#include <iostream> using namespace std;int main(){ boost::array<int, 10> arr = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; for (int i = 0; i < 10; i++) { cout << "Geek Rank is :" << arr[i] << "*" << "\n"; } return 0;} Geek Rank is :1* Geek Rank is :2* Geek Rank is :3* Geek Rank is :4* Geek Rank is :5* Geek Rank is :6* Geek Rank is :7* Geek Rank is :8* Geek Rank is :9* Geek Rank is :10* how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2021" }, { "code": null, "e": 445, "s": 28, "text": "Boost is a set of libraries for the C++ programming language. It contains 164 individual libraries. It was initially released on September 1, 1999. Furthermore, it provides support for many tasks such as pseudo-random number generation, linear algebra, multithreading, image processing, regular expressions, and unit testing. In this article, we are going to learn how we can install a boost library in C++ on Linux." }, { "code": null, "e": 539, "s": 445, "text": "To install the boost library on your Linux, run the following command in your Linux terminal." }, { "code": null, "e": 577, "s": 539, "text": "sudo apt-get install libboost-all-dev" }, { "code": null, "e": 606, "s": 577, "text": "installing the boost library" }, { "code": null, "e": 739, "s": 606, "text": "Confirm the installation by pressing y from the keyword. This will confirm that the user wants to install the above-listed packages." }, { "code": null, "e": 901, "s": 739, "text": "In this sample program, we are going to create an array using the boost library. For that, we have to include the boost’s array header file into our CPP program." }, { "code": null, "e": 907, "s": 901, "text": "Code:" }, { "code": null, "e": 911, "s": 907, "text": "C++" }, { "code": "#include <boost/array.hpp>#include <iostream> using namespace std;int main(){ boost::array<int, 10> arr = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; for (int i = 0; i < 10; i++) { cout << \"Geek Rank is :\" << arr[i] << \"*\" << \"\\n\"; } return 0;}", "e": 1190, "s": 911, "text": null }, { "code": null, "e": 1361, "s": 1190, "text": "Geek Rank is :1*\nGeek Rank is :2*\nGeek Rank is :3*\nGeek Rank is :4*\nGeek Rank is :5*\nGeek Rank is :6*\nGeek Rank is :7*\nGeek Rank is :8*\nGeek Rank is :9*\nGeek Rank is :10*" }, { "code": null, "e": 1376, "s": 1361, "text": "how-to-install" }, { "code": null, "e": 1383, "s": 1376, "text": "Picked" }, { "code": null, "e": 1390, "s": 1383, "text": "How To" }, { "code": null, "e": 1409, "s": 1390, "text": "Installation Guide" } ]
Forecasting Football Scores in R | Towards Data Science
In one of my earlier posts, I mentioned that the scores in a football match can be approximated somewhat using the Poisson distribution, but I didn’t go too much into the topic. Well, you’re in luck today... we’re going to have a look at the subject, and by the end of this post we’ll have Ggplot2 visual illustrating the likely scores of a football match, which really is excellent. First off, a little bit on the roots of the Poisson distribution. The discovery of this probability distribution is attributed to Siméon Denis Poisson, a French mathematician from the nineteenth century. Like many of his contemporaries at the time, he dealt mainly with its theories. It wasn’t until Russian statistician Ladislaus Bortkiewicz published his book The Law of Small Numbers in 1898 that the Poisson distribution became widely used in practice. Bortkiewicz famously had access to a data set of the Prussian army over a period of 20 years which recorded the number of soldiers that were killed by their horses’ kicks. Grim. Anyway, he showed that these deaths could be approximated by the Poisson distribution, and the rest, as they say, is history. Now... how does one go from Prussian cavalry to football scores? Let’s first have a look at the basic assumptions that satisfy a Poisson process: The probability of an event occurring in a given time interval does not vary with timeThe events occur at randomThe events occur independently The probability of an event occurring in a given time interval does not vary with time The events occur at random The events occur independently Now think of goals as an event in a football match. If we had a metric that could express a team’s scoring rate/intensity over 90 minutes, we can say that the first assumption is satisfied. This would’ve been a pain in the arse to define, but thankfully the sports nerds (people a hundred times more intelligent than me, I should add) have come up with expected goals (xG) for this. Thanks for today! Next question- do goals occur randomly in a football match? That is to say, is there a particular point in time in a match when goals are more likely to be scored? This guy says no, and many other articles and studies also suggest that goals do occur at random in a football match. In practice, goals might not be as random as one might think but... we have enough evidence to argue that they are, so let’s tick that box and move on for now. Now for the final assumption- that being, goals are independent of one another. If a team is behind, surely the players are working harder to get back into the game to score an equaliser. Or perhaps if a team is already leading by 5 goals, the players might take their foot off the gas and let one in due to complacency. Either way, you have to say that goals don’t occur independently of one another, and using a basic Poisson process to model football scores starts to break down here. There are techniques to adjust for goal dependencies in a match, but we all have day jobs- so let’s leave that for another day... and agree for now that two out of three isn’t bad (also, I’m pushing to generate useful content innit, so here we are). For further reading, I suggest having a look at this fantastic blog post that has basically done a Bortkiewicz for football, showing you can approximate the number goals scored over a season with the Poisson distribution. In my previous post on xG, I created a simple Poisson model to help predict the outcomes of a football match (home win, draw, away win) in R. We’re going to use something similar here, but focus more on obtaining the probabilities of the correct scores as an output. R has come a long way from its base heat map libraries which haven’t aged too well. Ggplot2 is a fantastic package which allows for all sorts of graphs and charts to be built. In order to use them, we have to first install some dependencies in RStudio: install.packages('tidyr')install.packages('dplyr')install.packages('scales')install.packages('ggplot2')library('tidyr')library('dplyr')library('scales')library('ggplot2') Cool, now let’s go back to one of our original assumptions- that teams have a constant scoring rate over 90 minutes in a football match. We’ll be using the shot-based xG taken from FiveThirtyEight’s model for the Champions League quarter-final between Barcelona and Bayern Munich (oh boy...). Let’s construct and source a ScoreGrid: We’ve created a data frame with 11 columns and 11 rows, each entry representing a correct score. So the entry in [row i , column j] is going to be the score i,j with i being the home score and j as the away score. Hence entry [1,2] is going to be a 2–1 win for the away team. dpois helps to generate a random Poisson probability for each score i, given the homeXg and awayXg. Finally, we cap the individual scores at 9, and once we get to 10 we’re going to sum the probabilities together and group them as a single entry. It just makes things easier. Let’s give it a quick spin. In the RStudio console, type ScoreGrid(1.7,1.1) and you should get this: Nice grid, but not too easy on the eye. Let’s build the correct score visual now. We’re going to use geom_tile() in Ggplot2, which generates a nice heat map at the end. Here’s the code: Ggplot2 requires the input data to be a tidy dataframe, so the conversion from base R data.frame takes place on line 10 with pivot_longer. Next, we’ll need to convert all our vars to factors and sort the levels in the correct order (remember that 10+ is a factor, using as.numeric will just cause it to become an NA. We want it to be the final level in the list). This is done on line 14 with ~forcats::fct_relevel. Everything beyond that just contains the usual building blocks of a Ggplot2 graph. Right, here we go. Fire up the R console and enter the team names and xG inputs from wherever your source was from: ScoreHeatMap("Barcelona", "Bayern_Munich", 1.2, 5.6, "FiveThirtyEight") Men against boys in this match, and just by looking at the visualisation/heat map you can see the most likely score would have been 5–1 to Bayern Munich based on xG. In reality, Bayern actually won 8–2. Robert Lewangoalski indeed. One more to illustrate a closer match, yesterday evening’s Champions League final between Paris Saint-Germain and Bayern Munich: ScoreHeatMap("Paris_SG", "Bayern_Munich", 1.4,1.6,"FiveThirtyEight") A much tighter match, with 1–1 being the most probable score- Bayern Munich actually won 1–0. As always there are several caveats, one of which we’ve already discussed- namely that goals aren’t independent of one another, so the model is worth revisiting. Also, if any one of those xG chances had a different result (i.e. a shot hit the post or went wide instead of going in), we likely wouldn’t be here speaking about this today... Let’s not forget too how xG itself is a flawed metric which doesn’t capture a lot of the nuances within a football match. Still, these visuals are a nice representation of how a match might have turned out- if anything, it’s a good exercise in using some of the impressive R libraries for graphics and visualisation. As usual, you can nick all of this on my Github repository if I struggled to make any sense. Cheers for today...
[ { "code": null, "e": 556, "s": 172, "text": "In one of my earlier posts, I mentioned that the scores in a football match can be approximated somewhat using the Poisson distribution, but I didn’t go too much into the topic. Well, you’re in luck today... we’re going to have a look at the subject, and by the end of this post we’ll have Ggplot2 visual illustrating the likely scores of a football match, which really is excellent." }, { "code": null, "e": 1014, "s": 556, "text": "First off, a little bit on the roots of the Poisson distribution. The discovery of this probability distribution is attributed to Siméon Denis Poisson, a French mathematician from the nineteenth century. Like many of his contemporaries at the time, he dealt mainly with its theories. It wasn’t until Russian statistician Ladislaus Bortkiewicz published his book The Law of Small Numbers in 1898 that the Poisson distribution became widely used in practice." }, { "code": null, "e": 1192, "s": 1014, "text": "Bortkiewicz famously had access to a data set of the Prussian army over a period of 20 years which recorded the number of soldiers that were killed by their horses’ kicks. Grim." }, { "code": null, "e": 1318, "s": 1192, "text": "Anyway, he showed that these deaths could be approximated by the Poisson distribution, and the rest, as they say, is history." }, { "code": null, "e": 1383, "s": 1318, "text": "Now... how does one go from Prussian cavalry to football scores?" }, { "code": null, "e": 1464, "s": 1383, "text": "Let’s first have a look at the basic assumptions that satisfy a Poisson process:" }, { "code": null, "e": 1607, "s": 1464, "text": "The probability of an event occurring in a given time interval does not vary with timeThe events occur at randomThe events occur independently" }, { "code": null, "e": 1694, "s": 1607, "text": "The probability of an event occurring in a given time interval does not vary with time" }, { "code": null, "e": 1721, "s": 1694, "text": "The events occur at random" }, { "code": null, "e": 1752, "s": 1721, "text": "The events occur independently" }, { "code": null, "e": 2153, "s": 1752, "text": "Now think of goals as an event in a football match. If we had a metric that could express a team’s scoring rate/intensity over 90 minutes, we can say that the first assumption is satisfied. This would’ve been a pain in the arse to define, but thankfully the sports nerds (people a hundred times more intelligent than me, I should add) have come up with expected goals (xG) for this. Thanks for today!" }, { "code": null, "e": 2595, "s": 2153, "text": "Next question- do goals occur randomly in a football match? That is to say, is there a particular point in time in a match when goals are more likely to be scored? This guy says no, and many other articles and studies also suggest that goals do occur at random in a football match. In practice, goals might not be as random as one might think but... we have enough evidence to argue that they are, so let’s tick that box and move on for now." }, { "code": null, "e": 3083, "s": 2595, "text": "Now for the final assumption- that being, goals are independent of one another. If a team is behind, surely the players are working harder to get back into the game to score an equaliser. Or perhaps if a team is already leading by 5 goals, the players might take their foot off the gas and let one in due to complacency. Either way, you have to say that goals don’t occur independently of one another, and using a basic Poisson process to model football scores starts to break down here." }, { "code": null, "e": 3555, "s": 3083, "text": "There are techniques to adjust for goal dependencies in a match, but we all have day jobs- so let’s leave that for another day... and agree for now that two out of three isn’t bad (also, I’m pushing to generate useful content innit, so here we are). For further reading, I suggest having a look at this fantastic blog post that has basically done a Bortkiewicz for football, showing you can approximate the number goals scored over a season with the Poisson distribution." }, { "code": null, "e": 3822, "s": 3555, "text": "In my previous post on xG, I created a simple Poisson model to help predict the outcomes of a football match (home win, draw, away win) in R. We’re going to use something similar here, but focus more on obtaining the probabilities of the correct scores as an output." }, { "code": null, "e": 4075, "s": 3822, "text": "R has come a long way from its base heat map libraries which haven’t aged too well. Ggplot2 is a fantastic package which allows for all sorts of graphs and charts to be built. In order to use them, we have to first install some dependencies in RStudio:" }, { "code": null, "e": 4246, "s": 4075, "text": "install.packages('tidyr')install.packages('dplyr')install.packages('scales')install.packages('ggplot2')library('tidyr')library('dplyr')library('scales')library('ggplot2')" }, { "code": null, "e": 4579, "s": 4246, "text": "Cool, now let’s go back to one of our original assumptions- that teams have a constant scoring rate over 90 minutes in a football match. We’ll be using the shot-based xG taken from FiveThirtyEight’s model for the Champions League quarter-final between Barcelona and Bayern Munich (oh boy...). Let’s construct and source a ScoreGrid:" }, { "code": null, "e": 5130, "s": 4579, "text": "We’ve created a data frame with 11 columns and 11 rows, each entry representing a correct score. So the entry in [row i , column j] is going to be the score i,j with i being the home score and j as the away score. Hence entry [1,2] is going to be a 2–1 win for the away team. dpois helps to generate a random Poisson probability for each score i, given the homeXg and awayXg. Finally, we cap the individual scores at 9, and once we get to 10 we’re going to sum the probabilities together and group them as a single entry. It just makes things easier." }, { "code": null, "e": 5187, "s": 5130, "text": "Let’s give it a quick spin. In the RStudio console, type" }, { "code": null, "e": 5206, "s": 5187, "text": "ScoreGrid(1.7,1.1)" }, { "code": null, "e": 5231, "s": 5206, "text": "and you should get this:" }, { "code": null, "e": 5271, "s": 5231, "text": "Nice grid, but not too easy on the eye." }, { "code": null, "e": 5417, "s": 5271, "text": "Let’s build the correct score visual now. We’re going to use geom_tile() in Ggplot2, which generates a nice heat map at the end. Here’s the code:" }, { "code": null, "e": 5916, "s": 5417, "text": "Ggplot2 requires the input data to be a tidy dataframe, so the conversion from base R data.frame takes place on line 10 with pivot_longer. Next, we’ll need to convert all our vars to factors and sort the levels in the correct order (remember that 10+ is a factor, using as.numeric will just cause it to become an NA. We want it to be the final level in the list). This is done on line 14 with ~forcats::fct_relevel. Everything beyond that just contains the usual building blocks of a Ggplot2 graph." }, { "code": null, "e": 6032, "s": 5916, "text": "Right, here we go. Fire up the R console and enter the team names and xG inputs from wherever your source was from:" }, { "code": null, "e": 6104, "s": 6032, "text": "ScoreHeatMap(\"Barcelona\", \"Bayern_Munich\", 1.2, 5.6, \"FiveThirtyEight\")" }, { "code": null, "e": 6335, "s": 6104, "text": "Men against boys in this match, and just by looking at the visualisation/heat map you can see the most likely score would have been 5–1 to Bayern Munich based on xG. In reality, Bayern actually won 8–2. Robert Lewangoalski indeed." }, { "code": null, "e": 6464, "s": 6335, "text": "One more to illustrate a closer match, yesterday evening’s Champions League final between Paris Saint-Germain and Bayern Munich:" }, { "code": null, "e": 6533, "s": 6464, "text": "ScoreHeatMap(\"Paris_SG\", \"Bayern_Munich\", 1.4,1.6,\"FiveThirtyEight\")" }, { "code": null, "e": 6627, "s": 6533, "text": "A much tighter match, with 1–1 being the most probable score- Bayern Munich actually won 1–0." }, { "code": null, "e": 7088, "s": 6627, "text": "As always there are several caveats, one of which we’ve already discussed- namely that goals aren’t independent of one another, so the model is worth revisiting. Also, if any one of those xG chances had a different result (i.e. a shot hit the post or went wide instead of going in), we likely wouldn’t be here speaking about this today... Let’s not forget too how xG itself is a flawed metric which doesn’t capture a lot of the nuances within a football match." }, { "code": null, "e": 7283, "s": 7088, "text": "Still, these visuals are a nice representation of how a match might have turned out- if anything, it’s a good exercise in using some of the impressive R libraries for graphics and visualisation." } ]
Node.js path.parse() Method - GeeksforGeeks
13 Oct, 2021 The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties: root (root name) dir (directory name) base (filename with extension) ext (only extension) name (only filename) The values of these properties may be different for every platform. It ignores the platform’s trailing directory separators during parsing. Syntax: path.parse( path ) Parameters: This method accepts single parameter path which holds the file path that would be parsed by the method. It throws a TypeError if this parameter is not a string value. Return Value: This method returns an object with the details of the path. Below examples illustrate the path.parse() method in node.js: Example 1: On POSIX // Node.js program to demonstrate the // path.parse() method // Import the path moduleconst path = require('path'); path1 = path.parse("/users/admin/website/index.html");console.log(path1); path2 = path.parse("website/readme.md");console.log(path2); Output: { root: '/', dir: '/users/admin/website', base: 'index.html', ext: '.html', name: 'index' } { root: '', dir: 'website', base: 'readme.md', ext: '.md', name: 'readme' } Example 2: On Windows // Node.js program to demonstrate the // path.parse() method // Import the path moduleconst path = require('path'); path1 = path.parse("C:\\users\\admin\\website\\index.html");console.log(path1); path2 = path.parse("website\\style.css");console.log(path2); Output: { root: 'C:\\', dir: 'C:\\users\\admin\\website', base: 'index.html', ext: '.html', name: 'index' } { root: '', dir: 'website', base: 'style.css', ext: '.css', name: 'style' } Reference: https://nodejs.org/api/path.html#path_path_parse_path Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method How to update NPM ? Difference between promise and async await in Node.js Express.js express.Router() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37176, "s": 37148, "text": "\n13 Oct, 2021" }, { "code": null, "e": 37317, "s": 37176, "text": "The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties:" }, { "code": null, "e": 37334, "s": 37317, "text": "root (root name)" }, { "code": null, "e": 37355, "s": 37334, "text": "dir (directory name)" }, { "code": null, "e": 37386, "s": 37355, "text": "base (filename with extension)" }, { "code": null, "e": 37407, "s": 37386, "text": "ext (only extension)" }, { "code": null, "e": 37428, "s": 37407, "text": "name (only filename)" }, { "code": null, "e": 37568, "s": 37428, "text": "The values of these properties may be different for every platform. It ignores the platform’s trailing directory separators during parsing." }, { "code": null, "e": 37576, "s": 37568, "text": "Syntax:" }, { "code": null, "e": 37595, "s": 37576, "text": "path.parse( path )" }, { "code": null, "e": 37774, "s": 37595, "text": "Parameters: This method accepts single parameter path which holds the file path that would be parsed by the method. It throws a TypeError if this parameter is not a string value." }, { "code": null, "e": 37848, "s": 37774, "text": "Return Value: This method returns an object with the details of the path." }, { "code": null, "e": 37910, "s": 37848, "text": "Below examples illustrate the path.parse() method in node.js:" }, { "code": null, "e": 37930, "s": 37910, "text": "Example 1: On POSIX" }, { "code": "// Node.js program to demonstrate the // path.parse() method // Import the path moduleconst path = require('path'); path1 = path.parse(\"/users/admin/website/index.html\");console.log(path1); path2 = path.parse(\"website/readme.md\");console.log(path2);", "e": 38187, "s": 37930, "text": null }, { "code": null, "e": 38195, "s": 38187, "text": "Output:" }, { "code": null, "e": 38383, "s": 38195, "text": "{\n root: '/',\n dir: '/users/admin/website',\n base: 'index.html',\n ext: '.html',\n name: 'index'\n}\n{\n root: '',\n dir: 'website',\n base: 'readme.md',\n ext: '.md',\n name: 'readme'\n}" }, { "code": null, "e": 38405, "s": 38383, "text": "Example 2: On Windows" }, { "code": "// Node.js program to demonstrate the // path.parse() method // Import the path moduleconst path = require('path'); path1 = path.parse(\"C:\\\\users\\\\admin\\\\website\\\\index.html\");console.log(path1); path2 = path.parse(\"website\\\\style.css\");console.log(path2);", "e": 38669, "s": 38405, "text": null }, { "code": null, "e": 38677, "s": 38669, "text": "Output:" }, { "code": null, "e": 38873, "s": 38677, "text": "{\n root: 'C:\\\\',\n dir: 'C:\\\\users\\\\admin\\\\website',\n base: 'index.html',\n ext: '.html',\n name: 'index'\n}\n{\n root: '',\n dir: 'website',\n base: 'style.css',\n ext: '.css',\n name: 'style'\n}" }, { "code": null, "e": 38938, "s": 38873, "text": "Reference: https://nodejs.org/api/path.html#path_path_parse_path" }, { "code": null, "e": 38954, "s": 38938, "text": "Node.js-Methods" }, { "code": null, "e": 38962, "s": 38954, "text": "Node.js" }, { "code": null, "e": 38979, "s": 38962, "text": "Web Technologies" }, { "code": null, "e": 39077, "s": 38979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39086, "s": 39077, "text": "Comments" }, { "code": null, "e": 39099, "s": 39086, "text": "Old Comments" }, { "code": null, "e": 39136, "s": 39099, "text": "Express.js express.Router() Function" }, { "code": null, "e": 39184, "s": 39136, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39217, "s": 39184, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 39237, "s": 39217, "text": "How to update NPM ?" }, { "code": null, "e": 39291, "s": 39237, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 39328, "s": 39291, "text": "Express.js express.Router() Function" }, { "code": null, "e": 39390, "s": 39328, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39433, "s": 39390, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 39494, "s": 39433, "text": "Difference between var, let and const keywords in JavaScript" } ]
Accessing every row and column of array in Julia - colon() Operator - GeeksforGeeks
20 Jul, 2021 The Colon() is an inbuilt operator in julia which is used to indicate and access every row and column. And also this operator is used to get index of specific element in the specified array.Example 1: Python # Julia program to illustrate# the use of Colon (:) operator # Indicating every row and columnArray1 = [1 2 "Hello"; 3 4 "Geeks"]println(Array1[:, 3])println(Array1[1, :]) Output: Example 2: Python # Julia program to illustrate# the use of Colon (:) operator # Accessing every row and columnArray1 = cat([1 2; 3 4], ["hello" "Geeks"; "Welcome" "GFG"], [5 6; 7 8], dims = 3)println(Array1[:, :, 3]) # Using getindex with colon operatorprintln(getindex(Array1, 1, :, 2)) Output: simmytarika5 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Searching in Array for a given element in Julia Get array dimensions and size of a dimension in Julia - size() Method Get number of elements of array in Julia - length() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Getting the maximum value from a list in Julia - max() Method Find maximum element along with its index in Julia - findmax() Method Exception handling in Julia Getting the absolute value of a number in Julia - abs() Method Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods Working with Date and Time in Julia
[ { "code": null, "e": 24544, "s": 24516, "text": "\n20 Jul, 2021" }, { "code": null, "e": 24747, "s": 24544, "text": "The Colon() is an inbuilt operator in julia which is used to indicate and access every row and column. And also this operator is used to get index of specific element in the specified array.Example 1: " }, { "code": null, "e": 24754, "s": 24747, "text": "Python" }, { "code": "# Julia program to illustrate# the use of Colon (:) operator # Indicating every row and columnArray1 = [1 2 \"Hello\"; 3 4 \"Geeks\"]println(Array1[:, 3])println(Array1[1, :])", "e": 24926, "s": 24754, "text": null }, { "code": null, "e": 24936, "s": 24926, "text": "Output: " }, { "code": null, "e": 24949, "s": 24936, "text": "Example 2: " }, { "code": null, "e": 24956, "s": 24949, "text": "Python" }, { "code": "# Julia program to illustrate# the use of Colon (:) operator # Accessing every row and columnArray1 = cat([1 2; 3 4], [\"hello\" \"Geeks\"; \"Welcome\" \"GFG\"], [5 6; 7 8], dims = 3)println(Array1[:, :, 3]) # Using getindex with colon operatorprintln(getindex(Array1, 1, :, 2))", "e": 25255, "s": 24956, "text": null }, { "code": null, "e": 25265, "s": 25255, "text": "Output: " }, { "code": null, "e": 25280, "s": 25267, "text": "simmytarika5" }, { "code": null, "e": 25286, "s": 25280, "text": "Julia" }, { "code": null, "e": 25384, "s": 25286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25432, "s": 25384, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 25502, "s": 25432, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 25561, "s": 25502, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 25634, "s": 25561, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 25696, "s": 25634, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 25766, "s": 25696, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 25794, "s": 25766, "text": "Exception handling in Julia" }, { "code": null, "e": 25857, "s": 25794, "text": "Getting the absolute value of a number in Julia - abs() Method" }, { "code": null, "e": 25938, "s": 25857, "text": "Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods" } ]
All You Need to Know About Pandas Cut and Qcut Functions | by Soner Yıldırım | Towards Data Science
Pandas is arguably the most popular data analysis and manipulation tool in the data science ecosystem. Thanks to the numerous functions and methods, we can play around with data freely. The cut and qcut functions come in quite handy for many cases. The difference between them was not clear to me at first. I was able to figure it out after doing several examples. In this article, we will do the same. The examples in this article will demonstrate how to use the cut and qcut functions and also emphasize the difference between them. Let’s start with creating a sample data frame. import numpy as npimport pandas as pddf = pd.DataFrame({ "col_a": np.random.randint(1, 50, size=50), "col_b": np.random.randint(20, 100, size=50), "col_c": np.random.random(size=50).round(2)})df.head() The first and second columns contain integers between 1-50 and 20–100, respectively. The third column contains floats between 0 and 1. We have used numpy functions to generate these values randomly. The cut function divides the entire value range into bins. The range covered by each bin will be the same. In the first column (col_a), we randomly assign integers between 1 and 50. Let’s first check the minimum and maximum values in this column. df.col_a.max(), df.col_a.min()(49, 3) If you want to divide this column into 5 bins of equal range, the size of each bin will be 9.2 which can be calculated as follows: (49 - 3) / 5 = 9.2 The cut function performs this binning operation and then assign each value in the appropriate bin. df["col_a_binned"] = pd.cut(df.col_a, bins=5)df.col_a_binned.value_counts()(21.4, 30.6] 16 (39.8, 49.0] 14 (12.2, 21.4] 8 (30.6, 39.8] 6 (2.954, 12.2] 6 As we can see, the size of each bin is exactly 9.2 expect for the smallest one. The lower bounds are not inclusive. Thus, the lower bound of the smallest bin is a little less than the smallest value (3) to be able to include it. We can customize the bins by defining the bin edges manually. The edge values are passed to the bins parameter as a list. pd.cut(df.col_a, bins=[0, 10, 40, 50]).value_counts()(10, 40] 33 (40, 50] 13 (0, 10] 4 The right edges are inclusive by default but it can be changed. pd.cut(df.col_a, bins=[0, 10, 40, 50], right=False).value_counts()[10, 40) 33 [40, 50) 13 [0, 10) 4 With the cut function, we do not have any control over how many values fall into each bin. We can only specify the bin edges. This is where we need to learn about the qcut function. It can be used to divide the values into buckets in a way that each bucket contains approximately the same number of values. Let’s start with an example. pd.qcut(df.col_a, q=4).value_counts()(40.75, 49.0] 13 (19.5, 25.0] 13 (2.999, 19.5] 13 (25.0, 40.75] 11 We have 4 buckets and each one contains almost the same number of values. In case of 4, the buckets are also called quartiles. One quarter of the total number of values are in the first quartile, one half are in the first two buckets, and so on. With the qcut function, we do not have any control over the bin edges. They are calculated automatically. Consider there are 40 values (i.e. rows) in a column and we want to have 4 buckets. Starting from the smallest value, the upper range of the first bucket will be determined in a way that the first bucket contains 10 values. Cut function: The focus is on the size of bins in terms of the value range (i.e. the difference between the upper and lower bin edges) Qcut function: The focus is on the size of bins in terms of the number of values in each bin. The qcut function allows for customizing the bucket sizes. Let’s create 3 buckets. The first one contains the smallest 50 percent of values (i.e. lower half). Then, we divide the upper half into two bins. pd.qcut(df.col_a, q=[0, .50, .75, 1]).value_counts()(2.999, 25.0] 26 (40.75, 49.0] 13 (25.0, 40.75] 11 Both the cut and qcut functions allow for labelling the bins or buckets. We use the labels parameter as follows. df["new"] = pd.qcut(df.col_a, q=[0, .33, .66, 1], labels=["small", "medium", "high"])df["new"].value_counts()high 17 small 17 medium 16 It is like converting a continuous variable into a categorial one. Let’s check the average of values in each category to make sure qcut function has worked properly. df.groupby("new").agg(avg=("col_a","mean")) avgnewsmall 14.000000medium 26.687500high 43.705882 The average increase as we go from small to high which is expected. Both the cut and qcut functions can be used to convert a set of continuous values into a discrete or categorical variable. The cut function focuses on the value range of bins. It determines the entire range based on the difference between the smallest and largest values. Then, it divides the entire range into bins based on the desired number of bins. By default, the size of each bin is the same (approximately) and it is the difference between the lower and upper bin edge. The qcut function focuses on the number of values in each bin. The values are sorted from the smallest to largest. If we want 5 buckets, the first 20 percent of values are placed in the first bucket, the second 20 percent are placed in the second bucket, and so on. Both these functions allow for customizing the upper and lower edges. Thus, we can have bins or buckets with different sizes. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 458, "s": 272, "text": "Pandas is arguably the most popular data analysis and manipulation tool in the data science ecosystem. Thanks to the numerous functions and methods, we can play around with data freely." }, { "code": null, "e": 637, "s": 458, "text": "The cut and qcut functions come in quite handy for many cases. The difference between them was not clear to me at first. I was able to figure it out after doing several examples." }, { "code": null, "e": 807, "s": 637, "text": "In this article, we will do the same. The examples in this article will demonstrate how to use the cut and qcut functions and also emphasize the difference between them." }, { "code": null, "e": 854, "s": 807, "text": "Let’s start with creating a sample data frame." }, { "code": null, "e": 1059, "s": 854, "text": "import numpy as npimport pandas as pddf = pd.DataFrame({ \"col_a\": np.random.randint(1, 50, size=50), \"col_b\": np.random.randint(20, 100, size=50), \"col_c\": np.random.random(size=50).round(2)})df.head()" }, { "code": null, "e": 1258, "s": 1059, "text": "The first and second columns contain integers between 1-50 and 20–100, respectively. The third column contains floats between 0 and 1. We have used numpy functions to generate these values randomly." }, { "code": null, "e": 1365, "s": 1258, "text": "The cut function divides the entire value range into bins. The range covered by each bin will be the same." }, { "code": null, "e": 1505, "s": 1365, "text": "In the first column (col_a), we randomly assign integers between 1 and 50. Let’s first check the minimum and maximum values in this column." }, { "code": null, "e": 1543, "s": 1505, "text": "df.col_a.max(), df.col_a.min()(49, 3)" }, { "code": null, "e": 1674, "s": 1543, "text": "If you want to divide this column into 5 bins of equal range, the size of each bin will be 9.2 which can be calculated as follows:" }, { "code": null, "e": 1693, "s": 1674, "text": "(49 - 3) / 5 = 9.2" }, { "code": null, "e": 1793, "s": 1693, "text": "The cut function performs this binning operation and then assign each value in the appropriate bin." }, { "code": null, "e": 1968, "s": 1793, "text": "df[\"col_a_binned\"] = pd.cut(df.col_a, bins=5)df.col_a_binned.value_counts()(21.4, 30.6] 16 (39.8, 49.0] 14 (12.2, 21.4] 8 (30.6, 39.8] 6 (2.954, 12.2] 6" }, { "code": null, "e": 2197, "s": 1968, "text": "As we can see, the size of each bin is exactly 9.2 expect for the smallest one. The lower bounds are not inclusive. Thus, the lower bound of the smallest bin is a little less than the smallest value (3) to be able to include it." }, { "code": null, "e": 2319, "s": 2197, "text": "We can customize the bins by defining the bin edges manually. The edge values are passed to the bins parameter as a list." }, { "code": null, "e": 2417, "s": 2319, "text": "pd.cut(df.col_a, bins=[0, 10, 40, 50]).value_counts()(10, 40] 33 (40, 50] 13 (0, 10] 4" }, { "code": null, "e": 2481, "s": 2417, "text": "The right edges are inclusive by default but it can be changed." }, { "code": null, "e": 2592, "s": 2481, "text": "pd.cut(df.col_a, bins=[0, 10, 40, 50], right=False).value_counts()[10, 40) 33 [40, 50) 13 [0, 10) 4" }, { "code": null, "e": 2718, "s": 2592, "text": "With the cut function, we do not have any control over how many values fall into each bin. We can only specify the bin edges." }, { "code": null, "e": 2899, "s": 2718, "text": "This is where we need to learn about the qcut function. It can be used to divide the values into buckets in a way that each bucket contains approximately the same number of values." }, { "code": null, "e": 2928, "s": 2899, "text": "Let’s start with an example." }, { "code": null, "e": 3045, "s": 2928, "text": "pd.qcut(df.col_a, q=4).value_counts()(40.75, 49.0] 13 (19.5, 25.0] 13 (2.999, 19.5] 13 (25.0, 40.75] 11" }, { "code": null, "e": 3291, "s": 3045, "text": "We have 4 buckets and each one contains almost the same number of values. In case of 4, the buckets are also called quartiles. One quarter of the total number of values are in the first quartile, one half are in the first two buckets, and so on." }, { "code": null, "e": 3621, "s": 3291, "text": "With the qcut function, we do not have any control over the bin edges. They are calculated automatically. Consider there are 40 values (i.e. rows) in a column and we want to have 4 buckets. Starting from the smallest value, the upper range of the first bucket will be determined in a way that the first bucket contains 10 values." }, { "code": null, "e": 3756, "s": 3621, "text": "Cut function: The focus is on the size of bins in terms of the value range (i.e. the difference between the upper and lower bin edges)" }, { "code": null, "e": 3850, "s": 3756, "text": "Qcut function: The focus is on the size of bins in terms of the number of values in each bin." }, { "code": null, "e": 4055, "s": 3850, "text": "The qcut function allows for customizing the bucket sizes. Let’s create 3 buckets. The first one contains the smallest 50 percent of values (i.e. lower half). Then, we divide the upper half into two bins." }, { "code": null, "e": 4167, "s": 4055, "text": "pd.qcut(df.col_a, q=[0, .50, .75, 1]).value_counts()(2.999, 25.0] 26 (40.75, 49.0] 13 (25.0, 40.75] 11" }, { "code": null, "e": 4280, "s": 4167, "text": "Both the cut and qcut functions allow for labelling the bins or buckets. We use the labels parameter as follows." }, { "code": null, "e": 4428, "s": 4280, "text": "df[\"new\"] = pd.qcut(df.col_a, q=[0, .33, .66, 1], labels=[\"small\", \"medium\", \"high\"])df[\"new\"].value_counts()high 17 small 17 medium 16" }, { "code": null, "e": 4594, "s": 4428, "text": "It is like converting a continuous variable into a categorial one. Let’s check the average of values in each category to make sure qcut function has worked properly." }, { "code": null, "e": 4713, "s": 4594, "text": "df.groupby(\"new\").agg(avg=(\"col_a\",\"mean\")) avgnewsmall 14.000000medium 26.687500high 43.705882" }, { "code": null, "e": 4781, "s": 4713, "text": "The average increase as we go from small to high which is expected." }, { "code": null, "e": 4904, "s": 4781, "text": "Both the cut and qcut functions can be used to convert a set of continuous values into a discrete or categorical variable." }, { "code": null, "e": 5258, "s": 4904, "text": "The cut function focuses on the value range of bins. It determines the entire range based on the difference between the smallest and largest values. Then, it divides the entire range into bins based on the desired number of bins. By default, the size of each bin is the same (approximately) and it is the difference between the lower and upper bin edge." }, { "code": null, "e": 5524, "s": 5258, "text": "The qcut function focuses on the number of values in each bin. The values are sorted from the smallest to largest. If we want 5 buckets, the first 20 percent of values are placed in the first bucket, the second 20 percent are placed in the second bucket, and so on." }, { "code": null, "e": 5650, "s": 5524, "text": "Both these functions allow for customizing the upper and lower edges. Thus, we can have bins or buckets with different sizes." } ]
Fast & Easy Python APIs Using FastAPI | by Billy Bonaros | Towards Data Science
FastAPI is a modern, python-based high-performance web framework used to create Rest APIs. Its key features are that is fast, up to 300% faster to code, fewer bugs, easy to use, and production-friendly. The only con about Fast API is that it’s relatively new and its community is not so big as other frameworks like Flask but I think it will grow fast as many companies like Microsoft, Netflix, and Uber are already using it. In this post, I will show you how to create some simple GET and POST APIs using Fast API. pip install fastapi We will also need an ASGI server, for production such as Uvicorn. pip install uvicorn Let’s get started by creating the simplest API. It will return a JSON with the message “Hello World”. Create a “main.py” file with the following code. #import FastAPIfrom fastapi import FastAPI #create a FastAPI instanceapp = FastAPI() #create a path [email protected](“/”)#define the path operation functiondef root(): return {“message”: “Hello World”} As you can see, there are 4 main steps to create an API with FastAPI. The first step is to import it, and then to create a FastAPI instance(in our case it’s called app). After that, we have to create a path operation. That means we have to set the URL path(in our case is ‘/’ but we can set anything like ‘/helloworld’) and its operation. By operation we mean the HTTP methods like GET, POST, PUT and DELETE(in our case the operation is get). Lastly, we have to define the path operation function. In other words, a function that returns what we want to get from our API(in our case is a JSON with the message Hello World. Now, navigate to the main.py’s folder through the terminal and run the following: uvicorn main:app --reload You should see the following output. That means that our API is running at http://127.0.0.1:8000. Let’s see what we got. Let’s say we want to create a GET API that takes as input two numbers and returns their sum. To add the parameters you just have to put them as the parameters of the path operation function. from fastapi import FastAPI app = FastAPI() @app.get("/addition")def sum(a, b): return {"Result": a+b} You can pass parameters to the URL by adding the symbol “?” then the parameters with the symbol “&” between them. Let’s try the following: http://127.0.0.1:8000/addition?a=12&b=13 Easy as that. You can also set the type of the parameters like integer or string so if the user puts a different type, it will return a warning. @app.get("/addition")def sum(a:int, b:int): return {"Result": a+b} Let’s out a string and see what we will get. http://127.0.0.1:8000/addition?a=12&b=aa I will show you how you can create a POST API that expects as input a JSON file. Let’s see an easy example. from fastapi import FastAPIfrom pydantic import BaseModel app = FastAPI() class inputs(BaseModel): a:int b:int c:int d:int @app.post('/show_data')def show_data(data: inputs): return({"data":[data.a,data.b,data.c,data.d]}) We have to import BaseModel and create a BaseModel class that contains the variables of the JSON file(a, b, c, d in our example). Then, we have to set the class to a variable inside the operation function(data: inputs in our case). Now we can access the variable inside the function using the name of the class variable and the name of its variables like data.a to access the variable a, data.b, etc. FastAPI provides us automatically with SwaggerUI which is a genius and very helpful UI that allows us to visualize and interact with the API’s resources. It can also be used for testing even for POST APIs like the above. You can access it by adding the /docs in your APIs URL. http://127.0.0.1:8000/docs As you can see in the video above, we’ve tested our API and it runs perfectly. For this example, we will train a simple ML model to predict the type of irises (Setosa, Versicolour, and Virginica) using the famous Iris Dataset. Then we will create a POST API using FastAPI that will take as input the features and will return the prediction. First things first, let’s train our model and save it to a pickle file. from sklearn import datasetsfrom sklearn.linear_model import LogisticRegressionimport pandas as pdiris = datasets.load_iris()features=pd.DataFrame(iris['data'])target=iris['target']model=LogisticRegression(max_iter=1000)model.fit(features,target) import picklepickle.dump(model, open('model_iris', 'wb')) Now, we are ready to create our API. from fastapi import FastAPIfrom pydantic import BaseModel app = FastAPI() class iris(BaseModel): a:float b:float c:float d:float from sklearn.linear_model import LogisticRegressionimport pandas as pdimport pickle#we are loading the model using picklemodel = pickle.load(open('model_iris', 'rb')) @app.post('/make_predictions')async def make_predictions(features: iris): return({"prediction":str(model.predict([[features.a,features.b,features.c,features.d]])[0])}) Now If you feed the API above with the following JSON you will get a prediction. { "a": 1.1, "b": 3.3, "c": 5, "d": 1}{ "prediction": "2"} FastAPI is one of the best Python frameworks for Rest APIs because it’s fast, easy, and production-friendly. Its community will grow fast as companies like Netflix, Uber, and Microsoft are already using it. You don’t need anything more than we cover in this post to start, so start experiment with it! Originally published at https://predictivehacks.com.
[ { "code": null, "e": 374, "s": 171, "text": "FastAPI is a modern, python-based high-performance web framework used to create Rest APIs. Its key features are that is fast, up to 300% faster to code, fewer bugs, easy to use, and production-friendly." }, { "code": null, "e": 597, "s": 374, "text": "The only con about Fast API is that it’s relatively new and its community is not so big as other frameworks like Flask but I think it will grow fast as many companies like Microsoft, Netflix, and Uber are already using it." }, { "code": null, "e": 687, "s": 597, "text": "In this post, I will show you how to create some simple GET and POST APIs using Fast API." }, { "code": null, "e": 707, "s": 687, "text": "pip install fastapi" }, { "code": null, "e": 773, "s": 707, "text": "We will also need an ASGI server, for production such as Uvicorn." }, { "code": null, "e": 793, "s": 773, "text": "pip install uvicorn" }, { "code": null, "e": 895, "s": 793, "text": "Let’s get started by creating the simplest API. It will return a JSON with the message “Hello World”." }, { "code": null, "e": 944, "s": 895, "text": "Create a “main.py” file with the following code." }, { "code": null, "e": 1147, "s": 944, "text": "#import FastAPIfrom fastapi import FastAPI #create a FastAPI instanceapp = FastAPI() #create a path [email protected](“/”)#define the path operation functiondef root(): return {“message”: “Hello World”}" }, { "code": null, "e": 1317, "s": 1147, "text": "As you can see, there are 4 main steps to create an API with FastAPI. The first step is to import it, and then to create a FastAPI instance(in our case it’s called app)." }, { "code": null, "e": 1590, "s": 1317, "text": "After that, we have to create a path operation. That means we have to set the URL path(in our case is ‘/’ but we can set anything like ‘/helloworld’) and its operation. By operation we mean the HTTP methods like GET, POST, PUT and DELETE(in our case the operation is get)." }, { "code": null, "e": 1770, "s": 1590, "text": "Lastly, we have to define the path operation function. In other words, a function that returns what we want to get from our API(in our case is a JSON with the message Hello World." }, { "code": null, "e": 1852, "s": 1770, "text": "Now, navigate to the main.py’s folder through the terminal and run the following:" }, { "code": null, "e": 1878, "s": 1852, "text": "uvicorn main:app --reload" }, { "code": null, "e": 1915, "s": 1878, "text": "You should see the following output." }, { "code": null, "e": 1999, "s": 1915, "text": "That means that our API is running at http://127.0.0.1:8000. Let’s see what we got." }, { "code": null, "e": 2190, "s": 1999, "text": "Let’s say we want to create a GET API that takes as input two numbers and returns their sum. To add the parameters you just have to put them as the parameters of the path operation function." }, { "code": null, "e": 2296, "s": 2190, "text": "from fastapi import FastAPI app = FastAPI() @app.get(\"/addition\")def sum(a, b): return {\"Result\": a+b}" }, { "code": null, "e": 2435, "s": 2296, "text": "You can pass parameters to the URL by adding the symbol “?” then the parameters with the symbol “&” between them. Let’s try the following:" }, { "code": null, "e": 2476, "s": 2435, "text": "http://127.0.0.1:8000/addition?a=12&b=13" }, { "code": null, "e": 2621, "s": 2476, "text": "Easy as that. You can also set the type of the parameters like integer or string so if the user puts a different type, it will return a warning." }, { "code": null, "e": 2691, "s": 2621, "text": "@app.get(\"/addition\")def sum(a:int, b:int): return {\"Result\": a+b}" }, { "code": null, "e": 2736, "s": 2691, "text": "Let’s out a string and see what we will get." }, { "code": null, "e": 2777, "s": 2736, "text": "http://127.0.0.1:8000/addition?a=12&b=aa" }, { "code": null, "e": 2885, "s": 2777, "text": "I will show you how you can create a POST API that expects as input a JSON file. Let’s see an easy example." }, { "code": null, "e": 3140, "s": 2885, "text": "from fastapi import FastAPIfrom pydantic import BaseModel app = FastAPI() class inputs(BaseModel): a:int b:int c:int d:int @app.post('/show_data')def show_data(data: inputs): return({\"data\":[data.a,data.b,data.c,data.d]})" }, { "code": null, "e": 3541, "s": 3140, "text": "We have to import BaseModel and create a BaseModel class that contains the variables of the JSON file(a, b, c, d in our example). Then, we have to set the class to a variable inside the operation function(data: inputs in our case). Now we can access the variable inside the function using the name of the class variable and the name of its variables like data.a to access the variable a, data.b, etc." }, { "code": null, "e": 3818, "s": 3541, "text": "FastAPI provides us automatically with SwaggerUI which is a genius and very helpful UI that allows us to visualize and interact with the API’s resources. It can also be used for testing even for POST APIs like the above. You can access it by adding the /docs in your APIs URL." }, { "code": null, "e": 3845, "s": 3818, "text": "http://127.0.0.1:8000/docs" }, { "code": null, "e": 3924, "s": 3845, "text": "As you can see in the video above, we’ve tested our API and it runs perfectly." }, { "code": null, "e": 4186, "s": 3924, "text": "For this example, we will train a simple ML model to predict the type of irises (Setosa, Versicolour, and Virginica) using the famous Iris Dataset. Then we will create a POST API using FastAPI that will take as input the features and will return the prediction." }, { "code": null, "e": 4258, "s": 4186, "text": "First things first, let’s train our model and save it to a pickle file." }, { "code": null, "e": 4563, "s": 4258, "text": "from sklearn import datasetsfrom sklearn.linear_model import LogisticRegressionimport pandas as pdiris = datasets.load_iris()features=pd.DataFrame(iris['data'])target=iris['target']model=LogisticRegression(max_iter=1000)model.fit(features,target) import picklepickle.dump(model, open('model_iris', 'wb'))" }, { "code": null, "e": 4600, "s": 4563, "text": "Now, we are ready to create our API." }, { "code": null, "e": 5102, "s": 4600, "text": "from fastapi import FastAPIfrom pydantic import BaseModel app = FastAPI() class iris(BaseModel): a:float b:float c:float d:float from sklearn.linear_model import LogisticRegressionimport pandas as pdimport pickle#we are loading the model using picklemodel = pickle.load(open('model_iris', 'rb')) @app.post('/make_predictions')async def make_predictions(features: iris): return({\"prediction\":str(model.predict([[features.a,features.b,features.c,features.d]])[0])})" }, { "code": null, "e": 5183, "s": 5102, "text": "Now If you feed the API above with the following JSON you will get a prediction." }, { "code": null, "e": 5246, "s": 5183, "text": "{ \"a\": 1.1, \"b\": 3.3, \"c\": 5, \"d\": 1}{ \"prediction\": \"2\"}" }, { "code": null, "e": 5548, "s": 5246, "text": "FastAPI is one of the best Python frameworks for Rest APIs because it’s fast, easy, and production-friendly. Its community will grow fast as companies like Netflix, Uber, and Microsoft are already using it. You don’t need anything more than we cover in this post to start, so start experiment with it!" } ]
Image Classification on Tensorflow Serving with gRPC or REST Call for Inference | by Sushrut Ashtikar | Towards Data Science
Tensorflow provides a variety of ways to deploy the model. I have explored most of the ways of serving a model in production. I was looking out for a simple, secure, and robust solution that should be easy to access on both edge devices as well as servers written on other programming languages. Model Server was perfect for my needs. I connected edge devices through REST API and made internal RPC calls to my other server. I am also able to serve different versions to different devices which I can easily control from a central server. In this article, I have demonstrated how you can make calls to the model server in both ways and find out which method suits your problem statement. We are going to deploy an image classifier trained on Keras. To make our model run on the model server, we need to export our weights in a specific format as mentioned below. model_name/ version/ saved_model.pb variables/ variables.index variables.data-000-of-n In TensorFlow 2 we can directly export trained model with tf.keras.models.save_model function. MODEL_DIR = './cat_dog_classifier'version = 1export_path = os.path.join(MODEL_DIR, str(version))tf.keras.models.save_model( model, export_path, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None) We will be using saved_model_cli utility for examining graphs. This will be useful for finding out the input and output node name. saved_model_cli show --dir ./cat_dog_classifier/1/ --all echo "deb [arch=amd64] http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal" | sudo tee /etc/apt/sources.list.d/tensorflow-serving.list && \curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | sudo apt-key add -sudo apt-get updatesudo apt-get install tensorflow-model-server We are going to run the model server on default ports 8500 for grpc and 8501 for HTTP. You can also specify different ports if you want. Assuming your terminal location is in the same folder where the model folder is present. export MODEL_DIR=$(pwd)/cat_dog_classifiertensorflow_model_server --port=8500 --rest_api_port=8501 --model_name=cat_dog_classifier --model_base_path="${MODEL_DIR}" After successfully running a model server with your saved model you will get similar output for your model. 2020–06–30 15:22:57.309568: I tensorflow_serving/core/loader_harness.cc:87] Successfully loaded servable version {name: cat_dog_classifier version: 1}2020–06–30 15:22:57.311296: I tensorflow_serving/model_servers/server.cc:355] Running gRPC ModelServer at 0.0.0.0:8500 ...[evhttp_server.cc : 238] NET_LOG: Entering the event loop ...2020–06–30 15:22:57.315925: I tensorflow_serving/model_servers/server.cc:375] Exporting HTTP/REST API at:localhost:8501 ... Necessary Imports: import grpcimport numpy as npimport nsvision as nvimport tensorflow as tffrom tensorflow_serving.apis import predict_pb2from tensorflow_serving.apis import prediction_service_pb2_grpc Setting gRPC channel: label = ['cat', 'dog']GRPC_MAX_RECEIVE_MESSAGE_LENGTH = 4096 * 4096 * 3channel = grpc.insecure_channel('localhost:8500', options=[('grpc.max_receive_message_length', GRPC_MAX_RECEIVE_MESSAGE_LENGTH)])stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)grpc_request = predict_pb2.PredictRequest()grpc_request.model_spec.name = 'cat_dog_classifier'grpc_request.model_spec.signature_name = 'serving_default' Predicting output from an image: Make sure you specify correct inputs and outputs to the gRPC request object. In case if you want to know what is the input-output key of your model you can check using metadata which can be found by calling a systematic URL in the browser. In this case, it is: http://localhost:8501/v1/models/cat_dog_classifier/metadata My input layer name was conv2d_input and output layer name was dense_1 but it will differ as per model. image = nv.imread('golden-retriever-royalty-free-image-506756303-1560962726.jpg',resize=(150,150),normalize=True)image = nv.expand_dims(image,axis=0)grpc_request.inputs['conv2d_input'].CopyFrom(tf.make_tensor_proto(image, shape=image.shape))result = stub.Predict(grpc_request,10)result = int(result.outputs['dense_1'].float_val[0])print(label[result])#This printed 'dog' on my console Rest API requires fewer libraries and less setup than grpc. Imports: import jsonimport requestsimport nsvision as nv Creating JSON for REST call: label = ['cat','dog']image = nv.imread('cat.2033.jpg',resize=(150,150),normalize=True)image = nv.expand_dims(image,axis=0)data = json.dumps({ "instances": image.tolist()})headers = {"content-type": "application/json"} Predicting output from an image: REST API call requires a URL for POST call, the model server has specified a URL format for API calls: http://host_ip:port/version_number/models/model_name:predict In this case, the API URL will be: http://localhost:8501/v1/models/cat_dog_classifier:predict response = requests.post('http://localhost:8501/v1/models/cat_dog_classifier:predict', data=data, headers=headers)result = int(response.json()['predictions'][0][0])print(label[result])#This printed 'cat' on my console Since it’s a REST API you can connect endpoint to web client like javascript or on the edge devices like Android, Ios, or IoT devices like Raspberry Pi or Jetson Nano.
[ { "code": null, "e": 860, "s": 172, "text": "Tensorflow provides a variety of ways to deploy the model. I have explored most of the ways of serving a model in production. I was looking out for a simple, secure, and robust solution that should be easy to access on both edge devices as well as servers written on other programming languages. Model Server was perfect for my needs. I connected edge devices through REST API and made internal RPC calls to my other server. I am also able to serve different versions to different devices which I can easily control from a central server. In this article, I have demonstrated how you can make calls to the model server in both ways and find out which method suits your problem statement." }, { "code": null, "e": 1035, "s": 860, "text": "We are going to deploy an image classifier trained on Keras. To make our model run on the model server, we need to export our weights in a specific format as mentioned below." }, { "code": null, "e": 1159, "s": 1035, "text": "model_name/ version/ saved_model.pb variables/ variables.index variables.data-000-of-n" }, { "code": null, "e": 1254, "s": 1159, "text": "In TensorFlow 2 we can directly export trained model with tf.keras.models.save_model function." }, { "code": null, "e": 1508, "s": 1254, "text": "MODEL_DIR = './cat_dog_classifier'version = 1export_path = os.path.join(MODEL_DIR, str(version))tf.keras.models.save_model( model, export_path, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None)" }, { "code": null, "e": 1639, "s": 1508, "text": "We will be using saved_model_cli utility for examining graphs. This will be useful for finding out the input and output node name." }, { "code": null, "e": 1696, "s": 1639, "text": "saved_model_cli show --dir ./cat_dog_classifier/1/ --all" }, { "code": null, "e": 2079, "s": 1696, "text": "echo \"deb [arch=amd64] http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal\" | sudo tee /etc/apt/sources.list.d/tensorflow-serving.list && \\curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | sudo apt-key add -sudo apt-get updatesudo apt-get install tensorflow-model-server" }, { "code": null, "e": 2216, "s": 2079, "text": "We are going to run the model server on default ports 8500 for grpc and 8501 for HTTP. You can also specify different ports if you want." }, { "code": null, "e": 2305, "s": 2216, "text": "Assuming your terminal location is in the same folder where the model folder is present." }, { "code": null, "e": 2469, "s": 2305, "text": "export MODEL_DIR=$(pwd)/cat_dog_classifiertensorflow_model_server --port=8500 --rest_api_port=8501 --model_name=cat_dog_classifier --model_base_path=\"${MODEL_DIR}\"" }, { "code": null, "e": 2577, "s": 2469, "text": "After successfully running a model server with your saved model you will get similar output for your model." }, { "code": null, "e": 3034, "s": 2577, "text": "2020–06–30 15:22:57.309568: I tensorflow_serving/core/loader_harness.cc:87] Successfully loaded servable version {name: cat_dog_classifier version: 1}2020–06–30 15:22:57.311296: I tensorflow_serving/model_servers/server.cc:355] Running gRPC ModelServer at 0.0.0.0:8500 ...[evhttp_server.cc : 238] NET_LOG: Entering the event loop ...2020–06–30 15:22:57.315925: I tensorflow_serving/model_servers/server.cc:375] Exporting HTTP/REST API at:localhost:8501 ..." }, { "code": null, "e": 3053, "s": 3034, "text": "Necessary Imports:" }, { "code": null, "e": 3237, "s": 3053, "text": "import grpcimport numpy as npimport nsvision as nvimport tensorflow as tffrom tensorflow_serving.apis import predict_pb2from tensorflow_serving.apis import prediction_service_pb2_grpc" }, { "code": null, "e": 3259, "s": 3237, "text": "Setting gRPC channel:" }, { "code": null, "e": 3677, "s": 3259, "text": "label = ['cat', 'dog']GRPC_MAX_RECEIVE_MESSAGE_LENGTH = 4096 * 4096 * 3channel = grpc.insecure_channel('localhost:8500', options=[('grpc.max_receive_message_length', GRPC_MAX_RECEIVE_MESSAGE_LENGTH)])stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)grpc_request = predict_pb2.PredictRequest()grpc_request.model_spec.name = 'cat_dog_classifier'grpc_request.model_spec.signature_name = 'serving_default'" }, { "code": null, "e": 3710, "s": 3677, "text": "Predicting output from an image:" }, { "code": null, "e": 3971, "s": 3710, "text": "Make sure you specify correct inputs and outputs to the gRPC request object. In case if you want to know what is the input-output key of your model you can check using metadata which can be found by calling a systematic URL in the browser. In this case, it is:" }, { "code": null, "e": 4031, "s": 3971, "text": "http://localhost:8501/v1/models/cat_dog_classifier/metadata" }, { "code": null, "e": 4135, "s": 4031, "text": "My input layer name was conv2d_input and output layer name was dense_1 but it will differ as per model." }, { "code": null, "e": 4520, "s": 4135, "text": "image = nv.imread('golden-retriever-royalty-free-image-506756303-1560962726.jpg',resize=(150,150),normalize=True)image = nv.expand_dims(image,axis=0)grpc_request.inputs['conv2d_input'].CopyFrom(tf.make_tensor_proto(image, shape=image.shape))result = stub.Predict(grpc_request,10)result = int(result.outputs['dense_1'].float_val[0])print(label[result])#This printed 'dog' on my console" }, { "code": null, "e": 4580, "s": 4520, "text": "Rest API requires fewer libraries and less setup than grpc." }, { "code": null, "e": 4589, "s": 4580, "text": "Imports:" }, { "code": null, "e": 4637, "s": 4589, "text": "import jsonimport requestsimport nsvision as nv" }, { "code": null, "e": 4666, "s": 4637, "text": "Creating JSON for REST call:" }, { "code": null, "e": 4888, "s": 4666, "text": "label = ['cat','dog']image = nv.imread('cat.2033.jpg',resize=(150,150),normalize=True)image = nv.expand_dims(image,axis=0)data = json.dumps({ \"instances\": image.tolist()})headers = {\"content-type\": \"application/json\"}" }, { "code": null, "e": 4921, "s": 4888, "text": "Predicting output from an image:" }, { "code": null, "e": 5085, "s": 4921, "text": "REST API call requires a URL for POST call, the model server has specified a URL format for API calls: http://host_ip:port/version_number/models/model_name:predict" }, { "code": null, "e": 5120, "s": 5085, "text": "In this case, the API URL will be:" }, { "code": null, "e": 5179, "s": 5120, "text": "http://localhost:8501/v1/models/cat_dog_classifier:predict" }, { "code": null, "e": 5397, "s": 5179, "text": "response = requests.post('http://localhost:8501/v1/models/cat_dog_classifier:predict', data=data, headers=headers)result = int(response.json()['predictions'][0][0])print(label[result])#This printed 'cat' on my console" } ]
Find elements in given Array that are a factor of sum of remaining elements - GeeksforGeeks
10 Feb, 2022 Given an array A[] of size N, the task is to find the elements in the array which are factors of the sum of the remaining element. So just select an element from an array and take the sum of the remaining elements and check whether the sum is perfectly divisible by the selected element or not. If it is divisible then return the element. Examples: Input: A[] = {2, 4, 6, 8, 10, 12, 14}Output: [2, 4, 8, 14]Explanation: 1. Take sum for remaining element except selected one.2. For element 2, sum of remaining element is 4+6+8+10+12+14=54 3. Similarly for complete array: [54, 52, 50, 48, 46, 44, 42]3. 54/2, 52/4, 48/8, 42/14 are perfectly divisible so resultant elements are [2, 4, 8, 14] Input: A[]= {3, 6, 8, 10, 7, 15}Output: [7] Naive Approach: Take the sum of all elements from the array. Now subtract each element one by one from sum and append it to new array p[]. Divide each sum by the corresponding index element from a given array and append it to new array q[ ]. Multiply the corresponding element from array A[] and array q[] and compare it with similar indexed elements from array p[]. If they are equal then append it to a new array z[ ]. If no such element is found return -1. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // c++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find elementvector<int> Factor(vector<int> A){ // Sum of all element int s = 0; for (int i = 0; i < A.size(); i++) { s += A[i]; } // Subtract each element from sum vector<int> p; for (int i : A) p.push_back(s - i); // Divide corresponding element // from array p and l vector<int> q; for (int i = 0; i < A.size(); i++) q.push_back(p[i] / A[i]); // Check sum is divisible by // corresponding element or not vector<int> z; for (int i = 0; i < q.size(); i++) { // First we divided element now multiple // to check perfect divisibility of element if (q[i] * A[i] == p[i]) z.push_back(A[i]); } return z;} // Driver codeint main(){ vector<int> A = {2, 4, 6, 8, 10, 12, 14}; // Calling function vector<int> b = Factor(A); // Print required array for (auto i : b) { cout << i << " "; }} // This code is contributed by amreshkumar3. // Java program for the above approachimport java.util.ArrayList; class GFG{ // Function to find elementstatic ArrayList<Integer> Factor(int[] A){ // Sum of all element int s = 0; for(int i = 0; i < A.length; i++) { s += A[i]; } // Subtract each element from sum ArrayList<Integer> p = new ArrayList<>(); for(int i : A) p.add(s - i); // Divide corresponding element // from array p and l ArrayList<Integer> q = new ArrayList<Integer>(); for(int i = 0; i < A.length; i++) q.add((int) Math.floor(p.get(i) / A[i])); // Check sum is divisible by // corresponding element or not ArrayList<Integer> z = new ArrayList<Integer>(); for(int i = 0; i < q.size(); i++) { // First we divided element now multiple // to check perfect divisibility of element if (q.get(i) * A[i] == p.get(i)) z.add(A[i]); } // If no such element found return -1 if (z.size() == 0) return new ArrayList<Integer>(); return z;} // Driver codepublic static void main(String args[]){ int[] A = { 2, 4, 6, 8, 10, 12, 14 }; // Calling function ArrayList<Integer> b = Factor(A); // Print required array System.out.println(b);}} // This code is contributed by gfgking # Python program for the above approach # Function to find elementdef Factor(A): # Sum of all element s = sum(A) # Subtract each element from sum p =[] for i in A: p.append(s-i) # Divide corresponding element # from array p and l q =[] for i in range(len(A)): q.append(p[i]//A[i]) # Check sum is divisible by # corresponding element or not z =[] for i in range(len(q)): # First we divided element now multiple # to check perfect divisibility of element if q[i]*A[i]== p[i]: z.append(A[i]) # If no such element found return -1 if len(z)== 0: return -1 return z A = [2, 4, 6, 8, 10, 12, 14] # Calling functionb = Factor(A) # Print required arrayprint(b) // C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find element static List<int> Factor(int[] A) { // Sum of all element int s = 0; for(int i = 0; i < A.Length; i++) { s += A[i]; } // Subtract each element from sum List<int> p = new List<int>(); foreach(int i in A) p.Add(s - i); // Divide corresponding element // from array p and l List<int> q = new List<int>(); for(int i = 0; i < A.Length; i++) q.Add((int) Math.Floor((double)p[i] / A[i])); // Check sum is divisible by // corresponding element or not List<int> z = new List<int>(); for(int i = 0; i < q.Count; i++) { // First we divided element now multiple // to check perfect divisibility of element if (q[i] * A[i] == p[i]) z.Add(A[i]); } // If no such element found return -1 if (z.Count == 0) return new List<int>(); return z; } // Driver code public static void Main(String []args) { int[] A = { 2, 4, 6, 8, 10, 12, 14 }; // Calling function List<int> b = Factor(A); // Print required array foreach(int i in b) Console.Write(i+", "); }} // This code is contributed by 29AjayKumar <script> // JavaScript code for the above approach // Function to find element function Factor(A) { // Sum of all element let s = 0; for (let i = 0; i < A.length; i++) { s += A[i] } // Subtract each element from sum p = [] for (i of A) p.push(s - i) // Divide corresponding element // from array p and l q = [] for (i = 0; i < A.length; i++) q.push(Math.floor(p[i] / A[i])) // Check sum is divisible by // corresponding element or not z = [] for (let i = 0; i < q.length; i++) { // First we divided element now multiple // to check perfect divisibility of element if (q[i] * A[i] == p[i]) z.push(A[i]) } // If no such element found return -1 if (z.length == 0) return -1 return z } A = [2, 4, 6, 8, 10, 12, 14] // Calling function b = Factor(A) // Print required array document.write(b) // This code is contributed by Potta Lokesh </script> [2, 4, 8, 14] Time Complexity: O(N)Auxiliary Space: O(N) Efficient Approach: In this approach, there is no need to use multiple loops and multiple arrays. so space complexity and time complexity will be decreased. In this, all the subtraction, division, multiplication operation are performed in a single loop. Follow the steps below to solve the problem: Initialize the variable s as the sum of the array A[]. Initialize the array z[] to store the result. Iterate over the range [0, len(A)) using the variables i and perform the following tasks:Initialize the variable a as s-l[i], b as a/A[i].If b*A[i] equals a then append A[i] into z[]. Initialize the variable a as s-l[i], b as a/A[i]. If b*A[i] equals a then append A[i] into z[]. After performing the above steps, print -1 if the resultant array is empty, else print the elements of the array z[] as the answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find sum of all elements of an arrayint sum(vector<int>& A){ int res = 0; for (auto it : A) res += it; return res;} // Function to find elementvector<int> Factor(vector<int>& A){ // Sum of all element int s = sum(A); vector<int> z; // Loop to find the factors of sum. for (int i = 0; i < A.size(); ++i) { // a is sum of remaining elements. int a = s - A[i]; // b is integer value or factor of b. int b = a / A[i]; // Check the divisibility if (b * A[i] == a) z.push_back(A[i]); } // If no element found return -1 if (z.size() == 0) return { -1 }; return z;} // Drive Code int main(){ vector<int> A = { 2, 4, 6, 8, 10, 12, 14 }; // Calling function vector<int> b = Factor(A); // Print resultant element for (auto it : b) cout << it << " "; return 0;} // This code is contributed by rakeshsahni // Java program for the above approachimport java.util.*;class GFG{ // Function to find sum of all elements of an array static int sum(int[] A) { int res = 0; for (int i = 0; i < A.length; i++) { res += A[i]; } return res; } // Function to find element static ArrayList<Integer> Factor(int[] A) { // Sum of all element int s = sum(A); ArrayList<Integer> z = new ArrayList<Integer>(); // Loop to find the factors of sum. for (int i = 0; i < A.length; ++i) { // a is sum of remaining elements. int a = s - A[i]; // b is integer value or factor of b. int b = a / A[i]; // Check the divisibility if (b * A[i] == a){ z.add(A[i]); } } // If no element found return -1 if (z.size() == 0){ ArrayList<Integer> l1 = new ArrayList<Integer>(); l1.add(-1); return l1; } return z; } // Drive Code public static void main (String[] args) { int A[] = new int[] { 2, 4, 6, 8, 10, 12, 14 }; // Calling function ArrayList<Integer> b = Factor(A); // Print resultant element System.out.println(b); }} // This code is contributed by Shubham Singh # Python program for the above approach # Function to find elementdef Factor(A): # Sum of all element s = sum(A) z = [] # Loop to find the factors of sum. for i in range(len(A)): # a is sum of remaining elements. a = s-A[i] # b is integer value or factor of b. b = a//A[i] # Check the divisibility if b * A[i] == a: z.append(A[i]) # If no element found return -1 if len(z) == 0: return -1 return z A = [2, 4, 6, 8, 10, 12, 14] # Calling functionb = Factor(A) # Print resultant elementprint(b) // C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to find sum of all elements of an array static int sum(List<int> A) { int res = 0; foreach(int it in A) res += it; return res; } // Function to find element static List<int> Factor(List<int> A) { // Sum of all element int s = sum(A); List<int> z = new List<int>(); // Loop to find the factors of sum. for (int i = 0; i < A.Count; ++i) { // a is sum of remaining elements. int a = s - A[i]; // b is integer value or factor of b. int b = a / A[i]; // Check the divisibility if (b * A[i] == a) z.Add(A[i]); } // If no element found return -1 if (z.Count == 0) return new List<int>() { -1 }; return z; } // Drive Code public static void Main() { List<int> A = new List<int>() { 2, 4, 6, 8, 10, 12, 14 }; // Calling function List<int> b = Factor(A); // Print resultant element Console.Write("[ "); int it; for (it = 0; it < b.Count - 1; it++) { Console.Write(b[it] + ", "); } Console.Write(b[it] + " ]"); }} // This code is contributed by ukasp. <script>// JavaScript program for the above approach // Function to find sum of all elements of an arrayfunction sum(A){ var res = 0; for (var it of A){ res += parseInt(it);} return res;} // Function to find elementfunction Factor(A){ // Sum of all element var s = sum(A); var z =[]; // Loop to find the factors of sum. for (var i = 0; i < A.length; ++i) { // a is sum of remaining elements. var a = s - A[i]; // b is integer value or factor of b. var b = parseInt(a / A[i]); // Check the divisibility if (b * A[i] == a) z.push(A[i]); } // If no element found return -1 if (z.length == 0) return [ -1 ]; return z;} // Drive CodeA = [ 2, 4, 6, 8, 10, 12, 14 ]; // Calling functionb = Factor(A); // Print resultant elementfor (var it of b)document.write(it + " "); //This code is contributed by Shubham Singh</script> [2, 4, 8, 14] Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 rakeshsahni ukasp gfgking 29AjayKumar SHUBHAMSINGH10 amreshkumar3 simmytarika5 surinderdawra388 Algo-Geek 2021 factor Algo Geek Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of operation required to water all the plants Encode given String by inserting in Matrix column-wise and printing it row-wise Lexicographically smallest string formed by concatenating any prefix and its mirrored form Check if the given string is valid English word or not Bit Manipulation technique to replace boolean arrays of fixed size less than 64 Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26352, "s": 26324, "text": "\n10 Feb, 2022" }, { "code": null, "e": 26691, "s": 26352, "text": "Given an array A[] of size N, the task is to find the elements in the array which are factors of the sum of the remaining element. So just select an element from an array and take the sum of the remaining elements and check whether the sum is perfectly divisible by the selected element or not. If it is divisible then return the element." }, { "code": null, "e": 26701, "s": 26691, "text": "Examples:" }, { "code": null, "e": 27042, "s": 26701, "text": "Input: A[] = {2, 4, 6, 8, 10, 12, 14}Output: [2, 4, 8, 14]Explanation: 1. Take sum for remaining element except selected one.2. For element 2, sum of remaining element is 4+6+8+10+12+14=54 3. Similarly for complete array: [54, 52, 50, 48, 46, 44, 42]3. 54/2, 52/4, 48/8, 42/14 are perfectly divisible so resultant elements are [2, 4, 8, 14]" }, { "code": null, "e": 27086, "s": 27042, "text": "Input: A[]= {3, 6, 8, 10, 7, 15}Output: [7]" }, { "code": null, "e": 27546, "s": 27086, "text": "Naive Approach: Take the sum of all elements from the array. Now subtract each element one by one from sum and append it to new array p[]. Divide each sum by the corresponding index element from a given array and append it to new array q[ ]. Multiply the corresponding element from array A[] and array q[] and compare it with similar indexed elements from array p[]. If they are equal then append it to a new array z[ ]. If no such element is found return -1." }, { "code": null, "e": 27597, "s": 27546, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27601, "s": 27597, "text": "C++" }, { "code": null, "e": 27606, "s": 27601, "text": "Java" }, { "code": null, "e": 27614, "s": 27606, "text": "Python3" }, { "code": null, "e": 27617, "s": 27614, "text": "C#" }, { "code": null, "e": 27628, "s": 27617, "text": "Javascript" }, { "code": "// c++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find elementvector<int> Factor(vector<int> A){ // Sum of all element int s = 0; for (int i = 0; i < A.size(); i++) { s += A[i]; } // Subtract each element from sum vector<int> p; for (int i : A) p.push_back(s - i); // Divide corresponding element // from array p and l vector<int> q; for (int i = 0; i < A.size(); i++) q.push_back(p[i] / A[i]); // Check sum is divisible by // corresponding element or not vector<int> z; for (int i = 0; i < q.size(); i++) { // First we divided element now multiple // to check perfect divisibility of element if (q[i] * A[i] == p[i]) z.push_back(A[i]); } return z;} // Driver codeint main(){ vector<int> A = {2, 4, 6, 8, 10, 12, 14}; // Calling function vector<int> b = Factor(A); // Print required array for (auto i : b) { cout << i << \" \"; }} // This code is contributed by amreshkumar3.", "e": 28610, "s": 27628, "text": null }, { "code": "// Java program for the above approachimport java.util.ArrayList; class GFG{ // Function to find elementstatic ArrayList<Integer> Factor(int[] A){ // Sum of all element int s = 0; for(int i = 0; i < A.length; i++) { s += A[i]; } // Subtract each element from sum ArrayList<Integer> p = new ArrayList<>(); for(int i : A) p.add(s - i); // Divide corresponding element // from array p and l ArrayList<Integer> q = new ArrayList<Integer>(); for(int i = 0; i < A.length; i++) q.add((int) Math.floor(p.get(i) / A[i])); // Check sum is divisible by // corresponding element or not ArrayList<Integer> z = new ArrayList<Integer>(); for(int i = 0; i < q.size(); i++) { // First we divided element now multiple // to check perfect divisibility of element if (q.get(i) * A[i] == p.get(i)) z.add(A[i]); } // If no such element found return -1 if (z.size() == 0) return new ArrayList<Integer>(); return z;} // Driver codepublic static void main(String args[]){ int[] A = { 2, 4, 6, 8, 10, 12, 14 }; // Calling function ArrayList<Integer> b = Factor(A); // Print required array System.out.println(b);}} // This code is contributed by gfgking", "e": 29909, "s": 28610, "text": null }, { "code": "# Python program for the above approach # Function to find elementdef Factor(A): # Sum of all element s = sum(A) # Subtract each element from sum p =[] for i in A: p.append(s-i) # Divide corresponding element # from array p and l q =[] for i in range(len(A)): q.append(p[i]//A[i]) # Check sum is divisible by # corresponding element or not z =[] for i in range(len(q)): # First we divided element now multiple # to check perfect divisibility of element if q[i]*A[i]== p[i]: z.append(A[i]) # If no such element found return -1 if len(z)== 0: return -1 return z A = [2, 4, 6, 8, 10, 12, 14] # Calling functionb = Factor(A) # Print required arrayprint(b)", "e": 30692, "s": 29909, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find element static List<int> Factor(int[] A) { // Sum of all element int s = 0; for(int i = 0; i < A.Length; i++) { s += A[i]; } // Subtract each element from sum List<int> p = new List<int>(); foreach(int i in A) p.Add(s - i); // Divide corresponding element // from array p and l List<int> q = new List<int>(); for(int i = 0; i < A.Length; i++) q.Add((int) Math.Floor((double)p[i] / A[i])); // Check sum is divisible by // corresponding element or not List<int> z = new List<int>(); for(int i = 0; i < q.Count; i++) { // First we divided element now multiple // to check perfect divisibility of element if (q[i] * A[i] == p[i]) z.Add(A[i]); } // If no such element found return -1 if (z.Count == 0) return new List<int>(); return z; } // Driver code public static void Main(String []args) { int[] A = { 2, 4, 6, 8, 10, 12, 14 }; // Calling function List<int> b = Factor(A); // Print required array foreach(int i in b) Console.Write(i+\", \"); }} // This code is contributed by 29AjayKumar", "e": 31944, "s": 30692, "text": null }, { "code": " <script> // JavaScript code for the above approach // Function to find element function Factor(A) { // Sum of all element let s = 0; for (let i = 0; i < A.length; i++) { s += A[i] } // Subtract each element from sum p = [] for (i of A) p.push(s - i) // Divide corresponding element // from array p and l q = [] for (i = 0; i < A.length; i++) q.push(Math.floor(p[i] / A[i])) // Check sum is divisible by // corresponding element or not z = [] for (let i = 0; i < q.length; i++) { // First we divided element now multiple // to check perfect divisibility of element if (q[i] * A[i] == p[i]) z.push(A[i]) } // If no such element found return -1 if (z.length == 0) return -1 return z } A = [2, 4, 6, 8, 10, 12, 14] // Calling function b = Factor(A) // Print required array document.write(b) // This code is contributed by Potta Lokesh </script>", "e": 33121, "s": 31944, "text": null }, { "code": null, "e": 33135, "s": 33121, "text": "[2, 4, 8, 14]" }, { "code": null, "e": 33178, "s": 33135, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 33477, "s": 33178, "text": "Efficient Approach: In this approach, there is no need to use multiple loops and multiple arrays. so space complexity and time complexity will be decreased. In this, all the subtraction, division, multiplication operation are performed in a single loop. Follow the steps below to solve the problem:" }, { "code": null, "e": 33532, "s": 33477, "text": "Initialize the variable s as the sum of the array A[]." }, { "code": null, "e": 33578, "s": 33532, "text": "Initialize the array z[] to store the result." }, { "code": null, "e": 33762, "s": 33578, "text": "Iterate over the range [0, len(A)) using the variables i and perform the following tasks:Initialize the variable a as s-l[i], b as a/A[i].If b*A[i] equals a then append A[i] into z[]." }, { "code": null, "e": 33812, "s": 33762, "text": "Initialize the variable a as s-l[i], b as a/A[i]." }, { "code": null, "e": 33858, "s": 33812, "text": "If b*A[i] equals a then append A[i] into z[]." }, { "code": null, "e": 33990, "s": 33858, "text": "After performing the above steps, print -1 if the resultant array is empty, else print the elements of the array z[] as the answer." }, { "code": null, "e": 34041, "s": 33990, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 34045, "s": 34041, "text": "C++" }, { "code": null, "e": 34050, "s": 34045, "text": "Java" }, { "code": null, "e": 34058, "s": 34050, "text": "Python3" }, { "code": null, "e": 34061, "s": 34058, "text": "C#" }, { "code": null, "e": 34072, "s": 34061, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find sum of all elements of an arrayint sum(vector<int>& A){ int res = 0; for (auto it : A) res += it; return res;} // Function to find elementvector<int> Factor(vector<int>& A){ // Sum of all element int s = sum(A); vector<int> z; // Loop to find the factors of sum. for (int i = 0; i < A.size(); ++i) { // a is sum of remaining elements. int a = s - A[i]; // b is integer value or factor of b. int b = a / A[i]; // Check the divisibility if (b * A[i] == a) z.push_back(A[i]); } // If no element found return -1 if (z.size() == 0) return { -1 }; return z;} // Drive Code int main(){ vector<int> A = { 2, 4, 6, 8, 10, 12, 14 }; // Calling function vector<int> b = Factor(A); // Print resultant element for (auto it : b) cout << it << \" \"; return 0;} // This code is contributed by rakeshsahni", "e": 35022, "s": 34072, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find sum of all elements of an array static int sum(int[] A) { int res = 0; for (int i = 0; i < A.length; i++) { res += A[i]; } return res; } // Function to find element static ArrayList<Integer> Factor(int[] A) { // Sum of all element int s = sum(A); ArrayList<Integer> z = new ArrayList<Integer>(); // Loop to find the factors of sum. for (int i = 0; i < A.length; ++i) { // a is sum of remaining elements. int a = s - A[i]; // b is integer value or factor of b. int b = a / A[i]; // Check the divisibility if (b * A[i] == a){ z.add(A[i]); } } // If no element found return -1 if (z.size() == 0){ ArrayList<Integer> l1 = new ArrayList<Integer>(); l1.add(-1); return l1; } return z; } // Drive Code public static void main (String[] args) { int A[] = new int[] { 2, 4, 6, 8, 10, 12, 14 }; // Calling function ArrayList<Integer> b = Factor(A); // Print resultant element System.out.println(b); }} // This code is contributed by Shubham Singh", "e": 36190, "s": 35022, "text": null }, { "code": "# Python program for the above approach # Function to find elementdef Factor(A): # Sum of all element s = sum(A) z = [] # Loop to find the factors of sum. for i in range(len(A)): # a is sum of remaining elements. a = s-A[i] # b is integer value or factor of b. b = a//A[i] # Check the divisibility if b * A[i] == a: z.append(A[i]) # If no element found return -1 if len(z) == 0: return -1 return z A = [2, 4, 6, 8, 10, 12, 14] # Calling functionb = Factor(A) # Print resultant elementprint(b)", "e": 36775, "s": 36190, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to find sum of all elements of an array static int sum(List<int> A) { int res = 0; foreach(int it in A) res += it; return res; } // Function to find element static List<int> Factor(List<int> A) { // Sum of all element int s = sum(A); List<int> z = new List<int>(); // Loop to find the factors of sum. for (int i = 0; i < A.Count; ++i) { // a is sum of remaining elements. int a = s - A[i]; // b is integer value or factor of b. int b = a / A[i]; // Check the divisibility if (b * A[i] == a) z.Add(A[i]); } // If no element found return -1 if (z.Count == 0) return new List<int>() { -1 }; return z; } // Drive Code public static void Main() { List<int> A = new List<int>() { 2, 4, 6, 8, 10, 12, 14 }; // Calling function List<int> b = Factor(A); // Print resultant element Console.Write(\"[ \"); int it; for (it = 0; it < b.Count - 1; it++) { Console.Write(b[it] + \", \"); } Console.Write(b[it] + \" ]\"); }} // This code is contributed by ukasp.", "e": 37962, "s": 36775, "text": null }, { "code": "<script>// JavaScript program for the above approach // Function to find sum of all elements of an arrayfunction sum(A){ var res = 0; for (var it of A){ res += parseInt(it);} return res;} // Function to find elementfunction Factor(A){ // Sum of all element var s = sum(A); var z =[]; // Loop to find the factors of sum. for (var i = 0; i < A.length; ++i) { // a is sum of remaining elements. var a = s - A[i]; // b is integer value or factor of b. var b = parseInt(a / A[i]); // Check the divisibility if (b * A[i] == a) z.push(A[i]); } // If no element found return -1 if (z.length == 0) return [ -1 ]; return z;} // Drive CodeA = [ 2, 4, 6, 8, 10, 12, 14 ]; // Calling functionb = Factor(A); // Print resultant elementfor (var it of b)document.write(it + \" \"); //This code is contributed by Shubham Singh</script>", "e": 38829, "s": 37962, "text": null }, { "code": null, "e": 38843, "s": 38829, "text": "[2, 4, 8, 14]" }, { "code": null, "e": 38886, "s": 38843, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 38900, "s": 38886, "text": "lokeshpotta20" }, { "code": null, "e": 38912, "s": 38900, "text": "rakeshsahni" }, { "code": null, "e": 38918, "s": 38912, "text": "ukasp" }, { "code": null, "e": 38926, "s": 38918, "text": "gfgking" }, { "code": null, "e": 38938, "s": 38926, "text": "29AjayKumar" }, { "code": null, "e": 38953, "s": 38938, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 38966, "s": 38953, "text": "amreshkumar3" }, { "code": null, "e": 38979, "s": 38966, "text": "simmytarika5" }, { "code": null, "e": 38996, "s": 38979, "text": "surinderdawra388" }, { "code": null, "e": 39011, "s": 38996, "text": "Algo-Geek 2021" }, { "code": null, "e": 39018, "s": 39011, "text": "factor" }, { "code": null, "e": 39028, "s": 39018, "text": "Algo Geek" }, { "code": null, "e": 39041, "s": 39028, "text": "Mathematical" }, { "code": null, "e": 39054, "s": 39041, "text": "Mathematical" }, { "code": null, "e": 39152, "s": 39054, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39204, "s": 39152, "text": "Count of operation required to water all the plants" }, { "code": null, "e": 39284, "s": 39204, "text": "Encode given String by inserting in Matrix column-wise and printing it row-wise" }, { "code": null, "e": 39375, "s": 39284, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 39430, "s": 39375, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 39510, "s": 39430, "text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64" }, { "code": null, "e": 39540, "s": 39510, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 39600, "s": 39540, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39615, "s": 39600, "text": "C++ Data Types" }, { "code": null, "e": 39658, "s": 39615, "text": "Set in C++ Standard Template Library (STL)" } ]
MS Project - Assign Resources to Task
Once the task and resource list are complete, resources need to be assigned to tasks in order to work on them. With MS Project you can track task progress, resource and tasks costs. Click View Tab → Gantt Chart View → Resource Name column. Click the box below the Resource Name column for the task you need the resource to be assigned. From the dropdown, choose the resource name. In the following screenshot as an example. For Task 1 “PT1”, we have chosen the resource “Celic”. You can also select multiple resources to work on a single task. Click Resource tab → Under Assignments group → Assign Resources. In the Assign Resources dialog box, click the resource name you like to assign. Here let’s choose “Hitesh”. Now click the Assign button. You can also select multiple resources to work on a single task. Click View Tab → Gantt Chart → Task Name column. Double-click the Task Name. Task Information dialog box opens. Click the Resources tab. Click the cell below the Resource Name column. Select the resource from the dropdown list. You can also select multiple resources to work on a single task. Click View Tab → Split View group → Details → Task Form. The window is split in two, Gantt Chart view and Task Form view below it. In the Task Form view, click under the Resource Name column and select the resource. You can also select multiple resources to work on a single task. Click View Tab → Gantt Chart View → Task Name column. Double-click the Task Name. Task Information dialog box opens. Click the Resources tab. Click the cell below the Resource Name column. Select the resource from the dropdown list. In the following example below, let’s choose “Travel” as cost resource and enter the cost at $800. We can also assign other material resources to the same task. 32 Lectures 2.5 hours Pavan Lalwani 18 Lectures 1.5 hours Dr. Saatya Prasad 102 Lectures 10 hours Pavan Lalwani 52 Lectures 4 hours Pavan Lalwani 239 Lectures 33 hours Gowthami Swarna 53 Lectures 5 hours Akshay Magre Print Add Notes Bookmark this page
[ { "code": null, "e": 2063, "s": 1881, "text": "Once the task and resource list are complete, resources need to be assigned to tasks in order to work on them. With MS Project you can track task progress, resource and tasks costs." }, { "code": null, "e": 2367, "s": 2063, "text": "Click View Tab → Gantt Chart View → Resource Name column.\n\nClick the box below the Resource Name column for the task you need the resource to be assigned.\n\nFrom the dropdown, choose the resource name. In the following screenshot as an \n example. For Task 1 “PT1”, we have chosen the resource “Celic”.\n" }, { "code": null, "e": 2432, "s": 2367, "text": "You can also select multiple resources to work on a single task." }, { "code": null, "e": 2579, "s": 2432, "text": "Click Resource tab → Under Assignments group → Assign Resources.\n\nIn the Assign Resources dialog box, click the resource name you like to assign.\n" }, { "code": null, "e": 2636, "s": 2579, "text": "Here let’s choose “Hitesh”. Now click the Assign button." }, { "code": null, "e": 2701, "s": 2636, "text": "You can also select multiple resources to work on a single task." }, { "code": null, "e": 2933, "s": 2701, "text": "Click View Tab → Gantt Chart → Task Name column.\n\nDouble-click the Task Name. Task Information dialog box opens.\n\nClick the Resources tab.\n\nClick the cell below the Resource Name column. Select the resource from the dropdown list.\n" }, { "code": null, "e": 2998, "s": 2933, "text": "You can also select multiple resources to work on a single task." }, { "code": null, "e": 3056, "s": 2998, "text": "Click View Tab → Split View group → Details → Task Form.\n" }, { "code": null, "e": 3130, "s": 3056, "text": "The window is split in two, Gantt Chart view and Task Form view below it." }, { "code": null, "e": 3216, "s": 3130, "text": "In the Task Form view, click under the Resource Name column and select the resource.\n" }, { "code": null, "e": 3281, "s": 3216, "text": "You can also select multiple resources to work on a single task." }, { "code": null, "e": 3518, "s": 3281, "text": "Click View Tab → Gantt Chart View → Task Name column.\n\nDouble-click the Task Name. Task Information dialog box opens.\n\nClick the Resources tab.\n\nClick the cell below the Resource Name column. Select the resource from the dropdown list.\n" }, { "code": null, "e": 3617, "s": 3518, "text": "In the following example below, let’s choose “Travel” as cost resource and enter the cost at $800." }, { "code": null, "e": 3679, "s": 3617, "text": "We can also assign other material resources to the same task." }, { "code": null, "e": 3714, "s": 3679, "text": "\n 32 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3729, "s": 3714, "text": " Pavan Lalwani" }, { "code": null, "e": 3764, "s": 3729, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3783, "s": 3764, "text": " Dr. Saatya Prasad" }, { "code": null, "e": 3818, "s": 3783, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 3833, "s": 3818, "text": " Pavan Lalwani" }, { "code": null, "e": 3866, "s": 3833, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 3881, "s": 3866, "text": " Pavan Lalwani" }, { "code": null, "e": 3916, "s": 3881, "text": "\n 239 Lectures \n 33 hours \n" }, { "code": null, "e": 3933, "s": 3916, "text": " Gowthami Swarna" }, { "code": null, "e": 3966, "s": 3933, "text": "\n 53 Lectures \n 5 hours \n" }, { "code": null, "e": 3980, "s": 3966, "text": " Akshay Magre" }, { "code": null, "e": 3987, "s": 3980, "text": " Print" }, { "code": null, "e": 3998, "s": 3987, "text": " Add Notes" } ]
Data Persistence - Openpyxl Module
Microsoft’s Excel is the most popular spreadsheet application. It has been in use since last more than 25 years. Later versions of Excel use Office Open XML (OOXML) file format. Hence, it has been possible to access spreadsheet files through other programming environments. OOXML is an ECMA standard file format. Python’s openpyxl package provides functionality to read/write Excel files with .xlsx extension. The openpyxl package uses class nomenclature that is similar to Microsoft Excel terminology. An Excel document is called as workbook and is saved with .xlsx extension in the file system. A workbook may have multiple worksheets. A worksheet presents a large grid of cells, each one of them can store either value or formula. Rows and columns that form the grid are numbered. Columns are identified by alphabets, A, B, C, ...., Z, AA, AB, and so on. Rows are numbered starting from 1. A typical Excel worksheet appears as follows − The pip utility is good enough to install openpyxl package. pip install openpyxl The Workbook class represents an empty workbook with one blank worksheet. We need to activate it so that some data can be added to the worksheet. from openpyxl import Workbook wb=Workbook() sheet1=wb.active sheet1.title='StudentList' As we know, a cell in worksheet is named as ColumnNameRownumber format. Accordingly, top left cell is A1. We assign a string to this cell as − sheet1['A1']= 'Student List' Alternately, use worksheet’s cell() method which uses row and column number to identify a cell. Call value property to cell object to assign a value. cell1=sheet1.cell(row=1, column=1) cell1.value='Student List' After populating worksheet with data, the workbook is saved by calling save() method of workbook object. wb.save('Student.xlsx') This workbook file is created in current working directory. Following Python script writes a list of tuples into a workbook document. Each tuple stores roll number, age and marks of student. from openpyxl import Workbook wb = Workbook() sheet1 = wb.active sheet1.title='Student List' sheet1.cell(column=1, row=1).value='Student List' studentlist=[('RollNo','Name', 'age', 'marks'),(1,'Juhi',20,100), (2,'dilip',20, 110) , (3,'jeevan',24,145)] for col in range(1,5): for row in range(1,5): sheet1.cell(column=col, row=1+row).value=studentlist[row-1][col-1] wb.save('students.xlsx') The workbook students.xlsx is saved in current working directory. If opened using Excel application, it appears as below − The openpyxl module offers load_workbook() function that helps in reading back data in the workbook document. from openpyxl import load_workbook wb=load_workbook('students.xlsx') You can now access value of any cell specified by row and column number. cell1=sheet1.cell(row=1, column=1) print (cell1.value) Student List Following code populates a list with work sheet data. from openpyxl import load_workbook wb=load_workbook('students.xlsx') sheet1 = wb['Student List'] studentlist=[] for row in range(1,5): stud=[] for col in range(1,5): val=sheet1.cell(column=col, row=1+row).value stud.append(val) studentlist.append(tuple(stud)) print (studentlist) [('RollNo', 'Name', 'age', 'marks'), (1, 'Juhi', 20, 100), (2, 'dilip', 20, 110), (3, 'jeevan', 24, 145)] One very important feature of Excel application is the formula. To assign formula to a cell, assign it to a string containing Excel’s formula syntax. Assign AVERAGE function to c6 cell having age. sheet1['C6']= 'AVERAGE(C3:C5)' Openpyxl module has Translate_formula() function to copy the formula across a range. Following program defines AVERAGE function in C6 and copies it to C7 that calculates average of marks. from openpyxl import load_workbook wb=load_workbook('students.xlsx') sheet1 = wb['Student List'] from openpyxl.formula.translate import Translator#copy formula sheet1['B6']='Average' sheet1['C6']='=AVERAGE(C3:C5)' sheet1['D6'] = Translator('=AVERAGE(C3:C5)', origin="C6").translate_formula("D6") wb.save('students.xlsx') The changed worksheet now appears as follows − 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": 2629, "s": 2355, "text": "Microsoft’s Excel is the most popular spreadsheet application. It has been in use since last more than 25 years. Later versions of Excel use Office Open XML (OOXML) file format. Hence, it has been possible to access spreadsheet files through other programming environments." }, { "code": null, "e": 2765, "s": 2629, "text": "OOXML is an ECMA standard file format. Python’s openpyxl package provides functionality to read/write Excel files with .xlsx extension." }, { "code": null, "e": 3248, "s": 2765, "text": "The openpyxl package uses class nomenclature that is similar to Microsoft Excel terminology. An Excel document is called as workbook and is saved with .xlsx extension in the file system. A workbook may have multiple worksheets. A worksheet presents a large grid of cells, each one of them can store either value or formula. Rows and columns that form the grid are numbered. Columns are identified by alphabets, A, B, C, ...., Z, AA, AB, and so on. Rows are numbered starting from 1." }, { "code": null, "e": 3295, "s": 3248, "text": "A typical Excel worksheet appears as follows −" }, { "code": null, "e": 3355, "s": 3295, "text": "The pip utility is good enough to install openpyxl package." }, { "code": null, "e": 3377, "s": 3355, "text": "pip install openpyxl\n" }, { "code": null, "e": 3523, "s": 3377, "text": "The Workbook class represents an empty workbook with one blank worksheet. We need to activate it so that some data can be added to the worksheet." }, { "code": null, "e": 3611, "s": 3523, "text": "from openpyxl import Workbook\nwb=Workbook()\nsheet1=wb.active\nsheet1.title='StudentList'" }, { "code": null, "e": 3754, "s": 3611, "text": "As we know, a cell in worksheet is named as ColumnNameRownumber format. Accordingly, top left cell is A1. We assign a string to this cell as −" }, { "code": null, "e": 3784, "s": 3754, "text": "sheet1['A1']= 'Student List'\n" }, { "code": null, "e": 3934, "s": 3784, "text": "Alternately, use worksheet’s cell() method which uses row and column number to identify a cell. Call value property to cell object to assign a value." }, { "code": null, "e": 3997, "s": 3934, "text": "cell1=sheet1.cell(row=1, column=1)\ncell1.value='Student List'\n" }, { "code": null, "e": 4102, "s": 3997, "text": "After populating worksheet with data, the workbook is saved by calling save() method of workbook object." }, { "code": null, "e": 4127, "s": 4102, "text": "wb.save('Student.xlsx')\n" }, { "code": null, "e": 4187, "s": 4127, "text": "This workbook file is created in current working directory." }, { "code": null, "e": 4318, "s": 4187, "text": "Following Python script writes a list of tuples into a workbook document. Each tuple stores roll number, age and marks of student." }, { "code": null, "e": 4721, "s": 4318, "text": "from openpyxl import Workbook\nwb = Workbook()\nsheet1 = wb.active\nsheet1.title='Student List'\nsheet1.cell(column=1, row=1).value='Student List'\nstudentlist=[('RollNo','Name', 'age', 'marks'),(1,'Juhi',20,100), \n (2,'dilip',20, 110) , (3,'jeevan',24,145)]\nfor col in range(1,5):\n for row in range(1,5):\n sheet1.cell(column=col, row=1+row).value=studentlist[row-1][col-1]\nwb.save('students.xlsx')" }, { "code": null, "e": 4844, "s": 4721, "text": "The workbook students.xlsx is saved in current working directory. If opened using Excel application, it appears as below −" }, { "code": null, "e": 4954, "s": 4844, "text": "The openpyxl module offers load_workbook() function that helps in reading back data in the workbook document." }, { "code": null, "e": 5023, "s": 4954, "text": "from openpyxl import load_workbook\nwb=load_workbook('students.xlsx')" }, { "code": null, "e": 5096, "s": 5023, "text": "You can now access value of any cell specified by row and column number." }, { "code": null, "e": 5164, "s": 5096, "text": "cell1=sheet1.cell(row=1, column=1)\nprint (cell1.value)\nStudent List" }, { "code": null, "e": 5218, "s": 5164, "text": "Following code populates a list with work sheet data." }, { "code": null, "e": 5504, "s": 5218, "text": "from openpyxl import load_workbook\nwb=load_workbook('students.xlsx')\nsheet1 = wb['Student List']\nstudentlist=[]\nfor row in range(1,5):\n stud=[]\nfor col in range(1,5):\n val=sheet1.cell(column=col, row=1+row).value\nstud.append(val)\nstudentlist.append(tuple(stud))\nprint (studentlist)" }, { "code": null, "e": 5611, "s": 5504, "text": "[('RollNo', 'Name', 'age', 'marks'), (1, 'Juhi', 20, 100), (2, 'dilip', 20, 110), (3, 'jeevan', 24, 145)]\n" }, { "code": null, "e": 5808, "s": 5611, "text": "One very important feature of Excel application is the formula. To assign formula to a cell, assign it to a string containing Excel’s formula syntax. Assign AVERAGE function to c6 cell having age." }, { "code": null, "e": 5840, "s": 5808, "text": "sheet1['C6']= 'AVERAGE(C3:C5)'\n" }, { "code": null, "e": 6028, "s": 5840, "text": "Openpyxl module has Translate_formula() function to copy the formula across a range. Following program defines AVERAGE function in C6 and copies it to C7 that calculates average of marks." }, { "code": null, "e": 6350, "s": 6028, "text": "from openpyxl import load_workbook\nwb=load_workbook('students.xlsx')\n\nsheet1 = wb['Student List']\nfrom openpyxl.formula.translate import Translator#copy formula\nsheet1['B6']='Average'\nsheet1['C6']='=AVERAGE(C3:C5)'\nsheet1['D6'] = Translator('=AVERAGE(C3:C5)', origin=\"C6\").translate_formula(\"D6\")\nwb.save('students.xlsx')" }, { "code": null, "e": 6397, "s": 6350, "text": "The changed worksheet now appears as follows −" }, { "code": null, "e": 6434, "s": 6397, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6450, "s": 6434, "text": " Malhar Lathkar" }, { "code": null, "e": 6483, "s": 6450, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6502, "s": 6483, "text": " Arnab Chakraborty" }, { "code": null, "e": 6537, "s": 6502, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6559, "s": 6537, "text": " In28Minutes Official" }, { "code": null, "e": 6593, "s": 6559, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6621, "s": 6593, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6656, "s": 6621, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6670, "s": 6656, "text": " Lets Kode It" }, { "code": null, "e": 6703, "s": 6670, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6720, "s": 6703, "text": " Abhilash Nelson" }, { "code": null, "e": 6727, "s": 6720, "text": " Print" }, { "code": null, "e": 6738, "s": 6727, "text": " Add Notes" } ]
Create a red button that indicates danger in Bootstrap
To create a button in Bootstrap indicating danger, use the .btn-danger class. You can try to run the following code to implement. btn-danger class − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <p>Cick the below button in case of issues:</p> <div class = "container"> <button type = "button" class="btn btn-danger">Danger</button> </div> </body> </html>
[ { "code": null, "e": 1140, "s": 1062, "text": "To create a button in Bootstrap indicating danger, use the .btn-danger class." }, { "code": null, "e": 1211, "s": 1140, "text": "You can try to run the following code to implement. btn-danger class −" }, { "code": null, "e": 1221, "s": 1211, "text": "Live Demo" }, { "code": null, "e": 1810, "s": 1221, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>Cick the below button in case of issues:</p>\n <div class = \"container\">\n <button type = \"button\" class=\"btn btn-danger\">Danger</button>\n </div>\n </body>\n</html>" } ]
Difference between Composition and Inheritance in JavaScript - GeeksforGeeks
26 Jan, 2022 JavaScript Composition: Composition means to Compose. Everything in JavaScript is treated as an object even functions in JavaScript are treated as a high-class object. Such objects are quite complex in nature to make large complex objects simple, many small objects are composed together. Thus, we can say that composition is the cleaner, reusable and better solution for such large complex objects. Example: Javascript <script> const Motor = { accelerate(motorspeed, incrementSpeed) { return motorspeed + incrementSpeed; }, decelerate(motorspeed, decrementSpeed) { return motorspeed - decrementSpeed; }, }; const StopMotor = { stop(motorspeed) { this.motorspeed = 0; return 0; }, }; const Brand = { model: "Maxpro", }; const Treadmill = function (Design, Motor, StopMotor) { const brand = Object.create(Design); const motor = Object.create(Motor); const stopmotor = Object.create(StopMotor); const props = { motorspeed: 0, model: brand.model, }; return { set(name, value) { props[name] = value; }, get(name) { return props[name]; }, log(name) { console.log(`${name}: ${props[name]}`); }, slowDown() { props.motorspeed = motor.decelerate(props.motorspeed, 5); }, speedUp() { props.motorspeed = motor.accelerate(props.motorspeed, 10); }, stop() { props.motorspeed = stopmotor.stop(props.motorspeed); }, }; }; const Treadmill1 = Treadmill(Brand, Motor, StopMotor); // One can increase & decrease the motorspeed // according to their preferences Treadmill1.speedUp(); Treadmill1.log("motorspeed"); Treadmill1.slowDown(); Treadmill1.log("motorspeed"); Treadmill1.stop(); Treadmill1.log("motorspeed"); Treadmill1.log("model"); // Let us change the model of Treadmill1 to Powermax Treadmill1.set("model", "PowerMax"); Treadmill1.log("model");</script> Output: "motorspeed: 10" "motorspeed: 5" "motorspeed: 0" "model: Maxpro" "model: PowerMax" As it can be seen the above code is much cleaner than the one below because here the machine functionality & Features are all separated. So the class can implement functionality suitable as per their requirements.Treadmill1 can implement the functionality of Treadmill when needed. Now, Treadmill1 can increase its motorspeed, decrease its motorspped, and even change its model name as per requirement. When talked about composition, the Inheritance gets assisted automatically. JavaScript Inheritance: Inheritance is gaining some or all traits (functionality) of parent and then providing a relational structure which seems to be a tedious little, Unlike Class Composition which implements each functionality separately so that each and every class can use the functionality according to their requirements. Mixin plays a vital role when it comes to inheritance in JavaScript. Mixin is actually mixing which could be any i.e. car into a vehiclemixin means mixing car to the vehicle. To understand the concept properly let’s take an example of Gym/Exercise Machine which is a fitness machine mixin. motorspeed is used to increase, decrease and stop the machine, the case depicted below is of inheritance as Treadmill1 is assigned the object & all its properties of Treadmill. So, now Treadmill1 can perform all the functions of Treadmill i.e. One can increase the motorspeed, decrease the motospeed, and even set the properties in our case which is brand which was Maxpro before and PowerMax later. Example: Javascript <script> const machineMixin = { set(name, value) { this[name] = value; }, get(name) { return this[name]; }, motorspeed: 0, inclinespeed() { this.motorspeed += 10; console.log(`Inclinedspeed is: ${this.motorspeed}`); }, declinespeed() { this.motorspeed -= 5; console.log(`Declinedspeed is: ${this.motorspeed}`); }, stopmachine() { this.motorspeed = 0; console.log(`Now the speed is: ${this.motorspeed}`); }, }; const Treadmill = { brand: "Maxpro", motorspeed: 0 }; const Treadmill1 = Object.assign({}, Treadmill, machineMixin); // You can increase the speed of Treadmill1 Treadmill1.inclinespeed(); // You can even decrease the speed of Treadmill1 Treadmill1.declinespeed(); // Let's just stop the machine Treadmill1.stopmachine(); // It's Time to access the brand of treadmill1 console.log(Treadmill1.get("brand")); // let's change the brand of Treadmill1 Treadmill1.brand = "PowerMax"; console.log(Treadmill1.get("brand"));</script> Output: "Inclinedspeed is: 10" "Declinedspeed is: 5" "Now the speed is: 0" "Maxpro" "PowerMax" In the output above it is clearly visible that all operations are performed by Treadmill1 which was assigned Treadmill object which possesses machinemixin.At First and foremost, the motorspeed was 0 after applying inclinespeed() method the motorspeed increased by 5 after that decline speed method was performed which reduced the speed by 5 finally stop operation was performed which stopped the machine by making its motor speed zero. The brand was changed from Maxpro to Powermax which shows the power of Inheritance. Given below is the comparison table between Composition & JavaScript. Conclusion: Both Inheritance & Composition yields the same result but the way of implementation matters. The composition implementation way is much easily readable & preferable to first inheritance. Attention reader! Don’t stop learning now. Get hold of all the important JavaScript Courses at a student-friendly price and become industry-ready. simranarora5sos adnanirshad158 javascript-object javascript-oop Technical Scripter 2020 JavaScript Technical Scripter Web Technologies 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 PUT and PATCH Request How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n26 Jan, 2022" }, { "code": null, "e": 25700, "s": 25300, "text": "JavaScript Composition: Composition means to Compose. Everything in JavaScript is treated as an object even functions in JavaScript are treated as a high-class object. Such objects are quite complex in nature to make large complex objects simple, many small objects are composed together. Thus, we can say that composition is the cleaner, reusable and better solution for such large complex objects." }, { "code": null, "e": 25709, "s": 25700, "text": "Example:" }, { "code": null, "e": 25720, "s": 25709, "text": "Javascript" }, { "code": "<script> const Motor = { accelerate(motorspeed, incrementSpeed) { return motorspeed + incrementSpeed; }, decelerate(motorspeed, decrementSpeed) { return motorspeed - decrementSpeed; }, }; const StopMotor = { stop(motorspeed) { this.motorspeed = 0; return 0; }, }; const Brand = { model: \"Maxpro\", }; const Treadmill = function (Design, Motor, StopMotor) { const brand = Object.create(Design); const motor = Object.create(Motor); const stopmotor = Object.create(StopMotor); const props = { motorspeed: 0, model: brand.model, }; return { set(name, value) { props[name] = value; }, get(name) { return props[name]; }, log(name) { console.log(`${name}: ${props[name]}`); }, slowDown() { props.motorspeed = motor.decelerate(props.motorspeed, 5); }, speedUp() { props.motorspeed = motor.accelerate(props.motorspeed, 10); }, stop() { props.motorspeed = stopmotor.stop(props.motorspeed); }, }; }; const Treadmill1 = Treadmill(Brand, Motor, StopMotor); // One can increase & decrease the motorspeed // according to their preferences Treadmill1.speedUp(); Treadmill1.log(\"motorspeed\"); Treadmill1.slowDown(); Treadmill1.log(\"motorspeed\"); Treadmill1.stop(); Treadmill1.log(\"motorspeed\"); Treadmill1.log(\"model\"); // Let us change the model of Treadmill1 to Powermax Treadmill1.set(\"model\", \"PowerMax\"); Treadmill1.log(\"model\");</script>", "e": 27256, "s": 25720, "text": null }, { "code": null, "e": 27264, "s": 27256, "text": "Output:" }, { "code": null, "e": 27347, "s": 27264, "text": "\"motorspeed: 10\"\n\"motorspeed: 5\"\n\"motorspeed: 0\"\n\"model: Maxpro\"\n\"model: PowerMax\"" }, { "code": null, "e": 27827, "s": 27347, "text": "As it can be seen the above code is much cleaner than the one below because here the machine functionality & Features are all separated. So the class can implement functionality suitable as per their requirements.Treadmill1 can implement the functionality of Treadmill when needed. Now, Treadmill1 can increase its motorspeed, decrease its motorspped, and even change its model name as per requirement. When talked about composition, the Inheritance gets assisted automatically. " }, { "code": null, "e": 28847, "s": 27827, "text": "JavaScript Inheritance: Inheritance is gaining some or all traits (functionality) of parent and then providing a relational structure which seems to be a tedious little, Unlike Class Composition which implements each functionality separately so that each and every class can use the functionality according to their requirements. Mixin plays a vital role when it comes to inheritance in JavaScript. Mixin is actually mixing which could be any i.e. car into a vehiclemixin means mixing car to the vehicle. To understand the concept properly let’s take an example of Gym/Exercise Machine which is a fitness machine mixin. motorspeed is used to increase, decrease and stop the machine, the case depicted below is of inheritance as Treadmill1 is assigned the object & all its properties of Treadmill. So, now Treadmill1 can perform all the functions of Treadmill i.e. One can increase the motorspeed, decrease the motospeed, and even set the properties in our case which is brand which was Maxpro before and PowerMax later." }, { "code": null, "e": 28856, "s": 28847, "text": "Example:" }, { "code": null, "e": 28867, "s": 28856, "text": "Javascript" }, { "code": "<script> const machineMixin = { set(name, value) { this[name] = value; }, get(name) { return this[name]; }, motorspeed: 0, inclinespeed() { this.motorspeed += 10; console.log(`Inclinedspeed is: ${this.motorspeed}`); }, declinespeed() { this.motorspeed -= 5; console.log(`Declinedspeed is: ${this.motorspeed}`); }, stopmachine() { this.motorspeed = 0; console.log(`Now the speed is: ${this.motorspeed}`); }, }; const Treadmill = { brand: \"Maxpro\", motorspeed: 0 }; const Treadmill1 = Object.assign({}, Treadmill, machineMixin); // You can increase the speed of Treadmill1 Treadmill1.inclinespeed(); // You can even decrease the speed of Treadmill1 Treadmill1.declinespeed(); // Let's just stop the machine Treadmill1.stopmachine(); // It's Time to access the brand of treadmill1 console.log(Treadmill1.get(\"brand\")); // let's change the brand of Treadmill1 Treadmill1.brand = \"PowerMax\"; console.log(Treadmill1.get(\"brand\"));</script>", "e": 29900, "s": 28867, "text": null }, { "code": null, "e": 29908, "s": 29900, "text": "Output:" }, { "code": null, "e": 29995, "s": 29908, "text": "\"Inclinedspeed is: 10\"\n\"Declinedspeed is: 5\"\n\"Now the speed is: 0\"\n\"Maxpro\"\n\"PowerMax\"" }, { "code": null, "e": 30585, "s": 29995, "text": "In the output above it is clearly visible that all operations are performed by Treadmill1 which was assigned Treadmill object which possesses machinemixin.At First and foremost, the motorspeed was 0 after applying inclinespeed() method the motorspeed increased by 5 after that decline speed method was performed which reduced the speed by 5 finally stop operation was performed which stopped the machine by making its motor speed zero. The brand was changed from Maxpro to Powermax which shows the power of Inheritance. Given below is the comparison table between Composition & JavaScript." }, { "code": null, "e": 30784, "s": 30585, "text": "Conclusion: Both Inheritance & Composition yields the same result but the way of implementation matters. The composition implementation way is much easily readable & preferable to first inheritance." }, { "code": null, "e": 30931, "s": 30784, "text": "Attention reader! Don’t stop learning now. Get hold of all the important JavaScript Courses at a student-friendly price and become industry-ready." }, { "code": null, "e": 30947, "s": 30931, "text": "simranarora5sos" }, { "code": null, "e": 30962, "s": 30947, "text": "adnanirshad158" }, { "code": null, "e": 30980, "s": 30962, "text": "javascript-object" }, { "code": null, "e": 30995, "s": 30980, "text": "javascript-oop" }, { "code": null, "e": 31019, "s": 30995, "text": "Technical Scripter 2020" }, { "code": null, "e": 31030, "s": 31019, "text": "JavaScript" }, { "code": null, "e": 31049, "s": 31030, "text": "Technical Scripter" }, { "code": null, "e": 31066, "s": 31049, "text": "Web Technologies" }, { "code": null, "e": 31164, "s": 31066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31173, "s": 31164, "text": "Comments" }, { "code": null, "e": 31186, "s": 31173, "text": "Old Comments" }, { "code": null, "e": 31247, "s": 31186, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31288, "s": 31247, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31342, "s": 31288, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 31404, "s": 31342, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 31461, "s": 31404, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 31503, "s": 31461, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31536, "s": 31503, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31579, "s": 31536, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31641, "s": 31579, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
REVERSE() Function in MySQL - GeeksforGeeks
31 Aug, 2020 REVERSE() :This function could be used to reverse a string and find the result. The REVERSE() function takes input parameter as string and results the reverse order of that string. Syntax : SELECT REVERSE(string) Note –The parameter string is mandatory, It is the string that will be reversed. Example-1: SELECT REVERSE("GFG"); Output : Example-2:Using REVERSE() function to reverse a string : SELECT REVERSE("Geeksforgeeks"); Output : Using REVERSE() function to reverse a sentence : SELECT REVERSE("Geeksforgeeks is an interesting site"); Output : Using REVERSE() function to find if a string is Palindrome : DECLARE @input VARCHAR(100) = 'madam'; SELECT CASE WHEN @input = REVERSE(@input) THEN 'Palindrome' ELSE 'Not Palindrome' END result; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database SQL | Views Difference between DDL and DML in DBMS CTE in SQL SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? How to Alter Multiple Columns at Once in SQL Server? Difference between DELETE, DROP and TRUNCATE SQL | GROUP BY Difference between SQL and NoSQL
[ { "code": null, "e": 24852, "s": 24824, "text": "\n31 Aug, 2020" }, { "code": null, "e": 25033, "s": 24852, "text": "REVERSE() :This function could be used to reverse a string and find the result. The REVERSE() function takes input parameter as string and results the reverse order of that string." }, { "code": null, "e": 25042, "s": 25033, "text": "Syntax :" }, { "code": null, "e": 25066, "s": 25042, "text": "SELECT REVERSE(string)\n" }, { "code": null, "e": 25147, "s": 25066, "text": "Note –The parameter string is mandatory, It is the string that will be reversed." }, { "code": null, "e": 25158, "s": 25147, "text": "Example-1:" }, { "code": null, "e": 25182, "s": 25158, "text": "SELECT REVERSE(\"GFG\");\n" }, { "code": null, "e": 25191, "s": 25182, "text": "Output :" }, { "code": null, "e": 25248, "s": 25191, "text": "Example-2:Using REVERSE() function to reverse a string :" }, { "code": null, "e": 25282, "s": 25248, "text": "SELECT REVERSE(\"Geeksforgeeks\");\n" }, { "code": null, "e": 25291, "s": 25282, "text": "Output :" }, { "code": null, "e": 25340, "s": 25291, "text": "Using REVERSE() function to reverse a sentence :" }, { "code": null, "e": 25397, "s": 25340, "text": "SELECT REVERSE(\"Geeksforgeeks is an interesting site\");\n" }, { "code": null, "e": 25406, "s": 25397, "text": "Output :" }, { "code": null, "e": 25467, "s": 25406, "text": "Using REVERSE() function to find if a string is Palindrome :" }, { "code": null, "e": 25603, "s": 25467, "text": "DECLARE \n@input VARCHAR(100) = 'madam';\nSELECT \nCASE\nWHEN @input = REVERSE(@input)\nTHEN 'Palindrome'\nELSE 'Not Palindrome'\nEND result;\n" }, { "code": null, "e": 25612, "s": 25603, "text": "Output :" }, { "code": null, "e": 25621, "s": 25612, "text": "DBMS-SQL" }, { "code": null, "e": 25627, "s": 25621, "text": "mysql" }, { "code": null, "e": 25631, "s": 25627, "text": "SQL" }, { "code": null, "e": 25635, "s": 25631, "text": "SQL" }, { "code": null, "e": 25733, "s": 25635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25742, "s": 25733, "text": "Comments" }, { "code": null, "e": 25755, "s": 25742, "text": "Old Comments" }, { "code": null, "e": 25786, "s": 25755, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 25798, "s": 25786, "text": "SQL | Views" }, { "code": null, "e": 25837, "s": 25798, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25848, "s": 25837, "text": "CTE in SQL" }, { "code": null, "e": 25872, "s": 25848, "text": "SQL Interview Questions" }, { "code": null, "e": 25938, "s": 25872, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25991, "s": 25938, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 26036, "s": 25991, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26051, "s": 26036, "text": "SQL | GROUP BY" } ]
5 Anomaly Detection Algorithms every Data Scientist should know | by Satyam Kumar | Towards Data Science
A real-world dataset often contains anomalies or outlier data points. The cause of anomalies may be data corruption, experimental or human errors. The presence of anomalies may impact the performance of the model, hence to train a robust data science model, the dataset should be free from anomalies. In this article, we will discuss 5 such anomaly detection techniques and compare their performance for a random sample of data. Anomalies are data points that stand out amongst other data points in the dataset and do not confirm the normal behavior in the data. These data points or observations deviate from the dataset’s normal behavioral patterns. Anomaly detection is an unsupervised data processing technique to detect anomalies from the dataset. An anomaly can be broadly classified into different categories: Outliers: Short/small anomalous patterns that appear in a non-systematic way in data collection. Change in Events: Systematic or sudden change from the previous normal behavior. Drifts: Slow, undirectional, long-term change in the data. Anomalies detection are very useful to detect fraudulent transactions, disease detection, or handle any case studies with high-class imbalance. Anomalies detection techniques can be used to build more robust data science models. Simple statistical techniques such as mean, median, quantiles can be used to detect univariate anomalies feature values in the dataset. Various data visualization and exploratory data analysis techniques can be also be used to detect anomalies. In this article, we will discuss some unsupervised machine learning algorithms to detect anomalies, and further compare their performance for a random sample dataset. Checklist:1. Isolation Forest2. Local Outlier Factor3. Robust Covariance4. One-Class SVM5. One-Class SVM (SGD) Isolation Forest is an unsupervised anomaly detection algorithm that uses a random forest algorithm (decision trees) under the hood to detect outliers in the dataset. The algorithm tries to split or divide the data points such that each observation gets isolated from the others. Usually, the anomalies lie away from the cluster of data points, so it's easier to isolate the anomalies compare to the regular data points. From the above-mentioned images, it can be observed that the regular data points require a comparatively larger number of partitions than an anomaly data point. The anomaly score is computed for all the data points and the points anomaly score > threshold value can be considered as anomalies. Scikit-learn implementation of Isolation Forest algorithm Local Outlier Factor is another anomaly detection technique that takes the density of data points into consideration to decide whether a point is an anomaly or not. The local outlier factor computes an anomaly score called anomaly score that measures how isolated the point is with respect to the surrounding neighborhood. It takes into account the local as well as the global density to compute the anomaly score. Scikit-learn implementation of Local Outlier Factor For gaussian independent features, simple statistical techniques can be employed to detect anomalies in the dataset. For a gaussian/normal distribution, the data points lying away from 3rd deviation can be considered as anomalies. For a dataset having all the feature gaussian in nature, then the statistical approach can be generalized by defining an elliptical hypersphere that covers most of the regular data points, and the data points that lie away from the hypersphere can be considered as anomalies. Scikit-learn implementation of Robust Covariance using Elliptic Envelope A regular SVM algorithm tries to find a hyperplane that best separates the two classes of data points. For one-class SVM where we have one class of data points, and the task is to predict a hypersphere that separates the cluster of data points from the anomalies. Scikit-learn implementation of One-Class SVM One-class SVM with SGD solves the linear One-Class SVM using Stochastic Gradient Descent. The implementation is meant to be used with a kernel approximation technique to obtain results similar to sklearn.svm.OneClassSVM which uses a Gaussian kernel by default. Scikit-learn implementation of One-Class SVM with SGD The 5 anomalies detection are trained on two sets of sample datasets (row 1 and row 2). One-class SVM tends to overfit a bit, whereas the other algorithms perform well with the sample dataset. Anomaly detection algorithms are very useful for fraud detection or disease detection case studies where the distribution of the target class is highly imbalanced. Anomaly detection algorithms are also to further improve the performance of the model by removing the anomalies from the training sample. Apart from the above-discussed machine learning algorithms, the data scientist can always employ advanced statistical techniques to handle the anomalies. [1] Scikit-learn documentation: https://scikit-learn.org/stable/auto_examples/miscellaneous/plot_anomaly_comparison.html Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you. satyam-kumar.medium.com Thank You for Reading
[ { "code": null, "e": 473, "s": 172, "text": "A real-world dataset often contains anomalies or outlier data points. The cause of anomalies may be data corruption, experimental or human errors. The presence of anomalies may impact the performance of the model, hence to train a robust data science model, the dataset should be free from anomalies." }, { "code": null, "e": 601, "s": 473, "text": "In this article, we will discuss 5 such anomaly detection techniques and compare their performance for a random sample of data." }, { "code": null, "e": 824, "s": 601, "text": "Anomalies are data points that stand out amongst other data points in the dataset and do not confirm the normal behavior in the data. These data points or observations deviate from the dataset’s normal behavioral patterns." }, { "code": null, "e": 989, "s": 824, "text": "Anomaly detection is an unsupervised data processing technique to detect anomalies from the dataset. An anomaly can be broadly classified into different categories:" }, { "code": null, "e": 1086, "s": 989, "text": "Outliers: Short/small anomalous patterns that appear in a non-systematic way in data collection." }, { "code": null, "e": 1167, "s": 1086, "text": "Change in Events: Systematic or sudden change from the previous normal behavior." }, { "code": null, "e": 1226, "s": 1167, "text": "Drifts: Slow, undirectional, long-term change in the data." }, { "code": null, "e": 1455, "s": 1226, "text": "Anomalies detection are very useful to detect fraudulent transactions, disease detection, or handle any case studies with high-class imbalance. Anomalies detection techniques can be used to build more robust data science models." }, { "code": null, "e": 1700, "s": 1455, "text": "Simple statistical techniques such as mean, median, quantiles can be used to detect univariate anomalies feature values in the dataset. Various data visualization and exploratory data analysis techniques can be also be used to detect anomalies." }, { "code": null, "e": 1867, "s": 1700, "text": "In this article, we will discuss some unsupervised machine learning algorithms to detect anomalies, and further compare their performance for a random sample dataset." }, { "code": null, "e": 1978, "s": 1867, "text": "Checklist:1. Isolation Forest2. Local Outlier Factor3. Robust Covariance4. One-Class SVM5. One-Class SVM (SGD)" }, { "code": null, "e": 2258, "s": 1978, "text": "Isolation Forest is an unsupervised anomaly detection algorithm that uses a random forest algorithm (decision trees) under the hood to detect outliers in the dataset. The algorithm tries to split or divide the data points such that each observation gets isolated from the others." }, { "code": null, "e": 2399, "s": 2258, "text": "Usually, the anomalies lie away from the cluster of data points, so it's easier to isolate the anomalies compare to the regular data points." }, { "code": null, "e": 2560, "s": 2399, "text": "From the above-mentioned images, it can be observed that the regular data points require a comparatively larger number of partitions than an anomaly data point." }, { "code": null, "e": 2693, "s": 2560, "text": "The anomaly score is computed for all the data points and the points anomaly score > threshold value can be considered as anomalies." }, { "code": null, "e": 2751, "s": 2693, "text": "Scikit-learn implementation of Isolation Forest algorithm" }, { "code": null, "e": 3166, "s": 2751, "text": "Local Outlier Factor is another anomaly detection technique that takes the density of data points into consideration to decide whether a point is an anomaly or not. The local outlier factor computes an anomaly score called anomaly score that measures how isolated the point is with respect to the surrounding neighborhood. It takes into account the local as well as the global density to compute the anomaly score." }, { "code": null, "e": 3218, "s": 3166, "text": "Scikit-learn implementation of Local Outlier Factor" }, { "code": null, "e": 3449, "s": 3218, "text": "For gaussian independent features, simple statistical techniques can be employed to detect anomalies in the dataset. For a gaussian/normal distribution, the data points lying away from 3rd deviation can be considered as anomalies." }, { "code": null, "e": 3725, "s": 3449, "text": "For a dataset having all the feature gaussian in nature, then the statistical approach can be generalized by defining an elliptical hypersphere that covers most of the regular data points, and the data points that lie away from the hypersphere can be considered as anomalies." }, { "code": null, "e": 3798, "s": 3725, "text": "Scikit-learn implementation of Robust Covariance using Elliptic Envelope" }, { "code": null, "e": 4062, "s": 3798, "text": "A regular SVM algorithm tries to find a hyperplane that best separates the two classes of data points. For one-class SVM where we have one class of data points, and the task is to predict a hypersphere that separates the cluster of data points from the anomalies." }, { "code": null, "e": 4107, "s": 4062, "text": "Scikit-learn implementation of One-Class SVM" }, { "code": null, "e": 4368, "s": 4107, "text": "One-class SVM with SGD solves the linear One-Class SVM using Stochastic Gradient Descent. The implementation is meant to be used with a kernel approximation technique to obtain results similar to sklearn.svm.OneClassSVM which uses a Gaussian kernel by default." }, { "code": null, "e": 4422, "s": 4368, "text": "Scikit-learn implementation of One-Class SVM with SGD" }, { "code": null, "e": 4510, "s": 4422, "text": "The 5 anomalies detection are trained on two sets of sample datasets (row 1 and row 2)." }, { "code": null, "e": 4615, "s": 4510, "text": "One-class SVM tends to overfit a bit, whereas the other algorithms perform well with the sample dataset." }, { "code": null, "e": 4917, "s": 4615, "text": "Anomaly detection algorithms are very useful for fraud detection or disease detection case studies where the distribution of the target class is highly imbalanced. Anomaly detection algorithms are also to further improve the performance of the model by removing the anomalies from the training sample." }, { "code": null, "e": 5071, "s": 4917, "text": "Apart from the above-discussed machine learning algorithms, the data scientist can always employ advanced statistical techniques to handle the anomalies." }, { "code": null, "e": 5192, "s": 5071, "text": "[1] Scikit-learn documentation: https://scikit-learn.org/stable/auto_examples/miscellaneous/plot_anomaly_comparison.html" }, { "code": null, "e": 5381, "s": 5192, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 5405, "s": 5381, "text": "satyam-kumar.medium.com" } ]
How to Handle duplicate attributes in BeautifulSoup ? - GeeksforGeeks
07 Apr, 2021 Sometimes while obtaining the information, are you facing any issue in handling the information received from duplicate attributes of the same tags? If YES, then read the article and clear all your doubts. Once you have created the list to store the items, write the given below code. Syntax: list=soup.find_all(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”}) After writing the following code, remove the attributes from the output and print the certain item you want from the list. Import module Now, remove the last segment of the path by entering the name of Python file in which you are currently working. Syntax: base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working’)) Then, open the HTML file from which you want to read the value. Syntax: html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’)) Parse the HTML file in BeautifulSoup. Further, create a list to store all the item values of the same tag and attributes. Next, find all the items which have same tag and attributes. Syntax: list=soup.find_all(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”}) Later on, remove all the attributes from the tag. Finally, print the certain item of the widget tag. Webpage in use: HTML <!DOCTYPE html><html> <head> Geeks For Geeks </head> <body> <div> <p id="vinayak">King</p> <p id="vinayak">Prince</p> <p id="vinayak">Queen</p> </div> <p id="vinayak">Princess</p> </body></html> Program: Python # Import the libraries beautifulsoup and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the path# Here replace the name of your python file with# gfg4.pybase = os.path.dirname(os.path.abspath("gfg4.py")) # Open the HTML in which you want to make # changeshtml = open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Create a list to store the itemslist = [3] # Finding all the elements inside div# with paragraph having id: vinayaklist = soup.div.find_all("p", {"id": "vinayak"}) # Removing attributes from the outputfor i in list: i.attrs = {} # Printing the value Princeprint(list[1]) # Printing the value Queenprint(list[2]) Output: <p>Prince</p> <p>Queen</p> Picked Python BeautifulSoup Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n07 Apr, 2021" }, { "code": null, "e": 24418, "s": 24212, "text": "Sometimes while obtaining the information, are you facing any issue in handling the information received from duplicate attributes of the same tags? If YES, then read the article and clear all your doubts." }, { "code": null, "e": 24497, "s": 24418, "text": "Once you have created the list to store the items, write the given below code." }, { "code": null, "e": 24506, "s": 24497, "text": "Syntax: " }, { "code": null, "e": 24596, "s": 24506, "text": "list=soup.find_all(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”})" }, { "code": null, "e": 24719, "s": 24596, "text": "After writing the following code, remove the attributes from the output and print the certain item you want from the list." }, { "code": null, "e": 24733, "s": 24719, "text": "Import module" }, { "code": null, "e": 24846, "s": 24733, "text": "Now, remove the last segment of the path by entering the name of Python file in which you are currently working." }, { "code": null, "e": 24854, "s": 24846, "text": "Syntax:" }, { "code": null, "e": 24951, "s": 24854, "text": "base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working’))" }, { "code": null, "e": 25015, "s": 24951, "text": "Then, open the HTML file from which you want to read the value." }, { "code": null, "e": 25023, "s": 25015, "text": "Syntax:" }, { "code": null, "e": 25109, "s": 25023, "text": "html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’))" }, { "code": null, "e": 25147, "s": 25109, "text": "Parse the HTML file in BeautifulSoup." }, { "code": null, "e": 25231, "s": 25147, "text": "Further, create a list to store all the item values of the same tag and attributes." }, { "code": null, "e": 25292, "s": 25231, "text": "Next, find all the items which have same tag and attributes." }, { "code": null, "e": 25300, "s": 25292, "text": "Syntax:" }, { "code": null, "e": 25390, "s": 25300, "text": "list=soup.find_all(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”})" }, { "code": null, "e": 25440, "s": 25390, "text": "Later on, remove all the attributes from the tag." }, { "code": null, "e": 25491, "s": 25440, "text": "Finally, print the certain item of the widget tag." }, { "code": null, "e": 25507, "s": 25491, "text": "Webpage in use:" }, { "code": null, "e": 25512, "s": 25507, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> Geeks For Geeks </head> <body> <div> <p id=\"vinayak\">King</p> <p id=\"vinayak\">Prince</p> <p id=\"vinayak\">Queen</p> </div> <p id=\"vinayak\">Princess</p> </body></html>", "e": 25730, "s": 25512, "text": null }, { "code": null, "e": 25739, "s": 25730, "text": "Program:" }, { "code": null, "e": 25746, "s": 25739, "text": "Python" }, { "code": "# Import the libraries beautifulsoup and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the path# Here replace the name of your python file with# gfg4.pybase = os.path.dirname(os.path.abspath(\"gfg4.py\")) # Open the HTML in which you want to make # changeshtml = open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Create a list to store the itemslist = [3] # Finding all the elements inside div# with paragraph having id: vinayaklist = soup.div.find_all(\"p\", {\"id\": \"vinayak\"}) # Removing attributes from the outputfor i in list: i.attrs = {} # Printing the value Princeprint(list[1]) # Printing the value Queenprint(list[2])", "e": 26465, "s": 25746, "text": null }, { "code": null, "e": 26473, "s": 26465, "text": "Output:" }, { "code": null, "e": 26487, "s": 26473, "text": "<p>Prince</p>" }, { "code": null, "e": 26500, "s": 26487, "text": "<p>Queen</p>" }, { "code": null, "e": 26507, "s": 26500, "text": "Picked" }, { "code": null, "e": 26528, "s": 26507, "text": "Python BeautifulSoup" }, { "code": null, "e": 26535, "s": 26528, "text": "Python" }, { "code": null, "e": 26633, "s": 26535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26642, "s": 26633, "text": "Comments" }, { "code": null, "e": 26655, "s": 26642, "text": "Old Comments" }, { "code": null, "e": 26676, "s": 26655, "text": "Python OOPs Concepts" }, { "code": null, "e": 26708, "s": 26676, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26731, "s": 26708, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26753, "s": 26731, "text": "Defaultdict in Python" }, { "code": null, "e": 26780, "s": 26753, "text": "Python Classes and Objects" }, { "code": null, "e": 26796, "s": 26780, "text": "Deque in Python" }, { "code": null, "e": 26838, "s": 26796, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26894, "s": 26838, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26939, "s": 26894, "text": "Python - Ways to remove duplicates from list" } ]
Stack Unwinding in C++
Here we will see what is the meaning of stack unwinding. When we call some functions, it stores the address into call stack, and after coming back from the functions, pops out the address to start the work where it was left of. The stack unwinding is a process where the function call stack entries are removed at runtime. To remove stack elements, we can use exceptions. If an exception is thrown from the inner function, then all of the entries of the stack is removed, and return to the main invoker function. Let us see the effect of stack unwinding through an example. #include <iostream> using namespace std; void function1() throw (int) { //this function throws exception cout<<"\n Entering into function 1"; throw 100; cout<<"\n Exiting function 1"; } void function2() throw (int) { //This function calls function 1 cout<<"\n Entering into function 2"; function1(); cout<<"\n Exiting function 2"; } void function3() { //function to call function2, and handle exception thrown by function1 cout<<"\n Entering function 3 "; try { function2(); //try to execute function 2 } catch(int i) { cout<<"\n Caught Exception: "<<i; } cout<<"\n Exiting function 3"; } int main() { function3(); return 0; } Entering function 3 Entering into function 2 Entering into function 1 Caught Exception: 100 Exiting function 3 Here we can see that the control stores info of function3, then enters into function2, and then into function1. After that one exception occurs, so it removes all of the information from stack, and returns back to function3 again.
[ { "code": null, "e": 1290, "s": 1062, "text": "Here we will see what is the meaning of stack unwinding. When we call some functions, it stores the address into call stack, and after coming back from the functions, pops out the address to start the work where it was left of." }, { "code": null, "e": 1575, "s": 1290, "text": "The stack unwinding is a process where the function call stack entries are removed at runtime. To remove stack elements, we can use exceptions. If an exception is thrown from the inner function, then all of the entries of the stack is removed, and return to the main invoker function." }, { "code": null, "e": 1636, "s": 1575, "text": "Let us see the effect of stack unwinding through an example." }, { "code": null, "e": 2324, "s": 1636, "text": "#include <iostream>\nusing namespace std;\n\nvoid function1() throw (int) { //this function throws exception\n cout<<\"\\n Entering into function 1\";\n throw 100;\n cout<<\"\\n Exiting function 1\";\n}\n\nvoid function2() throw (int) { //This function calls function 1\n cout<<\"\\n Entering into function 2\";\n function1();\n cout<<\"\\n Exiting function 2\";\n}\n\nvoid function3() { //function to call function2, and handle\n exception thrown by function1\n cout<<\"\\n Entering function 3 \";\n try {\n function2(); //try to execute function 2\n }\n catch(int i) {\n cout<<\"\\n Caught Exception: \"<<i;\n }\n cout<<\"\\n Exiting function 3\";\n}\n\nint main() {\n function3();\n return 0;\n}" }, { "code": null, "e": 2435, "s": 2324, "text": "Entering function 3\nEntering into function 2\nEntering into function 1\nCaught Exception: 100\nExiting function 3" }, { "code": null, "e": 2666, "s": 2435, "text": "Here we can see that the control stores info of function3, then enters into function2, and then into function1. After that one exception occurs, so it removes all of the information from stack, and returns back to function3 again." } ]
Perl fork Function
This function forks a new process using the fork( ) system call. Any shared sockets or filehandles are duplicated across processes. You must ensure that you wait on your children to prevent "zombie" processes from forming. Following is the simple syntax for this function − fork This function returns undef on failure to fork and Child process ID to parent on success 0 to child on success. Following is the example code showing its basic usage − #!/usr/bin/perl $pid = fork(); if( $pid == 0 ) { print "This is child process\n"; print "Child process is existing\n"; exit 0; } print "This is parent process and child ID is $pid\n"; print "Parent process is existing\n"; exit 0; When above code is executed, it produces the following result − This is parent process and child ID is 18641 Parent process is existing This is child process Child process is existing 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2443, "s": 2220, "text": "This function forks a new process using the fork( ) system call. Any shared sockets or filehandles are duplicated across processes. You must ensure that you wait on your children to prevent \"zombie\" processes from forming." }, { "code": null, "e": 2494, "s": 2443, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2500, "s": 2494, "text": "fork\n" }, { "code": null, "e": 2612, "s": 2500, "text": "This function returns undef on failure to fork and Child process ID to parent on success 0 to child on success." }, { "code": null, "e": 2668, "s": 2612, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 2908, "s": 2668, "text": "#!/usr/bin/perl\n\n$pid = fork();\nif( $pid == 0 ) {\n print \"This is child process\\n\";\n print \"Child process is existing\\n\";\n exit 0;\n}\nprint \"This is parent process and child ID is $pid\\n\";\nprint \"Parent process is existing\\n\";\nexit 0;" }, { "code": null, "e": 2972, "s": 2908, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 3093, "s": 2972, "text": "This is parent process and child ID is 18641\nParent process is existing\nThis is child process\nChild process is existing\n" }, { "code": null, "e": 3128, "s": 3093, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3142, "s": 3128, "text": " Devi Killada" }, { "code": null, "e": 3177, "s": 3142, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3197, "s": 3177, "text": " Harshit Srivastava" }, { "code": null, "e": 3230, "s": 3197, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3246, "s": 3230, "text": " TELCOMA Global" }, { "code": null, "e": 3279, "s": 3246, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3296, "s": 3279, "text": " Mohammad Nauman" }, { "code": null, "e": 3329, "s": 3296, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3352, "s": 3329, "text": " Stone River ELearning" }, { "code": null, "e": 3387, "s": 3352, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3410, "s": 3387, "text": " Stone River ELearning" }, { "code": null, "e": 3417, "s": 3410, "text": " Print" }, { "code": null, "e": 3428, "s": 3417, "text": " Add Notes" } ]
Why do we get warning 'newdata' had 1 row but variables found have X rows while predicting a linear model in R?
The reason we get newdata had 1 row warning is the newdata is not correctly defined. We should give the name of the explanatory variable or independent variable to the newdata so that the model can identify that we are passing the mean of the explanatory variable, otherwise it considers all the values of the explanatory hence the result of the predict function yields the predicted values for the sample size. Live Demo Consider the below data frame − set.seed(123) x<-rnorm(20,0.05) y<-rpois(20,5) df<-data.frame(x,y) df x y 1 -0.5104756 3 2 -0.1801775 4 3 1.6087083 4 4 0.1205084 4 5 0.1792877 3 6 1.7650650 3 7 0.5109162 3 8 -1.2150612 5 9 -0.6368529 4 10 -0.3956620 7 11 1.2740818 2 12 0.4098138 5 13 0.4507715 7 14 0.1606827 2 15 -0.5058411 5 16 1.8369131 3 17 0.5478505 3 18 -1.9166172 6 19 0.7513559 8 20 -0.4227914 4 Creating the linear model − M<-lm(y~x,data=df) Now let’s predict the value of y for the mean of x − predict(M,newdata=data.frame(mean(df$x)),interval="confidence") fit lwr upr 1 4.645695 3.690676 5.600715 2 4.459543 3.635161 5.283925 3 3.451347 2.071115 4.831579 4 4.290080 3.520452 5.059707 5 4.256952 3.489416 5.024489 6 3.363226 1.876124 4.850329 7 4.070050 3.260221 4.879880 8 5.042792 3.669549 6.416034 9 4.716920 3.697691 5.736149 10 4.580988 3.678189 5.483786 11 3.639939 2.475080 4.804798 12 4.127031 3.339496 4.914565 13 4.103947 3.308320 4.899575 14 4.267438 3.499558 5.035318 15 4.643083 3.690292 5.595875 16 3.322734 1.785518 4.859949 17 4.049235 3.229372 4.869097 18 5.438181 3.566862 7.309500 19 3.934541 3.043288 4.825795 20 4.596277 3.681723 5.510832 Warning message − 'newdata' had 1 row but variables found have 20 rows To get rid of this warning we need to define the newdata for x variable as shown below − predict(M,newdata=data.frame(x=mean(df$x)),interval="confidence") fit lwr upr 1 4.25 3.482529 5.017471 Same thing happens when we try to predict y for a fixed value − predict(M,newdata=data.frame(1.2),interval="confidence") fit lwr upr 1 4.645695 3.690676 5.600715 2 4.459543 3.635161 5.283925 3 3.451347 2.071115 4.831579 4 4.290080 3.520452 5.059707 5 4.256952 3.489416 5.024489 6 3.363226 1.876124 4.850329 7 4.070050 3.260221 4.879880 8 5.042792 3.669549 6.416034 9 4.716920 3.697691 5.736149 10 4.580988 3.678189 5.483786 11 3.639939 2.475080 4.804798 12 4.127031 3.339496 4.914565 13 4.103947 3.308320 4.899575 14 4.267438 3.499558 5.035318 15 4.643083 3.690292 5.595875 16 3.322734 1.785518 4.859949 17 4.049235 3.229372 4.869097 18 5.438181 3.566862 7.309500 19 3.934541 3.043288 4.825795 20 4.596277 3.681723 5.510832 Warning message − 'newdata' had 1 row but variables found have 20 rows predict(M,newdata=data.frame(x=1.2),interval="confidence") fit lwr upr 1 3.681691 2.56125 4.802131
[ { "code": null, "e": 1474, "s": 1062, "text": "The reason we get newdata had 1 row warning is the newdata is not correctly defined. We should give the name of the explanatory variable or independent variable to the newdata so that the model can identify that we are passing the mean of the explanatory variable, otherwise it considers all the values of the explanatory hence the result of the predict function yields the predicted values for the sample size." }, { "code": null, "e": 1485, "s": 1474, "text": " Live Demo" }, { "code": null, "e": 1517, "s": 1485, "text": "Consider the below data frame −" }, { "code": null, "e": 1920, "s": 1517, "text": "set.seed(123)\nx<-rnorm(20,0.05)\ny<-rpois(20,5)\ndf<-data.frame(x,y)\ndf x y\n 1 -0.5104756 3\n 2 -0.1801775 4\n 3 1.6087083 4\n 4 0.1205084 4\n 5 0.1792877 3\n 6 1.7650650 3\n 7 0.5109162 3\n 8 -1.2150612 5\n 9 -0.6368529 4\n10 -0.3956620 7\n11 1.2740818 2\n12 0.4098138 5\n13 0.4507715 7\n14 0.1606827 2\n15 -0.5058411 5\n16 1.8369131 3\n17 0.5478505 3\n18 -1.9166172 6\n19 0.7513559 8\n20 -0.4227914 4" }, { "code": null, "e": 1948, "s": 1920, "text": "Creating the linear model −" }, { "code": null, "e": 1967, "s": 1948, "text": "M<-lm(y~x,data=df)" }, { "code": null, "e": 2020, "s": 1967, "text": "Now let’s predict the value of y for the mean of x −" }, { "code": null, "e": 2710, "s": 2020, "text": "predict(M,newdata=data.frame(mean(df$x)),interval=\"confidence\")\n fit lwr upr\n 1 4.645695 3.690676 5.600715\n 2 4.459543 3.635161 5.283925\n 3 3.451347 2.071115 4.831579\n 4 4.290080 3.520452 5.059707\n 5 4.256952 3.489416 5.024489\n 6 3.363226 1.876124 4.850329\n 7 4.070050 3.260221 4.879880\n 8 5.042792 3.669549 6.416034\n 9 4.716920 3.697691 5.736149\n10 4.580988 3.678189 5.483786\n11 3.639939 2.475080 4.804798\n12 4.127031 3.339496 4.914565\n13 4.103947 3.308320 4.899575\n14 4.267438 3.499558 5.035318\n15 4.643083 3.690292 5.595875\n16 3.322734 1.785518 4.859949\n17 4.049235 3.229372 4.869097\n18 5.438181 3.566862 7.309500\n19 3.934541 3.043288 4.825795\n20 4.596277 3.681723 5.510832" }, { "code": null, "e": 2728, "s": 2710, "text": "Warning message −" }, { "code": null, "e": 2781, "s": 2728, "text": "'newdata' had 1 row but variables found have 20 rows" }, { "code": null, "e": 2870, "s": 2781, "text": "To get rid of this warning we need to define the newdata for x variable as shown below −" }, { "code": null, "e": 2982, "s": 2870, "text": "predict(M,newdata=data.frame(x=mean(df$x)),interval=\"confidence\")\n fit lwr upr\n1 4.25 3.482529 5.017471" }, { "code": null, "e": 3046, "s": 2982, "text": "Same thing happens when we try to predict y for a fixed value −" }, { "code": null, "e": 3729, "s": 3046, "text": "predict(M,newdata=data.frame(1.2),interval=\"confidence\")\n fit lwr upr\n 1 4.645695 3.690676 5.600715\n 2 4.459543 3.635161 5.283925\n 3 3.451347 2.071115 4.831579\n 4 4.290080 3.520452 5.059707\n 5 4.256952 3.489416 5.024489\n 6 3.363226 1.876124 4.850329\n 7 4.070050 3.260221 4.879880\n 8 5.042792 3.669549 6.416034\n 9 4.716920 3.697691 5.736149\n10 4.580988 3.678189 5.483786\n11 3.639939 2.475080 4.804798\n12 4.127031 3.339496 4.914565\n13 4.103947 3.308320 4.899575\n14 4.267438 3.499558 5.035318\n15 4.643083 3.690292 5.595875\n16 3.322734 1.785518 4.859949\n17 4.049235 3.229372 4.869097\n18 5.438181 3.566862 7.309500\n19 3.934541 3.043288 4.825795\n20 4.596277 3.681723 5.510832" }, { "code": null, "e": 3747, "s": 3729, "text": "Warning message −" }, { "code": null, "e": 3800, "s": 3747, "text": "'newdata' had 1 row but variables found have 20 rows" }, { "code": null, "e": 3911, "s": 3800, "text": "predict(M,newdata=data.frame(x=1.2),interval=\"confidence\")\n fit lwr upr\n1 3.681691 2.56125 4.802131" } ]
Armstrong numbers between a range - JavaScript
A number is called Armstrong number if the following equation holds true for that number − xy..z = x^n + y^n+.....+ z^n Where, n denotes the number of digits in the number For example − 370 is an Armstrong number because − 3^3 + 7^3 + 0^3 = 27 + 343 + 0 = 370 We are required to write a JavaScript function that takes in two numbers, a range, and returns all the numbers between them that are Armstrong numbers (including them, if they are Armstrong). Let’s write the code for this function − const isArmstrong = number => { let num = number; const len = String(num).split("").length; let res = 0; while(num){ const last = num % 10; res += Math.pow(last, len); num = Math.floor(num / 10); }; return res === number; }; const armstrongBetween = (lower, upper) => { const res = []; for(let i = lower; i <= upper; i++){ if(isArmstrong(i)){ res.push(i); }; }; return res; }; console.log(armstrongBetween(1, 400)); The output in the console: − [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371 ]
[ { "code": null, "e": 1153, "s": 1062, "text": "A number is called Armstrong number if the following equation holds true for that number −" }, { "code": null, "e": 1182, "s": 1153, "text": "xy..z = x^n + y^n+.....+ z^n" }, { "code": null, "e": 1234, "s": 1182, "text": "Where, n denotes the number of digits in the number" }, { "code": null, "e": 1285, "s": 1234, "text": "For example − 370 is an Armstrong number because −" }, { "code": null, "e": 1322, "s": 1285, "text": "3^3 + 7^3 + 0^3 = 27 + 343 + 0 = 370" }, { "code": null, "e": 1514, "s": 1322, "text": "We are required to write a JavaScript function that takes in two numbers, a range, and returns all the numbers between them that are Armstrong numbers (including them, if they are Armstrong)." }, { "code": null, "e": 1555, "s": 1514, "text": "Let’s write the code for this function −" }, { "code": null, "e": 2040, "s": 1555, "text": "const isArmstrong = number => {\n let num = number;\n const len = String(num).split(\"\").length;\n let res = 0;\n while(num){\n const last = num % 10;\n res += Math.pow(last, len);\n num = Math.floor(num / 10);\n };\n return res === number;\n};\nconst armstrongBetween = (lower, upper) => {\n const res = [];\n for(let i = lower; i <= upper; i++){\n if(isArmstrong(i)){\n res.push(i);\n };\n };\n return res;\n};\nconsole.log(armstrongBetween(1, 400));" }, { "code": null, "e": 2069, "s": 2040, "text": "The output in the console: −" }, { "code": null, "e": 2129, "s": 2069, "text": "[\n 1, 2, 3, 4, 5,\n 6, 7, 8, 9, 153,\n 370, 371\n]" } ]
Support Vector Machine: Digit Classification with Python; Including my Hand Written Digits | by Saptashwa Bhattacharyya | Towards Data Science
Following the previous detailed discussions of SVM algorithm, I will finish this series with an application of SVM to classify handwritten digits. Here we will use the MNIST database for handwritten digits and classify numbers from 0 to 9 using SVM. The original data-set is complicated to process, so I am using the data-set processed by Joseph Redmon. I have followed the Kaggle competition procedures and, you can download the data-set from the kaggle itself. The data-set is based on gray-scale images of handwritten digits and, each image is 28 pixel in height and 28 pixel in width. Each pixel has a number associated with it, where 0 represents a dark pixel and, 255 represents a white pixel. Both the train and test data-set have 785 columns where, ‘label’ column represents the handwritten digit and remaining 784 columns represent the (28, 28) pixel values. The train and test data-set contains 60,000 and 10,000 samples respectively. I will use several techniques like GridSearchCV and Pipeline which I have introduced in a previous post, and some new concepts like representing a gray-scale image in a numpy array. I have used 12000 samples and 5000 samples from the training and test data-sets just to reduce the time of computation and it is recommended to use the full set to obtain a better score and avoid selection bias. import math, time import matplotlib.pyplot as pltimport numpy as np import pandas as pdstart = time.time() MNIST_train_small_df = pd.read_csv('mnist_train_small.csv', sep=',', index_col=0)#print MNIST_train_small_df.head(3)print MNIST_train_small_df.shape>> (12000, 785) We can check whether the training data-set is biased towards certain numbers or not by printing out the value_counts() and/or from the distribution plot of labels. sns.countplot(MNIST_train_small_df['label'])plt.show()# looks kinda okay# or we can just printprint MNIST_train_small_df['label'].value_counts()>>1 13517 12793 12286 12080 12069 11934 11842 11768 11275 1048 We see that selection is little biased towards digit 1 and the sample count for label 1 is around 30% higher than sample 5, and this problem persists even if we use the compete training data-set (60,000 samples). So moving on, it is time to separate label and pixel columns and, label is the 1st column of the data-frame. X_tr = MNIST_train_small_df.iloc[:,1:] # iloc ensures X_tr will be a dataframey_tr = MNIST_train_small_df.iloc[:, 0] Then I have separated training and test data with 20% samples reserved for test data. I used stratify=y to preserve distribution of labels (digits)- X_train, X_test, y_train, y_test = train_test_split(X_tr,y_tr,test_size=0.2, random_state=30, stratify=y_tr) As the pixel values vary in the range 0–255, it is time to use some standardization and I have used StandardScaler which standardize features by removing mean and scaling it to unit variance. Also after trying all the kernels, best score and least time is achieved with polynomial kernel. To understand more about Kernel tricks you can check the previous post. Here we will set up the Pipeline object with StandardScaler and SVC as a transformer and estimator respectively. steps = [('scaler', StandardScaler()), ('SVM', SVC(kernel='poly'))]pipeline = Pipeline(steps) # define Pipeline object To decide on the value of C, gamma we will use the GridSearchCV method with 5 folds cross-validation. If you wanna learn more about pipeline and grid-search, please check my previous post. parameters = {'SVM__C':[0.001, 0.1, 100, 10e5], 'SVM__gamma':[10,1,0.1,0.01]}grid = GridSearchCV(pipeline, param_grid=parameters, cv=5) Now we are ready to test the model and find the best-fit parameters. grid.fit(X_train, y_train)print "score = %3.2f" %(grid.score(X_test, y_test))print "best parameters from train data: ", grid.best_params_>> score = 0.96best parameters from train data: {'SVM__C': 0.001, 'SVM__gamma': 10}>>y_pred = grid.predict(X_test) 96% accuracy is obtained with 12000 samples and I expect this score to increase a bit with the complete 60,000 samples. The GridSearchCV part is time consuming and if you want, you can directly use the C and gamma parameters. We can check some of the predictions print y_pred[100:105]print y_test[100:105]>> [4 2 9 6 0]1765 4220 2932 96201 611636 0 We can now plot the digits using python matplotlib pyplot imshow . We use the prediction list and the pixel values from the test list for comparison. for i in (np.random.randint(0,270,6)): two_d = (np.reshape(X_test.values[i], (28, 28)) * 255).astype(np.uint8) plt.title('predicted label: {0}'. format(y_pred[i])) plt.imshow(two_d, interpolation='nearest', cmap='gray') plt.show() Let me briefly explain the second line of the code. As the pixel values are arranged in a row with 784 columns in the data-set, first we use numpy ‘reshape’ module to arrange it in 28 X 28 array and then multiply with 255 as the pixel values were standardized initially. Please be aware that X_test.values returns a ‘numpy’ representation of the data-frame. As you can see in the images above, all of them except one was correctly classified (I think the image (1,1) is digit 7 and not 4). To know how many digits were misclassified we can print out the Confusion-Matrix. According to the definition given in scikit-learn Confusion matrix C is such that c(i,j) is equal to the number of observations known to be in group i but predicted to be in group j. print "confusion matrix: \n ", confusion_matrix(y_test, y_pred)>>[[236 0 0 1 1 2 1 0 0 0] [ 0 264 1 1 0 0 1 1 2 0] [ 0 1 229 1 2 0 0 0 1 1] [ 0 0 2 232 0 3 0 2 5 2] [ 0 1 0 0 229 1 1 0 1 4] [ 0 0 1 4 1 201 0 0 1 2] [ 3 1 2 0 3 3 229 0 0 0] [ 0 1 3 0 6 0 0 241 0 5] [ 0 0 3 6 1 2 0 0 213 0] [ 3 1 1 0 1 0 0 1 2 230]] So if we consider the 1st row, we can understand that out of 241 zeros, 236 were correctly classified and so on.. Now we will repeat the process for the test-data set (mnist_test.csv) but instead of going through finding the best parameters for SVM (C, gamma) using GridSearchCV , I have used the same parameters from the training data set. I have used 5000 samples instead of 10,000 test samples to reduce time consumption, as mentioned before. MNIST_df = pd.read_csv('mnist_test.csv')MNIST_test_small = MNIST_df.iloc[0:5000]MNIST_test_small.to_csv('mnist_test_small.csv')MNIST_test_small_df = pd.read_csv('mnist_test_small.csv', sep=',', index_col=0) Next step is choosing features and labels — X_small_test = MNIST_test_small_df.iloc[:,1:]Y_small_test = MNIST_test_small_df.iloc[:,0] Divide the features and labels into train and test sets X_test_train, X_test_test, y_test_train, y_test_test = train_test_split(X_small_test,Y_small_test,test_size=0.2, random_state=30, stratify=Y_small_test) Set up the Pipeline object steps1 = [('scaler', StandardScaler()), ('SVM', SVC(kernel='poly'))]pipeline1 = Pipeline(steps1) # define Set up GridSearchCV object but this time we use the parameters estimated using the mnist_train.csv file. parameters1 = {'SVM__C':[grid.best_params_['SVM__C']], 'SVM__gamma':[grid.best_params_['SVM__gamma']]} grid1 = GridSearchCV(pipeline1, param_grid=parameters1, cv=5)grid1.fit(X_test_train, y_test_train)print "score on the test data set= %3.2f" %(grid1.score(X_test_test, y_test_test))print "best parameters from train data: ", grid1.best_params_ # same as previous with training data set>>score on the test data set= 0.93best parameters from train data: {'SVM__C': 0.001, 'SVM__gamma': 10}>>y_test_pred = grid1.predict(X_test_test) Score on the test data set is 93% compared to the score of 96% on train data set. Below are some of the random images from the test data set compared with the predicted level. We can check the confusion matrix for the test data-set to have an overall view of misclassification. print "confusion matrix: \n ", confusion_matrix(y_test_test, y_test_pred)>>[[ 91 0 0 0 0 0 0 0 1 0] [ 0 111 2 0 1 0 0 0 0 0] [ 0 0 98 1 0 0 1 2 4 0] [ 0 0 1 91 0 2 0 0 4 2] [ 0 0 0 1 95 0 0 1 0 3] [ 0 0 1 3 1 77 4 0 3 2] [ 1 1 1 0 2 0 85 0 2 0] [ 0 0 0 1 0 0 0 100 0 2] [ 0 0 1 1 0 2 0 1 93 0] [ 0 0 0 0 4 1 0 3 3 93]] Notice that there’s just only 1 misclassification in digit 0 out of 92 labels. Now we will move on to discuss the possibility of classifying my own hand-written images. Below are the steps I have taken to prepare the data-set and then classify digits starting from 0 to 9 I’ve used mypaint to first write (paint) images and and then used Imagemagick to resize images with height and width of 28X28 pixels. I’ve used mypaint to first write (paint) images and and then used Imagemagick to resize images with height and width of 28X28 pixels. convert -resize 28X28! sample_image0.png sample_image0_r.png 2. Converting an image to numpy array and check how the pixel values are distributed. You can find the code on my github and below are 2 examples — 3. Flatten the array (28X28) to (784,) and convert it to to a list. Then write it on a csv file including label i.e. the digits the pixels represent. So total number columns now is 785, in consistence with the train and test csv files that I have used before. The codes are available in github.com. 4. Concatenate the new data-frame with the test data-frame, So that the new file now have 10 more rows. 5. Finally run the same classification process with this new file, with only one difference — train and test data are not prepared using train_test_split method as my primary intention is to see how the algorithm works on the new data. So I have chosen first 3500 rows for training and remaining rows (including the new data) as test samples. X_hand_train = new_file_df_hand.iloc[0:3500, 1:]X_hand_test = new_file_df_hand.iloc[3500:5011, 1:]y_hand_test = new_file_df_hand.iloc[3500:5011, 0]y_hand_train = new_file_df_hand.iloc[0:3500, 0] 6. To plot the hand-written images and how well they matches with the predicted output, I have used the following for loop as before — Since last 1500 samples including my own handwritten images are taken as test data, the loop is over final few rows. for ik in range(1496, 1511, 1): three_d = (np.reshape(X_hand_test.values[ik], (28, 28)) * 255).astype(np.uint8) plt.title('predicted label: {0}'. format(y_hand_pred[ik])) plt.imshow(three_d, interpolation='nearest', cmap='gray') plt.show() 7. The score on the test data-set including my own hand-written data is 93% . 8. Let’s look at how well the classifier the could classify my handwriting from 0 to 9 So 7 out of 10 hand-written digits were correctly classified and that’s great because if you compare with the MNIST database images, my own images are different and I think one reason is the choice of brush. As I realized, the brush I have used, produced much thicker images. Especially while comparing with the MNIST images, I see between the edges the pixels are brighter (higher pixel values — > 255 ) in my images compared with the MNIST images and that could be reason of 30% misclassification. I guess you have got an idea how to use Support Vector Machine to deal with more realistic problems. As a mini project you can use similar algorithm to classify MNIST fashion data. Hopefully you have enjoyed the post, and to learn more about the fundamentals about SVM please check my previous posts in this series.
[ { "code": null, "e": 526, "s": 172, "text": "Following the previous detailed discussions of SVM algorithm, I will finish this series with an application of SVM to classify handwritten digits. Here we will use the MNIST database for handwritten digits and classify numbers from 0 to 9 using SVM. The original data-set is complicated to process, so I am using the data-set processed by Joseph Redmon." }, { "code": null, "e": 1299, "s": 526, "text": "I have followed the Kaggle competition procedures and, you can download the data-set from the kaggle itself. The data-set is based on gray-scale images of handwritten digits and, each image is 28 pixel in height and 28 pixel in width. Each pixel has a number associated with it, where 0 represents a dark pixel and, 255 represents a white pixel. Both the train and test data-set have 785 columns where, ‘label’ column represents the handwritten digit and remaining 784 columns represent the (28, 28) pixel values. The train and test data-set contains 60,000 and 10,000 samples respectively. I will use several techniques like GridSearchCV and Pipeline which I have introduced in a previous post, and some new concepts like representing a gray-scale image in a numpy array." }, { "code": null, "e": 1511, "s": 1299, "text": "I have used 12000 samples and 5000 samples from the training and test data-sets just to reduce the time of computation and it is recommended to use the full set to obtain a better score and avoid selection bias." }, { "code": null, "e": 1782, "s": 1511, "text": "import math, time import matplotlib.pyplot as pltimport numpy as np import pandas as pdstart = time.time() MNIST_train_small_df = pd.read_csv('mnist_train_small.csv', sep=',', index_col=0)#print MNIST_train_small_df.head(3)print MNIST_train_small_df.shape>> (12000, 785)" }, { "code": null, "e": 1946, "s": 1782, "text": "We can check whether the training data-set is biased towards certain numbers or not by printing out the value_counts() and/or from the distribution plot of labels." }, { "code": null, "e": 2183, "s": 1946, "text": "sns.countplot(MNIST_train_small_df['label'])plt.show()# looks kinda okay# or we can just printprint MNIST_train_small_df['label'].value_counts()>>1 13517 12793 12286 12080 12069 11934 11842 11768 11275 1048" }, { "code": null, "e": 2505, "s": 2183, "text": "We see that selection is little biased towards digit 1 and the sample count for label 1 is around 30% higher than sample 5, and this problem persists even if we use the compete training data-set (60,000 samples). So moving on, it is time to separate label and pixel columns and, label is the 1st column of the data-frame." }, { "code": null, "e": 2622, "s": 2505, "text": "X_tr = MNIST_train_small_df.iloc[:,1:] # iloc ensures X_tr will be a dataframey_tr = MNIST_train_small_df.iloc[:, 0]" }, { "code": null, "e": 2771, "s": 2622, "text": "Then I have separated training and test data with 20% samples reserved for test data. I used stratify=y to preserve distribution of labels (digits)-" }, { "code": null, "e": 2880, "s": 2771, "text": "X_train, X_test, y_train, y_test = train_test_split(X_tr,y_tr,test_size=0.2, random_state=30, stratify=y_tr)" }, { "code": null, "e": 3241, "s": 2880, "text": "As the pixel values vary in the range 0–255, it is time to use some standardization and I have used StandardScaler which standardize features by removing mean and scaling it to unit variance. Also after trying all the kernels, best score and least time is achieved with polynomial kernel. To understand more about Kernel tricks you can check the previous post." }, { "code": null, "e": 3354, "s": 3241, "text": "Here we will set up the Pipeline object with StandardScaler and SVC as a transformer and estimator respectively." }, { "code": null, "e": 3473, "s": 3354, "text": "steps = [('scaler', StandardScaler()), ('SVM', SVC(kernel='poly'))]pipeline = Pipeline(steps) # define Pipeline object" }, { "code": null, "e": 3662, "s": 3473, "text": "To decide on the value of C, gamma we will use the GridSearchCV method with 5 folds cross-validation. If you wanna learn more about pipeline and grid-search, please check my previous post." }, { "code": null, "e": 3798, "s": 3662, "text": "parameters = {'SVM__C':[0.001, 0.1, 100, 10e5], 'SVM__gamma':[10,1,0.1,0.01]}grid = GridSearchCV(pipeline, param_grid=parameters, cv=5)" }, { "code": null, "e": 3867, "s": 3798, "text": "Now we are ready to test the model and find the best-fit parameters." }, { "code": null, "e": 4120, "s": 3867, "text": "grid.fit(X_train, y_train)print \"score = %3.2f\" %(grid.score(X_test, y_test))print \"best parameters from train data: \", grid.best_params_>> score = 0.96best parameters from train data: {'SVM__C': 0.001, 'SVM__gamma': 10}>>y_pred = grid.predict(X_test)" }, { "code": null, "e": 4346, "s": 4120, "text": "96% accuracy is obtained with 12000 samples and I expect this score to increase a bit with the complete 60,000 samples. The GridSearchCV part is time consuming and if you want, you can directly use the C and gamma parameters." }, { "code": null, "e": 4383, "s": 4346, "text": "We can check some of the predictions" }, { "code": null, "e": 4490, "s": 4383, "text": "print y_pred[100:105]print y_test[100:105]>> [4 2 9 6 0]1765 4220 2932 96201 611636 0" }, { "code": null, "e": 4640, "s": 4490, "text": "We can now plot the digits using python matplotlib pyplot imshow . We use the prediction list and the pixel values from the test list for comparison." }, { "code": null, "e": 4871, "s": 4640, "text": "for i in (np.random.randint(0,270,6)): two_d = (np.reshape(X_test.values[i], (28, 28)) * 255).astype(np.uint8) plt.title('predicted label: {0}'. format(y_pred[i])) plt.imshow(two_d, interpolation='nearest', cmap='gray') plt.show()" }, { "code": null, "e": 5229, "s": 4871, "text": "Let me briefly explain the second line of the code. As the pixel values are arranged in a row with 784 columns in the data-set, first we use numpy ‘reshape’ module to arrange it in 28 X 28 array and then multiply with 255 as the pixel values were standardized initially. Please be aware that X_test.values returns a ‘numpy’ representation of the data-frame." }, { "code": null, "e": 5493, "s": 5229, "text": "As you can see in the images above, all of them except one was correctly classified (I think the image (1,1) is digit 7 and not 4). To know how many digits were misclassified we can print out the Confusion-Matrix. According to the definition given in scikit-learn" }, { "code": null, "e": 5626, "s": 5493, "text": "Confusion matrix C is such that c(i,j) is equal to the number of observations known to be in group i but predicted to be in group j." }, { "code": null, "e": 6113, "s": 5626, "text": "print \"confusion matrix: \\n \", confusion_matrix(y_test, y_pred)>>[[236 0 0 1 1 2 1 0 0 0] [ 0 264 1 1 0 0 1 1 2 0] [ 0 1 229 1 2 0 0 0 1 1] [ 0 0 2 232 0 3 0 2 5 2] [ 0 1 0 0 229 1 1 0 1 4] [ 0 0 1 4 1 201 0 0 1 2] [ 3 1 2 0 3 3 229 0 0 0] [ 0 1 3 0 6 0 0 241 0 5] [ 0 0 3 6 1 2 0 0 213 0] [ 3 1 1 0 1 0 0 1 2 230]]" }, { "code": null, "e": 6227, "s": 6113, "text": "So if we consider the 1st row, we can understand that out of 241 zeros, 236 were correctly classified and so on.." }, { "code": null, "e": 6454, "s": 6227, "text": "Now we will repeat the process for the test-data set (mnist_test.csv) but instead of going through finding the best parameters for SVM (C, gamma) using GridSearchCV , I have used the same parameters from the training data set." }, { "code": null, "e": 6559, "s": 6454, "text": "I have used 5000 samples instead of 10,000 test samples to reduce time consumption, as mentioned before." }, { "code": null, "e": 6766, "s": 6559, "text": "MNIST_df = pd.read_csv('mnist_test.csv')MNIST_test_small = MNIST_df.iloc[0:5000]MNIST_test_small.to_csv('mnist_test_small.csv')MNIST_test_small_df = pd.read_csv('mnist_test_small.csv', sep=',', index_col=0)" }, { "code": null, "e": 6810, "s": 6766, "text": "Next step is choosing features and labels —" }, { "code": null, "e": 6900, "s": 6810, "text": "X_small_test = MNIST_test_small_df.iloc[:,1:]Y_small_test = MNIST_test_small_df.iloc[:,0]" }, { "code": null, "e": 6956, "s": 6900, "text": "Divide the features and labels into train and test sets" }, { "code": null, "e": 7109, "s": 6956, "text": "X_test_train, X_test_test, y_test_train, y_test_test = train_test_split(X_small_test,Y_small_test,test_size=0.2, random_state=30, stratify=Y_small_test)" }, { "code": null, "e": 7136, "s": 7109, "text": "Set up the Pipeline object" }, { "code": null, "e": 7242, "s": 7136, "text": "steps1 = [('scaler', StandardScaler()), ('SVM', SVC(kernel='poly'))]pipeline1 = Pipeline(steps1) # define" }, { "code": null, "e": 7347, "s": 7242, "text": "Set up GridSearchCV object but this time we use the parameters estimated using the mnist_train.csv file." }, { "code": null, "e": 7879, "s": 7347, "text": "parameters1 = {'SVM__C':[grid.best_params_['SVM__C']], 'SVM__gamma':[grid.best_params_['SVM__gamma']]} grid1 = GridSearchCV(pipeline1, param_grid=parameters1, cv=5)grid1.fit(X_test_train, y_test_train)print \"score on the test data set= %3.2f\" %(grid1.score(X_test_test, y_test_test))print \"best parameters from train data: \", grid1.best_params_ # same as previous with training data set>>score on the test data set= 0.93best parameters from train data: {'SVM__C': 0.001, 'SVM__gamma': 10}>>y_test_pred = grid1.predict(X_test_test)" }, { "code": null, "e": 8055, "s": 7879, "text": "Score on the test data set is 93% compared to the score of 96% on train data set. Below are some of the random images from the test data set compared with the predicted level." }, { "code": null, "e": 8157, "s": 8055, "text": "We can check the confusion matrix for the test data-set to have an overall view of misclassification." }, { "code": null, "e": 8654, "s": 8157, "text": "print \"confusion matrix: \\n \", confusion_matrix(y_test_test, y_test_pred)>>[[ 91 0 0 0 0 0 0 0 1 0] [ 0 111 2 0 1 0 0 0 0 0] [ 0 0 98 1 0 0 1 2 4 0] [ 0 0 1 91 0 2 0 0 4 2] [ 0 0 0 1 95 0 0 1 0 3] [ 0 0 1 3 1 77 4 0 3 2] [ 1 1 1 0 2 0 85 0 2 0] [ 0 0 0 1 0 0 0 100 0 2] [ 0 0 1 1 0 2 0 1 93 0] [ 0 0 0 0 4 1 0 3 3 93]]" }, { "code": null, "e": 8823, "s": 8654, "text": "Notice that there’s just only 1 misclassification in digit 0 out of 92 labels. Now we will move on to discuss the possibility of classifying my own hand-written images." }, { "code": null, "e": 8926, "s": 8823, "text": "Below are the steps I have taken to prepare the data-set and then classify digits starting from 0 to 9" }, { "code": null, "e": 9060, "s": 8926, "text": "I’ve used mypaint to first write (paint) images and and then used Imagemagick to resize images with height and width of 28X28 pixels." }, { "code": null, "e": 9194, "s": 9060, "text": "I’ve used mypaint to first write (paint) images and and then used Imagemagick to resize images with height and width of 28X28 pixels." }, { "code": null, "e": 9255, "s": 9194, "text": "convert -resize 28X28! sample_image0.png sample_image0_r.png" }, { "code": null, "e": 9403, "s": 9255, "text": "2. Converting an image to numpy array and check how the pixel values are distributed. You can find the code on my github and below are 2 examples —" }, { "code": null, "e": 9702, "s": 9403, "text": "3. Flatten the array (28X28) to (784,) and convert it to to a list. Then write it on a csv file including label i.e. the digits the pixels represent. So total number columns now is 785, in consistence with the train and test csv files that I have used before. The codes are available in github.com." }, { "code": null, "e": 9806, "s": 9702, "text": "4. Concatenate the new data-frame with the test data-frame, So that the new file now have 10 more rows." }, { "code": null, "e": 10149, "s": 9806, "text": "5. Finally run the same classification process with this new file, with only one difference — train and test data are not prepared using train_test_split method as my primary intention is to see how the algorithm works on the new data. So I have chosen first 3500 rows for training and remaining rows (including the new data) as test samples." }, { "code": null, "e": 10345, "s": 10149, "text": "X_hand_train = new_file_df_hand.iloc[0:3500, 1:]X_hand_test = new_file_df_hand.iloc[3500:5011, 1:]y_hand_test = new_file_df_hand.iloc[3500:5011, 0]y_hand_train = new_file_df_hand.iloc[0:3500, 0]" }, { "code": null, "e": 10597, "s": 10345, "text": "6. To plot the hand-written images and how well they matches with the predicted output, I have used the following for loop as before — Since last 1500 samples including my own handwritten images are taken as test data, the loop is over final few rows." }, { "code": null, "e": 10837, "s": 10597, "text": "for ik in range(1496, 1511, 1): three_d = (np.reshape(X_hand_test.values[ik], (28, 28)) * 255).astype(np.uint8) plt.title('predicted label: {0}'. format(y_hand_pred[ik])) plt.imshow(three_d, interpolation='nearest', cmap='gray') plt.show()" }, { "code": null, "e": 10915, "s": 10837, "text": "7. The score on the test data-set including my own hand-written data is 93% ." }, { "code": null, "e": 11002, "s": 10915, "text": "8. Let’s look at how well the classifier the could classify my handwriting from 0 to 9" }, { "code": null, "e": 11502, "s": 11002, "text": "So 7 out of 10 hand-written digits were correctly classified and that’s great because if you compare with the MNIST database images, my own images are different and I think one reason is the choice of brush. As I realized, the brush I have used, produced much thicker images. Especially while comparing with the MNIST images, I see between the edges the pixels are brighter (higher pixel values — > 255 ) in my images compared with the MNIST images and that could be reason of 30% misclassification." }, { "code": null, "e": 11683, "s": 11502, "text": "I guess you have got an idea how to use Support Vector Machine to deal with more realistic problems. As a mini project you can use similar algorithm to classify MNIST fashion data." } ]
How do I sort natural in MongoDB?
Use $natural to sort natural in MongoDB. Let us create a collection with documents − > db.demo684.insertOne({Value:10}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530cea7e81adc6a0b3957") } > db.demo684.insertOne({Value:50}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530d1a7e81adc6a0b3958") } > db.demo684.insertOne({Value:60}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530d4a7e81adc6a0b3959") } > db.demo684.insertOne({Value:40}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530d8a7e81adc6a0b395a") } Display all documents from a collection with the help of find() method − > db.demo684.find(); This will produce the following output − { "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 } { "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 } { "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 } { "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 } Following is the query to sort on the basis of _id − > db.demo684.find(). sort({'_id': 1}); This will produce the following output − { "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 } { "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 } { "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 } { "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 } You can also use $natural − > db.demo684.find().sort({$natural: 1}); This will produce the following output − { "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 } { "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 } { "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 } { "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
[ { "code": null, "e": 1147, "s": 1062, "text": "Use $natural to sort natural in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1631, "s": 1147, "text": "> db.demo684.insertOne({Value:10});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea530cea7e81adc6a0b3957\")\n}\n> db.demo684.insertOne({Value:50});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea530d1a7e81adc6a0b3958\")\n}\n> db.demo684.insertOne({Value:60});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea530d4a7e81adc6a0b3959\")\n}\n> db.demo684.insertOne({Value:40});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea530d8a7e81adc6a0b395a\")\n}" }, { "code": null, "e": 1704, "s": 1631, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1725, "s": 1704, "text": "> db.demo684.find();" }, { "code": null, "e": 1766, "s": 1725, "text": "This will produce the following output −" }, { "code": null, "e": 2018, "s": 1766, "text": "{ \"_id\" : ObjectId(\"5ea530cea7e81adc6a0b3957\"), \"Value\" : 10 }\n{ \"_id\" : ObjectId(\"5ea530d1a7e81adc6a0b3958\"), \"Value\" : 50 }\n{ \"_id\" : ObjectId(\"5ea530d4a7e81adc6a0b3959\"), \"Value\" : 60 }\n{ \"_id\" : ObjectId(\"5ea530d8a7e81adc6a0b395a\"), \"Value\" : 40 }" }, { "code": null, "e": 2071, "s": 2018, "text": "Following is the query to sort on the basis of _id −" }, { "code": null, "e": 2110, "s": 2071, "text": "> db.demo684.find(). sort({'_id': 1});" }, { "code": null, "e": 2151, "s": 2110, "text": "This will produce the following output −" }, { "code": null, "e": 2403, "s": 2151, "text": "{ \"_id\" : ObjectId(\"5ea530cea7e81adc6a0b3957\"), \"Value\" : 10 }\n{ \"_id\" : ObjectId(\"5ea530d1a7e81adc6a0b3958\"), \"Value\" : 50 }\n{ \"_id\" : ObjectId(\"5ea530d4a7e81adc6a0b3959\"), \"Value\" : 60 }\n{ \"_id\" : ObjectId(\"5ea530d8a7e81adc6a0b395a\"), \"Value\" : 40 }" }, { "code": null, "e": 2431, "s": 2403, "text": "You can also use $natural −" }, { "code": null, "e": 2472, "s": 2431, "text": "> db.demo684.find().sort({$natural: 1});" }, { "code": null, "e": 2513, "s": 2472, "text": "This will produce the following output −" }, { "code": null, "e": 2765, "s": 2513, "text": "{ \"_id\" : ObjectId(\"5ea530cea7e81adc6a0b3957\"), \"Value\" : 10 }\n{ \"_id\" : ObjectId(\"5ea530d1a7e81adc6a0b3958\"), \"Value\" : 50 }\n{ \"_id\" : ObjectId(\"5ea530d4a7e81adc6a0b3959\"), \"Value\" : 60 }\n{ \"_id\" : ObjectId(\"5ea530d8a7e81adc6a0b395a\"), \"Value\" : 40 }" } ]
CSS - page-break-after
The page-break-after property indicates whether (and how many) page breaks should be allowed after an element's box. The value of this property is not the sole factor in determining whether a page break should follow the element. This decision will also be affected by the value of page-break-before for a following element, and the value of page-break-inside for any ancestor elements. auto − Page breaks should be neither forced nor prevented after the element's box. auto − Page breaks should be neither forced nor prevented after the element's box. always − A page break should be forced after this element's box. always − A page break should be forced after this element's box. avoid − No page break should be placed after the element's box if at all possible. avoid − No page break should be placed after the element's box if at all possible. left − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a left-hand page. left − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a left-hand page. right − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a right-hand page. right − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a right-hand page. All the block level elements. Here is the example − <html> <head> <style type = "text/css"> p {page-break-after: always;} </style> </head> <body> <p> Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008. On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2 </p> <p> Android applications are usually developed in the Java language using the Android Software Development Kit. Once developed, Android applications can be packaged easily and sold out either through a store such as Google Play or the Amazon Appstore. Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide. This tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications </p> <button onclick = "myFunction()">Print this page</button> <script> function myFunction() { window.print(); } </script> </body> </html> It will produce the following result − Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008. On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2. Android applications are usually developed in the Java language using the Android Software Development Kit. Once developed, Android applications can be packaged easily and sold out either through a store such as Google Play or the Amazon Appstore. Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide. This tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications. For more detail please look into CSS Paged Media. 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2743, "s": 2626, "text": "The page-break-after property indicates whether (and how many) page breaks should be allowed after an element's box." }, { "code": null, "e": 3013, "s": 2743, "text": "The value of this property is not the sole factor in determining whether a page break should follow the element. This decision will also be affected by the value of page-break-before for a following element, and the value of page-break-inside for any ancestor elements." }, { "code": null, "e": 3096, "s": 3013, "text": "auto − Page breaks should be neither forced nor prevented after the element's box." }, { "code": null, "e": 3179, "s": 3096, "text": "auto − Page breaks should be neither forced nor prevented after the element's box." }, { "code": null, "e": 3244, "s": 3179, "text": "always − A page break should be forced after this element's box." }, { "code": null, "e": 3309, "s": 3244, "text": "always − A page break should be forced after this element's box." }, { "code": null, "e": 3392, "s": 3309, "text": "avoid − No page break should be placed after the element's box if at all possible." }, { "code": null, "e": 3475, "s": 3392, "text": "avoid − No page break should be placed after the element's box if at all possible." }, { "code": null, "e": 3617, "s": 3475, "text": "left − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a left-hand page." }, { "code": null, "e": 3759, "s": 3617, "text": "left − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a left-hand page." }, { "code": null, "e": 3903, "s": 3759, "text": "right − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a right-hand page." }, { "code": null, "e": 4047, "s": 3903, "text": "right − Force one or two page breaks after the element's box, such that the next page on which an element is printed will be a right-hand page." }, { "code": null, "e": 4077, "s": 4047, "text": "All the block level elements." }, { "code": null, "e": 4099, "s": 4077, "text": "Here is the example −" }, { "code": null, "e": 6415, "s": 4099, "text": "<html>\n <head> \n \n <style type = \"text/css\">\n p {page-break-after: always;}\n </style>\n </head>\n\n <body>\n \n <p>\n Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.\n Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.\n The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008.\n On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance.\n The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2\n </p>\n \n <p>\n Android applications are usually developed in the Java language using the Android Software Development Kit.\n Once developed, Android applications can be packaged easily and sold out either through a store such as Google Play or the Amazon Appstore.\n Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide.\n This tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications\n </p>\n \n <button onclick = \"myFunction()\">Print this page</button>\n \n <script>\n function myFunction() {\n window.print();\n }\n </script>\n \n </body>\n</html> " }, { "code": null, "e": 6454, "s": 6415, "text": "It will produce the following result −" }, { "code": null, "e": 7558, "s": 6454, "text": "Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.\n\nAndroid offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.\n\nThe first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008.\n\nOn June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance.\n\nThe source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2." }, { "code": null, "e": 8307, "s": 7558, "text": "Android applications are usually developed in the Java language using the Android Software Development Kit.\n\nOnce developed, Android applications can be packaged easily and sold out either through a store such as Google Play or the Amazon Appstore.\n\nAndroid powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide.\n\nThis tutorial has been written with an aim to teach you how to develop and package Android application. We will start from environment setup for Android application programming and then drill down to look into various aspects of Android applications." }, { "code": null, "e": 8357, "s": 8307, "text": "For more detail please look into CSS Paged Media." }, { "code": null, "e": 8392, "s": 8357, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8406, "s": 8392, "text": " Anadi Sharma" }, { "code": null, "e": 8441, "s": 8406, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8458, "s": 8441, "text": " Frahaan Hussain" }, { "code": null, "e": 8493, "s": 8458, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8524, "s": 8493, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8559, "s": 8524, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8590, "s": 8559, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8625, "s": 8590, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8656, "s": 8625, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8689, "s": 8656, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 8720, "s": 8689, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8727, "s": 8720, "text": " Print" }, { "code": null, "e": 8738, "s": 8727, "text": " Add Notes" } ]
What is Debouncing in JavaScript?
Debouncing is nothing but reducing unnecessary time consuming computations so as to increase browser performance. There are some scenarios in which some functionalities take more time to execute a certain operation. For instance, take an example of a search bar in an e-commerce website. For suppose a user wants to get "Tutorix study kit". He types every character of the product in the search bar. After typing each character, there is an Api calling takes place from browser to server so as to get the required product. Since he wants "Tutorix study kit", the user has to make 17 Api calls from browser to server. Think of a scenario that when millions of people making the same search there by calling billions of Api's. So calling billions of Api's at a time will definitely leads to a slower browser performance. To reduce this drawback, Debouncing comes in to picture. In this scenario, Debouncing will set a time interval, for suppose 2 secs, between two keystrokes. If the time between two keystrokes exceeds 2 secs, then only Api calling will takes place. In those 2 secs the user may type at least some characters, reducing those characters Api calling. Since the Api calling has reduced, the browser performance will be increased. One must heed that the Debouncing function updates for every key stroke. In the following example a button is attached to a event listener that calls a debounce function. Debounce function is provided with 2 parameters, one is a function and the other a number(time). A Timer is declared, which as the name suggests calls debounce function after a specific time. Once the debounce button clicked, an alert box opens up and displays a message. The function updates every time which means if the button clicked prior to the delay time(2 secs), initial timer will be cleared and fresh timer will be started. To achieve this task clearTimeOut() function is used. Live Demo <html> <body> <input type = "button" id="debounce" value = "Debounce"> <script> var button = document.getElementById("debounce"); var debounce = (func, delay) => { let Timer return function() { const context = this const args = arguments clearTimeout(Timer)Timer= setTimeout(() => func.apply(context, args), delay) } } button.addEventListener('click', debounce(function() { alert("Hello\nNo matter how many times you" + "click the debounce button, I get " +"executed once every 2 seconds!!")}, 2000)); </script> </body> </html> After executing the above function the following button will be displayed After clicking the button and waiting for 2 secs the following alert box will be displayed as the output.
[ { "code": null, "e": 1350, "s": 1062, "text": "Debouncing is nothing but reducing unnecessary time consuming computations so as to increase browser performance. There are some scenarios in which some functionalities take more time to execute a certain operation. For instance, take an example of a search bar in an e-commerce website." }, { "code": null, "e": 1938, "s": 1350, "text": "For suppose a user wants to get \"Tutorix study kit\". He types every character of the product in the search bar. After typing each character, there is an Api calling takes place from browser to server so as to get the required product. Since he wants \"Tutorix study kit\", the user has to make 17 Api calls from browser to server. Think of a scenario that when millions of people making the same search there by calling billions of Api's. So calling billions of Api's at a time will definitely leads to a slower browser performance. To reduce this drawback, Debouncing comes in to picture." }, { "code": null, "e": 2378, "s": 1938, "text": "In this scenario, Debouncing will set a time interval, for suppose 2 secs, between two keystrokes. If the time between two keystrokes exceeds 2 secs, then only Api calling will takes place. In those 2 secs the user may type at least some characters, reducing those characters Api calling. Since the Api calling has reduced, the browser performance will be increased. One must heed that the Debouncing function updates for every key stroke." }, { "code": null, "e": 2668, "s": 2378, "text": "In the following example a button is attached to a event listener that calls a debounce function. Debounce function is provided with 2 parameters, one is a function and the other a number(time). A Timer is declared, which as the name suggests calls debounce function after a specific time." }, { "code": null, "e": 2964, "s": 2668, "text": "Once the debounce button clicked, an alert box opens up and displays a message. The function updates every time which means if the button clicked prior to the delay time(2 secs), initial timer will be cleared and fresh timer will be started. To achieve this task clearTimeOut() function is used." }, { "code": null, "e": 2974, "s": 2964, "text": "Live Demo" }, { "code": null, "e": 3583, "s": 2974, "text": "<html>\n<body>\n<input type = \"button\" id=\"debounce\" value = \"Debounce\">\n<script>\n var button = document.getElementById(\"debounce\");\n var debounce = (func, delay) => {\n let Timer\n return function() {\n const context = this\n const args = arguments\n clearTimeout(Timer)Timer= setTimeout(() =>\n func.apply(context, args), delay)\n }\n }\n button.addEventListener('click', debounce(function() {\n alert(\"Hello\\nNo matter how many times you\" +\n \"click the debounce button, I get \" +\"executed once every 2 seconds!!\")}, 2000));\n</script>\n</body>\n</html>" }, { "code": null, "e": 3657, "s": 3583, "text": "After executing the above function the following button will be displayed" }, { "code": null, "e": 3763, "s": 3657, "text": "After clicking the button and waiting for 2 secs the following alert box will be displayed as the output." } ]
Tryit Editor v3.7
CSS Grid Intro Tryit: Grid lines
[ { "code": null, "e": 24, "s": 9, "text": "CSS Grid Intro" } ]
Introduction to IBM Federated Learning: A Collaborative Approach to Train ML Models on Private Data | by Khuyen Tran | Towards Data Science
IBM Research has just released IBM Federated Learning on Github. If you have been looking for a way to boost your model training with the data collected from multiple resources while keeping the data private, this framework is for you. This article will explain why you need Federated learning and how to start using the framework. When training a machine learning model, we often know about how your data looks, the distribution, the statistics of the data. But in the real world, we might use the data from different sources without the privilege of knowing how the data is like. Why? Because data security is important in different enterprises. For example, an aviation alliance wants to model how the recent events with COVID-19 will impact airline delays. Within the aviation alliance, we have several different airlines with different data. Since these airlines are competitors, the raw data cannot be shared across each airline. But the aviation alliance needs to use the combination of data to train the model! There could be other non-competitive reasons are such as: For some enterprises, moving data into one location can be impractical or expensive, particularly if the data are generated at a high velocity or the amount of data is large. Even in the same company, customer databases might be in different countries and data cannot be taken out of the country. Financial firms cannot share transaction data and medical institutions cannot share patient data due to regulation and secrecy. So what is the solution? That is when we need Federated learning. Federated learning (FL) is an approach to train machine learning models that do not require sharing datasets with a central entity. In federated learning, a model is trained collaboratively among multiple parties. The parties could keep their training dataset to themselves but still be able to participate in a shared federated learning process. The learning process between parties most commonly uses a single aggregator. An aggregator would communicate with the parties and integrate the results of the training process. For example, the process for neural networks could be: Parties run a local training process on their training data, share the weights of their model with the aggregator. These weights would then aggregate the weight vectors of all parties using a fusion algorithm. Then, the merged model is sent back to all parties for the next round of training. A federated decision tree algorithm might grow the tree in the aggregator, and query (request) the parties for the count information based on the parties’ data sets. The whole process of FL is designed to ensure that a robust machine learning model is created from the collections of data without sharing the raw data of each party! While FL does not require the centralized management of training data, it also poses some new changes such as: Dataset heterogeneity: differences in the distribution, different dataset sizes for each party, different attributes (i.e. there might be more rich customers in one airline than another airline). Thus, there are no common properties of the overall training data set such as preprocessing methods, fine-tuning algorithms, and evaluation of model performance. Privacy: some federated learning scenarios require that different parties (or even the aggregator) are not able to derive insights about each other’s training data based on messages exchanged during the training process (e.g., weights) Skills: FL requires different skills from machine learning to distributed systems to cryptography. It’s rare to find employees who have all these skill sets. Ideally, we want to solve the above problems without the difficulty of deploying, avoiding time-consuming processes such as opening ports as much as possible. Fortunately, IBM Federated Learning framework addresses all of the above challenges and plus the ease of integration of FL into productive machine learning workflows! The best way to know how a framework is to play with it! We would need more than one party to test this out. But don’t worry, we can simulate the scenarios of multiple parties trying to train their data from different machines! How good will the training perform? Stay tuned and observe the magic. The steps below could be found in the setup section of IBM Federated learning Github repo Start with cloning this repo. Then go to the folder created. Install all the requirements. I really highly recommend using Conda installation for this project. conda create -n <env_name> python=3.6conda activate <env_name> Install the IBM FL package by running: pip install <IBM_federated_learning_whl_file> This example explains how to run federated learning on CNNs implemented with Keras training on MNIST data. We will need more than one party to see how FL works. We can use generate_data.py to generate sample data on any of the integrated datasets. For example, we could run: python examples/generate_data.py -n 2 -d mnist -pp 200 This command would generate 2 parties with 200 data points each from the MNIST dataset. To run IBM federated learning, you must have configuration files for the aggregator and for each party. Each config file consists of the information about each party. You can generate these config files using the generate_configs.py script. For example, you could run: python examples/generate_configs.py -m keras_classifier -n 2 -d mnist -p examples/data/mnist/random This command would generate the configs for the keras_classifier model, assuming 2 parties. -p is the path of party data. Now put yourself in the seat of each party and the aggregator. Remember, in real life, the parties and the aggregator will not see one another’s screen but they will coordinate in the training process. To start the aggregator, open a terminal window running the IBM FL environment set up previously. In the terminal run: In the terminal run: python -m ibmfl.aggregator.aggregator examples/configs/keras_classifier/config_agg.yml where the path provided is the aggregator config file path. 2. Then in the terminal, type START , and press enter. This means the aggregator starts accepting connections from other parties. To register new parties, open a new terminal window for each party, running the IBM FL environment set up previously. In the terminal run: In the terminal run: python -m ibmfl.party.party examples/configs/keras_classifier/config_party0.yml where the path provided is the path to the party config file. 2. In the terminal for each party, type START and press enter. This means the party start accepting connections from the aggregator 3. Then in the terminal for each party, type REGISTER and press enter. This means the parties join the FL project To initiate federated training, type TRAIN in your aggregator terminal, and press enter. To synchronize model among parties, type SYNC To save the model, type SAVE in your aggregator terminal, and press enter. Voila! Now models for each party are saved to your folder. In the real scenario, each party would just see one model file for their party. Now we have the model that is ready to be used for prediction! Remember to type STOP in both the aggregator terminal and parties’ terminal to end the experiment process. Congratulation! Your party has just finished the training process without revealing your data. Imagine you are party 0, to use the model to predict the test data of your party, all you need to do is to load the model and predict the test data of your party. Awesome! Your party gets a f1-score of .81. You have not just secured your data but also get a robust machine learning model! I will use the screenshot from IBM Data Science and AI Session 4 to compare the performance between the two As you can see, all metrics including accuracy, f1, precision, recall of local model performance at party 1 are greater than the local model performance! By combining the data from other sources, you get a more robust model to predict your party’s data. Congratulation! You have just learned how to train machine learning on the combination of datasets without sharing the data! Best of all, setting up training does not require advanced skills. All you need is to add to your project file is a config that specifies the relevant information such as connection, data, model. Then use some simple command lines on the terminal to set up and train all parties at the same time. The Github repository, as well as the literature for the framework, could be found here. You could also use IBM Federated Learning Slack channel to contact directly to the development team of the framework. I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 504, "s": 172, "text": "IBM Research has just released IBM Federated Learning on Github. If you have been looking for a way to boost your model training with the data collected from multiple resources while keeping the data private, this framework is for you. This article will explain why you need Federated learning and how to start using the framework." }, { "code": null, "e": 631, "s": 504, "text": "When training a machine learning model, we often know about how your data looks, the distribution, the statistics of the data." }, { "code": null, "e": 820, "s": 631, "text": "But in the real world, we might use the data from different sources without the privilege of knowing how the data is like. Why? Because data security is important in different enterprises." }, { "code": null, "e": 1191, "s": 820, "text": "For example, an aviation alliance wants to model how the recent events with COVID-19 will impact airline delays. Within the aviation alliance, we have several different airlines with different data. Since these airlines are competitors, the raw data cannot be shared across each airline. But the aviation alliance needs to use the combination of data to train the model!" }, { "code": null, "e": 1249, "s": 1191, "text": "There could be other non-competitive reasons are such as:" }, { "code": null, "e": 1424, "s": 1249, "text": "For some enterprises, moving data into one location can be impractical or expensive, particularly if the data are generated at a high velocity or the amount of data is large." }, { "code": null, "e": 1546, "s": 1424, "text": "Even in the same company, customer databases might be in different countries and data cannot be taken out of the country." }, { "code": null, "e": 1674, "s": 1546, "text": "Financial firms cannot share transaction data and medical institutions cannot share patient data due to regulation and secrecy." }, { "code": null, "e": 1740, "s": 1674, "text": "So what is the solution? That is when we need Federated learning." }, { "code": null, "e": 2087, "s": 1740, "text": "Federated learning (FL) is an approach to train machine learning models that do not require sharing datasets with a central entity. In federated learning, a model is trained collaboratively among multiple parties. The parties could keep their training dataset to themselves but still be able to participate in a shared federated learning process." }, { "code": null, "e": 2264, "s": 2087, "text": "The learning process between parties most commonly uses a single aggregator. An aggregator would communicate with the parties and integrate the results of the training process." }, { "code": null, "e": 2319, "s": 2264, "text": "For example, the process for neural networks could be:" }, { "code": null, "e": 2434, "s": 2319, "text": "Parties run a local training process on their training data, share the weights of their model with the aggregator." }, { "code": null, "e": 2529, "s": 2434, "text": "These weights would then aggregate the weight vectors of all parties using a fusion algorithm." }, { "code": null, "e": 2612, "s": 2529, "text": "Then, the merged model is sent back to all parties for the next round of training." }, { "code": null, "e": 2778, "s": 2612, "text": "A federated decision tree algorithm might grow the tree in the aggregator, and query (request) the parties for the count information based on the parties’ data sets." }, { "code": null, "e": 2945, "s": 2778, "text": "The whole process of FL is designed to ensure that a robust machine learning model is created from the collections of data without sharing the raw data of each party!" }, { "code": null, "e": 3056, "s": 2945, "text": "While FL does not require the centralized management of training data, it also poses some new changes such as:" }, { "code": null, "e": 3414, "s": 3056, "text": "Dataset heterogeneity: differences in the distribution, different dataset sizes for each party, different attributes (i.e. there might be more rich customers in one airline than another airline). Thus, there are no common properties of the overall training data set such as preprocessing methods, fine-tuning algorithms, and evaluation of model performance." }, { "code": null, "e": 3650, "s": 3414, "text": "Privacy: some federated learning scenarios require that different parties (or even the aggregator) are not able to derive insights about each other’s training data based on messages exchanged during the training process (e.g., weights)" }, { "code": null, "e": 3808, "s": 3650, "text": "Skills: FL requires different skills from machine learning to distributed systems to cryptography. It’s rare to find employees who have all these skill sets." }, { "code": null, "e": 3967, "s": 3808, "text": "Ideally, we want to solve the above problems without the difficulty of deploying, avoiding time-consuming processes such as opening ports as much as possible." }, { "code": null, "e": 4134, "s": 3967, "text": "Fortunately, IBM Federated Learning framework addresses all of the above challenges and plus the ease of integration of FL into productive machine learning workflows!" }, { "code": null, "e": 4432, "s": 4134, "text": "The best way to know how a framework is to play with it! We would need more than one party to test this out. But don’t worry, we can simulate the scenarios of multiple parties trying to train their data from different machines! How good will the training perform? Stay tuned and observe the magic." }, { "code": null, "e": 4522, "s": 4432, "text": "The steps below could be found in the setup section of IBM Federated learning Github repo" }, { "code": null, "e": 4583, "s": 4522, "text": "Start with cloning this repo. Then go to the folder created." }, { "code": null, "e": 4682, "s": 4583, "text": "Install all the requirements. I really highly recommend using Conda installation for this project." }, { "code": null, "e": 4745, "s": 4682, "text": "conda create -n <env_name> python=3.6conda activate <env_name>" }, { "code": null, "e": 4784, "s": 4745, "text": "Install the IBM FL package by running:" }, { "code": null, "e": 4830, "s": 4784, "text": "pip install <IBM_federated_learning_whl_file>" }, { "code": null, "e": 4937, "s": 4830, "text": "This example explains how to run federated learning on CNNs implemented with Keras training on MNIST data." }, { "code": null, "e": 5105, "s": 4937, "text": "We will need more than one party to see how FL works. We can use generate_data.py to generate sample data on any of the integrated datasets. For example, we could run:" }, { "code": null, "e": 5160, "s": 5105, "text": "python examples/generate_data.py -n 2 -d mnist -pp 200" }, { "code": null, "e": 5248, "s": 5160, "text": "This command would generate 2 parties with 200 data points each from the MNIST dataset." }, { "code": null, "e": 5489, "s": 5248, "text": "To run IBM federated learning, you must have configuration files for the aggregator and for each party. Each config file consists of the information about each party. You can generate these config files using the generate_configs.py script." }, { "code": null, "e": 5517, "s": 5489, "text": "For example, you could run:" }, { "code": null, "e": 5617, "s": 5517, "text": "python examples/generate_configs.py -m keras_classifier -n 2 -d mnist -p examples/data/mnist/random" }, { "code": null, "e": 5739, "s": 5617, "text": "This command would generate the configs for the keras_classifier model, assuming 2 parties. -p is the path of party data." }, { "code": null, "e": 5941, "s": 5739, "text": "Now put yourself in the seat of each party and the aggregator. Remember, in real life, the parties and the aggregator will not see one another’s screen but they will coordinate in the training process." }, { "code": null, "e": 6039, "s": 5941, "text": "To start the aggregator, open a terminal window running the IBM FL environment set up previously." }, { "code": null, "e": 6060, "s": 6039, "text": "In the terminal run:" }, { "code": null, "e": 6081, "s": 6060, "text": "In the terminal run:" }, { "code": null, "e": 6168, "s": 6081, "text": "python -m ibmfl.aggregator.aggregator examples/configs/keras_classifier/config_agg.yml" }, { "code": null, "e": 6228, "s": 6168, "text": "where the path provided is the aggregator config file path." }, { "code": null, "e": 6358, "s": 6228, "text": "2. Then in the terminal, type START , and press enter. This means the aggregator starts accepting connections from other parties." }, { "code": null, "e": 6476, "s": 6358, "text": "To register new parties, open a new terminal window for each party, running the IBM FL environment set up previously." }, { "code": null, "e": 6497, "s": 6476, "text": "In the terminal run:" }, { "code": null, "e": 6518, "s": 6497, "text": "In the terminal run:" }, { "code": null, "e": 6598, "s": 6518, "text": "python -m ibmfl.party.party examples/configs/keras_classifier/config_party0.yml" }, { "code": null, "e": 6660, "s": 6598, "text": "where the path provided is the path to the party config file." }, { "code": null, "e": 6792, "s": 6660, "text": "2. In the terminal for each party, type START and press enter. This means the party start accepting connections from the aggregator" }, { "code": null, "e": 6906, "s": 6792, "text": "3. Then in the terminal for each party, type REGISTER and press enter. This means the parties join the FL project" }, { "code": null, "e": 6995, "s": 6906, "text": "To initiate federated training, type TRAIN in your aggregator terminal, and press enter." }, { "code": null, "e": 7041, "s": 6995, "text": "To synchronize model among parties, type SYNC" }, { "code": null, "e": 7116, "s": 7041, "text": "To save the model, type SAVE in your aggregator terminal, and press enter." }, { "code": null, "e": 7255, "s": 7116, "text": "Voila! Now models for each party are saved to your folder. In the real scenario, each party would just see one model file for their party." }, { "code": null, "e": 7318, "s": 7255, "text": "Now we have the model that is ready to be used for prediction!" }, { "code": null, "e": 7520, "s": 7318, "text": "Remember to type STOP in both the aggregator terminal and parties’ terminal to end the experiment process. Congratulation! Your party has just finished the training process without revealing your data." }, { "code": null, "e": 7683, "s": 7520, "text": "Imagine you are party 0, to use the model to predict the test data of your party, all you need to do is to load the model and predict the test data of your party." }, { "code": null, "e": 7809, "s": 7683, "text": "Awesome! Your party gets a f1-score of .81. You have not just secured your data but also get a robust machine learning model!" }, { "code": null, "e": 7917, "s": 7809, "text": "I will use the screenshot from IBM Data Science and AI Session 4 to compare the performance between the two" }, { "code": null, "e": 8171, "s": 7917, "text": "As you can see, all metrics including accuracy, f1, precision, recall of local model performance at party 1 are greater than the local model performance! By combining the data from other sources, you get a more robust model to predict your party’s data." }, { "code": null, "e": 8363, "s": 8171, "text": "Congratulation! You have just learned how to train machine learning on the combination of datasets without sharing the data! Best of all, setting up training does not require advanced skills." }, { "code": null, "e": 8593, "s": 8363, "text": "All you need is to add to your project file is a config that specifies the relevant information such as connection, data, model. Then use some simple command lines on the terminal to set up and train all parties at the same time." }, { "code": null, "e": 8800, "s": 8593, "text": "The Github repository, as well as the literature for the framework, could be found here. You could also use IBM Federated Learning Slack channel to contact directly to the development team of the framework." }, { "code": null, "e": 8960, "s": 8800, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Exploring Netflix Data in Python. Exploratory Data Analysis of Netflix... | by Sadrach Pierre, Ph.D. | Towards Data Science
Flixable is a search engine for video streaming services that offers a complete list of movies and shows streaming on Netflix. The search engine released the Netflix Movies and TV Shows data set, which includes the complete list of movies and shows available in 2019. In this post, we will perform exploratory data analysis on Netflix Movies and TV Shows data set. The data can be found here. Let’s get started! First, let’s import Pandas and read the data into a data frame: import pandas as pd df = pd.read_csv("netflix_titles.csv") Next, let’s print the list of columns: print(list(df.columns)) We can also take a look at the number of rows in the data: print("Number of rows: ", len(df)) Let’s print the first five rows of the data: print(df.head()) We can see that there are several categorical columns. Let’s define a function that takes as input a data frame, column name, and limit. When called, it prints a dictionary of categorical values and how frequently they appear: def return_counter(data_frame, column_name, limit): from collections import Counter print(dict(Counter(data_frame[column_name].values).most_common(limit))) Let’s apply our function to the ‘country’ column and limit our results to the five most common values: return_counter(df, 'country', 5) As we can see, we have 2,032 titles in the US, 777 in India, 476 missing country values, 348 in the UK, and 176 in Japan. Let’s apply our function to the ‘director’ column, upon dropping missing values: df['director'].dropna(inplace = True)return_counter(df, 'director', 5) Now, let’s look at the titles from the most common directors ‘Raul Campos’ and ‘Jan Suter’: df_d1 = df[df['director'] =='Raúl Campos, Jan Suter']print(set(df_d1['title'])) And the countries: print(set(df_d1['country'])) We see that these are titles from Colombia, Chile, Argentina, and Mexico. Let’s do the same for Marcus Raboy: df_d2 = df[df['director'] =='Marcus Raboy']print(set(df_d2['title'])) Now we’ll analyze movie durations. First, we need to filter the data set to only include movie titles: df = df[df['type'] =='Movie'] Let’s then print the set of movie durations: print(set(df['duration'])) We see that all values are reported as strings and the duration is measured in minutes. Let’s remove ‘min’ from the string values and convert the result to integers: df['duration'] = df['duration'].map(lambda x: x.rstrip('min')).astype(int)print(set(df['duration'])) Next, it would be useful to generate summary statistics from numerical columns like ‘duration’. Let’s define a function that takes a data frame, a categorical column, and a numerical column. The mean and standard deviation of the numerical column for each category is stored in a data frame and the data frame is sorted in descending order according to the mean. This is useful if you want to quickly see if certain categories have higher or lower mean and/or standard deviation values for a particular numerical column. def return_statistics(data_frame, categorical_column, numerical_column): mean = [] std = [] field = [] for i in set(list(data_frame[categorical_column].values)): new_data = data_frame[data_frame[categorical_column] == i] field.append(i) mean.append(new_data[numerical_column].mean()) std.append(new_data[numerical_column].std()) df = pd.DataFrame({'{}'.format(categorical_column): field, 'mean {}'.format(numerical_column): mean, 'std in {}'.format(numerical_column): std}) df.sort_values('mean {}'.format(numerical_column), inplace = True, ascending = False) df.dropna(inplace = True) return df Let’s call our function with categorical column ‘listed_in’ and numerical column ‘duration’: stats = return_statistics(df, 'listed_in', 'duration')print(stats.head(15)) Next, we will use boxplots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile. If you are unfamiliar with them, take a look at the article Understanding Boxplots. Similar to the summary statistics function, this function takes a data frame, categorical column, and numerical column and displays boxplots for the most common categories based on the limit: def get_boxplot_of_categories(data_frame, categorical_column, numerical_column, limit): import seaborn as sns from collections import Counter keys = [] for i in dict(Counter(df[categorical_column].values).most_common(limit)): keys.append(i) print(keys) df_new = df[df[categorical_column].isin(keys)] sns.set() sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column]) Let’s generate boxplots for ‘duration’ in the 5 most commonly occurring ‘listed in’ categories: get_boxplot_of_categories(df, 'listed_in', 'duration', 5) Finally, let’s define a function takes a data frame and a numerical column as input and displays a histogram: def get_histogram(data_frame, numerical_column): df_new = data_frame df_new[numerical_column].hist(bins=100) Let’s call the function with the data frame and generate a histogram from ‘duration’: get_histogram(df, 'duration') I will stop here but please feel free to play around with the data and code yourself. To recap, I went over several methods for analyzing the Netflix Movies and TV Shows data set. This included defining functions for generating summary statistics like the mean, standard deviation, and counts for categorical values. We also defined functions for visualizing data with boxplots and histograms. I hope this post was interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 440, "s": 172, "text": "Flixable is a search engine for video streaming services that offers a complete list of movies and shows streaming on Netflix. The search engine released the Netflix Movies and TV Shows data set, which includes the complete list of movies and shows available in 2019." }, { "code": null, "e": 565, "s": 440, "text": "In this post, we will perform exploratory data analysis on Netflix Movies and TV Shows data set. The data can be found here." }, { "code": null, "e": 584, "s": 565, "text": "Let’s get started!" }, { "code": null, "e": 648, "s": 584, "text": "First, let’s import Pandas and read the data into a data frame:" }, { "code": null, "e": 707, "s": 648, "text": "import pandas as pd df = pd.read_csv(\"netflix_titles.csv\")" }, { "code": null, "e": 746, "s": 707, "text": "Next, let’s print the list of columns:" }, { "code": null, "e": 770, "s": 746, "text": "print(list(df.columns))" }, { "code": null, "e": 829, "s": 770, "text": "We can also take a look at the number of rows in the data:" }, { "code": null, "e": 864, "s": 829, "text": "print(\"Number of rows: \", len(df))" }, { "code": null, "e": 909, "s": 864, "text": "Let’s print the first five rows of the data:" }, { "code": null, "e": 926, "s": 909, "text": "print(df.head())" }, { "code": null, "e": 1153, "s": 926, "text": "We can see that there are several categorical columns. Let’s define a function that takes as input a data frame, column name, and limit. When called, it prints a dictionary of categorical values and how frequently they appear:" }, { "code": null, "e": 1314, "s": 1153, "text": "def return_counter(data_frame, column_name, limit): from collections import Counter print(dict(Counter(data_frame[column_name].values).most_common(limit)))" }, { "code": null, "e": 1417, "s": 1314, "text": "Let’s apply our function to the ‘country’ column and limit our results to the five most common values:" }, { "code": null, "e": 1450, "s": 1417, "text": "return_counter(df, 'country', 5)" }, { "code": null, "e": 1572, "s": 1450, "text": "As we can see, we have 2,032 titles in the US, 777 in India, 476 missing country values, 348 in the UK, and 176 in Japan." }, { "code": null, "e": 1653, "s": 1572, "text": "Let’s apply our function to the ‘director’ column, upon dropping missing values:" }, { "code": null, "e": 1724, "s": 1653, "text": "df['director'].dropna(inplace = True)return_counter(df, 'director', 5)" }, { "code": null, "e": 1816, "s": 1724, "text": "Now, let’s look at the titles from the most common directors ‘Raul Campos’ and ‘Jan Suter’:" }, { "code": null, "e": 1897, "s": 1816, "text": "df_d1 = df[df['director'] =='Raúl Campos, Jan Suter']print(set(df_d1['title']))" }, { "code": null, "e": 1916, "s": 1897, "text": "And the countries:" }, { "code": null, "e": 1945, "s": 1916, "text": "print(set(df_d1['country']))" }, { "code": null, "e": 2055, "s": 1945, "text": "We see that these are titles from Colombia, Chile, Argentina, and Mexico. Let’s do the same for Marcus Raboy:" }, { "code": null, "e": 2125, "s": 2055, "text": "df_d2 = df[df['director'] =='Marcus Raboy']print(set(df_d2['title']))" }, { "code": null, "e": 2228, "s": 2125, "text": "Now we’ll analyze movie durations. First, we need to filter the data set to only include movie titles:" }, { "code": null, "e": 2258, "s": 2228, "text": "df = df[df['type'] =='Movie']" }, { "code": null, "e": 2303, "s": 2258, "text": "Let’s then print the set of movie durations:" }, { "code": null, "e": 2330, "s": 2303, "text": "print(set(df['duration']))" }, { "code": null, "e": 2496, "s": 2330, "text": "We see that all values are reported as strings and the duration is measured in minutes. Let’s remove ‘min’ from the string values and convert the result to integers:" }, { "code": null, "e": 2597, "s": 2496, "text": "df['duration'] = df['duration'].map(lambda x: x.rstrip('min')).astype(int)print(set(df['duration']))" }, { "code": null, "e": 3118, "s": 2597, "text": "Next, it would be useful to generate summary statistics from numerical columns like ‘duration’. Let’s define a function that takes a data frame, a categorical column, and a numerical column. The mean and standard deviation of the numerical column for each category is stored in a data frame and the data frame is sorted in descending order according to the mean. This is useful if you want to quickly see if certain categories have higher or lower mean and/or standard deviation values for a particular numerical column." }, { "code": null, "e": 3766, "s": 3118, "text": "def return_statistics(data_frame, categorical_column, numerical_column): mean = [] std = [] field = [] for i in set(list(data_frame[categorical_column].values)): new_data = data_frame[data_frame[categorical_column] == i] field.append(i) mean.append(new_data[numerical_column].mean()) std.append(new_data[numerical_column].std()) df = pd.DataFrame({'{}'.format(categorical_column): field, 'mean {}'.format(numerical_column): mean, 'std in {}'.format(numerical_column): std}) df.sort_values('mean {}'.format(numerical_column), inplace = True, ascending = False) df.dropna(inplace = True) return df" }, { "code": null, "e": 3859, "s": 3766, "text": "Let’s call our function with categorical column ‘listed_in’ and numerical column ‘duration’:" }, { "code": null, "e": 3935, "s": 3859, "text": "stats = return_statistics(df, 'listed_in', 'duration')print(stats.head(15))" }, { "code": null, "e": 4169, "s": 3935, "text": "Next, we will use boxplots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile. If you are unfamiliar with them, take a look at the article Understanding Boxplots." }, { "code": null, "e": 4361, "s": 4169, "text": "Similar to the summary statistics function, this function takes a data frame, categorical column, and numerical column and displays boxplots for the most common categories based on the limit:" }, { "code": null, "e": 4781, "s": 4361, "text": "def get_boxplot_of_categories(data_frame, categorical_column, numerical_column, limit): import seaborn as sns from collections import Counter keys = [] for i in dict(Counter(df[categorical_column].values).most_common(limit)): keys.append(i) print(keys) df_new = df[df[categorical_column].isin(keys)] sns.set() sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column])" }, { "code": null, "e": 4877, "s": 4781, "text": "Let’s generate boxplots for ‘duration’ in the 5 most commonly occurring ‘listed in’ categories:" }, { "code": null, "e": 4935, "s": 4877, "text": "get_boxplot_of_categories(df, 'listed_in', 'duration', 5)" }, { "code": null, "e": 5045, "s": 4935, "text": "Finally, let’s define a function takes a data frame and a numerical column as input and displays a histogram:" }, { "code": null, "e": 5160, "s": 5045, "text": "def get_histogram(data_frame, numerical_column): df_new = data_frame df_new[numerical_column].hist(bins=100)" }, { "code": null, "e": 5246, "s": 5160, "text": "Let’s call the function with the data frame and generate a histogram from ‘duration’:" }, { "code": null, "e": 5276, "s": 5246, "text": "get_histogram(df, 'duration')" }, { "code": null, "e": 5362, "s": 5276, "text": "I will stop here but please feel free to play around with the data and code yourself." } ]
How to Open a Specific Folder Via Intent in Android? - GeeksforGeeks
06 Jun, 2021 In this article, we are going to open a specific folder from our App. This feature is useful in many cases. Most of the time when we want to upload any file then the app simply opens the file manager. But we can implement this feature for effective use like whenever any user wants to upload any file then the user will simply choose the folder name like WhatsApp, downloads, etc. Then the user will be directed to that folder only. Let’s see the implementation of this feature. Reference Articles: Intent in Android Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file 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"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <Button android:id="@+id/download" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Download Folder" /> <Button android:id="@+id/movies" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Movies Folder" /> <Button android:id="@+id/pic" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Pictures Folder" /> <Button android:id="@+id/whtsapp" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Whatsapp Content" /> <Button android:id="@+id/music" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Music Folder" /> </LinearLayout> Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button movie, download, pic, music, whatsapp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); movie = findViewById(R.id.movies); download = findViewById(R.id.download); whatsapp = findViewById(R.id.whtsapp); pic = findViewById(R.id.pic); music = findViewById(R.id.music); movie.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + "/" + "Movies" + "/"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, "*/*"); startActivity(intent); } }); whatsapp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + "/" + "WhatsApp" + "/"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, "*/*"); startActivity(intent); } }); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + "/" + "Downloads" + "/"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, "*/*"); startActivity(intent); } }); music.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + "/" + "Music" + "/"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, "*/*"); startActivity(intent); } }); pic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + "/" + "Pictures" + "/"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, "*/*"); startActivity(intent); } }); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Change the Background Color After Clicking the Button in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25116, "s": 25088, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25595, "s": 25116, "text": "In this article, we are going to open a specific folder from our App. This feature is useful in many cases. Most of the time when we want to upload any file then the app simply opens the file manager. But we can implement this feature for effective use like whenever any user wants to upload any file then the user will simply choose the folder name like WhatsApp, downloads, etc. Then the user will be directed to that folder only. Let’s see the implementation of this feature." }, { "code": null, "e": 25633, "s": 25595, "text": "Reference Articles: Intent in Android" }, { "code": null, "e": 25662, "s": 25633, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25824, "s": 25662, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 25872, "s": 25824, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26015, "s": 25872, "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": 26019, "s": 26015, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/download\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Download Folder\" /> <Button android:id=\"@+id/movies\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Movies Folder\" /> <Button android:id=\"@+id/pic\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Pictures Folder\" /> <Button android:id=\"@+id/whtsapp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Whatsapp Content\" /> <Button android:id=\"@+id/music\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Music Folder\" /> </LinearLayout>", "e": 27265, "s": 26019, "text": null }, { "code": null, "e": 27313, "s": 27265, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 27503, "s": 27313, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 27508, "s": 27503, "text": "Java" }, { "code": "import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button movie, download, pic, music, whatsapp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); movie = findViewById(R.id.movies); download = findViewById(R.id.download); whatsapp = findViewById(R.id.whtsapp); pic = findViewById(R.id.pic); music = findViewById(R.id.music); movie.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + \"/\" + \"Movies\" + \"/\"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, \"*/*\"); startActivity(intent); } }); whatsapp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + \"/\" + \"WhatsApp\" + \"/\"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, \"*/*\"); startActivity(intent); } }); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + \"/\" + \"Downloads\" + \"/\"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, \"*/*\"); startActivity(intent); } }); music.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + \"/\" + \"Music\" + \"/\"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, \"*/*\"); startActivity(intent); } }); pic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String path = Environment.getExternalStorageDirectory() + \"/\" + \"Pictures\" + \"/\"; Uri uri = Uri.parse(path); Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(uri, \"*/*\"); startActivity(intent); } }); }}", "e": 30407, "s": 27508, "text": null }, { "code": null, "e": 30415, "s": 30407, "text": "Output:" }, { "code": null, "e": 30423, "s": 30415, "text": "Android" }, { "code": null, "e": 30428, "s": 30423, "text": "Java" }, { "code": null, "e": 30433, "s": 30428, "text": "Java" }, { "code": null, "e": 30441, "s": 30433, "text": "Android" }, { "code": null, "e": 30539, "s": 30441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30578, "s": 30539, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30628, "s": 30578, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30670, "s": 30628, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30708, "s": 30670, "text": "Android Listview in Java with Example" }, { "code": null, "e": 30781, "s": 30708, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 30796, "s": 30781, "text": "Arrays in Java" }, { "code": null, "e": 30840, "s": 30796, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30862, "s": 30840, "text": "For-each loop in Java" }, { "code": null, "e": 30898, "s": 30862, "text": "Arrays.sort() in Java with examples" } ]
Tryit Editor v3.7
CSS Color Keywords Tryit: Using the transparent keyword
[ { "code": null, "e": 28, "s": 9, "text": "CSS Color Keywords" } ]
Generating optical flow using NVIDIA flownet2-pytorch implementation | by Mark Gituma | Towards Data Science
This blog was originally published in blog.dancelogue.com. In a previous post, an introduction to optical flow was conducted, as well an overview of it’s architecture based on the FlowNet 2.o paper. This blog will focus in going deeper into optical flow, which will be done by generating optical flow files both from the standard Sintel data and a custom dance video. It will be conducted using a fork of the NVIDIA flownet2-pytorch code base which can be found in the Dancelogue linked repo. The goal of this blog is to: Get the flownet2-pytorch codebase up and running. Download the relevant dataset as described by the example provided in the original repository. Generate optical flow files and then investigate the structure of the flow files. Convert the flow files into the color coding scheme to make them easier for humans to understand. Apply optical flow generation to dance videos and analyse the result. The flownet2-pytorch implementation has been designed to work with a GPU. Unfortunately, it means if you don’t have access to one it will not be possible to follow this blog completely. In order to mitigate this problem, sample data generated by the model is provided and allows the reader to follow through with the rest of the blog. The rest of this tutorial is conducted using ubuntu 18.04 with a NVIDIA GEFORCE GTX 1080 Ti GPU. Docker is required and must be GPU enabled which can be done using the the nvidia-docker package. Here is a list of all the code and data required so as to follow through with the blog (downloading the data has been automated so the reader doesn’t have to do it manually, please see the Getting Started section): The code base for this blog can be cloned from the following repo. The Sintel data can be downloaded by clicking the following link, the zipped file is 5.63 GB which increases to 12.24 GB when unzipped. Custom data can be downloaded which includes a sample optical flow .flofile, a generated color coding scheme from the sample optical flow file, a dance video to conduct optical flow on, an optical flow video representation of the dance video. The memory space requirements required to follow through with this blog is approximately 32 GB. The reason for this will be explained later on. As mentioned, a fork of the original flownet2-pytorch was created, and it’s because at the time of the writing of this blog, the original repository had issues when building and running the docker image e.g. python package version issues, c libraries compile issues etc. The updates include: Modifying the Dockerfile by fixing the python package versions, updating the cuda and pytorch versions, running an automated build and installation of the correlation layer, adding ffmpeg, adding a third party github package that will allow the reading, processing and conversion of the flow files to the color coding scheme. Writing download scripts for both the datasets and trained models in order to make it easier to get started, the inspiration for this is from the vid2vid repository which is also from NVIDIA. With this in mind, let’s get started. The first thing is to clone the dancelogue fork of the original repository from https://github.com/dancelogue/flownet2-pytorch. Then run the docker script using the following command: bash launch_docker.sh It should take a few minutes to set up, after which, it should change the terminal context to the docker session. The next thing is to download the relevant datasets, all the required data for the initial setup can be achieved by running the following command within the docker context: bash scripts/download.sh This downloads the FlowNet2_checkpoint.pth.tar model weights to the models folder, as well as the MPI-Sintel data to the datasets folder. This is required in order to follow the instructions for the inference example as indicated in the flownet2-pytorch getting started guide. The custom dance video is also downloaded as well as a sample optical flow .flo file. The rest of the commands in this blog have been automated and can be run by the following: bash scripts/run.sh The command to run the original inference example is as follows: python main.py --inference --model FlowNet2 --save_flow \ --inference_dataset MpiSintelClean \--inference_dataset_root /path/to/mpi-sintel/clean/dataset \--resume /path/to/checkpoints However based on the fork, this has modified to: python main.py --inference --model FlowNet2 --save_flow \ --inference_dataset MpiSintelClean \--inference_dataset_root datasets/sintel/training \--resume checkpoints/FlowNet2_checkpoint.pth.tar \--save datasets/sintel/output Let’s break it down: The --model indicates what variation of the model to use. From the previous blog we saw this can be FlowNetC, FlowNetCSS or FlowNet2 but for this blog it is set to FlowNet2. The --resume argument indicates the location of the trained model weights. This has been downloaded into the checkpoints folder using the download scripts. Note the trained model weights have certain license restrictions which you should go through in case you need to use them outside this blog. The --inference argument simply means, based on the learned capability as defined by the model weights from the training data, what can you tell me about the new dataset. This is different from training the models where the model weights will change. The --inference_dataset indicates what type of data will be fed. In the current case it is sintel as specified by MpiSintelClean. More options for this can be found in https://github.com/dancelogue/flownet2-pytorch/blob/master/datasets.py and are defined as classes e.g. FlyingChairs. There is also the ImagesFromFolder class which means we can feed custom data e.g. frames from a video and we can get inference from that. The --inference_dataset_root indicates the location of the data that will be used for the inference process, which has been downloaded and unzipped into the datasets/sintel folder. The --save_flow argument indicates that the inferred optical flow should be saved as .flo files. The --save argument indicates the location to which the inferred optical flow files as well as the logs should be saved to. It is an optional field and defaults to the work/ location. Running the above command saves the generated optical flow files into the datasets/sintel/output/inference/run.epoch-0-flow-field folder. The generated optical flow files have the extension .flo which are the flow fields representations. Now that the optical flow files have been generated, it’s time to analyze the structure in order get a better understanding of the result, as well as convert them to the flow field color coding scheme. The sample flow file used in this section can be downloaded from the following link. Loading an optical flow file into numpy is a fairly trivial process, which can be conducted as follows: path = Path('path/to/flow/file/<filename>.flo')with path.open(mode='r') as flo: np_flow = np.fromfile(flo, np.float32) print(np_flow.shape) The above syntax is based on python3, where the file is loaded into a buffer and then fed into numpy. The next thing is trying to understand the basic features of the flow file which is achieved by the print statement. Assuming you are following with the sample flow file that was provided, the print statement should output(786435,). The implication is that for each flow file, it contains a single array with 786453 elements in the array. The memory footprint of a single flow file is approximately 15.7 MB, which even though looks trivial, increases quite quickly especially when looking at video with thousands of frames. Before proceeding further we need to look at the optical flow specification as defined in http://vision.middlebury.edu/flow/code/flow-code/README.txt. What we care about is the following: ".flo" file format used for optical flow evaluationStores 2-band float image for horizontal (u) and vertical (v) flow components.Floats are stored in little-endian order.A flow value is considered "unknown" if either |u| or |v| is greater than 1e9. bytes contents 0-3 tag: "PIEH" in ASCII, which in little endian happens to be the float 202021.25 (just a sanity check that floats are represented correctly) 4-7 width as an integer 8-11 height as an integer 12-end data (width*height*2*4 bytes total) the float values for u and v, interleaved, in row order, i.e., u[row0,col0], v[row0,col0], u[row0,col1], v[row0,col1], ... Based on the above specification, the following code will allow us to read the flow file correctly (borrowed from https://github.com/georgegach/flowiz/blob/master/flowiz/flowiz.py). with path.open(mode='r') as flo: tag = np.fromfile(flo, np.float32, count=1)[0] width = np.fromfile(flo, np.int32, count=1)[0] height = np.fromfile(flo, np.int32, count=1)[0] print('tag', tag, 'width', width, 'height', height) nbands = 2 tmp = np.fromfile(flo, np.float32, count= nbands * width * height) flow = np.resize(tmp, (int(height), int(width), int(nbands))) Based on the optical flow format specification, hopefully the above code should make more sense about what’s happening i.e. we get the tag, then the width, followed by height. The output of the print statement is tag 202021.25 width 1024 height 384. From the given specification we can see that the tag matches the sanity check value, the width of the flow file is 1024 and the height is 384. Note, it is important to have the correct order when reading the file buffer and loading it into numpy, this is due to the way the files are read in python (bytes are read sequentially) otherwise the tag, height and width can get mixed up. Now that we have the width and the height, we can read the rest of the optical flow data and resize into a shape that's more familiar, which is done using the np.resize method. A quick way to understand how the flow vectors have been resized is to print them to the terminal, this is done by running the following code: >> print(flow.shape)(384, 1024, 2)>> print(flow[0][0])[-1.2117167 -1.557275] As we expect the shape of the new representation implies a height of 384, a width of 1024 and has a displacement vector consisting of 2 values. Focusing on the pixel at location 0, 0 we can see the displacement vector at that point seems to be pointing to the left and to the bottom i.e. the bottom left quadrant of an x, y plot, which means we expect the color code for this location to be a light blue or even a green color based on the color coding scheme given below. There are quite a few open source code bases written to visualize optical flow files. The one chosen for this purpose can be found in the github repository https://github.com/georgegach/flowiz. The reason for this is that it allows the generation of video clips from the color coding scheme which will be useful at a later stage. Assuming the docker context provided at the beginning of this tutorial is used, the following command can be used to generate color coded image files of the optical flow. python -m flowiz \datasets/sintel/output/inference/run.epoch-0-flow-field/*.flo \-o datasets/sintel/output/color_coding \-v datasets/sintel/output/color_coding/video \-r 30 This takes the optical flow files and generates image files where the displacement vector is color coded as shown below. In order to understand the color coding scheme, please view the previous blog on optical flow. At position 0, 0 i.e. the bottom right portion of the image, we can indeed see a light blue color and is what we expected from the displacement vector, i.e. it is the color for a vector pointing to the left and bottom. In this section, we will use a dance video, and generate optical flow files from it. The dance video is: It consists of a dance choreography class in a real world setting. As the flownet code base takes in images, the first thing we need to do is to convert the videos into frames, which can be done by the following command using ffmpeg. ffmpeg -i datasets/dancelogue/sample-video.mp4 \datasets/dancelogue/frames/output_%02d.png It will output the frames in an ordered sequence within the frames folder, the order is important as the flownet algorithm uses adjacent images to calculate the optical flow between the images. The generated frames occupy 1.7 GB of memory whereas the video is only 11.7 MB, each frame is about 2 MB. The optical flow representations can be generated by running the following command. python main.py --inference --model FlowNet2 --save_flow \--inference_dataset ImagesFromFolder \--inference_dataset_root datasets/dancelogue/frames/ \--resume checkpoints/FlowNet2_checkpoint.pth.tar \--save datasets/dancelogue/output This is similar to the inference model we ran with the sintel dataset where the differences are in the --inference_dataset argument which changes to ImagesFromFolder and as defined in the codebase. The --inference_dataset_root is the path to the generated video frames. The generated optical flow files occupy 14.6 GB of memory, this is because each optical flow file is approximately 15.7 MB for this example. The command to generate the color coding scheme is: python -m flowiz \datasets/dancelogue/output/inference/run.epoch-0-flow-field/*.flo \-o datasets/dancelogue/output/color_coding \-v datasets/dancelogue/output/color_coding/video \-r 30 This makes use of the flowviz repository as well as ffmpeg. Not only does it generate the optical flow color encodings as .png files, but the -v -r 30 parameter generates videos from the image files at 30 fps. The generated color coding frames occupy 422 MB of memory which includes a 8.7 MB video file which has the name 000000.flo.mp4 if you are following through this blog. The generated video representation of the optical flow is as follows: The gist of the choreography can be seen from the generated video, the different colors indicate the direction of motion. However, it can be seen there is a lot of background noise especially around the central dancers despite no apparent motion in the video. Unfortunately, it is not clear why this is the case. When running the flownet algorithm, one needs to be aware of the size implications, a 11.7 MB video for example, generates a 1.7 GB file of individual frames when extracted. However when generating optical flow this becomes a 14.6 GB file containing all the optical flow representations. This is because each optical flow file occupies about 15.7 MB in memory, however each image frame occupies 2 MB of memory (for the case of the examples provided). Thus when running optical flow algorithms one needs to be aware of the computation requirements vs space tradeoff. This trade off will impact the architecture when building deep learning systems for video, meaning either generate optical flow files as needed (i.e. lazily) at the cost of computation time or generate all the required formats and representations before hand and save them to the file system at the cost of storage space. We have seen how to generate optical flow files using a fork of NVIDIA’s flownet2-pytorch implementation, as well as have had an overview understanding of optical flow files. The next blog will cover how to use the optical flow representations to understand video content and will be focusing on 2 stream networks. If you have any questions or anything needs clarification, you can book a time with me on https://mbele.io/mark
[ { "code": null, "e": 664, "s": 171, "text": "This blog was originally published in blog.dancelogue.com. In a previous post, an introduction to optical flow was conducted, as well an overview of it’s architecture based on the FlowNet 2.o paper. This blog will focus in going deeper into optical flow, which will be done by generating optical flow files both from the standard Sintel data and a custom dance video. It will be conducted using a fork of the NVIDIA flownet2-pytorch code base which can be found in the Dancelogue linked repo." }, { "code": null, "e": 693, "s": 664, "text": "The goal of this blog is to:" }, { "code": null, "e": 743, "s": 693, "text": "Get the flownet2-pytorch codebase up and running." }, { "code": null, "e": 838, "s": 743, "text": "Download the relevant dataset as described by the example provided in the original repository." }, { "code": null, "e": 920, "s": 838, "text": "Generate optical flow files and then investigate the structure of the flow files." }, { "code": null, "e": 1018, "s": 920, "text": "Convert the flow files into the color coding scheme to make them easier for humans to understand." }, { "code": null, "e": 1088, "s": 1018, "text": "Apply optical flow generation to dance videos and analyse the result." }, { "code": null, "e": 1423, "s": 1088, "text": "The flownet2-pytorch implementation has been designed to work with a GPU. Unfortunately, it means if you don’t have access to one it will not be possible to follow this blog completely. In order to mitigate this problem, sample data generated by the model is provided and allows the reader to follow through with the rest of the blog." }, { "code": null, "e": 1618, "s": 1423, "text": "The rest of this tutorial is conducted using ubuntu 18.04 with a NVIDIA GEFORCE GTX 1080 Ti GPU. Docker is required and must be GPU enabled which can be done using the the nvidia-docker package." }, { "code": null, "e": 1833, "s": 1618, "text": "Here is a list of all the code and data required so as to follow through with the blog (downloading the data has been automated so the reader doesn’t have to do it manually, please see the Getting Started section):" }, { "code": null, "e": 1900, "s": 1833, "text": "The code base for this blog can be cloned from the following repo." }, { "code": null, "e": 2036, "s": 1900, "text": "The Sintel data can be downloaded by clicking the following link, the zipped file is 5.63 GB which increases to 12.24 GB when unzipped." }, { "code": null, "e": 2279, "s": 2036, "text": "Custom data can be downloaded which includes a sample optical flow .flofile, a generated color coding scheme from the sample optical flow file, a dance video to conduct optical flow on, an optical flow video representation of the dance video." }, { "code": null, "e": 2423, "s": 2279, "text": "The memory space requirements required to follow through with this blog is approximately 32 GB. The reason for this will be explained later on." }, { "code": null, "e": 2715, "s": 2423, "text": "As mentioned, a fork of the original flownet2-pytorch was created, and it’s because at the time of the writing of this blog, the original repository had issues when building and running the docker image e.g. python package version issues, c libraries compile issues etc. The updates include:" }, { "code": null, "e": 3041, "s": 2715, "text": "Modifying the Dockerfile by fixing the python package versions, updating the cuda and pytorch versions, running an automated build and installation of the correlation layer, adding ffmpeg, adding a third party github package that will allow the reading, processing and conversion of the flow files to the color coding scheme." }, { "code": null, "e": 3233, "s": 3041, "text": "Writing download scripts for both the datasets and trained models in order to make it easier to get started, the inspiration for this is from the vid2vid repository which is also from NVIDIA." }, { "code": null, "e": 3455, "s": 3233, "text": "With this in mind, let’s get started. The first thing is to clone the dancelogue fork of the original repository from https://github.com/dancelogue/flownet2-pytorch. Then run the docker script using the following command:" }, { "code": null, "e": 3477, "s": 3455, "text": "bash launch_docker.sh" }, { "code": null, "e": 3591, "s": 3477, "text": "It should take a few minutes to set up, after which, it should change the terminal context to the docker session." }, { "code": null, "e": 3764, "s": 3591, "text": "The next thing is to download the relevant datasets, all the required data for the initial setup can be achieved by running the following command within the docker context:" }, { "code": null, "e": 3789, "s": 3764, "text": "bash scripts/download.sh" }, { "code": null, "e": 4152, "s": 3789, "text": "This downloads the FlowNet2_checkpoint.pth.tar model weights to the models folder, as well as the MPI-Sintel data to the datasets folder. This is required in order to follow the instructions for the inference example as indicated in the flownet2-pytorch getting started guide. The custom dance video is also downloaded as well as a sample optical flow .flo file." }, { "code": null, "e": 4243, "s": 4152, "text": "The rest of the commands in this blog have been automated and can be run by the following:" }, { "code": null, "e": 4263, "s": 4243, "text": "bash scripts/run.sh" }, { "code": null, "e": 4328, "s": 4263, "text": "The command to run the original inference example is as follows:" }, { "code": null, "e": 4512, "s": 4328, "text": "python main.py --inference --model FlowNet2 --save_flow \\ --inference_dataset MpiSintelClean \\--inference_dataset_root /path/to/mpi-sintel/clean/dataset \\--resume /path/to/checkpoints" }, { "code": null, "e": 4561, "s": 4512, "text": "However based on the fork, this has modified to:" }, { "code": null, "e": 4786, "s": 4561, "text": "python main.py --inference --model FlowNet2 --save_flow \\ --inference_dataset MpiSintelClean \\--inference_dataset_root datasets/sintel/training \\--resume checkpoints/FlowNet2_checkpoint.pth.tar \\--save datasets/sintel/output" }, { "code": null, "e": 4807, "s": 4786, "text": "Let’s break it down:" }, { "code": null, "e": 4981, "s": 4807, "text": "The --model indicates what variation of the model to use. From the previous blog we saw this can be FlowNetC, FlowNetCSS or FlowNet2 but for this blog it is set to FlowNet2." }, { "code": null, "e": 5278, "s": 4981, "text": "The --resume argument indicates the location of the trained model weights. This has been downloaded into the checkpoints folder using the download scripts. Note the trained model weights have certain license restrictions which you should go through in case you need to use them outside this blog." }, { "code": null, "e": 5529, "s": 5278, "text": "The --inference argument simply means, based on the learned capability as defined by the model weights from the training data, what can you tell me about the new dataset. This is different from training the models where the model weights will change." }, { "code": null, "e": 5952, "s": 5529, "text": "The --inference_dataset indicates what type of data will be fed. In the current case it is sintel as specified by MpiSintelClean. More options for this can be found in https://github.com/dancelogue/flownet2-pytorch/blob/master/datasets.py and are defined as classes e.g. FlyingChairs. There is also the ImagesFromFolder class which means we can feed custom data e.g. frames from a video and we can get inference from that." }, { "code": null, "e": 6133, "s": 5952, "text": "The --inference_dataset_root indicates the location of the data that will be used for the inference process, which has been downloaded and unzipped into the datasets/sintel folder." }, { "code": null, "e": 6230, "s": 6133, "text": "The --save_flow argument indicates that the inferred optical flow should be saved as .flo files." }, { "code": null, "e": 6414, "s": 6230, "text": "The --save argument indicates the location to which the inferred optical flow files as well as the logs should be saved to. It is an optional field and defaults to the work/ location." }, { "code": null, "e": 6652, "s": 6414, "text": "Running the above command saves the generated optical flow files into the datasets/sintel/output/inference/run.epoch-0-flow-field folder. The generated optical flow files have the extension .flo which are the flow fields representations." }, { "code": null, "e": 6939, "s": 6652, "text": "Now that the optical flow files have been generated, it’s time to analyze the structure in order get a better understanding of the result, as well as convert them to the flow field color coding scheme. The sample flow file used in this section can be downloaded from the following link." }, { "code": null, "e": 7043, "s": 6939, "text": "Loading an optical flow file into numpy is a fairly trivial process, which can be conducted as follows:" }, { "code": null, "e": 7189, "s": 7043, "text": "path = Path('path/to/flow/file/<filename>.flo')with path.open(mode='r') as flo: np_flow = np.fromfile(flo, np.float32) print(np_flow.shape)" }, { "code": null, "e": 7815, "s": 7189, "text": "The above syntax is based on python3, where the file is loaded into a buffer and then fed into numpy. The next thing is trying to understand the basic features of the flow file which is achieved by the print statement. Assuming you are following with the sample flow file that was provided, the print statement should output(786435,). The implication is that for each flow file, it contains a single array with 786453 elements in the array. The memory footprint of a single flow file is approximately 15.7 MB, which even though looks trivial, increases quite quickly especially when looking at video with thousands of frames." }, { "code": null, "e": 8003, "s": 7815, "text": "Before proceeding further we need to look at the optical flow specification as defined in http://vision.middlebury.edu/flow/code/flow-code/README.txt. What we care about is the following:" }, { "code": null, "e": 8671, "s": 8003, "text": "\".flo\" file format used for optical flow evaluationStores 2-band float image for horizontal (u) and vertical (v) flow components.Floats are stored in little-endian order.A flow value is considered \"unknown\" if either |u| or |v| is greater than 1e9. bytes contents 0-3 tag: \"PIEH\" in ASCII, which in little endian happens to be the float 202021.25 (just a sanity check that floats are represented correctly) 4-7 width as an integer 8-11 height as an integer 12-end data (width*height*2*4 bytes total) the float values for u and v, interleaved, in row order, i.e., u[row0,col0], v[row0,col0], u[row0,col1], v[row0,col1], ..." }, { "code": null, "e": 8853, "s": 8671, "text": "Based on the above specification, the following code will allow us to read the flow file correctly (borrowed from https://github.com/georgegach/flowiz/blob/master/flowiz/flowiz.py)." }, { "code": null, "e": 9227, "s": 8853, "text": "with path.open(mode='r') as flo: tag = np.fromfile(flo, np.float32, count=1)[0] width = np.fromfile(flo, np.int32, count=1)[0] height = np.fromfile(flo, np.int32, count=1)[0] print('tag', tag, 'width', width, 'height', height) nbands = 2 tmp = np.fromfile(flo, np.float32, count= nbands * width * height) flow = np.resize(tmp, (int(height), int(width), int(nbands)))" }, { "code": null, "e": 10037, "s": 9227, "text": "Based on the optical flow format specification, hopefully the above code should make more sense about what’s happening i.e. we get the tag, then the width, followed by height. The output of the print statement is tag 202021.25 width 1024 height 384. From the given specification we can see that the tag matches the sanity check value, the width of the flow file is 1024 and the height is 384. Note, it is important to have the correct order when reading the file buffer and loading it into numpy, this is due to the way the files are read in python (bytes are read sequentially) otherwise the tag, height and width can get mixed up. Now that we have the width and the height, we can read the rest of the optical flow data and resize into a shape that's more familiar, which is done using the np.resize method." }, { "code": null, "e": 10180, "s": 10037, "text": "A quick way to understand how the flow vectors have been resized is to print them to the terminal, this is done by running the following code:" }, { "code": null, "e": 10257, "s": 10180, "text": ">> print(flow.shape)(384, 1024, 2)>> print(flow[0][0])[-1.2117167 -1.557275]" }, { "code": null, "e": 10729, "s": 10257, "text": "As we expect the shape of the new representation implies a height of 384, a width of 1024 and has a displacement vector consisting of 2 values. Focusing on the pixel at location 0, 0 we can see the displacement vector at that point seems to be pointing to the left and to the bottom i.e. the bottom left quadrant of an x, y plot, which means we expect the color code for this location to be a light blue or even a green color based on the color coding scheme given below." }, { "code": null, "e": 11230, "s": 10729, "text": "There are quite a few open source code bases written to visualize optical flow files. The one chosen for this purpose can be found in the github repository https://github.com/georgegach/flowiz. The reason for this is that it allows the generation of video clips from the color coding scheme which will be useful at a later stage. Assuming the docker context provided at the beginning of this tutorial is used, the following command can be used to generate color coded image files of the optical flow." }, { "code": null, "e": 11403, "s": 11230, "text": "python -m flowiz \\datasets/sintel/output/inference/run.epoch-0-flow-field/*.flo \\-o datasets/sintel/output/color_coding \\-v datasets/sintel/output/color_coding/video \\-r 30" }, { "code": null, "e": 11524, "s": 11403, "text": "This takes the optical flow files and generates image files where the displacement vector is color coded as shown below." }, { "code": null, "e": 11838, "s": 11524, "text": "In order to understand the color coding scheme, please view the previous blog on optical flow. At position 0, 0 i.e. the bottom right portion of the image, we can indeed see a light blue color and is what we expected from the displacement vector, i.e. it is the color for a vector pointing to the left and bottom." }, { "code": null, "e": 11943, "s": 11838, "text": "In this section, we will use a dance video, and generate optical flow files from it. The dance video is:" }, { "code": null, "e": 12010, "s": 11943, "text": "It consists of a dance choreography class in a real world setting." }, { "code": null, "e": 12177, "s": 12010, "text": "As the flownet code base takes in images, the first thing we need to do is to convert the videos into frames, which can be done by the following command using ffmpeg." }, { "code": null, "e": 12268, "s": 12177, "text": "ffmpeg -i datasets/dancelogue/sample-video.mp4 \\datasets/dancelogue/frames/output_%02d.png" }, { "code": null, "e": 12568, "s": 12268, "text": "It will output the frames in an ordered sequence within the frames folder, the order is important as the flownet algorithm uses adjacent images to calculate the optical flow between the images. The generated frames occupy 1.7 GB of memory whereas the video is only 11.7 MB, each frame is about 2 MB." }, { "code": null, "e": 12652, "s": 12568, "text": "The optical flow representations can be generated by running the following command." }, { "code": null, "e": 12885, "s": 12652, "text": "python main.py --inference --model FlowNet2 --save_flow \\--inference_dataset ImagesFromFolder \\--inference_dataset_root datasets/dancelogue/frames/ \\--resume checkpoints/FlowNet2_checkpoint.pth.tar \\--save datasets/dancelogue/output" }, { "code": null, "e": 13296, "s": 12885, "text": "This is similar to the inference model we ran with the sintel dataset where the differences are in the --inference_dataset argument which changes to ImagesFromFolder and as defined in the codebase. The --inference_dataset_root is the path to the generated video frames. The generated optical flow files occupy 14.6 GB of memory, this is because each optical flow file is approximately 15.7 MB for this example." }, { "code": null, "e": 13348, "s": 13296, "text": "The command to generate the color coding scheme is:" }, { "code": null, "e": 13533, "s": 13348, "text": "python -m flowiz \\datasets/dancelogue/output/inference/run.epoch-0-flow-field/*.flo \\-o datasets/dancelogue/output/color_coding \\-v datasets/dancelogue/output/color_coding/video \\-r 30" }, { "code": null, "e": 13910, "s": 13533, "text": "This makes use of the flowviz repository as well as ffmpeg. Not only does it generate the optical flow color encodings as .png files, but the -v -r 30 parameter generates videos from the image files at 30 fps. The generated color coding frames occupy 422 MB of memory which includes a 8.7 MB video file which has the name 000000.flo.mp4 if you are following through this blog." }, { "code": null, "e": 13980, "s": 13910, "text": "The generated video representation of the optical flow is as follows:" }, { "code": null, "e": 14293, "s": 13980, "text": "The gist of the choreography can be seen from the generated video, the different colors indicate the direction of motion. However, it can be seen there is a lot of background noise especially around the central dancers despite no apparent motion in the video. Unfortunately, it is not clear why this is the case." }, { "code": null, "e": 15181, "s": 14293, "text": "When running the flownet algorithm, one needs to be aware of the size implications, a 11.7 MB video for example, generates a 1.7 GB file of individual frames when extracted. However when generating optical flow this becomes a 14.6 GB file containing all the optical flow representations. This is because each optical flow file occupies about 15.7 MB in memory, however each image frame occupies 2 MB of memory (for the case of the examples provided). Thus when running optical flow algorithms one needs to be aware of the computation requirements vs space tradeoff. This trade off will impact the architecture when building deep learning systems for video, meaning either generate optical flow files as needed (i.e. lazily) at the cost of computation time or generate all the required formats and representations before hand and save them to the file system at the cost of storage space." }, { "code": null, "e": 15496, "s": 15181, "text": "We have seen how to generate optical flow files using a fork of NVIDIA’s flownet2-pytorch implementation, as well as have had an overview understanding of optical flow files. The next blog will cover how to use the optical flow representations to understand video content and will be focusing on 2 stream networks." } ]
Guava - CaseFormat Class
CaseFormat is a utility class to provide conversion between various ASCII char formats. Following is the declaration for com.google.common.base.CaseFormat class − @GwtCompatible public enum CaseFormat extends Enum<CaseFormat> LOWER_CAMEL Java variable naming convention, e.g., "lowerCamel". LOWER_HYPHEN Hyphenated variable naming convention, e.g., "lower-hyphen". LOWER_UNDERSCORE C++ variable naming convention, e.g., "lower_underscore". UPPER_CAMEL Java and C++ class naming convention, e.g., "UpperCamel". UPPER_UNDERSCORE Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE". Converter<String,String> converterTo(CaseFormat targetFormat) Returns a Converter that converts strings from this format to targetFormat. String to(CaseFormat format, String str) Converts the specified String str from this format to the specified format. static CaseFormat valueOf(String name) Returns the enum constant of this type with the specified name. static CaseFormat[] values() Returns an array containing the constants of this enum type, in the order they are declared. This class inherits methods from the following classes − java.lang.Enum java.lang.Object Create the following java program using any editor of your choice in say C:/> Guava. import com.google.common.base.CaseFormat; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); tester.testCaseFormat(); } private void testCaseFormat() { String data = "test_data"; System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, "test-data")); System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "test_data")); System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "test_data")); } } Compile the class using javac compiler as follows − C:\Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:\Guava>java GuavaTester See the result. testData testData TestData Print Add Notes Bookmark this page
[ { "code": null, "e": 1973, "s": 1885, "text": "CaseFormat is a utility class to provide conversion between various ASCII char formats." }, { "code": null, "e": 2048, "s": 1973, "text": "Following is the declaration for com.google.common.base.CaseFormat class −" }, { "code": null, "e": 2114, "s": 2048, "text": "@GwtCompatible\npublic enum CaseFormat\n extends Enum<CaseFormat>" }, { "code": null, "e": 2126, "s": 2114, "text": "LOWER_CAMEL" }, { "code": null, "e": 2179, "s": 2126, "text": "Java variable naming convention, e.g., \"lowerCamel\"." }, { "code": null, "e": 2192, "s": 2179, "text": "LOWER_HYPHEN" }, { "code": null, "e": 2253, "s": 2192, "text": "Hyphenated variable naming convention, e.g., \"lower-hyphen\"." }, { "code": null, "e": 2270, "s": 2253, "text": "LOWER_UNDERSCORE" }, { "code": null, "e": 2328, "s": 2270, "text": "C++ variable naming convention, e.g., \"lower_underscore\"." }, { "code": null, "e": 2340, "s": 2328, "text": "UPPER_CAMEL" }, { "code": null, "e": 2398, "s": 2340, "text": "Java and C++ class naming convention, e.g., \"UpperCamel\"." }, { "code": null, "e": 2415, "s": 2398, "text": "UPPER_UNDERSCORE" }, { "code": null, "e": 2482, "s": 2415, "text": "Java and C++ constant naming convention, e.g., \"UPPER_UNDERSCORE\"." }, { "code": null, "e": 2544, "s": 2482, "text": "Converter<String,String> converterTo(CaseFormat targetFormat)" }, { "code": null, "e": 2620, "s": 2544, "text": "Returns a Converter that converts strings from this format to targetFormat." }, { "code": null, "e": 2661, "s": 2620, "text": "String to(CaseFormat format, String str)" }, { "code": null, "e": 2737, "s": 2661, "text": "Converts the specified String str from this format to the specified format." }, { "code": null, "e": 2776, "s": 2737, "text": "static CaseFormat\tvalueOf(String name)" }, { "code": null, "e": 2840, "s": 2776, "text": "Returns the enum constant of this type with the specified name." }, { "code": null, "e": 2869, "s": 2840, "text": "static CaseFormat[] values()" }, { "code": null, "e": 2962, "s": 2869, "text": "Returns an array containing the constants of this enum type, in the order they are declared." }, { "code": null, "e": 3019, "s": 2962, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 3034, "s": 3019, "text": "java.lang.Enum" }, { "code": null, "e": 3051, "s": 3034, "text": "java.lang.Object" }, { "code": null, "e": 3136, "s": 3051, "text": "Create the following java program using any editor of your choice in say C:/> Guava." }, { "code": null, "e": 3689, "s": 3136, "text": "import com.google.common.base.CaseFormat;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n GuavaTester tester = new GuavaTester();\n tester.testCaseFormat();\n }\n\n private void testCaseFormat() {\n String data = \"test_data\";\n System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, \"test-data\"));\n System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, \"test_data\"));\n System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, \"test_data\"));\n }\n}" }, { "code": null, "e": 3741, "s": 3689, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 3774, "s": 3741, "text": "C:\\Guava>javac GuavaTester.java\n" }, { "code": null, "e": 3817, "s": 3774, "text": "Now run the GuavaTester to see the result." }, { "code": null, "e": 3844, "s": 3817, "text": "C:\\Guava>java GuavaTester\n" }, { "code": null, "e": 3860, "s": 3844, "text": "See the result." }, { "code": null, "e": 3888, "s": 3860, "text": "testData\ntestData\nTestData\n" }, { "code": null, "e": 3895, "s": 3888, "text": " Print" }, { "code": null, "e": 3906, "s": 3895, "text": " Add Notes" } ]
Matcher find() method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The find() method of Matcher Class attempts to find the next subsequence of the input sequence that find the pattern. It returns a boolean value showing the same. Syntax: public boolean find() Parameters: This method do not takes any parameter. Return Value: This method returns a boolean value showing whether a subsequence of the input sequence find this matcher’s pattern Below examples illustrate the Matcher.find() method: Example 1: // Java code to illustrate find() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "Geeks"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the subsequence // using find() method System.out.println(matcher.find()); }} true Example 2: // Java code to illustrate find() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "GFG"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the subsequence // using find() method System.out.println(matcher.find()); }} true Reference: Oracle Doc Java - util package Java-Functions Java-Matcher Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java
[ { "code": null, "e": 25064, "s": 25036, "text": "\n26 Nov, 2018" }, { "code": null, "e": 25227, "s": 25064, "text": "The find() method of Matcher Class attempts to find the next subsequence of the input sequence that find the pattern. It returns a boolean value showing the same." }, { "code": null, "e": 25235, "s": 25227, "text": "Syntax:" }, { "code": null, "e": 25258, "s": 25235, "text": "public boolean find()\n" }, { "code": null, "e": 25310, "s": 25258, "text": "Parameters: This method do not takes any parameter." }, { "code": null, "e": 25440, "s": 25310, "text": "Return Value: This method returns a boolean value showing whether a subsequence of the input sequence find this matcher’s pattern" }, { "code": null, "e": 25493, "s": 25440, "text": "Below examples illustrate the Matcher.find() method:" }, { "code": null, "e": 25504, "s": 25493, "text": "Example 1:" }, { "code": "// Java code to illustrate find() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"Geeks\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the subsequence // using find() method System.out.println(matcher.find()); }}", "e": 26164, "s": 25504, "text": null }, { "code": null, "e": 26170, "s": 26164, "text": "true\n" }, { "code": null, "e": 26181, "s": 26170, "text": "Example 2:" }, { "code": "// Java code to illustrate find() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"GFG\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the subsequence // using find() method System.out.println(matcher.find()); }}", "e": 26845, "s": 26181, "text": null }, { "code": null, "e": 26851, "s": 26845, "text": "true\n" }, { "code": null, "e": 26873, "s": 26851, "text": "Reference: Oracle Doc" }, { "code": null, "e": 26893, "s": 26873, "text": "Java - util package" }, { "code": null, "e": 26908, "s": 26893, "text": "Java-Functions" }, { "code": null, "e": 26921, "s": 26908, "text": "Java-Matcher" }, { "code": null, "e": 26926, "s": 26921, "text": "Java" }, { "code": null, "e": 26931, "s": 26926, "text": "Java" }, { "code": null, "e": 27029, "s": 26931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27038, "s": 27029, "text": "Comments" }, { "code": null, "e": 27051, "s": 27038, "text": "Old Comments" }, { "code": null, "e": 27081, "s": 27051, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27113, "s": 27081, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27164, "s": 27113, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27183, "s": 27164, "text": "Interfaces in Java" }, { "code": null, "e": 27201, "s": 27183, "text": "ArrayList in Java" }, { "code": null, "e": 27232, "s": 27201, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27264, "s": 27232, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27288, "s": 27264, "text": "Singleton Class in Java" }, { "code": null, "e": 27308, "s": 27288, "text": "Stack Class in Java" } ]
Check if a number exists with X divisors out of which Y are composite - GeeksforGeeks
23 Apr, 2021 Given two integers X and Y representing the total number of divisors and the number of composite divisors respectively, the task is to check if there exists an integer N which has exactly X divisors and Y are composite numbers. Examples: Input: X = 6, Y = 3 Output: YES Explanation: N = 18 is such a number.The divisors of 18 are 1, 2, 3, 6, 9 and 18. The composite divisors of 18 are 6, 9 and 18.Input: X = 7, Y = 3 Output: NO Explanation: We see that no such number exists that has 7 positive divisors out of which 3 are composite divisors. Approach: Firstly calculate the number of prime divisors of a number, which is equal to: Firstly calculate the number of prime divisors of a number, which is equal to: Number of prime divisors = Total number of divisors – Number of composite divisors – 1 So, the number of prime divisors, C = X – Y – 1 Since every number has 1 as a factor and 1 is neither a prime number nor a composite number, we have to exclude it from being counted in the number of prime divisors. If the number of composite divisors is less than the number of prime divisors, then it is not possible to find such a number at all. So if the prime factorization of X contains at least C distinct integers, then a solution is possible. Otherwise, we cannot find a number N that will satisfy the given conditions. Find the maximum number of values X can be decomposed into such that each value is greater than 1. In other words, we can find out the prime factorization of X.If that prime factorization has a number of terms greater than or equal to C, then such a number is possible. So, the number of prime divisors, C = X – Y – 1 Since every number has 1 as a factor and 1 is neither a prime number nor a composite number, we have to exclude it from being counted in the number of prime divisors. If the number of composite divisors is less than the number of prime divisors, then it is not possible to find such a number at all. So if the prime factorization of X contains at least C distinct integers, then a solution is possible. Otherwise, we cannot find a number N that will satisfy the given conditions. Find the maximum number of values X can be decomposed into such that each value is greater than 1. In other words, we can find out the prime factorization of X. If that prime factorization has a number of terms greater than or equal to C, then such a number is possible. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisors#include <bits/stdc++.h>using namespace std; int factorize(int N){ int count = 0; int cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // check for all possible // numbers that can divide it for (int i = 3; i <= sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // if N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt;} // Function to check if any// such number existsvoid ifNumberExists(int X, int Y){ int C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) cout << "YES \n"; else cout << "NO \n";} // Driver Codeint main(){ int X, Y; X = 6; Y = 4; ifNumberExists(X, Y); return 0;} // Java program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisorsimport java.lang.Math;class GFG{ public static int factorize(int N){ int count = 0; int cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // Check for all possible // numbers that can divide it for(int i = 3; i <= Math.sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // If N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt;} // Function to check if any// such number existspublic static void ifNumberExists(int X, int Y){ int C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) System.out.println("YES"); else System.out.println("NO");} // Driver code public static void main(String[] args){ int X, Y; X = 6; Y = 4; ifNumberExists(X, Y);}} // This code is contributed by divyeshrabadiya07 # Python3 program to check if a number exists# having exactly X positive divisors out of# which Y are composite divisorsimport math def factorize(N): count = 0 cnt = 0 # Count the number of # times 2 divides N while ((N % 2) == 0): N = N // 2 count+=1 cnt = cnt + count # Check for all possible # numbers that can divide it sq = int(math.sqrt(N)) for i in range(3, sq, 2): count = 0 while (N % i == 0): count += 1 N = N // i cnt = cnt + count # If N at the end # is a prime number. if (N > 2): cnt = cnt + 1 return cnt # Function to check if any# such number existsdef ifNumberExists(X, Y): C = X - Y - 1 dsum = factorize(X) if (dsum >= C): print ("YES") else: print("NO") # Driver Codeif __name__ == "__main__": X = 6 Y = 4 ifNumberExists(X, Y) # This code is contributed by chitranayal // C# program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisorsusing System;class GFG{ public static int factorize(int N){ int count = 0; int cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // Check for all possible // numbers that can divide it for(int i = 3; i <= Math.Sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // If N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt;} // Function to check if any// such number existspublic static void ifNumberExists(int X, int Y){ int C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) Console.WriteLine("YES"); else Console.WriteLine("NO");} // Driver codepublic static void Main(string[] args){ int X, Y; X = 6; Y = 4; ifNumberExists(X, Y);}} // This code is contributed by AnkitRai01 <script>// javascript program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisors function factorize(N) { var count = 0; var cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // Check for all possible // numbers that can divide it for (i = 3; i <= Math.sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // If N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt; } // Function to check if any // such number exists function ifNumberExists(X , Y) { var C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) document.write("YES"); else document.write("NO"); } // Driver code var X, Y; X = 6; Y = 4; ifNumberExists(X, Y); // This code is contributed by todaysgaurav</script> YES Time Complexity: O (N 1/2) Auxiliary Space: O (1) divyeshrabadiya07 ukasp ankthon todaysgaurav divisors number-theory Algorithms Combinatorial Competitive Programming Mathematical number-theory Mathematical Combinatorial Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Quadratic Probing in Hashing SCAN (Elevator) Disk Scheduling Algorithms K means Clustering - Introduction Program for SSTF disk scheduling algorithm Write a program to print all permutations of a given string Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Factorial of a large number Count ways to reach the nth stair using step 1, 2 or 3
[ { "code": null, "e": 24666, "s": 24638, "text": "\n23 Apr, 2021" }, { "code": null, "e": 24895, "s": 24666, "text": "Given two integers X and Y representing the total number of divisors and the number of composite divisors respectively, the task is to check if there exists an integer N which has exactly X divisors and Y are composite numbers. " }, { "code": null, "e": 24905, "s": 24895, "text": "Examples:" }, { "code": null, "e": 25213, "s": 24905, "text": " Input: X = 6, Y = 3 Output: YES Explanation: N = 18 is such a number.The divisors of 18 are 1, 2, 3, 6, 9 and 18. The composite divisors of 18 are 6, 9 and 18.Input: X = 7, Y = 3 Output: NO Explanation: We see that no such number exists that has 7 positive divisors out of which 3 are composite divisors. " }, { "code": null, "e": 25225, "s": 25213, "text": "Approach: " }, { "code": null, "e": 25305, "s": 25225, "text": "Firstly calculate the number of prime divisors of a number, which is equal to: " }, { "code": null, "e": 25385, "s": 25305, "text": "Firstly calculate the number of prime divisors of a number, which is equal to: " }, { "code": null, "e": 25491, "s": 25385, "text": " Number of prime divisors = Total number of divisors – Number of composite divisors – 1 " }, { "code": null, "e": 26293, "s": 25491, "text": "So, the number of prime divisors, C = X – Y – 1 Since every number has 1 as a factor and 1 is neither a prime number nor a composite number, we have to exclude it from being counted in the number of prime divisors. If the number of composite divisors is less than the number of prime divisors, then it is not possible to find such a number at all. So if the prime factorization of X contains at least C distinct integers, then a solution is possible. Otherwise, we cannot find a number N that will satisfy the given conditions. Find the maximum number of values X can be decomposed into such that each value is greater than 1. In other words, we can find out the prime factorization of X.If that prime factorization has a number of terms greater than or equal to C, then such a number is possible." }, { "code": null, "e": 26343, "s": 26293, "text": "So, the number of prime divisors, C = X – Y – 1 " }, { "code": null, "e": 26512, "s": 26343, "text": "Since every number has 1 as a factor and 1 is neither a prime number nor a composite number, we have to exclude it from being counted in the number of prime divisors. " }, { "code": null, "e": 26647, "s": 26512, "text": "If the number of composite divisors is less than the number of prime divisors, then it is not possible to find such a number at all. " }, { "code": null, "e": 26829, "s": 26647, "text": "So if the prime factorization of X contains at least C distinct integers, then a solution is possible. Otherwise, we cannot find a number N that will satisfy the given conditions. " }, { "code": null, "e": 26990, "s": 26829, "text": "Find the maximum number of values X can be decomposed into such that each value is greater than 1. In other words, we can find out the prime factorization of X." }, { "code": null, "e": 27100, "s": 26990, "text": "If that prime factorization has a number of terms greater than or equal to C, then such a number is possible." }, { "code": null, "e": 27152, "s": 27100, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27156, "s": 27152, "text": "C++" }, { "code": null, "e": 27161, "s": 27156, "text": "Java" }, { "code": null, "e": 27169, "s": 27161, "text": "Python3" }, { "code": null, "e": 27172, "s": 27169, "text": "C#" }, { "code": null, "e": 27183, "s": 27172, "text": "Javascript" }, { "code": "// C++ program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisors#include <bits/stdc++.h>using namespace std; int factorize(int N){ int count = 0; int cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // check for all possible // numbers that can divide it for (int i = 3; i <= sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // if N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt;} // Function to check if any// such number existsvoid ifNumberExists(int X, int Y){ int C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) cout << \"YES \\n\"; else cout << \"NO \\n\";} // Driver Codeint main(){ int X, Y; X = 6; Y = 4; ifNumberExists(X, Y); return 0;}", "e": 28196, "s": 27183, "text": null }, { "code": "// Java program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisorsimport java.lang.Math;class GFG{ public static int factorize(int N){ int count = 0; int cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // Check for all possible // numbers that can divide it for(int i = 3; i <= Math.sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // If N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt;} // Function to check if any// such number existspublic static void ifNumberExists(int X, int Y){ int C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) System.out.println(\"YES\"); else System.out.println(\"NO\");} // Driver code public static void main(String[] args){ int X, Y; X = 6; Y = 4; ifNumberExists(X, Y);}} // This code is contributed by divyeshrabadiya07", "e": 29357, "s": 28196, "text": null }, { "code": "# Python3 program to check if a number exists# having exactly X positive divisors out of# which Y are composite divisorsimport math def factorize(N): count = 0 cnt = 0 # Count the number of # times 2 divides N while ((N % 2) == 0): N = N // 2 count+=1 cnt = cnt + count # Check for all possible # numbers that can divide it sq = int(math.sqrt(N)) for i in range(3, sq, 2): count = 0 while (N % i == 0): count += 1 N = N // i cnt = cnt + count # If N at the end # is a prime number. if (N > 2): cnt = cnt + 1 return cnt # Function to check if any# such number existsdef ifNumberExists(X, Y): C = X - Y - 1 dsum = factorize(X) if (dsum >= C): print (\"YES\") else: print(\"NO\") # Driver Codeif __name__ == \"__main__\": X = 6 Y = 4 ifNumberExists(X, Y) # This code is contributed by chitranayal", "e": 30322, "s": 29357, "text": null }, { "code": "// C# program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisorsusing System;class GFG{ public static int factorize(int N){ int count = 0; int cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // Check for all possible // numbers that can divide it for(int i = 3; i <= Math.Sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // If N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt;} // Function to check if any// such number existspublic static void ifNumberExists(int X, int Y){ int C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");} // Driver codepublic static void Main(string[] args){ int X, Y; X = 6; Y = 4; ifNumberExists(X, Y);}} // This code is contributed by AnkitRai01", "e": 31463, "s": 30322, "text": null }, { "code": "<script>// javascript program to check if a number// exists having exactly X positive// divisors out of which Y are// composite divisors function factorize(N) { var count = 0; var cnt = 0; // Count the number of // times 2 divides N while ((N % 2) == 0) { N = N / 2; count++; } cnt = cnt + count; // Check for all possible // numbers that can divide it for (i = 3; i <= Math.sqrt(N); i += 2) { count = 0; while (N % i == 0) { count++; N = N / i; } cnt = cnt + count; } // If N at the end // is a prime number. if (N > 2) cnt = cnt + 1; return cnt; } // Function to check if any // such number exists function ifNumberExists(X , Y) { var C, dsum; C = X - Y - 1; dsum = factorize(X); if (dsum >= C) document.write(\"YES\"); else document.write(\"NO\"); } // Driver code var X, Y; X = 6; Y = 4; ifNumberExists(X, Y); // This code is contributed by todaysgaurav</script>", "e": 32658, "s": 31463, "text": null }, { "code": null, "e": 32662, "s": 32658, "text": "YES" }, { "code": null, "e": 32715, "s": 32664, "text": "Time Complexity: O (N 1/2) Auxiliary Space: O (1) " }, { "code": null, "e": 32733, "s": 32715, "text": "divyeshrabadiya07" }, { "code": null, "e": 32739, "s": 32733, "text": "ukasp" }, { "code": null, "e": 32747, "s": 32739, "text": "ankthon" }, { "code": null, "e": 32760, "s": 32747, "text": "todaysgaurav" }, { "code": null, "e": 32769, "s": 32760, "text": "divisors" }, { "code": null, "e": 32783, "s": 32769, "text": "number-theory" }, { "code": null, "e": 32794, "s": 32783, "text": "Algorithms" }, { "code": null, "e": 32808, "s": 32794, "text": "Combinatorial" }, { "code": null, "e": 32832, "s": 32808, "text": "Competitive Programming" }, { "code": null, "e": 32845, "s": 32832, "text": "Mathematical" }, { "code": null, "e": 32859, "s": 32845, "text": "number-theory" }, { "code": null, "e": 32872, "s": 32859, "text": "Mathematical" }, { "code": null, "e": 32886, "s": 32872, "text": "Combinatorial" }, { "code": null, "e": 32897, "s": 32886, "text": "Algorithms" }, { "code": null, "e": 32995, "s": 32897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33004, "s": 32995, "text": "Comments" }, { "code": null, "e": 33017, "s": 33004, "text": "Old Comments" }, { "code": null, "e": 33042, "s": 33017, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33071, "s": 33042, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 33114, "s": 33071, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 33148, "s": 33114, "text": "K means Clustering - Introduction" }, { "code": null, "e": 33191, "s": 33148, "text": "Program for SSTF disk scheduling algorithm" }, { "code": null, "e": 33251, "s": 33191, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33289, "s": 33251, "text": "Permutation and Combination in Python" }, { "code": null, "e": 33366, "s": 33289, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 33394, "s": 33366, "text": "Factorial of a large number" } ]
Python | Combine the values of two dictionaries having same key - GeeksforGeeks
26 Feb, 2019 Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations of dictionary. Let’s see how to combine the values of two dictionaries having same key.Method #1: Using CounterCounter is a special subclass of dictionary which performs acts same as dictionary in most cases. # Python code to demonstrate combining # two dictionaries having same key from collections import Counter # initialising dictionariesini_dictionary1 = Counter({'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15})ini_dictionary2 = Counter({'akash' : 7, 'akshat' : 5, 'm' : 15}) # printing initial dictionariesprint ("initial 1st dictionary", str(ini_dictionary1))print ("initial 2nd dictionary", str(ini_dictionary2)) # combining dictionaries# using Counterfinal_dictionary = ini_dictionary1 + ini_dictionary2 # printing final resultprint ("final dictionary", str(final_dictionary)) initial 1st dictionary Counter({‘akshat’: 15, ‘manjeet’: 10, ‘akash’: 5, ‘nikhil’: 1})initial 2nd dictionary Counter({‘m’: 15, ‘akash’: 7, ‘akshat’: 5})final dictionary Counter({‘akshat’: 20, ‘m’: 15, ‘akash’: 12, ‘manjeet’: 10, ‘nikhil’: 1}) Method #2: Using dict() and itemsThis method is for Python version 2. # Python code to demonstrate combining # two dictionaries having same key # initialising dictionariesini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15} # printing initial dictionariesprint ("initial 1st dictionary", str(ini_dictionary1))print ("initial 2nd dictionary", str(ini_dictionary2)) # combining dictionaries# using dict() and items()final_dictionary = dict(ini_dictionary1.items() + ini_dictionary2.items() + [(k, ini_dictionary1[k] + ini_dictionary2[k]) for k in set(ini_dictionary2) & set(ini_dictionary1)]) # printing final resultprint ("final dictionary", str(final_dictionary)) (‘initial 1st dictionary’, “{‘manjeet’: 10, ‘nikhil’: 1, ‘akshat’: 15, ‘akash’: 5}”)(‘initial 2nd dictionary’, “{‘m’: 15, ‘akshat’: 5, ‘akash’: 7}”)(‘final dictionary’, “{‘nikhil’: 1, ‘m’: 15, ‘manjeet’: 10, ‘akshat’: 20, ‘akash’: 12}”) Method #3: Using dict comprehension and set # Python code to demonstrate combining # two dictionaries having same key # initialising dictionariesini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15} # printing initial dictionariesprint ("initial 1st dictionary", str(ini_dictionary1))print ("initial 2nd dictionary", str(ini_dictionary2)) # combining dictionaries# using dict comprehension and setfinal_dictionary = {x: ini_dictionary1.get(x, 0) + ini_dictionary2.get(x, 0) for x in set(ini_dictionary1).union(ini_dictionary2)} # printing final resultprint ("final dictionary", str(final_dictionary)) initial 1st dictionary {‘nikhil’: 1, ‘akshat’: 15, ‘akash’: 5, ‘manjeet’: 10}initial 2nd dictionary {‘akshat’: 5, ‘akash’: 7, ‘m’: 15}final dictionary {‘nikhil’: 1, ‘akshat’: 20, ‘akash’: 12, ‘m’: 15, ‘manjeet’: 10} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24954, "s": 24926, "text": "\n26 Feb, 2019" }, { "code": null, "e": 25269, "s": 24954, "text": "Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations of dictionary." }, { "code": null, "e": 25463, "s": 25269, "text": "Let’s see how to combine the values of two dictionaries having same key.Method #1: Using CounterCounter is a special subclass of dictionary which performs acts same as dictionary in most cases." }, { "code": "# Python code to demonstrate combining # two dictionaries having same key from collections import Counter # initialising dictionariesini_dictionary1 = Counter({'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15})ini_dictionary2 = Counter({'akash' : 7, 'akshat' : 5, 'm' : 15}) # printing initial dictionariesprint (\"initial 1st dictionary\", str(ini_dictionary1))print (\"initial 2nd dictionary\", str(ini_dictionary2)) # combining dictionaries# using Counterfinal_dictionary = ini_dictionary1 + ini_dictionary2 # printing final resultprint (\"final dictionary\", str(final_dictionary))", "e": 26116, "s": 25463, "text": null }, { "code": null, "e": 26359, "s": 26116, "text": "initial 1st dictionary Counter({‘akshat’: 15, ‘manjeet’: 10, ‘akash’: 5, ‘nikhil’: 1})initial 2nd dictionary Counter({‘m’: 15, ‘akash’: 7, ‘akshat’: 5})final dictionary Counter({‘akshat’: 20, ‘m’: 15, ‘akash’: 12, ‘manjeet’: 10, ‘nikhil’: 1})" }, { "code": null, "e": 26430, "s": 26359, "text": " Method #2: Using dict() and itemsThis method is for Python version 2." }, { "code": "# Python code to demonstrate combining # two dictionaries having same key # initialising dictionariesini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15} # printing initial dictionariesprint (\"initial 1st dictionary\", str(ini_dictionary1))print (\"initial 2nd dictionary\", str(ini_dictionary2)) # combining dictionaries# using dict() and items()final_dictionary = dict(ini_dictionary1.items() + ini_dictionary2.items() + [(k, ini_dictionary1[k] + ini_dictionary2[k]) for k in set(ini_dictionary2) & set(ini_dictionary1)]) # printing final resultprint (\"final dictionary\", str(final_dictionary))", "e": 27213, "s": 26430, "text": null }, { "code": null, "e": 27450, "s": 27213, "text": "(‘initial 1st dictionary’, “{‘manjeet’: 10, ‘nikhil’: 1, ‘akshat’: 15, ‘akash’: 5}”)(‘initial 2nd dictionary’, “{‘m’: 15, ‘akshat’: 5, ‘akash’: 7}”)(‘final dictionary’, “{‘nikhil’: 1, ‘m’: 15, ‘manjeet’: 10, ‘akshat’: 20, ‘akash’: 12}”)" }, { "code": null, "e": 27495, "s": 27450, "text": " Method #3: Using dict comprehension and set" }, { "code": "# Python code to demonstrate combining # two dictionaries having same key # initialising dictionariesini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15} # printing initial dictionariesprint (\"initial 1st dictionary\", str(ini_dictionary1))print (\"initial 2nd dictionary\", str(ini_dictionary2)) # combining dictionaries# using dict comprehension and setfinal_dictionary = {x: ini_dictionary1.get(x, 0) + ini_dictionary2.get(x, 0) for x in set(ini_dictionary1).union(ini_dictionary2)} # printing final resultprint (\"final dictionary\", str(final_dictionary))", "e": 28203, "s": 27495, "text": null }, { "code": null, "e": 28419, "s": 28203, "text": "initial 1st dictionary {‘nikhil’: 1, ‘akshat’: 15, ‘akash’: 5, ‘manjeet’: 10}initial 2nd dictionary {‘akshat’: 5, ‘akash’: 7, ‘m’: 15}final dictionary {‘nikhil’: 1, ‘akshat’: 20, ‘akash’: 12, ‘m’: 15, ‘manjeet’: 10}" }, { "code": null, "e": 28446, "s": 28419, "text": "Python dictionary-programs" }, { "code": null, "e": 28453, "s": 28446, "text": "Python" }, { "code": null, "e": 28469, "s": 28453, "text": "Python Programs" }, { "code": null, "e": 28567, "s": 28469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28585, "s": 28567, "text": "Python Dictionary" }, { "code": null, "e": 28620, "s": 28585, "text": "Read a file line by line in Python" }, { "code": null, "e": 28642, "s": 28620, "text": "Enumerate() in Python" }, { "code": null, "e": 28674, "s": 28642, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28704, "s": 28674, "text": "Iterate over a list in Python" }, { "code": null, "e": 28747, "s": 28704, "text": "Python program to convert a list to string" }, { "code": null, "e": 28769, "s": 28747, "text": "Defaultdict in Python" }, { "code": null, "e": 28815, "s": 28769, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28854, "s": 28815, "text": "Python | Get dictionary keys as a list" } ]
Can a Java array be declared as a static field, local variable or a method parameter?
We can declare an array as a local variable or method parameter but, an array cannot be static. public class Test{ public void sample(){ static int[] myArray = {20, 30}; System.out.println(); } public static void main(String args[]){ Test t = new Test(); t.sample(); } } C:\Sample>javac Test.java Test.java:3: error: illegal start of expression static int[] myArray = {20, 30}; ^ 1 error
[ { "code": null, "e": 1158, "s": 1062, "text": "We can declare an array as a local variable or method parameter but, an array cannot be static." }, { "code": null, "e": 1369, "s": 1158, "text": "public class Test{\n public void sample(){\n static int[] myArray = {20, 30};\n System.out.println();\n }\n public static void main(String args[]){\n Test t = new Test();\n t.sample();\n }\n}" }, { "code": null, "e": 1493, "s": 1369, "text": "C:\\Sample>javac Test.java\nTest.java:3: error: illegal start of expression\n static int[] myArray = {20, 30};\n ^\n1 error\n" } ]
Iterators & Iterables in Python. Introduction to Iterators and Iterables | by Sadrach Pierre, Ph.D. | Towards Data Science
In this post, we will discuss python iterators and iterables. We will go over the definitions of each of these objects as well as work towards developing an understanding of the underlying concepts behind each object. Let’s get started! Iterables are objects in python that are capable of returning their elements one at a time. Additionally, these objects have a double underscore (also called dunder) method called ‘__iter__()’, where the ‘__iter__()’ method returns an iterator (more on that later). An example of an iterable is a list. To help us understand what it means for lists to be iterable objects, let’s define a list. Let’s define a list that contains the top five best albums of all time according to Rolling Stones: best_albums = ["Sgt. Pepper’s Lonely Hearts Club Band", "Pet Sounds", "Revolver", "Highway 61 Revisited", "Rubber Soul"] The first part of our definition for iterables stated that they allow us to return their elements one by one. Let’s demonstrate this by looping over our list: for album in best_albums: print(album) This feature of iterables is pretty clear. We also specified the ‘__iter__()’ method, which also qualifies a python object as an iterable. We can check the methods and attributes available to our object using the built-in ‘dir()’ method: print(dir(best_albums)) We can see that the ‘__iter__()’ method is present in the list of methods and attributes for our object . In general, any object with the ‘__iter__()’ method can be looped over. Further, when we use for-loops on iterables, we call the ‘__iter__()’ method. When the ‘__iter__()’ method is called it returns an iterator. Now, let’s define iterators. Iterators are objects with states, where the state specifies the current value during iteration. Iterators also have a dunder method called ‘__next__()’, which allows us to access subsequent values. If we look at the attributes and methods for our list, we can see that there is no ‘__next__()’, which means that lists are not iterators. We can demonstrate this by trying to use the ‘next’ method on our list: print(next(best_albums)) We get an error telling us that our list object is not an iterator. Since we know list objects are iterables, meaning they have ‘__iter__()’ methods, we can call ‘__iter__()’ on our list to return an iterator: iter_best_albums = best_albums.__iter__() A cleaner and equivalent way to define our iterator is as follows: iter_best_albums = iter(best_albums) Let’s print our iterator: print(iter_best_albums) We see that our object is indeed an iterator. Now, let’s print the attributes and methods for our iterator object: print(dir(iter_best_albums)) We can see that our iterator object has the ‘__next__()’ method. Let’s call this method on our iterator: print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums)) We can see that each time we call ‘next’, our object remembered where it left off and the ‘next’ method pointed to the subsequent value. Let’s see what happens if we call ‘next’ until we run out of values. Let’s call next 6 times: print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums)) We can handle this error with a ‘StopIteration’ exception: while True: try: element = next(iter_best_albums) print(element) except(StopIteration): break We get the same result that we did from looping over our list from earlier. This is essentially what happens under the hood when we loop over lists with for-loops. I’ll stop here but feel free to play around with the code yourself. If you’re interested in learning more about iterators and iterables, Cory Schafer’s YouTube tutorial is a great resource. To summarize, in this post we discussed iterables and iterators in python. Iterables are objects that have the method ‘__iter__()’, which returns an iterator object. Iterators are objects that have the method ‘__next()__’ , which allows us to access subsequent values. Further, iterators have information about state during iteration. Put simply, iterators are what’s going on under the hood of every for-loop in python. I hope you found this useful/interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 390, "s": 172, "text": "In this post, we will discuss python iterators and iterables. We will go over the definitions of each of these objects as well as work towards developing an understanding of the underlying concepts behind each object." }, { "code": null, "e": 409, "s": 390, "text": "Let’s get started!" }, { "code": null, "e": 903, "s": 409, "text": "Iterables are objects in python that are capable of returning their elements one at a time. Additionally, these objects have a double underscore (also called dunder) method called ‘__iter__()’, where the ‘__iter__()’ method returns an iterator (more on that later). An example of an iterable is a list. To help us understand what it means for lists to be iterable objects, let’s define a list. Let’s define a list that contains the top five best albums of all time according to Rolling Stones:" }, { "code": null, "e": 1025, "s": 903, "text": "best_albums = [\"Sgt. Pepper’s Lonely Hearts Club Band\", \"Pet Sounds\", \"Revolver\", \"Highway 61 Revisited\", \"Rubber Soul\"]" }, { "code": null, "e": 1184, "s": 1025, "text": "The first part of our definition for iterables stated that they allow us to return their elements one by one. Let’s demonstrate this by looping over our list:" }, { "code": null, "e": 1226, "s": 1184, "text": "for album in best_albums: print(album)" }, { "code": null, "e": 1464, "s": 1226, "text": "This feature of iterables is pretty clear. We also specified the ‘__iter__()’ method, which also qualifies a python object as an iterable. We can check the methods and attributes available to our object using the built-in ‘dir()’ method:" }, { "code": null, "e": 1488, "s": 1464, "text": "print(dir(best_albums))" }, { "code": null, "e": 1666, "s": 1488, "text": "We can see that the ‘__iter__()’ method is present in the list of methods and attributes for our object . In general, any object with the ‘__iter__()’ method can be looped over." }, { "code": null, "e": 1807, "s": 1666, "text": "Further, when we use for-loops on iterables, we call the ‘__iter__()’ method. When the ‘__iter__()’ method is called it returns an iterator." }, { "code": null, "e": 1836, "s": 1807, "text": "Now, let’s define iterators." }, { "code": null, "e": 2174, "s": 1836, "text": "Iterators are objects with states, where the state specifies the current value during iteration. Iterators also have a dunder method called ‘__next__()’, which allows us to access subsequent values. If we look at the attributes and methods for our list, we can see that there is no ‘__next__()’, which means that lists are not iterators." }, { "code": null, "e": 2246, "s": 2174, "text": "We can demonstrate this by trying to use the ‘next’ method on our list:" }, { "code": null, "e": 2271, "s": 2246, "text": "print(next(best_albums))" }, { "code": null, "e": 2481, "s": 2271, "text": "We get an error telling us that our list object is not an iterator. Since we know list objects are iterables, meaning they have ‘__iter__()’ methods, we can call ‘__iter__()’ on our list to return an iterator:" }, { "code": null, "e": 2523, "s": 2481, "text": "iter_best_albums = best_albums.__iter__()" }, { "code": null, "e": 2590, "s": 2523, "text": "A cleaner and equivalent way to define our iterator is as follows:" }, { "code": null, "e": 2627, "s": 2590, "text": "iter_best_albums = iter(best_albums)" }, { "code": null, "e": 2653, "s": 2627, "text": "Let’s print our iterator:" }, { "code": null, "e": 2677, "s": 2653, "text": "print(iter_best_albums)" }, { "code": null, "e": 2792, "s": 2677, "text": "We see that our object is indeed an iterator. Now, let’s print the attributes and methods for our iterator object:" }, { "code": null, "e": 2821, "s": 2792, "text": "print(dir(iter_best_albums))" }, { "code": null, "e": 2926, "s": 2821, "text": "We can see that our iterator object has the ‘__next__()’ method. Let’s call this method on our iterator:" }, { "code": null, "e": 3014, "s": 2926, "text": "print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))" }, { "code": null, "e": 3245, "s": 3014, "text": "We can see that each time we call ‘next’, our object remembered where it left off and the ‘next’ method pointed to the subsequent value. Let’s see what happens if we call ‘next’ until we run out of values. Let’s call next 6 times:" }, { "code": null, "e": 3420, "s": 3245, "text": "print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))print(next(iter_best_albums))" }, { "code": null, "e": 3479, "s": 3420, "text": "We can handle this error with a ‘StopIteration’ exception:" }, { "code": null, "e": 3600, "s": 3479, "text": "while True: try: element = next(iter_best_albums) print(element) except(StopIteration): break" }, { "code": null, "e": 3764, "s": 3600, "text": "We get the same result that we did from looping over our list from earlier. This is essentially what happens under the hood when we loop over lists with for-loops." }, { "code": null, "e": 3954, "s": 3764, "text": "I’ll stop here but feel free to play around with the code yourself. If you’re interested in learning more about iterators and iterables, Cory Schafer’s YouTube tutorial is a great resource." } ]
C library function - mktime()
The C library function time_t mktime(struct tm *timeptr) converts the structure pointed to by timeptr into a time_t value according to the local time zone. Following is the declaration for mktime() function. time_t mktime(struct tm *timeptr) timeptr − This is the pointer to a time_t value representing a calendar time, broken down into its components. Below is the detail of timeptr structure timeptr − This is the pointer to a time_t value representing a calendar time, broken down into its components. Below is the detail of timeptr structure struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ }; This function returns a time_t value corresponding to the calendar time passed as argument. On error, a -1 value is returned. The following example shows the usage of mktime() function. #include #include int main () { int ret; struct tm info; char buffer[80]; info.tm_year = 2001 - 1900; info.tm_mon = 7 - 1; info.tm_mday = 4; info.tm_hour = 0; info.tm_min = 0; info.tm_sec = 1; info.tm_isdst = -1; ret = mktime(&info); if( ret == -1 ) { printf("Error: unable to make time using mktime\n"); } else { strftime(buffer, sizeof(buffer), "%c", &info ); printf(buffer); } return(0); } Let us compile and run the above program that will produce the following result − Wed Jul 4 00:00:01 2001 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2163, "s": 2007, "text": "The C library function time_t mktime(struct tm *timeptr) converts the structure pointed to by timeptr into a time_t value according to the local time zone." }, { "code": null, "e": 2215, "s": 2163, "text": "Following is the declaration for mktime() function." }, { "code": null, "e": 2249, "s": 2215, "text": "time_t mktime(struct tm *timeptr)" }, { "code": null, "e": 2401, "s": 2249, "text": "timeptr − This is the pointer to a time_t value representing a calendar time, broken down into its components. Below is the detail of timeptr structure" }, { "code": null, "e": 2553, "s": 2401, "text": "timeptr − This is the pointer to a time_t value representing a calendar time, broken down into its components. Below is the detail of timeptr structure" }, { "code": null, "e": 3127, "s": 2553, "text": "struct tm {\n int tm_sec; /* seconds, range 0 to 59 */\n int tm_min; /* minutes, range 0 to 59 */\n int tm_hour; /* hours, range 0 to 23 */\n int tm_mday; /* day of the month, range 1 to 31 */\n int tm_mon; /* month, range 0 to 11 */\n int tm_year; /* The number of years since 1900 */\n int tm_wday; /* day of the week, range 0 to 6 */\n int tm_yday; /* day in the year, range 0 to 365 */\n int tm_isdst; /* daylight saving time */\t\n};" }, { "code": null, "e": 3253, "s": 3127, "text": "This function returns a time_t value corresponding to the calendar time passed as argument. On error, a -1 value is returned." }, { "code": null, "e": 3313, "s": 3253, "text": "The following example shows the usage of mktime() function." }, { "code": null, "e": 3775, "s": 3313, "text": "#include \n#include \n\nint main () {\n int ret;\n struct tm info;\n char buffer[80];\n\n info.tm_year = 2001 - 1900;\n info.tm_mon = 7 - 1;\n info.tm_mday = 4;\n info.tm_hour = 0;\n info.tm_min = 0;\n info.tm_sec = 1;\n info.tm_isdst = -1;\n\n ret = mktime(&info);\n if( ret == -1 ) {\n printf(\"Error: unable to make time using mktime\\n\");\n } else {\n strftime(buffer, sizeof(buffer), \"%c\", &info );\n printf(buffer);\n }\n\n return(0);\n}" }, { "code": null, "e": 3857, "s": 3775, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3882, "s": 3857, "text": "Wed Jul 4 00:00:01 2001\n" }, { "code": null, "e": 3915, "s": 3882, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3930, "s": 3915, "text": " Nishant Malik" }, { "code": null, "e": 3965, "s": 3930, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3980, "s": 3965, "text": " Nishant Malik" }, { "code": null, "e": 4015, "s": 3980, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4029, "s": 4015, "text": " Asif Hussain" }, { "code": null, "e": 4062, "s": 4029, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4080, "s": 4062, "text": " Richa Maheshwari" }, { "code": null, "e": 4115, "s": 4080, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4134, "s": 4115, "text": " Vandana Annavaram" }, { "code": null, "e": 4167, "s": 4134, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4179, "s": 4167, "text": " Amit Diwan" }, { "code": null, "e": 4186, "s": 4179, "text": " Print" }, { "code": null, "e": 4197, "s": 4186, "text": " Add Notes" } ]
Convert a NumPy array to a Pandas series - GeeksforGeeks
18 Aug, 2020 Let us see how to convert a NumPy array to a Pandas series. A NumPy array can be converted into a Pandas series by passing it in the pandas.Series() function. Example 1 : # importing the modulesimport numpy as npimport pandas as pd # creating an NumPy arrayarray = np.array([10, 20, 1, 2, 3, 4, 5, 6, 7]) # displaying the NumPy arrayprint("Numpy array is :")display(array) # converting the NumPy array # to a Pandas seriesseries = pd.Series(array) # displaying the Pandas seriesprint("Pandas Series : ")display(series) Output : Example 2 : # importing the modulesimport numpy as npimport pandas as pd # creating an NumPy arrayarray = np.random.rand(5) # displaying the NumPy arrayprint("Numpy array is :")display(array) # converting the NumPy array # to a Pandas seriesseries = pd.Series(array) # displaying the Pandas seriesprint("Pandas Series : ")display(series) Output : Python pandas-series Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n18 Aug, 2020" }, { "code": null, "e": 24451, "s": 24292, "text": "Let us see how to convert a NumPy array to a Pandas series. A NumPy array can be converted into a Pandas series by passing it in the pandas.Series() function." }, { "code": null, "e": 24463, "s": 24451, "text": "Example 1 :" }, { "code": "# importing the modulesimport numpy as npimport pandas as pd # creating an NumPy arrayarray = np.array([10, 20, 1, 2, 3, 4, 5, 6, 7]) # displaying the NumPy arrayprint(\"Numpy array is :\")display(array) # converting the NumPy array # to a Pandas seriesseries = pd.Series(array) # displaying the Pandas seriesprint(\"Pandas Series : \")display(series)", "e": 24835, "s": 24463, "text": null }, { "code": null, "e": 24844, "s": 24835, "text": "Output :" }, { "code": null, "e": 24856, "s": 24844, "text": "Example 2 :" }, { "code": "# importing the modulesimport numpy as npimport pandas as pd # creating an NumPy arrayarray = np.random.rand(5) # displaying the NumPy arrayprint(\"Numpy array is :\")display(array) # converting the NumPy array # to a Pandas seriesseries = pd.Series(array) # displaying the Pandas seriesprint(\"Pandas Series : \")display(series)", "e": 25188, "s": 24856, "text": null }, { "code": null, "e": 25197, "s": 25188, "text": "Output :" }, { "code": null, "e": 25218, "s": 25197, "text": "Python pandas-series" }, { "code": null, "e": 25232, "s": 25218, "text": "Python-pandas" }, { "code": null, "e": 25239, "s": 25232, "text": "Python" }, { "code": null, "e": 25337, "s": 25239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25346, "s": 25337, "text": "Comments" }, { "code": null, "e": 25359, "s": 25346, "text": "Old Comments" }, { "code": null, "e": 25391, "s": 25359, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25447, "s": 25391, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25502, "s": 25447, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25544, "s": 25502, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25586, "s": 25544, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25617, "s": 25586, "text": "Python | os.path.join() method" }, { "code": null, "e": 25656, "s": 25617, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25685, "s": 25656, "text": "Create a directory in Python" }, { "code": null, "e": 25707, "s": 25685, "text": "Defaultdict in Python" } ]
Number of closing brackets needed to complete a regular bracket sequence
28 Jun, 2022 Given an incomplete bracket sequence S. The task is to find the number of closing brackets ‘)’ needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print “IMPOSSIBLE”.Let us define a regular bracket sequence in the following way: Empty string is a regular bracket sequence. If s is a regular bracket sequence, then (s) is a regular bracket sequence. If s & t are regular bracket sequences, then st is a regular bracket sequence. Examples: Input : str = “(()(()(” Output : (()(()())) Explanation : The minimum number of ) needed to make the sequence regular are 3 which are appended at the end.Input : str = “())(()” Output : IMPOSSIBLE We need to add minimal number of closing brackets ‘)’, so we will count the number of unbalanced opening brackets and then we will add that amount of closing brackets. If at any point the number of the closing bracket is greater than the opening bracket then the answer is IMPOSSIBLE.Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ program to find number of closing// brackets needed and complete a regular// bracket sequence#include <iostream>using namespace std; // Function to find number of closing// brackets and complete a regular// bracket sequencevoid completeSequence(string s){ // Finding the length of sequence int n = s.length(); int open = 0, close = 0; for (int i = 0; i < n; i++) { // Counting opening brackets if (s[i] == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { cout << "Impossible" << endl; return; } } // If possible, print 's' and // required closing brackets. cout << s; for (int i = 0; i < open - close; i++) cout << ')'; cout << endl;} // Driver codeint main(){ string s = "(()(()("; completeSequence(s); return 0;} // This code is contributed by// sanjeev2552 // Java program to find number of closing// brackets needed and complete a regular// bracket sequenceclass GFG { // Function to find number of closing // brackets and complete a regular // bracket sequence static void completeSequence(String s) { // Finding the length of sequence int n = s.length(); int open = 0, close = 0; for (int i = 0; i < n; i++) { // Counting opening brackets if (s.charAt(i) == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { System.out.print("IMPOSSIBLE"); return; } } // If possible, print 's' and required closing // brackets. System.out.print(s); for (int i = 0; i < open - close; i++) System.out.print(")"); } // Driver code public static void main(String[] args) { String s = "(()(()("; completeSequence(s); }} # Python 3 program to find number of# closing brackets needed and complete# a regular bracket sequence # Function to find number of closing# brackets and complete a regular# bracket sequencedef completeSequence(s): # Finding the length of sequence n = len(s) open = 0 close = 0 for i in range(n): # Counting opening brackets if (s[i] == '('): open += 1 else: # Counting closing brackets close += 1 # Checking if at any position the # number of closing bracket # is more then answer is impossible if (close > open): print("IMPOSSIBLE") return # If possible, print 's' and # required closing brackets. print(s, end = "") for i in range(open - close): print(")", end = "") # Driver codeif __name__ == "__main__": s = "(()(()(" completeSequence(s) # This code is contributed by ita_c // C# program to find number of closing// brackets needed and complete a// regular bracket sequenceusing System; class GFG{// Function to find number of closing// brackets and complete a regular// bracket sequencestatic void completeSequence(String s){ // Finding the length of sequence int n = s.Length; int open = 0, close = 0; for (int i = 0; i < n; i++) { // Counting opening brackets if (s[i] == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { Console.Write("IMPOSSIBLE"); return; } } // If possible, print 's' and // required closing brackets. Console.Write(s); for (int i = 0; i < open - close; i++) Console.Write(")"); } // Driver Codestatic void Main(){ String s = "(()(()("; completeSequence(s);}} // This code is contributed// by ANKITRAI1 <?php// PHP program to find number of closing// brackets needed and complete a// regular bracket sequence // Function to find number of closing// brackets and complete a regular// bracket sequencefunction completeSequence($s){ // Finding the length of sequence $n = strlen($s); $open = 0; $close = 0; for ($i = 0; $i < $n; $i++) { // Counting opening brackets if ($s[$i] == '(') $open++; else // Counting closing brackets $close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if ($close > $open) { echo ("IMPOSSIBLE"); return; } } // If possible, print 's' and // required closing brackets. echo ($s); for ($i = 0; $i < $open - $close; $i++) echo (")"); } // Driver Code$s = "(()(()(";completeSequence($s); // This code is contributed// by ajit?> <script> // Javascript program to find number of closing // brackets needed and complete a // regular bracket sequence // Function to find number of closing // brackets and complete a regular // bracket sequence function completeSequence(s) { // Finding the length of sequence let n = s.length; let open = 0, close = 0; for (let i = 0; i < n; i++) { // Counting opening brackets if (s[i] == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { document.write("IMPOSSIBLE"); return; } } // If possible, print 's' and // required closing brackets. document.write(s); for (let i = 0; i < open - close; i++) document.write(")"); } let s = "(()(()("; completeSequence(s); </script> (()(()())) ankthon jit_t ukasp sanjeev2552 divyesh072019 rkbhola5 Parentheses-Problems Greedy Strings Strings Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 458, "s": 54, "text": "Given an incomplete bracket sequence S. The task is to find the number of closing brackets ‘)’ needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print “IMPOSSIBLE”.Let us define a regular bracket sequence in the following way: " }, { "code": null, "e": 502, "s": 458, "text": "Empty string is a regular bracket sequence." }, { "code": null, "e": 578, "s": 502, "text": "If s is a regular bracket sequence, then (s) is a regular bracket sequence." }, { "code": null, "e": 657, "s": 578, "text": "If s & t are regular bracket sequences, then st is a regular bracket sequence." }, { "code": null, "e": 669, "s": 657, "text": "Examples: " }, { "code": null, "e": 868, "s": 669, "text": "Input : str = “(()(()(” Output : (()(()())) Explanation : The minimum number of ) needed to make the sequence regular are 3 which are appended at the end.Input : str = “())(()” Output : IMPOSSIBLE " }, { "code": null, "e": 1207, "s": 870, "text": "We need to add minimal number of closing brackets ‘)’, so we will count the number of unbalanced opening brackets and then we will add that amount of closing brackets. If at any point the number of the closing bracket is greater than the opening bracket then the answer is IMPOSSIBLE.Below is the implementation of the above approach: " }, { "code": null, "e": 1211, "s": 1207, "text": "C++" }, { "code": null, "e": 1216, "s": 1211, "text": "Java" }, { "code": null, "e": 1225, "s": 1216, "text": "Python 3" }, { "code": null, "e": 1228, "s": 1225, "text": "C#" }, { "code": null, "e": 1232, "s": 1228, "text": "PHP" }, { "code": null, "e": 1243, "s": 1232, "text": "Javascript" }, { "code": "// C++ program to find number of closing// brackets needed and complete a regular// bracket sequence#include <iostream>using namespace std; // Function to find number of closing// brackets and complete a regular// bracket sequencevoid completeSequence(string s){ // Finding the length of sequence int n = s.length(); int open = 0, close = 0; for (int i = 0; i < n; i++) { // Counting opening brackets if (s[i] == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { cout << \"Impossible\" << endl; return; } } // If possible, print 's' and // required closing brackets. cout << s; for (int i = 0; i < open - close; i++) cout << ')'; cout << endl;} // Driver codeint main(){ string s = \"(()(()(\"; completeSequence(s); return 0;} // This code is contributed by// sanjeev2552", "e": 2309, "s": 1243, "text": null }, { "code": "// Java program to find number of closing// brackets needed and complete a regular// bracket sequenceclass GFG { // Function to find number of closing // brackets and complete a regular // bracket sequence static void completeSequence(String s) { // Finding the length of sequence int n = s.length(); int open = 0, close = 0; for (int i = 0; i < n; i++) { // Counting opening brackets if (s.charAt(i) == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { System.out.print(\"IMPOSSIBLE\"); return; } } // If possible, print 's' and required closing // brackets. System.out.print(s); for (int i = 0; i < open - close; i++) System.out.print(\")\"); } // Driver code public static void main(String[] args) { String s = \"(()(()(\"; completeSequence(s); }}", "e": 3478, "s": 2309, "text": null }, { "code": "# Python 3 program to find number of# closing brackets needed and complete# a regular bracket sequence # Function to find number of closing# brackets and complete a regular# bracket sequencedef completeSequence(s): # Finding the length of sequence n = len(s) open = 0 close = 0 for i in range(n): # Counting opening brackets if (s[i] == '('): open += 1 else: # Counting closing brackets close += 1 # Checking if at any position the # number of closing bracket # is more then answer is impossible if (close > open): print(\"IMPOSSIBLE\") return # If possible, print 's' and # required closing brackets. print(s, end = \"\") for i in range(open - close): print(\")\", end = \"\") # Driver codeif __name__ == \"__main__\": s = \"(()(()(\" completeSequence(s) # This code is contributed by ita_c", "e": 4426, "s": 3478, "text": null }, { "code": "// C# program to find number of closing// brackets needed and complete a// regular bracket sequenceusing System; class GFG{// Function to find number of closing// brackets and complete a regular// bracket sequencestatic void completeSequence(String s){ // Finding the length of sequence int n = s.Length; int open = 0, close = 0; for (int i = 0; i < n; i++) { // Counting opening brackets if (s[i] == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { Console.Write(\"IMPOSSIBLE\"); return; } } // If possible, print 's' and // required closing brackets. Console.Write(s); for (int i = 0; i < open - close; i++) Console.Write(\")\"); } // Driver Codestatic void Main(){ String s = \"(()(()(\"; completeSequence(s);}} // This code is contributed// by ANKITRAI1", "e": 5479, "s": 4426, "text": null }, { "code": "<?php// PHP program to find number of closing// brackets needed and complete a// regular bracket sequence // Function to find number of closing// brackets and complete a regular// bracket sequencefunction completeSequence($s){ // Finding the length of sequence $n = strlen($s); $open = 0; $close = 0; for ($i = 0; $i < $n; $i++) { // Counting opening brackets if ($s[$i] == '(') $open++; else // Counting closing brackets $close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if ($close > $open) { echo (\"IMPOSSIBLE\"); return; } } // If possible, print 's' and // required closing brackets. echo ($s); for ($i = 0; $i < $open - $close; $i++) echo (\")\"); } // Driver Code$s = \"(()(()(\";completeSequence($s); // This code is contributed// by ajit?>", "e": 6448, "s": 5479, "text": null }, { "code": "<script> // Javascript program to find number of closing // brackets needed and complete a // regular bracket sequence // Function to find number of closing // brackets and complete a regular // bracket sequence function completeSequence(s) { // Finding the length of sequence let n = s.length; let open = 0, close = 0; for (let i = 0; i < n; i++) { // Counting opening brackets if (s[i] == '(') open++; else // Counting closing brackets close++; // Checking if at any position the // number of closing bracket // is more then answer is impossible if (close > open) { document.write(\"IMPOSSIBLE\"); return; } } // If possible, print 's' and // required closing brackets. document.write(s); for (let i = 0; i < open - close; i++) document.write(\")\"); } let s = \"(()(()(\"; completeSequence(s); </script>", "e": 7568, "s": 6448, "text": null }, { "code": null, "e": 7579, "s": 7568, "text": "(()(()()))" }, { "code": null, "e": 7589, "s": 7581, "text": "ankthon" }, { "code": null, "e": 7595, "s": 7589, "text": "jit_t" }, { "code": null, "e": 7601, "s": 7595, "text": "ukasp" }, { "code": null, "e": 7613, "s": 7601, "text": "sanjeev2552" }, { "code": null, "e": 7627, "s": 7613, "text": "divyesh072019" }, { "code": null, "e": 7636, "s": 7627, "text": "rkbhola5" }, { "code": null, "e": 7657, "s": 7636, "text": "Parentheses-Problems" }, { "code": null, "e": 7664, "s": 7657, "text": "Greedy" }, { "code": null, "e": 7672, "s": 7664, "text": "Strings" }, { "code": null, "e": 7680, "s": 7672, "text": "Strings" }, { "code": null, "e": 7687, "s": 7680, "text": "Greedy" } ]
Data Visualization with Python Seaborn
15 Jan, 2022 Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages. And it helps to understand the data, however, complex it is, the significance of data by summarizing and presenting a huge amount of data in a simple and easy-to-understand format and helps communicate information clearly and effectively. Pandas and Seaborn is one of those packages and makes importing and analyzing data much easier. In this article, we will use Pandas and Seaborn to analyze data. Pandas offer tools for cleaning and process your data. It is the most popular Python library that is used for data analysis. In pandas, a data table is called a dataframe. So, let’s start with creating Pandas data frame: Example 1: Python3 # Python code demonstrate creating import pandas as pd # initialise data of lists.data = {'Name':[ 'Mohe' , 'Karnal' , 'Yrik' , 'jack' ], 'Age':[ 30 , 21 , 29 , 28 ]} # Create DataFramedf = pd.DataFrame( data ) # Print the output.df Output: Example 2: load the CSV data from the system and display it through pandas. Python3 # import moduleimport pandas # load the csvdata = pandas.read_csv("nba.csv") # show first 5 columndata.head() Output: Seaborn is an amazing visualization library for statistical graphics plotting in Python. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas. Installation For python environment : pip install seaborn For conda environment : conda install seaborn Let’s create Some basic plots using seaborn: Python3 # Importing librariesimport numpy as npimport seaborn as sns # Selecting style as white,# dark, whitegrid, darkgrid # or tickssns.set( style = "white" ) # Generate a random univariate # datasetrs = np.random.RandomState( 10 )d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automaticallysns.distplot(d, kde = True, color = "g") Output: Seaborn helps to visualize the statistical relationships, To understand how variables in a dataset are related to one another and how that relationship is dependent on other variables, we perform statistical analysis. This Statistical analysis helps to visualize the trends and identify various patterns in the dataset. These are the plot will help to visualize: Line Plot Scatter Plot Box plot Point plot Count plot Violin plot Swarm plot Bar plot KDE Plot Lineplot Is the most popular plot to draw a relationship between x and y with the possibility of several semantic groupings. Syntax : sns.lineplot(x=None, y=None) Parameters: x, y: Input data variables; must be numeric. Can pass data directly or reference columns in data. Let’s visualize the data with a line plot and pandas: Example 1: Python3 # import moduleimport seaborn as snsimport pandas # loading csvdata = pandas.read_csv("nba.csv") # plotting lineplotsns.lineplot( data['Age'], data['Weight']) Output: Example 2: Use the hue parameter for plotting the graph. Python3 # import moduleimport seaborn as snsimport pandas # read the csv datadata = pandas.read_csv("nba.csv") # plotsns.lineplot(data['Age'],data['Weight'], hue =data["Position"]) Output: Scatterplot Can be used with several semantic groupings which can help to understand well in a graph against continuous/categorical data. It can draw a two-dimensional graph. Syntax: seaborn.scatterplot(x=None, y=None) Parameters:x, y: Input data variables that should be numeric. Returns: This method returns the Axes object with the plot drawn onto it. Let’s visualize the data with a scatter plot and pandas: Example 1: Python3 # import moduleimport seabornimport pandas # load csvdata = pandas.read_csv("nba.csv") # plottingseaborn.scatterplot(data['Age'],data['Weight']) Output: Example 2: Use the hue parameter for plotting the graph. Python3 import seabornimport pandasdata = pandas.read_csv("nba.csv") seaborn.scatterplot( data['Age'], data['Weight'], hue =data["Position"]) Output: A box plot (or box-and-whisker plot) s is the visual representation of the depicting groups of numerical data through their quartiles against continuous/categorical data. A box plot consists of 5 things. Minimum First Quartile or 25% Median (Second Quartile) or 50% Third Quartile or 75% Maximum Syntax: seaborn.boxplot(x=None, y=None, hue=None, data=None) Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Returns: It returns the Axes object with the plot drawn onto it. Draw the box plot with Pandas: Example 1: Python3 # import moduleimport seaborn as snsimport pandas # read csv and plottingdata = pandas.read_csv( "nba.csv" )sns.boxplot( data['Age'] ) Output: Example 2: Python3 # import moduleimport seaborn as snsimport pandas # read csv and plottingdata = pandas.read_csv( "nba.csv" )sns.boxplot( data['Age'], data['Weight']) Output: A violin plot is similar to a boxplot. It shows several quantitative data across one or more categorical variables such that those distributions can be compared. Syntax: seaborn.violinplot(x=None, y=None, hue=None, data=None) Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. Draw the violin plot with Pandas: Example 1: Python3 # import moduleimport seaborn as snsimport pandas # read csv and plotdata = pandas.read_csv("nba.csv")sns.violinplot(data['Age']) Output: Example 2: Python3 # import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv("nba.csv")seaborn.violinplot(x ="Age", y ="Weight",data = data) Output: A swarm plot is similar to a strip plot, We can draw a swarm plot with non-overlapping points against categorical data. Syntax: seaborn.swarmplot(x=None, y=None, hue=None, data=None) Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. Draw the swarm plot with Pandas: Example 1: Python3 # import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv( "nba.csv" )seaborn.swarmplot(x = data["Age"]) Output: Example 2: Python3 # import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv("nba.csv")seaborn.swarmplot(x ="Age", y ="Weight",data = data) Output: Barplot represents an estimate of central tendency for a numeric variable with the height of each rectangle and provides some indication of the uncertainty around that estimate using error bars. Syntax : seaborn.barplot(x=None, y=None, hue=None, data=None) Parameters : x, y : This parameter take names of variables in data or vector data, Inputs for plotting long-form data. hue : (optional) This parameter take column name for colour encoding. data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form. Returns : Returns the Axes object with the plot drawn onto it. Draw the bar plot with Pandas: Example 1: Python3 # import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv("nba.csv")seaborn.barplot(x =data["Age"]) Output: Example 2: Python3 # import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv("nba.csv")seaborn.barplot(x ="Age", y ="Weight", data = data) Output: Point plot used to show point estimates and confidence intervals using scatter plot glyphs. A point plot represents an estimate of central tendency for a numeric variable by the position of scatter plot points and provides some indication of the uncertainty around that estimate using error bars. Syntax: seaborn.pointplot(x=None, y=None, hue=None, data=None) Parameters: x, y: Inputs for plotting long-form data. hue: (optional) column name for color encoding. data: dataframe as a Dataset for plotting. Return: The Axes object with the plot drawn onto it. Draw the point plot with Pandas: Example: Python3 # import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv("nba.csv")seaborn.pointplot(x = "Age", y = "Weight", data = data) Output: Count plot used to Show the counts of observations in each categorical bin using bars. Syntax : seaborn.countplot(x=None, y=None, hue=None, data=None) Parameters : x, y: This parameter take names of variables in data or vector data, optional, Inputs for plotting long-form data. hue : (optional) This parameter take column name for color encoding. data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise, it is expected to be long-form. Returns: Returns the Axes object with the plot drawn onto it. Draw the count plot with Pandas: Example: Python3 # import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv("nba.csv")seaborn.countplot(data["Age"]) Output: KDE Plot described as Kernel Density Estimate is used for visualizing the Probability Density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can also plot a single graph for multiple samples which helps in more efficient data visualization. Syntax: seaborn.kdeplot(x=None, *, y=None, vertical=False, palette=None, **kwargs) Parameters: x, y : vectors or keys in data vertical : boolean (True or False) data : pandas.DataFrame, numpy.ndarray, mapping, or sequence Draw the KDE plot with Pandas: Example 1: Python3 # importing the required librariesfrom sklearn import datasetsimport pandas as pdimport seaborn as sns # Setting up the Data Frameiris = datasets.load_iris() iris_df = pd.DataFrame(iris.data, columns=['Sepal_Length', 'Sepal_Width', 'Patal_Length', 'Petal_Width']) iris_df['Target'] = iris.target iris_df['Target'].replace([0], 'Iris_Setosa', inplace=True)iris_df['Target'].replace([1], 'Iris_Vercicolor', inplace=True)iris_df['Target'].replace([2], 'Iris_Virginica', inplace=True) # Plotting the KDE Plotsns.kdeplot(iris_df.loc[(iris_df['Target'] =='Iris_Virginica'), 'Sepal_Length'], color = 'b', shade = True, Label ='Iris_Virginica') Output: Example 2: Python3 # import moduleimport seaborn as snsimport pandas # read top 5 columndata = pandas.read_csv("nba.csv").head() sns.kdeplot( data['Age'], data['Number']) Output: Before starting let’s have a small intro of bivariate and univariate data: Bivariate data: This type of data involves two different variables. The analysis of this type of data deals with causes and relationships and the analysis is done to find out the relationship between the two variables. Univariate data: This type of data consists of only one variable. The analysis of univariate data is thus the simplest form of analysis since the information deals with only one quantity that changes. It does not deal with causes or relationships and the main purpose of the analysis is to describe the data and find patterns that exist within it. Example 1: Using the box plot. Python3 # import moduleimport seaborn as snsimport pandas # read csv and plottingdata = pandas.read_csv( "nba.csv" )sns.boxplot( data['Age'], data['Height']) Output: Example 2: using KDE plot. Python3 # import moduleimport seaborn as snsimport pandas # read top 5 columndata = pandas.read_csv("nba.csv").head() sns.kdeplot( data['Age'], data['Weight']) Output: Example: Using the dist plot Python3 # import moduleimport seaborn as snsimport pandas # read top 5 columndata = pandas.read_csv("nba.csv").head() sns.distplot( data['Age']) Output: sooda367 adnanirshad158 ruhelaa48 Data Visualization Python-pandas Python-Seaborn Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jan, 2022" }, { "code": null, "e": 484, "s": 54, "text": "Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages. And it helps to understand the data, however, complex it is, the significance of data by summarizing and presenting a huge amount of data in a simple and easy-to-understand format and helps communicate information clearly and effectively." }, { "code": null, "e": 645, "s": 484, "text": "Pandas and Seaborn is one of those packages and makes importing and analyzing data much easier. In this article, we will use Pandas and Seaborn to analyze data." }, { "code": null, "e": 817, "s": 645, "text": "Pandas offer tools for cleaning and process your data. It is the most popular Python library that is used for data analysis. In pandas, a data table is called a dataframe." }, { "code": null, "e": 866, "s": 817, "text": "So, let’s start with creating Pandas data frame:" }, { "code": null, "e": 877, "s": 866, "text": "Example 1:" }, { "code": null, "e": 885, "s": 877, "text": "Python3" }, { "code": "# Python code demonstrate creating import pandas as pd # initialise data of lists.data = {'Name':[ 'Mohe' , 'Karnal' , 'Yrik' , 'jack' ], 'Age':[ 30 , 21 , 29 , 28 ]} # Create DataFramedf = pd.DataFrame( data ) # Print the output.df", "e": 1129, "s": 885, "text": null }, { "code": null, "e": 1137, "s": 1129, "text": "Output:" }, { "code": null, "e": 1213, "s": 1137, "text": "Example 2: load the CSV data from the system and display it through pandas." }, { "code": null, "e": 1221, "s": 1213, "text": "Python3" }, { "code": "# import moduleimport pandas # load the csvdata = pandas.read_csv(\"nba.csv\") # show first 5 columndata.head()", "e": 1331, "s": 1221, "text": null }, { "code": null, "e": 1339, "s": 1331, "text": "Output:" }, { "code": null, "e": 1539, "s": 1339, "text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas." }, { "code": null, "e": 1552, "s": 1539, "text": "Installation" }, { "code": null, "e": 1578, "s": 1552, "text": "For python environment : " }, { "code": null, "e": 1598, "s": 1578, "text": "pip install seaborn" }, { "code": null, "e": 1623, "s": 1598, "text": "For conda environment : " }, { "code": null, "e": 1645, "s": 1623, "text": "conda install seaborn" }, { "code": null, "e": 1690, "s": 1645, "text": "Let’s create Some basic plots using seaborn:" }, { "code": null, "e": 1698, "s": 1690, "text": "Python3" }, { "code": "# Importing librariesimport numpy as npimport seaborn as sns # Selecting style as white,# dark, whitegrid, darkgrid # or tickssns.set( style = \"white\" ) # Generate a random univariate # datasetrs = np.random.RandomState( 10 )d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automaticallysns.distplot(d, kde = True, color = \"g\")", "e": 2073, "s": 1698, "text": null }, { "code": null, "e": 2081, "s": 2073, "text": "Output:" }, { "code": null, "e": 2401, "s": 2081, "text": "Seaborn helps to visualize the statistical relationships, To understand how variables in a dataset are related to one another and how that relationship is dependent on other variables, we perform statistical analysis. This Statistical analysis helps to visualize the trends and identify various patterns in the dataset." }, { "code": null, "e": 2444, "s": 2401, "text": "These are the plot will help to visualize:" }, { "code": null, "e": 2454, "s": 2444, "text": "Line Plot" }, { "code": null, "e": 2467, "s": 2454, "text": "Scatter Plot" }, { "code": null, "e": 2476, "s": 2467, "text": "Box plot" }, { "code": null, "e": 2487, "s": 2476, "text": "Point plot" }, { "code": null, "e": 2498, "s": 2487, "text": "Count plot" }, { "code": null, "e": 2510, "s": 2498, "text": "Violin plot" }, { "code": null, "e": 2521, "s": 2510, "text": "Swarm plot" }, { "code": null, "e": 2530, "s": 2521, "text": "Bar plot" }, { "code": null, "e": 2539, "s": 2530, "text": "KDE Plot" }, { "code": null, "e": 2664, "s": 2539, "text": "Lineplot Is the most popular plot to draw a relationship between x and y with the possibility of several semantic groupings." }, { "code": null, "e": 2702, "s": 2664, "text": "Syntax : sns.lineplot(x=None, y=None)" }, { "code": null, "e": 2714, "s": 2702, "text": "Parameters:" }, { "code": null, "e": 2812, "s": 2714, "text": "x, y: Input data variables; must be numeric. Can pass data directly or reference columns in data." }, { "code": null, "e": 2866, "s": 2812, "text": "Let’s visualize the data with a line plot and pandas:" }, { "code": null, "e": 2877, "s": 2866, "text": "Example 1:" }, { "code": null, "e": 2885, "s": 2877, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # loading csvdata = pandas.read_csv(\"nba.csv\") # plotting lineplotsns.lineplot( data['Age'], data['Weight'])", "e": 3044, "s": 2885, "text": null }, { "code": null, "e": 3052, "s": 3044, "text": "Output:" }, { "code": null, "e": 3109, "s": 3052, "text": "Example 2: Use the hue parameter for plotting the graph." }, { "code": null, "e": 3117, "s": 3109, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read the csv datadata = pandas.read_csv(\"nba.csv\") # plotsns.lineplot(data['Age'],data['Weight'], hue =data[\"Position\"])", "e": 3290, "s": 3117, "text": null }, { "code": null, "e": 3298, "s": 3290, "text": "Output:" }, { "code": null, "e": 3473, "s": 3298, "text": "Scatterplot Can be used with several semantic groupings which can help to understand well in a graph against continuous/categorical data. It can draw a two-dimensional graph." }, { "code": null, "e": 3517, "s": 3473, "text": "Syntax: seaborn.scatterplot(x=None, y=None)" }, { "code": null, "e": 3579, "s": 3517, "text": "Parameters:x, y: Input data variables that should be numeric." }, { "code": null, "e": 3653, "s": 3579, "text": "Returns: This method returns the Axes object with the plot drawn onto it." }, { "code": null, "e": 3710, "s": 3653, "text": "Let’s visualize the data with a scatter plot and pandas:" }, { "code": null, "e": 3721, "s": 3710, "text": "Example 1:" }, { "code": null, "e": 3729, "s": 3721, "text": "Python3" }, { "code": "# import moduleimport seabornimport pandas # load csvdata = pandas.read_csv(\"nba.csv\") # plottingseaborn.scatterplot(data['Age'],data['Weight'])", "e": 3874, "s": 3729, "text": null }, { "code": null, "e": 3882, "s": 3874, "text": "Output:" }, { "code": null, "e": 3939, "s": 3882, "text": "Example 2: Use the hue parameter for plotting the graph." }, { "code": null, "e": 3947, "s": 3939, "text": "Python3" }, { "code": "import seabornimport pandasdata = pandas.read_csv(\"nba.csv\") seaborn.scatterplot( data['Age'], data['Weight'], hue =data[\"Position\"])", "e": 4081, "s": 3947, "text": null }, { "code": null, "e": 4089, "s": 4081, "text": "Output:" }, { "code": null, "e": 4260, "s": 4089, "text": "A box plot (or box-and-whisker plot) s is the visual representation of the depicting groups of numerical data through their quartiles against continuous/categorical data." }, { "code": null, "e": 4293, "s": 4260, "text": "A box plot consists of 5 things." }, { "code": null, "e": 4301, "s": 4293, "text": "Minimum" }, { "code": null, "e": 4323, "s": 4301, "text": "First Quartile or 25%" }, { "code": null, "e": 4355, "s": 4323, "text": "Median (Second Quartile) or 50%" }, { "code": null, "e": 4377, "s": 4355, "text": "Third Quartile or 75%" }, { "code": null, "e": 4385, "s": 4377, "text": "Maximum" }, { "code": null, "e": 4394, "s": 4385, "text": "Syntax: " }, { "code": null, "e": 4447, "s": 4394, "text": "seaborn.boxplot(x=None, y=None, hue=None, data=None)" }, { "code": null, "e": 4460, "s": 4447, "text": "Parameters: " }, { "code": null, "e": 4507, "s": 4460, "text": "x, y, hue: Inputs for plotting long-form data." }, { "code": null, "e": 4592, "s": 4507, "text": "data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form." }, { "code": null, "e": 4658, "s": 4592, "text": "Returns: It returns the Axes object with the plot drawn onto it. " }, { "code": null, "e": 4689, "s": 4658, "text": "Draw the box plot with Pandas:" }, { "code": null, "e": 4700, "s": 4689, "text": "Example 1:" }, { "code": null, "e": 4708, "s": 4700, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read csv and plottingdata = pandas.read_csv( \"nba.csv\" )sns.boxplot( data['Age'] )", "e": 4843, "s": 4708, "text": null }, { "code": null, "e": 4851, "s": 4843, "text": "Output:" }, { "code": null, "e": 4862, "s": 4851, "text": "Example 2:" }, { "code": null, "e": 4870, "s": 4862, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read csv and plottingdata = pandas.read_csv( \"nba.csv\" )sns.boxplot( data['Age'], data['Weight'])", "e": 5020, "s": 4870, "text": null }, { "code": null, "e": 5028, "s": 5020, "text": "Output:" }, { "code": null, "e": 5191, "s": 5028, "text": "A violin plot is similar to a boxplot. It shows several quantitative data across one or more categorical variables such that those distributions can be compared. " }, { "code": null, "e": 5255, "s": 5191, "text": "Syntax: seaborn.violinplot(x=None, y=None, hue=None, data=None)" }, { "code": null, "e": 5268, "s": 5255, "text": "Parameters: " }, { "code": null, "e": 5316, "s": 5268, "text": "x, y, hue: Inputs for plotting long-form data. " }, { "code": null, "e": 5345, "s": 5316, "text": "data: Dataset for plotting. " }, { "code": null, "e": 5379, "s": 5345, "text": "Draw the violin plot with Pandas:" }, { "code": null, "e": 5390, "s": 5379, "text": "Example 1:" }, { "code": null, "e": 5398, "s": 5390, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read csv and plotdata = pandas.read_csv(\"nba.csv\")sns.violinplot(data['Age'])", "e": 5528, "s": 5398, "text": null }, { "code": null, "e": 5536, "s": 5528, "text": "Output:" }, { "code": null, "e": 5547, "s": 5536, "text": "Example 2:" }, { "code": null, "e": 5555, "s": 5547, "text": "Python3" }, { "code": "# import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv(\"nba.csv\")seaborn.violinplot(x =\"Age\", y =\"Weight\",data = data)", "e": 5724, "s": 5555, "text": null }, { "code": null, "e": 5732, "s": 5724, "text": "Output:" }, { "code": null, "e": 5852, "s": 5732, "text": "A swarm plot is similar to a strip plot, We can draw a swarm plot with non-overlapping points against categorical data." }, { "code": null, "e": 5916, "s": 5852, "text": "Syntax: seaborn.swarmplot(x=None, y=None, hue=None, data=None) " }, { "code": null, "e": 5929, "s": 5916, "text": "Parameters: " }, { "code": null, "e": 5977, "s": 5929, "text": "x, y, hue: Inputs for plotting long-form data. " }, { "code": null, "e": 6007, "s": 5977, "text": "data: Dataset for plotting. " }, { "code": null, "e": 6040, "s": 6007, "text": "Draw the swarm plot with Pandas:" }, { "code": null, "e": 6051, "s": 6040, "text": "Example 1:" }, { "code": null, "e": 6059, "s": 6051, "text": "Python3" }, { "code": "# import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv( \"nba.csv\" )seaborn.swarmplot(x = data[\"Age\"])", "e": 6211, "s": 6059, "text": null }, { "code": null, "e": 6219, "s": 6211, "text": "Output:" }, { "code": null, "e": 6230, "s": 6219, "text": "Example 2:" }, { "code": null, "e": 6238, "s": 6230, "text": "Python3" }, { "code": "# import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv(\"nba.csv\")seaborn.swarmplot(x =\"Age\", y =\"Weight\",data = data)", "e": 6406, "s": 6238, "text": null }, { "code": null, "e": 6414, "s": 6406, "text": "Output:" }, { "code": null, "e": 6610, "s": 6414, "text": "Barplot represents an estimate of central tendency for a numeric variable with the height of each rectangle and provides some indication of the uncertainty around that estimate using error bars. " }, { "code": null, "e": 6672, "s": 6610, "text": "Syntax : seaborn.barplot(x=None, y=None, hue=None, data=None)" }, { "code": null, "e": 6685, "s": 6672, "text": "Parameters :" }, { "code": null, "e": 6791, "s": 6685, "text": "x, y : This parameter take names of variables in data or vector data, Inputs for plotting long-form data." }, { "code": null, "e": 6861, "s": 6791, "text": "hue : (optional) This parameter take column name for colour encoding." }, { "code": null, "e": 7057, "s": 6861, "text": "data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form." }, { "code": null, "e": 7121, "s": 7057, "text": "Returns : Returns the Axes object with the plot drawn onto it. " }, { "code": null, "e": 7152, "s": 7121, "text": "Draw the bar plot with Pandas:" }, { "code": null, "e": 7163, "s": 7152, "text": "Example 1:" }, { "code": null, "e": 7171, "s": 7163, "text": "Python3" }, { "code": "# import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv(\"nba.csv\")seaborn.barplot(x =data[\"Age\"])", "e": 7318, "s": 7171, "text": null }, { "code": null, "e": 7326, "s": 7318, "text": "Output:" }, { "code": null, "e": 7337, "s": 7326, "text": "Example 2:" }, { "code": null, "e": 7345, "s": 7337, "text": "Python3" }, { "code": "# import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv(\"nba.csv\")seaborn.barplot(x =\"Age\", y =\"Weight\", data = data)", "e": 7512, "s": 7345, "text": null }, { "code": null, "e": 7520, "s": 7512, "text": "Output:" }, { "code": null, "e": 7817, "s": 7520, "text": "Point plot used to show point estimates and confidence intervals using scatter plot glyphs. A point plot represents an estimate of central tendency for a numeric variable by the position of scatter plot points and provides some indication of the uncertainty around that estimate using error bars." }, { "code": null, "e": 7880, "s": 7817, "text": "Syntax: seaborn.pointplot(x=None, y=None, hue=None, data=None)" }, { "code": null, "e": 7892, "s": 7880, "text": "Parameters:" }, { "code": null, "e": 7934, "s": 7892, "text": "x, y: Inputs for plotting long-form data." }, { "code": null, "e": 7982, "s": 7934, "text": "hue: (optional) column name for color encoding." }, { "code": null, "e": 8025, "s": 7982, "text": "data: dataframe as a Dataset for plotting." }, { "code": null, "e": 8078, "s": 8025, "text": "Return: The Axes object with the plot drawn onto it." }, { "code": null, "e": 8111, "s": 8078, "text": "Draw the point plot with Pandas:" }, { "code": null, "e": 8120, "s": 8111, "text": "Example:" }, { "code": null, "e": 8128, "s": 8120, "text": "Python3" }, { "code": "# import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv(\"nba.csv\")seaborn.pointplot(x = \"Age\", y = \"Weight\", data = data)", "e": 8299, "s": 8128, "text": null }, { "code": null, "e": 8307, "s": 8299, "text": "Output:" }, { "code": null, "e": 8394, "s": 8307, "text": "Count plot used to Show the counts of observations in each categorical bin using bars." }, { "code": null, "e": 8458, "s": 8394, "text": "Syntax : seaborn.countplot(x=None, y=None, hue=None, data=None)" }, { "code": null, "e": 8471, "s": 8458, "text": "Parameters :" }, { "code": null, "e": 8586, "s": 8471, "text": "x, y: This parameter take names of variables in data or vector data, optional, Inputs for plotting long-form data." }, { "code": null, "e": 8655, "s": 8586, "text": "hue : (optional) This parameter take column name for color encoding." }, { "code": null, "e": 8852, "s": 8655, "text": "data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise, it is expected to be long-form." }, { "code": null, "e": 8915, "s": 8852, "text": "Returns: Returns the Axes object with the plot drawn onto it. " }, { "code": null, "e": 8948, "s": 8915, "text": "Draw the count plot with Pandas:" }, { "code": null, "e": 8957, "s": 8948, "text": "Example:" }, { "code": null, "e": 8965, "s": 8957, "text": "Python3" }, { "code": "# import moduleimport seaborn seaborn.set(style = 'whitegrid') # read csv and plotdata = pandas.read_csv(\"nba.csv\")seaborn.countplot(data[\"Age\"])", "e": 9111, "s": 8965, "text": null }, { "code": null, "e": 9119, "s": 9111, "text": "Output:" }, { "code": null, "e": 9423, "s": 9119, "text": "KDE Plot described as Kernel Density Estimate is used for visualizing the Probability Density of a continuous variable. It depicts the probability density at different values in a continuous variable. We can also plot a single graph for multiple samples which helps in more efficient data visualization." }, { "code": null, "e": 9506, "s": 9423, "text": "Syntax: seaborn.kdeplot(x=None, *, y=None, vertical=False, palette=None, **kwargs)" }, { "code": null, "e": 9518, "s": 9506, "text": "Parameters:" }, { "code": null, "e": 9549, "s": 9518, "text": "x, y : vectors or keys in data" }, { "code": null, "e": 9584, "s": 9549, "text": "vertical : boolean (True or False)" }, { "code": null, "e": 9645, "s": 9584, "text": "data : pandas.DataFrame, numpy.ndarray, mapping, or sequence" }, { "code": null, "e": 9676, "s": 9645, "text": "Draw the KDE plot with Pandas:" }, { "code": null, "e": 9687, "s": 9676, "text": "Example 1:" }, { "code": null, "e": 9695, "s": 9687, "text": "Python3" }, { "code": "# importing the required librariesfrom sklearn import datasetsimport pandas as pdimport seaborn as sns # Setting up the Data Frameiris = datasets.load_iris() iris_df = pd.DataFrame(iris.data, columns=['Sepal_Length', 'Sepal_Width', 'Patal_Length', 'Petal_Width']) iris_df['Target'] = iris.target iris_df['Target'].replace([0], 'Iris_Setosa', inplace=True)iris_df['Target'].replace([1], 'Iris_Vercicolor', inplace=True)iris_df['Target'].replace([2], 'Iris_Virginica', inplace=True) # Plotting the KDE Plotsns.kdeplot(iris_df.loc[(iris_df['Target'] =='Iris_Virginica'), 'Sepal_Length'], color = 'b', shade = True, Label ='Iris_Virginica')", "e": 10374, "s": 9695, "text": null }, { "code": null, "e": 10382, "s": 10374, "text": "Output:" }, { "code": null, "e": 10393, "s": 10382, "text": "Example 2:" }, { "code": null, "e": 10401, "s": 10393, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read top 5 columndata = pandas.read_csv(\"nba.csv\").head() sns.kdeplot( data['Age'], data['Number'])", "e": 10553, "s": 10401, "text": null }, { "code": null, "e": 10561, "s": 10553, "text": "Output:" }, { "code": null, "e": 10636, "s": 10561, "text": "Before starting let’s have a small intro of bivariate and univariate data:" }, { "code": null, "e": 10855, "s": 10636, "text": "Bivariate data: This type of data involves two different variables. The analysis of this type of data deals with causes and relationships and the analysis is done to find out the relationship between the two variables." }, { "code": null, "e": 11203, "s": 10855, "text": "Univariate data: This type of data consists of only one variable. The analysis of univariate data is thus the simplest form of analysis since the information deals with only one quantity that changes. It does not deal with causes or relationships and the main purpose of the analysis is to describe the data and find patterns that exist within it." }, { "code": null, "e": 11234, "s": 11203, "text": "Example 1: Using the box plot." }, { "code": null, "e": 11242, "s": 11234, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read csv and plottingdata = pandas.read_csv( \"nba.csv\" )sns.boxplot( data['Age'], data['Height'])", "e": 11392, "s": 11242, "text": null }, { "code": null, "e": 11400, "s": 11392, "text": "Output:" }, { "code": null, "e": 11427, "s": 11400, "text": "Example 2: using KDE plot." }, { "code": null, "e": 11435, "s": 11427, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read top 5 columndata = pandas.read_csv(\"nba.csv\").head() sns.kdeplot( data['Age'], data['Weight'])", "e": 11587, "s": 11435, "text": null }, { "code": null, "e": 11595, "s": 11587, "text": "Output:" }, { "code": null, "e": 11624, "s": 11595, "text": "Example: Using the dist plot" }, { "code": null, "e": 11632, "s": 11624, "text": "Python3" }, { "code": "# import moduleimport seaborn as snsimport pandas # read top 5 columndata = pandas.read_csv(\"nba.csv\").head() sns.distplot( data['Age'])", "e": 11769, "s": 11632, "text": null }, { "code": null, "e": 11777, "s": 11769, "text": "Output:" }, { "code": null, "e": 11786, "s": 11777, "text": "sooda367" }, { "code": null, "e": 11801, "s": 11786, "text": "adnanirshad158" }, { "code": null, "e": 11811, "s": 11801, "text": "ruhelaa48" }, { "code": null, "e": 11830, "s": 11811, "text": "Data Visualization" }, { "code": null, "e": 11844, "s": 11830, "text": "Python-pandas" }, { "code": null, "e": 11859, "s": 11844, "text": "Python-Seaborn" }, { "code": null, "e": 11883, "s": 11859, "text": "Technical Scripter 2020" }, { "code": null, "e": 11890, "s": 11883, "text": "Python" }, { "code": null, "e": 11909, "s": 11890, "text": "Technical Scripter" } ]