title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python | Pandas Series.str.translate() - GeeksforGeeks
29 Sep, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.translate() is one of most important and complex string method. It uses a translate table to translate the caller series of string according to the translate table. If there are more than one values to be translated, a dictionary is passed to maketrans function to create a translate table. Syntax: Series.str.translate(table, deletechars=None) Parameters:table: Translation table made of dictionary in Python3 and lists in Python2.deletechars: String type, characters to be deleted. This Parameter works properly in Python2 only(till pandas v0.23) Return type: Series of strings with translated values To download the data set used in following example, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1:In this example, a translation table is created through a dictionary. The dictionary has a, b and c as its keys and X, Y and Z as values respectively. Translation table is created to replace a, b and c with X, Y and Z respectively. This table is passed to str.translate() method to make changes accordingly. # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # creating dictionary for trans tabletrans_dict ={"a": "X", "b": "Y", "c": "Z"} # creating translate table from dictionarytrans_table ="abc".maketrans(trans_dict) # translating through passed transtabledata["Name"]= data["Name"].str.translate(trans_table) # displaydata Output:As shown in the output images, the changes were made and letters were replaced successfully. Python pandas-series Python pandas-series-methods Python-pandas Python-pandas-series-str 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": "\n29 Sep, 2018" }, { "code": null, "e": 25769, "s": 25555, "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": 26071, "s": 25769, "text": "Pandas str.translate() is one of most important and complex string method. It uses a translate table to translate the caller series of string according to the translate table. If there are more than one values to be translated, a dictionary is passed to maketrans function to create a translate table." }, { "code": null, "e": 26125, "s": 26071, "text": "Syntax: Series.str.translate(table, deletechars=None)" }, { "code": null, "e": 26329, "s": 26125, "text": "Parameters:table: Translation table made of dictionary in Python3 and lists in Python2.deletechars: String type, characters to be deleted. This Parameter works properly in Python2 only(till pandas v0.23)" }, { "code": null, "e": 26383, "s": 26329, "text": "Return type: Series of strings with translated values" }, { "code": null, "e": 26447, "s": 26383, "text": "To download the data set used in following example, click here." }, { "code": null, "e": 26594, "s": 26447, "text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 26913, "s": 26594, "text": "Example #1:In this example, a translation table is created through a dictionary. The dictionary has a, b and c as its keys and X, Y and Z as values respectively. Translation table is created to replace a, b and c with X, Y and Z respectively. This table is passed to str.translate() method to make changes accordingly." }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # creating dictionary for trans tabletrans_dict ={\"a\": \"X\", \"b\": \"Y\", \"c\": \"Z\"} # creating translate table from dictionarytrans_table =\"abc\".maketrans(trans_dict) # translating through passed transtabledata[\"Name\"]= data[\"Name\"].str.translate(trans_table) # displaydata", "e": 27418, "s": 26913, "text": null }, { "code": null, "e": 27518, "s": 27418, "text": "Output:As shown in the output images, the changes were made and letters were replaced successfully." }, { "code": null, "e": 27539, "s": 27518, "text": "Python pandas-series" }, { "code": null, "e": 27568, "s": 27539, "text": "Python pandas-series-methods" }, { "code": null, "e": 27582, "s": 27568, "text": "Python-pandas" }, { "code": null, "e": 27607, "s": 27582, "text": "Python-pandas-series-str" }, { "code": null, "e": 27614, "s": 27607, "text": "Python" }, { "code": null, "e": 27712, "s": 27614, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27744, "s": 27712, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27786, "s": 27744, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27828, "s": 27786, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27884, "s": 27828, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27911, "s": 27884, "text": "Python Classes and Objects" }, { "code": null, "e": 27942, "s": 27911, "text": "Python | os.path.join() method" }, { "code": null, "e": 27981, "s": 27942, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28010, "s": 27981, "text": "Create a directory in Python" }, { "code": null, "e": 28032, "s": 28010, "text": "Defaultdict in Python" } ]
Distance between two closest minimum - GeeksforGeeks
31 May, 2021 Given an array of n integers. Find the minimum distance between any two occurrences of the minimum integer in the array.Examples: Input : arr[] = {5, 1, 2, 3, 4, 1, 2, 1} Output : 2 Explanation: The minimum element 1 occurs at indexes: 1, 5 and 7. So the minimum distance is 7-5 = 2. Input : arr[] = {1, 2, 1} Output : 2 Brute Force Approach: The simplest approach is to find all pair of indexes of minimum element and calculate minimum distance. Time Complexity: O(n^2), where n is the total number of elements in the array.Efficient Approach: An efficient approach will be to observe that distance between index j and i will always be smaller than distance between indexes k and i where, k is greater than j. That is we only have to check distance between consecutive pairs of minimum elements and not all pairs. Below is the step by step algorithm: Find the minimum element in the array Find all occurrences of minimum element in the array and insert the indexes in a new array or list or vector. Check if size of the list of indexes is greater than one or not, i.e. the minimum element occurs atleast twice. If not than return -1. Traverse the list of indexes and calculate the minimum difference between any two consecutive indexes. Below is the implementation of above idea: C++ Java Python3 C# PHP Javascript // CPP program to find Distance between// two closest minimum#include <iostream>#include <limits.h>#include <vector> using namespace std; // function to find Distance between// two closest minimumint findClosestMin(int arr[], int n){ int min = INT_MAX; // find the min element in the array for (int i = 0; i < n; i++) if (arr[i] < min) min = arr[i]; // vector to store indexes of occurrences // of minimum element in the array vector<int> indexes; // store indexes of occurrences // of minimum element in the array for (int i = 0; i < n; i++) if (arr[i] == min) indexes.push_back(i); // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.size() < 2) return -1; int min_dist = INT_MAX; // calculate minimum difference between // any two consecutive indexes for (int i = 1; i < indexes.size(); i++) if ((indexes[i] - indexes[i - 1]) < min_dist) min_dist = (indexes[i] - indexes[i - 1]); return min_dist;} // Driver codeint main(){ int arr[] = { 5, 1, 2, 3, 4, 1, 2, 1 }; int size = sizeof(arr) / sizeof(arr[0]); cout << findClosestMin(arr, size); return 0;} // Java program to find Distance between// two closest minimumimport java.util.Vector; class GFG { // function to find Distance between// two closest minimum static int findClosestMin(int arr[], int n) { int min = Integer.MAX_VALUE; // find the min element in the array for (int i = 0; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } // vector to store indexes of occurrences // of minimum element in the array Vector<Integer> indexes = new Vector<>(); // store indexes of occurrences // of minimum element in the array for (int i = 0; i < n; i++) { if (arr[i] == min) { indexes.add(i); } } // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.size() < 2) { return -1; } int min_dist = Integer.MAX_VALUE; // calculate minimum difference between // any two consecutive indexes for (int i = 1; i < indexes.size(); i++) { if ((indexes.get(i) - indexes.get(i - 1)) < min_dist) { min_dist = (indexes.get(i) - indexes.get(i - 1)); } } return min_dist; } // Driver code public static void main(String args[]) { int arr[] = {5, 1, 2, 3, 4, 1, 2, 1}; int size = arr.length; System.out.println(findClosestMin(arr, size)); }} // This code is contributed by PrinciRaj19992 # Python3 program to find Distance# between two closest minimumimport sys # function to find Distance between# two closest minimumdef findClosestMin(arr, n): #assigning maximum value in python min = sys.maxsize for i in range(0, n): if (arr[i] < min): min = arr[i] # list in python to store indexes # of occurrences of minimum element # in the array indexes = [] # store indexes of occurrences # of minimum element in the array for i in range(0, n): if (arr[i] == min): indexes.append(i) # if minimum element doesnot occurs # atleast two times, return -1. if (len(indexes) < 2): return -1 min_dist = sys.maxsize # calculate minimum difference between # any two consecutive indexes for i in range(1, len(indexes)): if ((indexes[i] - indexes[i - 1]) < min_dist): min_dist = (indexes[i] - indexes[i - 1]); return min_dist; # Driver codearr = [ 5, 1, 2, 3, 4, 1, 2, 1 ]ans = findClosestMin(arr, 8)print (ans) # This code is contributed by saloni1297. // C# program to find Distance between// two closest minimumusing System;using System.Collections.Generic;public class GFG { // function to find Distance between// two closest minimum static int findClosestMin(int []arr, int n) { int min = int.MaxValue; // find the min element in the array for (int i = 0; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } // vector to store indexes of occurrences // of minimum element in the array List<int> indexes = new List<int>(); // store indexes of occurrences // of minimum element in the array for (int i = 0; i < n; i++) { if (arr[i] == min) { indexes.Add(i); } } // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.Count < 2) { return -1; } int min_dist = int.MaxValue; // calculate minimum difference between // any two consecutive indexes for (int i = 1; i < indexes.Count; i++) { if ((indexes[i] - indexes[i-1]) < min_dist) { min_dist = (indexes[i] - indexes[i-1]); } } return min_dist; } // Driver code public static void Main() { int []arr = {5, 1, 2, 3, 4, 1, 2, 1}; int size = arr.Length; Console.WriteLine(findClosestMin(arr, size)); }} // This code is contributed by PrinciRaj19992 <?php// Php program to find Distance between// two closest minimum // function to find Distance between// two closest minimumfunction findClosestMin($arr, $n){ $min = PHP_INT_MAX; # find the min element in the array for ($i = 0; $i < $n; $i++) if ($arr[$i] < $min) $min = $arr[$i]; // vector to store indexes of occurrences // of minimum element in the array $indexes = array() ; // store indexes of occurrences // of minimum element in the array for ($i = 0; $i < $n; $i++) if ($arr[$i] == $min) array_push($indexes, $i); // if minimum element doesnot occurs atleast // two times, return -1. if (sizeof($indexes) < 2) return -1; $min_dist = PHP_INT_MAX; // calculate minimum difference between // any two consecutive indexes for ($i = 1; $i < sizeof($indexes); $i++) if (($indexes[$i] - $indexes[$i - 1]) < $min_dist) $min_dist = ($indexes[$i] - $indexes[$i - 1]); return $min_dist;} // Driver code$arr = array( 5, 1, 2, 3, 4, 1, 2, 1 );$size = sizeof($arr);echo findClosestMin($arr, $size); // This code is contributed by Ryuga?> <script> // Javascript program to find Distance between two closest minimum // function to find Distance between // two closest minimum function findClosestMin(arr, n) { let min = Number.MAX_VALUE; // find the min element in the array for (let i = 0; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } // vector to store indexes of occurrences // of minimum element in the array let indexes = []; // store indexes of occurrences // of minimum element in the array for (let i = 0; i < n; i++) { if (arr[i] == min) { indexes.push(i); } } // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.length < 2) { return -1; } let min_dist = Number.MAX_VALUE; // calculate minimum difference between // any two consecutive indexes for (let i = 1; i < indexes.length; i++) { if ((indexes[i] - indexes[i-1]) < min_dist) { min_dist = (indexes[i] - indexes[i-1]); } } return min_dist; } let arr = [5, 1, 2, 3, 4, 1, 2, 1]; let size = arr.length; document.write(findClosestMin(arr, size)); // This code is contributed by suresh07.</script> Output: 2 Time Complexity: O(n) Auxiliary Space: O(n) princiraj1992 ankthon suresh07 Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find a triplet that sum to a given value Find subarray with given sum | Set 1 (Nonnegative Numbers) Find duplicates in O(n) time and O(1) extra space | Set 1 Remove duplicates from sorted array Move all negative numbers to beginning and positive to end with constant extra space
[ { "code": null, "e": 26065, "s": 26037, "text": "\n31 May, 2021" }, { "code": null, "e": 26197, "s": 26065, "text": "Given an array of n integers. Find the minimum distance between any two occurrences of the minimum integer in the array.Examples: " }, { "code": null, "e": 26416, "s": 26197, "text": "Input : arr[] = {5, 1, 2, 3, 4, 1, 2, 1}\nOutput : 2\nExplanation: The minimum element 1 occurs at \n indexes: 1, 5 and 7. So the minimum\n distance is 7-5 = 2.\n\nInput : arr[] = {1, 2, 1}\nOutput : 2" }, { "code": null, "e": 26951, "s": 26418, "text": "Brute Force Approach: The simplest approach is to find all pair of indexes of minimum element and calculate minimum distance. Time Complexity: O(n^2), where n is the total number of elements in the array.Efficient Approach: An efficient approach will be to observe that distance between index j and i will always be smaller than distance between indexes k and i where, k is greater than j. That is we only have to check distance between consecutive pairs of minimum elements and not all pairs. Below is the step by step algorithm: " }, { "code": null, "e": 26989, "s": 26951, "text": "Find the minimum element in the array" }, { "code": null, "e": 27099, "s": 26989, "text": "Find all occurrences of minimum element in the array and insert the indexes in a new array or list or vector." }, { "code": null, "e": 27234, "s": 27099, "text": "Check if size of the list of indexes is greater than one or not, i.e. the minimum element occurs atleast twice. If not than return -1." }, { "code": null, "e": 27337, "s": 27234, "text": "Traverse the list of indexes and calculate the minimum difference between any two consecutive indexes." }, { "code": null, "e": 27382, "s": 27337, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 27386, "s": 27382, "text": "C++" }, { "code": null, "e": 27391, "s": 27386, "text": "Java" }, { "code": null, "e": 27399, "s": 27391, "text": "Python3" }, { "code": null, "e": 27402, "s": 27399, "text": "C#" }, { "code": null, "e": 27406, "s": 27402, "text": "PHP" }, { "code": null, "e": 27417, "s": 27406, "text": "Javascript" }, { "code": "// CPP program to find Distance between// two closest minimum#include <iostream>#include <limits.h>#include <vector> using namespace std; // function to find Distance between// two closest minimumint findClosestMin(int arr[], int n){ int min = INT_MAX; // find the min element in the array for (int i = 0; i < n; i++) if (arr[i] < min) min = arr[i]; // vector to store indexes of occurrences // of minimum element in the array vector<int> indexes; // store indexes of occurrences // of minimum element in the array for (int i = 0; i < n; i++) if (arr[i] == min) indexes.push_back(i); // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.size() < 2) return -1; int min_dist = INT_MAX; // calculate minimum difference between // any two consecutive indexes for (int i = 1; i < indexes.size(); i++) if ((indexes[i] - indexes[i - 1]) < min_dist) min_dist = (indexes[i] - indexes[i - 1]); return min_dist;} // Driver codeint main(){ int arr[] = { 5, 1, 2, 3, 4, 1, 2, 1 }; int size = sizeof(arr) / sizeof(arr[0]); cout << findClosestMin(arr, size); return 0;}", "e": 28632, "s": 27417, "text": null }, { "code": "// Java program to find Distance between// two closest minimumimport java.util.Vector; class GFG { // function to find Distance between// two closest minimum static int findClosestMin(int arr[], int n) { int min = Integer.MAX_VALUE; // find the min element in the array for (int i = 0; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } // vector to store indexes of occurrences // of minimum element in the array Vector<Integer> indexes = new Vector<>(); // store indexes of occurrences // of minimum element in the array for (int i = 0; i < n; i++) { if (arr[i] == min) { indexes.add(i); } } // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.size() < 2) { return -1; } int min_dist = Integer.MAX_VALUE; // calculate minimum difference between // any two consecutive indexes for (int i = 1; i < indexes.size(); i++) { if ((indexes.get(i) - indexes.get(i - 1)) < min_dist) { min_dist = (indexes.get(i) - indexes.get(i - 1)); } } return min_dist; } // Driver code public static void main(String args[]) { int arr[] = {5, 1, 2, 3, 4, 1, 2, 1}; int size = arr.length; System.out.println(findClosestMin(arr, size)); }} // This code is contributed by PrinciRaj19992", "e": 30135, "s": 28632, "text": null }, { "code": "# Python3 program to find Distance# between two closest minimumimport sys # function to find Distance between# two closest minimumdef findClosestMin(arr, n): #assigning maximum value in python min = sys.maxsize for i in range(0, n): if (arr[i] < min): min = arr[i] # list in python to store indexes # of occurrences of minimum element # in the array indexes = [] # store indexes of occurrences # of minimum element in the array for i in range(0, n): if (arr[i] == min): indexes.append(i) # if minimum element doesnot occurs # atleast two times, return -1. if (len(indexes) < 2): return -1 min_dist = sys.maxsize # calculate minimum difference between # any two consecutive indexes for i in range(1, len(indexes)): if ((indexes[i] - indexes[i - 1]) < min_dist): min_dist = (indexes[i] - indexes[i - 1]); return min_dist; # Driver codearr = [ 5, 1, 2, 3, 4, 1, 2, 1 ]ans = findClosestMin(arr, 8)print (ans) # This code is contributed by saloni1297.", "e": 31219, "s": 30135, "text": null }, { "code": " // C# program to find Distance between// two closest minimumusing System;using System.Collections.Generic;public class GFG { // function to find Distance between// two closest minimum static int findClosestMin(int []arr, int n) { int min = int.MaxValue; // find the min element in the array for (int i = 0; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } // vector to store indexes of occurrences // of minimum element in the array List<int> indexes = new List<int>(); // store indexes of occurrences // of minimum element in the array for (int i = 0; i < n; i++) { if (arr[i] == min) { indexes.Add(i); } } // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.Count < 2) { return -1; } int min_dist = int.MaxValue; // calculate minimum difference between // any two consecutive indexes for (int i = 1; i < indexes.Count; i++) { if ((indexes[i] - indexes[i-1]) < min_dist) { min_dist = (indexes[i] - indexes[i-1]); } } return min_dist; } // Driver code public static void Main() { int []arr = {5, 1, 2, 3, 4, 1, 2, 1}; int size = arr.Length; Console.WriteLine(findClosestMin(arr, size)); }} // This code is contributed by PrinciRaj19992", "e": 32710, "s": 31219, "text": null }, { "code": "<?php// Php program to find Distance between// two closest minimum // function to find Distance between// two closest minimumfunction findClosestMin($arr, $n){ $min = PHP_INT_MAX; # find the min element in the array for ($i = 0; $i < $n; $i++) if ($arr[$i] < $min) $min = $arr[$i]; // vector to store indexes of occurrences // of minimum element in the array $indexes = array() ; // store indexes of occurrences // of minimum element in the array for ($i = 0; $i < $n; $i++) if ($arr[$i] == $min) array_push($indexes, $i); // if minimum element doesnot occurs atleast // two times, return -1. if (sizeof($indexes) < 2) return -1; $min_dist = PHP_INT_MAX; // calculate minimum difference between // any two consecutive indexes for ($i = 1; $i < sizeof($indexes); $i++) if (($indexes[$i] - $indexes[$i - 1]) < $min_dist) $min_dist = ($indexes[$i] - $indexes[$i - 1]); return $min_dist;} // Driver code$arr = array( 5, 1, 2, 3, 4, 1, 2, 1 );$size = sizeof($arr);echo findClosestMin($arr, $size); // This code is contributed by Ryuga?>", "e": 33897, "s": 32710, "text": null }, { "code": "<script> // Javascript program to find Distance between two closest minimum // function to find Distance between // two closest minimum function findClosestMin(arr, n) { let min = Number.MAX_VALUE; // find the min element in the array for (let i = 0; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } // vector to store indexes of occurrences // of minimum element in the array let indexes = []; // store indexes of occurrences // of minimum element in the array for (let i = 0; i < n; i++) { if (arr[i] == min) { indexes.push(i); } } // if minimum element doesnot occurs atleast // two times, return -1. if (indexes.length < 2) { return -1; } let min_dist = Number.MAX_VALUE; // calculate minimum difference between // any two consecutive indexes for (let i = 1; i < indexes.length; i++) { if ((indexes[i] - indexes[i-1]) < min_dist) { min_dist = (indexes[i] - indexes[i-1]); } } return min_dist; } let arr = [5, 1, 2, 3, 4, 1, 2, 1]; let size = arr.length; document.write(findClosestMin(arr, size)); // This code is contributed by suresh07.</script>", "e": 35286, "s": 33897, "text": null }, { "code": null, "e": 35296, "s": 35286, "text": "Output: " }, { "code": null, "e": 35298, "s": 35296, "text": "2" }, { "code": null, "e": 35343, "s": 35298, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 35357, "s": 35343, "text": "princiraj1992" }, { "code": null, "e": 35365, "s": 35357, "text": "ankthon" }, { "code": null, "e": 35374, "s": 35365, "text": "suresh07" }, { "code": null, "e": 35381, "s": 35374, "text": "Arrays" }, { "code": null, "e": 35388, "s": 35381, "text": "Arrays" }, { "code": null, "e": 35486, "s": 35388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35517, "s": 35486, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35544, "s": 35517, "text": "Count pairs with given sum" }, { "code": null, "e": 35569, "s": 35544, "text": "Window Sliding Technique" }, { "code": null, "e": 35607, "s": 35569, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35628, "s": 35607, "text": "Next Greater Element" }, { "code": null, "e": 35669, "s": 35628, "text": "Find a triplet that sum to a given value" }, { "code": null, "e": 35728, "s": 35669, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 35786, "s": 35728, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 35822, "s": 35786, "text": "Remove duplicates from sorted array" } ]
How to create a constant matrix in Python with NumPy? - GeeksforGeeks
17 Dec, 2020 A matrix represents a collection of numbers arranged in the order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. A constant matrix is a type of matrix whose elements are the same i.e. the element does not change irrespective of any index value thus acting as a constant. Examples: M = [[ x, x, x ] [ x ,x ,x] [ x, x, x]] Here M is the constant matrix and x is the constant element. Below are some examples of Constant Matrix: A = [[ 5 , 5] [ 5, 5]] B = [[ 12, 12, 12, 12, 12, 12]] There are various methods in numpy module, which can be used to create a constant matrix such as numpy.full(), numpy.ones(), and numpy.zeroes(). Syntax: numpy.full(shape, fill_value, dtype = None, order = ‘C’) Parameters: shape: Number of rows order: C_contiguous or F_contiguous dtype: [optional, float(by Default)] Data type of returned array. fill_value: [bool, optional] Value to fill in the array. Returns: ndarray of a given constant having given shape, order and datatype. Example 1: Here, we will create a constant matrix of size (2,2) (rows = 2, column = 2) with a constant value of 6.3 Python3 # import required moduleimport numpy as np # use full() with a# constant value of 6.3array = np.full((2, 2), 6.3) # display matrixprint(array) Output: [[6.3 6.3] [6.3 6.3]] Example 2: A similar example to the one showed above Python3 # import required moduleimport numpy as np # use full() with a# constant value of 60array = np.full((4, 3), 60) # display matrixprint(array) Output: [[60 60 60] [60 60 60] [60 60 60] [60 60 60]] Syntax: numpy.ones(shape, dtype = None, order = ‘C’) Parameters: shape: integer or sequence of integers order: C_contiguous or F_contiguous dtype: Data type of returned array. Returns: ndarray of ones having given shape, order and datatype. Example 1: Now, suppose we want to print a matrix consisting of only ones(1s). Python3 # import required moduleimport numpy as np # use ones() array = np.ones((2,2)) # display matrixprint(array) Output: [[1. 1.] [1. 1.]] Here by-default, the data type is float, hence all the numbers are written as 1. An alteration, to the above code. Now, we want the data type to be of an integer. Python3 # import required moduleimport numpy as np # use ones() with integer constantarray = np.ones((2, 2), dtype=np.uint8) # display matrixprint(array) Output: [[1 1] [1 1]] Notice the change in the last two outputs, one of them shows, 1. And the other is showing 1 only, which means we converted the data type to integer in the second one. uint8 stands for an unsigned 8-bit integer which can represent values ranging from 0 to 255. Example 2: Here we create a one-dimensional matrix of only 1s. Python3 # import required moduleimport numpy as np # use ones() with integer constantarray = np.ones((5), dtype=np.uint8) # display matrixprint(array) Output: [1 1 1 1 1] Syntax: numpy.zeros(shape, dtype = None, order = ‘C’) Parameters: shape: integer or sequence of integers order: C_contiguous or F_contiguous dtype: Data type of returned array. Returns: ndarray of zeros having given shape, order and datatype. Example 1: Now that we made a matrix of ones, let’s make one for zeroes. Python3 # import required moduleimport numpy as np # use zeroes()array = np.zeros((2,2)) # display matrixprint(array) Output: [[0. 0.] [0. 0.]] To change it to an integer type, Python3 # import required moduleimport numpy as np # use zeroes() with integer constantarray = np.zeros((2,2), dtype=np.uint8) # display matrixprint(array) Output: [[0 0] [0 0]] Example 2: Here is another example to create a constant one-dimensional matrix of zeroes. Python3 # import required moduleimport numpy as np # use zeroes() with integer constantarray = np.zeros((5), dtype=np.uint8) # display matrixprint(array) Output: [0 0 0 0 0] Picked Python numpy-arrayCreation Python numpy-Matrix Function 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 | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Dec, 2020" }, { "code": null, "e": 25862, "s": 25537, "text": "A matrix represents a collection of numbers arranged in the order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. A constant matrix is a type of matrix whose elements are the same i.e. the element does not change irrespective of any index value thus acting as a constant." }, { "code": null, "e": 25872, "s": 25862, "text": "Examples:" }, { "code": null, "e": 25889, "s": 25872, "text": "M = [[ x, x, x ]" }, { "code": null, "e": 25907, "s": 25889, "text": " [ x ,x ,x]" }, { "code": null, "e": 25925, "s": 25907, "text": " [ x, x, x]]" }, { "code": null, "e": 25986, "s": 25925, "text": "Here M is the constant matrix and x is the constant element." }, { "code": null, "e": 26030, "s": 25986, "text": "Below are some examples of Constant Matrix:" }, { "code": null, "e": 26044, "s": 26030, "text": "A = [[ 5 , 5]" }, { "code": null, "e": 26060, "s": 26044, "text": " [ 5, 5]]" }, { "code": null, "e": 26092, "s": 26060, "text": "B = [[ 12, 12, 12, 12, 12, 12]]" }, { "code": null, "e": 26237, "s": 26092, "text": "There are various methods in numpy module, which can be used to create a constant matrix such as numpy.full(), numpy.ones(), and numpy.zeroes()." }, { "code": null, "e": 26245, "s": 26237, "text": "Syntax:" }, { "code": null, "e": 26303, "s": 26245, "text": "numpy.full(shape, fill_value, dtype = None, order = ‘C’) " }, { "code": null, "e": 26315, "s": 26303, "text": "Parameters:" }, { "code": null, "e": 26338, "s": 26315, "text": "shape: Number of rows " }, { "code": null, "e": 26375, "s": 26338, "text": "order: C_contiguous or F_contiguous " }, { "code": null, "e": 26444, "s": 26375, "text": "dtype: [optional, float(by Default)] Data type of returned array. " }, { "code": null, "e": 26501, "s": 26444, "text": "fill_value: [bool, optional] Value to fill in the array." }, { "code": null, "e": 26579, "s": 26501, "text": "Returns: ndarray of a given constant having given shape, order and datatype." }, { "code": null, "e": 26591, "s": 26579, "text": "Example 1: " }, { "code": null, "e": 26696, "s": 26591, "text": "Here, we will create a constant matrix of size (2,2) (rows = 2, column = 2) with a constant value of 6.3" }, { "code": null, "e": 26704, "s": 26696, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use full() with a# constant value of 6.3array = np.full((2, 2), 6.3) # display matrixprint(array)", "e": 26849, "s": 26704, "text": null }, { "code": null, "e": 26857, "s": 26849, "text": "Output:" }, { "code": null, "e": 26880, "s": 26857, "text": "[[6.3 6.3]\n [6.3 6.3]]" }, { "code": null, "e": 26891, "s": 26880, "text": "Example 2:" }, { "code": null, "e": 26933, "s": 26891, "text": "A similar example to the one showed above" }, { "code": null, "e": 26941, "s": 26933, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use full() with a# constant value of 60array = np.full((4, 3), 60) # display matrixprint(array)", "e": 27084, "s": 26941, "text": null }, { "code": null, "e": 27092, "s": 27084, "text": "Output:" }, { "code": null, "e": 27141, "s": 27092, "text": "[[60 60 60]\n [60 60 60]\n [60 60 60]\n [60 60 60]]" }, { "code": null, "e": 27149, "s": 27141, "text": "Syntax:" }, { "code": null, "e": 27195, "s": 27149, "text": "numpy.ones(shape, dtype = None, order = ‘C’) " }, { "code": null, "e": 27207, "s": 27195, "text": "Parameters:" }, { "code": null, "e": 27246, "s": 27207, "text": "shape: integer or sequence of integers" }, { "code": null, "e": 27282, "s": 27246, "text": "order: C_contiguous or F_contiguous" }, { "code": null, "e": 27318, "s": 27282, "text": "dtype: Data type of returned array." }, { "code": null, "e": 27383, "s": 27318, "text": "Returns: ndarray of ones having given shape, order and datatype." }, { "code": null, "e": 27394, "s": 27383, "text": "Example 1:" }, { "code": null, "e": 27462, "s": 27394, "text": "Now, suppose we want to print a matrix consisting of only ones(1s)." }, { "code": null, "e": 27470, "s": 27462, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use ones() array = np.ones((2,2)) # display matrixprint(array)", "e": 27581, "s": 27470, "text": null }, { "code": null, "e": 27590, "s": 27581, "text": "Output: " }, { "code": null, "e": 27609, "s": 27590, "text": "[[1. 1.]\n [1. 1.]]" }, { "code": null, "e": 27772, "s": 27609, "text": "Here by-default, the data type is float, hence all the numbers are written as 1. An alteration, to the above code. Now, we want the data type to be of an integer." }, { "code": null, "e": 27780, "s": 27772, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use ones() with integer constantarray = np.ones((2, 2), dtype=np.uint8) # display matrixprint(array)", "e": 27928, "s": 27780, "text": null }, { "code": null, "e": 27936, "s": 27928, "text": "Output:" }, { "code": null, "e": 27951, "s": 27936, "text": "[[1 1]\n [1 1]]" }, { "code": null, "e": 28211, "s": 27951, "text": "Notice the change in the last two outputs, one of them shows, 1. And the other is showing 1 only, which means we converted the data type to integer in the second one. uint8 stands for an unsigned 8-bit integer which can represent values ranging from 0 to 255." }, { "code": null, "e": 28222, "s": 28211, "text": "Example 2:" }, { "code": null, "e": 28274, "s": 28222, "text": "Here we create a one-dimensional matrix of only 1s." }, { "code": null, "e": 28282, "s": 28274, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use ones() with integer constantarray = np.ones((5), dtype=np.uint8) # display matrixprint(array)", "e": 28427, "s": 28282, "text": null }, { "code": null, "e": 28435, "s": 28427, "text": "Output:" }, { "code": null, "e": 28447, "s": 28435, "text": "[1 1 1 1 1]" }, { "code": null, "e": 28455, "s": 28447, "text": "Syntax:" }, { "code": null, "e": 28501, "s": 28455, "text": "numpy.zeros(shape, dtype = None, order = ‘C’)" }, { "code": null, "e": 28513, "s": 28501, "text": "Parameters:" }, { "code": null, "e": 28552, "s": 28513, "text": "shape: integer or sequence of integers" }, { "code": null, "e": 28588, "s": 28552, "text": "order: C_contiguous or F_contiguous" }, { "code": null, "e": 28624, "s": 28588, "text": "dtype: Data type of returned array." }, { "code": null, "e": 28690, "s": 28624, "text": "Returns: ndarray of zeros having given shape, order and datatype." }, { "code": null, "e": 28701, "s": 28690, "text": "Example 1:" }, { "code": null, "e": 28763, "s": 28701, "text": "Now that we made a matrix of ones, let’s make one for zeroes." }, { "code": null, "e": 28771, "s": 28763, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use zeroes()array = np.zeros((2,2)) # display matrixprint(array)", "e": 28883, "s": 28771, "text": null }, { "code": null, "e": 28891, "s": 28883, "text": "Output:" }, { "code": null, "e": 28910, "s": 28891, "text": "[[0. 0.]\n [0. 0.]]" }, { "code": null, "e": 28943, "s": 28910, "text": "To change it to an integer type," }, { "code": null, "e": 28951, "s": 28943, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use zeroes() with integer constantarray = np.zeros((2,2), dtype=np.uint8) # display matrixprint(array)", "e": 29101, "s": 28951, "text": null }, { "code": null, "e": 29109, "s": 29101, "text": "Output:" }, { "code": null, "e": 29124, "s": 29109, "text": "[[0 0]\n [0 0]]" }, { "code": null, "e": 29135, "s": 29124, "text": "Example 2:" }, { "code": null, "e": 29214, "s": 29135, "text": "Here is another example to create a constant one-dimensional matrix of zeroes." }, { "code": null, "e": 29222, "s": 29214, "text": "Python3" }, { "code": "# import required moduleimport numpy as np # use zeroes() with integer constantarray = np.zeros((5), dtype=np.uint8) # display matrixprint(array)", "e": 29373, "s": 29222, "text": null }, { "code": null, "e": 29381, "s": 29373, "text": "Output:" }, { "code": null, "e": 29393, "s": 29381, "text": "[0 0 0 0 0]" }, { "code": null, "e": 29400, "s": 29393, "text": "Picked" }, { "code": null, "e": 29427, "s": 29400, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 29456, "s": 29427, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 29469, "s": 29456, "text": "Python-numpy" }, { "code": null, "e": 29476, "s": 29469, "text": "Python" }, { "code": null, "e": 29574, "s": 29476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29606, "s": 29574, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29648, "s": 29606, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29690, "s": 29648, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29746, "s": 29690, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29773, "s": 29746, "text": "Python Classes and Objects" }, { "code": null, "e": 29812, "s": 29773, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29843, "s": 29812, "text": "Python | os.path.join() method" }, { "code": null, "e": 29865, "s": 29843, "text": "Defaultdict in Python" }, { "code": null, "e": 29894, "s": 29865, "text": "Create a directory in Python" } ]
Flutter - Slider and RangeSlide - GeeksforGeeks
26 Nov, 2021 A slider is a widget to select a value from a given range in the application. We can slide through the value and select the desired value from it. We don’t need to install any dependency to implement a slider. A Range Slider is very similar to a Slider widget but instead of selecting a single value, we can select a continuous range of value from a given range. The slider widget can be implemented by simply using the slider widget and providing the range values. This widget takes two required parameters: value: Here we need to pass the default value whenever the app is launched and should be of type double.onChanged: This function is triggered whenever the slider value is changed are changed and we get a double value which we can use for further process. value: Here we need to pass the default value whenever the app is launched and should be of type double. onChanged: This function is triggered whenever the slider value is changed are changed and we get a double value which we can use for further process. Here is the syntax for Slider. Dart Slider( value: value, onChanged: (value) { },), RangeSlider widget is implemented by using the widget called RangeSlider. This widget takes two required parameters: values: Here we need to pass the RangeValues type of data which has a start and an end.onChanged: This function is triggered whenever the range values are changed and we get a RangeValue value. values: Here we need to pass the RangeValues type of data which has a start and an end. onChanged: This function is triggered whenever the range values are changed and we get a RangeValue value. Dart RangeSlider( values: RangeValues(start, end), onChanged: (value) {},) Example 1: Slider Widget Here we have created an age selector slider. The user can slide the slider and select a value. Dart import 'package:flutter/material.dart'; class SliderTutorial extends StatefulWidget { const SliderTutorial({Key? key, required this.title}) : super(key: key); final String title; @override _SliderTutorialState createState() => _SliderTutorialState();} class _SliderTutorialState extends State<SliderTutorial> { int age = 10; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Slider( label: "Select Age", value: age.toDouble(), onChanged: (value) { setState(() { age = value.toInt(); }); }, min: 5, max: 100, ), Text( "Your Age: " + age.toString(), style: const TextStyle( fontSize: 32.0, ), ), ], ), ); }} Output: Example 2: RangeSlider Widget In this example, we will implement the RangeSlider widget. We will need to create two double values, start and end respectively to implement the RangeSlider. Here is the code. Dart import 'package:flutter/material.dart'; class RangeSliderTutorial extends StatefulWidget { const RangeSliderTutorial({Key? key, required this.title}) : super(key: key); final String title; @override _RangeSliderTutorialState createState() => _RangeSliderTutorialState();} class _RangeSliderTutorialState extends State<RangeSliderTutorial> { double start = 30.0; double end = 50.0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ RangeSlider( values: RangeValues(start, end), labels: RangeLabels(start.toString(), end.toString()), onChanged: (value) { setState(() { start = value.start; end = value.end; }); }, min: 10.0, max: 80.0, ), Text( "Start: " + start.toStringAsFixed(2) + "\nEnd: " + end.toStringAsFixed(2), style: const TextStyle( fontSize: 32.0, ), ), ], ), ); }} Output: Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25261, "s": 25233, "text": "\n26 Nov, 2021" }, { "code": null, "e": 25471, "s": 25261, "text": "A slider is a widget to select a value from a given range in the application. We can slide through the value and select the desired value from it. We don’t need to install any dependency to implement a slider." }, { "code": null, "e": 25625, "s": 25471, "text": "A Range Slider is very similar to a Slider widget but instead of selecting a single value, we can select a continuous range of value from a given range. " }, { "code": null, "e": 25771, "s": 25625, "text": "The slider widget can be implemented by simply using the slider widget and providing the range values. This widget takes two required parameters:" }, { "code": null, "e": 26026, "s": 25771, "text": "value: Here we need to pass the default value whenever the app is launched and should be of type double.onChanged: This function is triggered whenever the slider value is changed are changed and we get a double value which we can use for further process." }, { "code": null, "e": 26131, "s": 26026, "text": "value: Here we need to pass the default value whenever the app is launched and should be of type double." }, { "code": null, "e": 26282, "s": 26131, "text": "onChanged: This function is triggered whenever the slider value is changed are changed and we get a double value which we can use for further process." }, { "code": null, "e": 26313, "s": 26282, "text": "Here is the syntax for Slider." }, { "code": null, "e": 26318, "s": 26313, "text": "Dart" }, { "code": "Slider( value: value, onChanged: (value) { },),", "e": 26373, "s": 26318, "text": null }, { "code": null, "e": 26490, "s": 26373, "text": "RangeSlider widget is implemented by using the widget called RangeSlider. This widget takes two required parameters:" }, { "code": null, "e": 26684, "s": 26490, "text": "values: Here we need to pass the RangeValues type of data which has a start and an end.onChanged: This function is triggered whenever the range values are changed and we get a RangeValue value." }, { "code": null, "e": 26772, "s": 26684, "text": "values: Here we need to pass the RangeValues type of data which has a start and an end." }, { "code": null, "e": 26879, "s": 26772, "text": "onChanged: This function is triggered whenever the range values are changed and we get a RangeValue value." }, { "code": null, "e": 26884, "s": 26879, "text": "Dart" }, { "code": "RangeSlider( values: RangeValues(start, end), onChanged: (value) {},)", "e": 26956, "s": 26884, "text": null }, { "code": null, "e": 26981, "s": 26956, "text": "Example 1: Slider Widget" }, { "code": null, "e": 27076, "s": 26981, "text": "Here we have created an age selector slider. The user can slide the slider and select a value." }, { "code": null, "e": 27081, "s": 27076, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class SliderTutorial extends StatefulWidget { const SliderTutorial({Key? key, required this.title}) : super(key: key); final String title; @override _SliderTutorialState createState() => _SliderTutorialState();} class _SliderTutorialState extends State<SliderTutorial> { int age = 10; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Slider( label: \"Select Age\", value: age.toDouble(), onChanged: (value) { setState(() { age = value.toInt(); }); }, min: 5, max: 100, ), Text( \"Your Age: \" + age.toString(), style: const TextStyle( fontSize: 32.0, ), ), ], ), ); }}", "e": 28076, "s": 27081, "text": null }, { "code": null, "e": 28084, "s": 28076, "text": "Output:" }, { "code": null, "e": 28114, "s": 28084, "text": "Example 2: RangeSlider Widget" }, { "code": null, "e": 28290, "s": 28114, "text": "In this example, we will implement the RangeSlider widget. We will need to create two double values, start and end respectively to implement the RangeSlider. Here is the code." }, { "code": null, "e": 28295, "s": 28290, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class RangeSliderTutorial extends StatefulWidget { const RangeSliderTutorial({Key? key, required this.title}) : super(key: key); final String title; @override _RangeSliderTutorialState createState() => _RangeSliderTutorialState();} class _RangeSliderTutorialState extends State<RangeSliderTutorial> { double start = 30.0; double end = 50.0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ RangeSlider( values: RangeValues(start, end), labels: RangeLabels(start.toString(), end.toString()), onChanged: (value) { setState(() { start = value.start; end = value.end; }); }, min: 10.0, max: 80.0, ), Text( \"Start: \" + start.toStringAsFixed(2) + \"\\nEnd: \" + end.toStringAsFixed(2), style: const TextStyle( fontSize: 32.0, ), ), ], ), ); }}", "e": 29521, "s": 28295, "text": null }, { "code": null, "e": 29529, "s": 29521, "text": "Output:" }, { "code": null, "e": 29545, "s": 29529, "text": "Flutter-widgets" }, { "code": null, "e": 29550, "s": 29545, "text": "Dart" }, { "code": null, "e": 29558, "s": 29550, "text": "Flutter" }, { "code": null, "e": 29656, "s": 29558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29695, "s": 29656, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29721, "s": 29695, "text": "ListView Class in Flutter" }, { "code": null, "e": 29747, "s": 29721, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 29770, "s": 29747, "text": "Flutter - Stack Widget" }, { "code": null, "e": 29788, "s": 29770, "text": "Flutter - Dialogs" }, { "code": null, "e": 29827, "s": 29788, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29844, "s": 29827, "text": "Flutter Tutorial" }, { "code": null, "e": 29870, "s": 29844, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 29893, "s": 29870, "text": "Flutter - Stack Widget" } ]
Change matplotlib line style in mid-graph - GeeksforGeeks
12 Nov, 2020 Prerequisite: Matplotlib In this article we will learn how to change line style in mid-graph using matplotlib in Python. Matplotlib: It is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002. Line style: Line style is a feature that describes in which fashion or style line is drawn. Following image shows the key that has to provided as input parameter and what line style it will produce: Approach: Import the matplotlib.pyplot library and other for data (optional)Import or create some dataDraw a graph plot with different line style is middle. Import the matplotlib.pyplot library and other for data (optional) Import or create some data Draw a graph plot with different line style is middle. Example 1: In this example we will use simple steps mentioned above and form a graph with two different line styles. Python3 # importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(0, 10, 100)y = 3 * x + 2 below = y < 15above = y >= 15 # Plot lines below as dotted-------plt.plot(x[below], y[below], '--') # Plot lines above as solid________plt.plot(x[above], y[above], '-') plt.show() Output : Example 2 : In this example we will use simple steps mentioned above and form a graph with two different line styles in one sine function. Python3 # importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(0, 10, 100)y = np.sin(x) below = y < .5above = y >= .5 # Plot lines below as dotted-------plt.plot(x[below], y[below], '--') # Plot lines above as solid_______plt.plot(x[above], y[above], '-') plt.show() Output : Example 3 : This is similar to above example with extra cosine function to show different feature of line styles in mid graph. Python3 # importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(0, 10, 100)y1 = np.sin(x)y2 = np.cos(x) below = abs(y1-y2) < .2above = abs(y1-y2) >= .2 # Plot lines below as dotted-------plt.plot(x[below], y1[below], 'r--') # Plot lines below as dotted-------plt.plot(x[below], y2[below], 'g--') # Plot lines above as solid_______plt.plot(x[above], y1[above], 'r-') # Plot lines above as solid_______plt.plot(x[above], y2[above], 'g-') plt.show() Output : Python-matplotlib 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 | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n12 Nov, 2020" }, { "code": null, "e": 25562, "s": 25537, "text": "Prerequisite: Matplotlib" }, { "code": null, "e": 25658, "s": 25562, "text": "In this article we will learn how to change line style in mid-graph using matplotlib in Python." }, { "code": null, "e": 25937, "s": 25658, "text": "Matplotlib: It is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002." }, { "code": null, "e": 26136, "s": 25937, "text": "Line style: Line style is a feature that describes in which fashion or style line is drawn. Following image shows the key that has to provided as input parameter and what line style it will produce:" }, { "code": null, "e": 26146, "s": 26136, "text": "Approach:" }, { "code": null, "e": 26293, "s": 26146, "text": "Import the matplotlib.pyplot library and other for data (optional)Import or create some dataDraw a graph plot with different line style is middle." }, { "code": null, "e": 26360, "s": 26293, "text": "Import the matplotlib.pyplot library and other for data (optional)" }, { "code": null, "e": 26387, "s": 26360, "text": "Import or create some data" }, { "code": null, "e": 26442, "s": 26387, "text": "Draw a graph plot with different line style is middle." }, { "code": null, "e": 26453, "s": 26442, "text": "Example 1:" }, { "code": null, "e": 26559, "s": 26453, "text": "In this example we will use simple steps mentioned above and form a graph with two different line styles." }, { "code": null, "e": 26567, "s": 26559, "text": "Python3" }, { "code": "# importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(0, 10, 100)y = 3 * x + 2 below = y < 15above = y >= 15 # Plot lines below as dotted-------plt.plot(x[below], y[below], '--') # Plot lines above as solid________plt.plot(x[above], y[above], '-') plt.show()", "e": 26876, "s": 26567, "text": null }, { "code": null, "e": 26885, "s": 26876, "text": "Output :" }, { "code": null, "e": 26897, "s": 26885, "text": "Example 2 :" }, { "code": null, "e": 27024, "s": 26897, "text": "In this example we will use simple steps mentioned above and form a graph with two different line styles in one sine function." }, { "code": null, "e": 27032, "s": 27024, "text": "Python3" }, { "code": "# importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(0, 10, 100)y = np.sin(x) below = y < .5above = y >= .5 # Plot lines below as dotted-------plt.plot(x[below], y[below], '--') # Plot lines above as solid_______plt.plot(x[above], y[above], '-') plt.show()", "e": 27340, "s": 27032, "text": null }, { "code": null, "e": 27349, "s": 27340, "text": "Output :" }, { "code": null, "e": 27361, "s": 27349, "text": "Example 3 :" }, { "code": null, "e": 27476, "s": 27361, "text": "This is similar to above example with extra cosine function to show different feature of line styles in mid graph." }, { "code": null, "e": 27484, "s": 27476, "text": "Python3" }, { "code": "# importing packagesimport matplotlib.pyplot as pltimport numpy as np # create datax = np.linspace(0, 10, 100)y1 = np.sin(x)y2 = np.cos(x) below = abs(y1-y2) < .2above = abs(y1-y2) >= .2 # Plot lines below as dotted-------plt.plot(x[below], y1[below], 'r--') # Plot lines below as dotted-------plt.plot(x[below], y2[below], 'g--') # Plot lines above as solid_______plt.plot(x[above], y1[above], 'r-') # Plot lines above as solid_______plt.plot(x[above], y2[above], 'g-') plt.show()", "e": 27973, "s": 27484, "text": null }, { "code": null, "e": 27982, "s": 27973, "text": "Output :" }, { "code": null, "e": 28000, "s": 27982, "text": "Python-matplotlib" }, { "code": null, "e": 28007, "s": 28000, "text": "Python" }, { "code": null, "e": 28105, "s": 28007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28137, "s": 28105, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28179, "s": 28137, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28221, "s": 28179, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28277, "s": 28221, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28304, "s": 28277, "text": "Python Classes and Objects" }, { "code": null, "e": 28343, "s": 28304, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28374, "s": 28343, "text": "Python | os.path.join() method" }, { "code": null, "e": 28403, "s": 28374, "text": "Create a directory in Python" }, { "code": null, "e": 28425, "s": 28403, "text": "Defaultdict in Python" } ]
Create your own secure Home Network using Pi-hole and Docker - GeeksforGeeks
16 Jul, 2021 Pi-hole is a Linux based web application, which is used as a shield from the unwanted advertisement in your network and also block the internet tracking system. This is very simple to use and best for home and small office networks. This is totally free and open-source. It also allows you to manage your accessibility and blocklist as well. It has a very decent graphical way of showing the network queries. Docker is a tool that works on containerization technology. This is used to launch containers for different requirements like a webserver, a DNS and many more. To know more about docker you check it out here on GeeksForGeeks and for launching your own web server on docker you could see it here. Step 1 Open your terminal and Start docker sudo systemctl start docker Enter the command to download pihole from docker hub sudo docker pull pihole/pihole Step 2: Skip this if you are not using Ubuntu sudo systemctl stop systemd-resolved.service sudo systemctl disable systemd-resolved.service Step 3 Change the DNS to something else like google sudo nano /etc/resolv.conf set DNS 8.8.8.8 and save. Step 4 Copy this code version: "3" services: pihole: container_name: pihole image: pihole/pihole:latest ports: - "53:53/tcp" - "53:53/udp" - "67:67/udp" - "80:80/tcp" - "443:443/tcp" environment: TZ: 'Asia/Kolkata' #this is the time zone volumes: - './etc-pihole/:/etc/pihole/' - './etc-dnsmasq.d/:/etc/dnsmasq.d/' dns: - 127.0.0.1 - 1.1.1.1 cap_add: - NET_ADMIN restart: unless-stopped Open a File sudo nano docker-compose.yml copy paste the above code here and save the file. Step4 Run the compose file to launch pihole sudo docker-compose up -d Step5 Move inside pihole container sudo docker exec -it pihole bash Change pihole password pihole -a -p exit Step7 Go to browser and search http://localhost/admin/ OR Use IP and copy-paste the IP to browser ifconfig Ip in browser pihole Step8 Login with the password That’s it all set. Go to dns setting in your windows... settings –> Network and Internet –> Ethernet (if you are connected to ethernet) or WiFi ( if your laptop connected to wifi) –> change adapter options –>right click on wifi or ethernet and go to properties –> select ipv4 –> properties –> change the DNS to the IP of pihole. WIFI settings Select IPv4 Change the DNS from obtain DNS automatically to Use following dns server and write the ip the box. In second you could write any dns like 8.8.8.8 Same Pi-hole IP can be used in the home router as DNS. lightningjay1 Computer Networks Linux-Unix Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. RSA Algorithm in Cryptography Differences between TCP and UDP TCP Server-Client implementation in C Data encryption standard (DES) | Set 1 Differences between IPv4 and IPv6 Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 25651, "s": 25623, "text": "\n16 Jul, 2021" }, { "code": null, "e": 26357, "s": 25651, "text": "Pi-hole is a Linux based web application, which is used as a shield from the unwanted advertisement in your network and also block the internet tracking system. This is very simple to use and best for home and small office networks. This is totally free and open-source. It also allows you to manage your accessibility and blocklist as well. It has a very decent graphical way of showing the network queries. Docker is a tool that works on containerization technology. This is used to launch containers for different requirements like a webserver, a DNS and many more. To know more about docker you check it out here on GeeksForGeeks and for launching your own web server on docker you could see it here. " }, { "code": null, "e": 26408, "s": 26363, "text": "Step 1 Open your terminal and Start docker " }, { "code": null, "e": 26436, "s": 26408, "text": "sudo systemctl start docker" }, { "code": null, "e": 26491, "s": 26436, "text": "Enter the command to download pihole from docker hub " }, { "code": null, "e": 26522, "s": 26491, "text": "sudo docker pull pihole/pihole" }, { "code": null, "e": 26570, "s": 26522, "text": "Step 2: Skip this if you are not using Ubuntu " }, { "code": null, "e": 26615, "s": 26570, "text": "sudo systemctl stop systemd-resolved.service" }, { "code": null, "e": 26666, "s": 26617, "text": "sudo systemctl disable systemd-resolved.service " }, { "code": null, "e": 26720, "s": 26666, "text": "Step 3 Change the DNS to something else like google " }, { "code": null, "e": 26747, "s": 26720, "text": "sudo nano /etc/resolv.conf" }, { "code": null, "e": 26774, "s": 26747, "text": "set DNS 8.8.8.8 and save. " }, { "code": null, "e": 26798, "s": 26774, "text": "Step 4 Copy this code " }, { "code": null, "e": 27266, "s": 26798, "text": "version: \"3\"\n\nservices:\n pihole:\n container_name: pihole\n image: pihole/pihole:latest\n ports:\n - \"53:53/tcp\"\n - \"53:53/udp\"\n - \"67:67/udp\"\n - \"80:80/tcp\"\n - \"443:443/tcp\"\n environment:\n TZ: 'Asia/Kolkata' #this is the time zone\n volumes:\n - './etc-pihole/:/etc/pihole/'\n - './etc-dnsmasq.d/:/etc/dnsmasq.d/'\n dns:\n - 127.0.0.1\n - 1.1.1.1\n cap_add:\n - NET_ADMIN\n restart: unless-stopped" }, { "code": null, "e": 27280, "s": 27266, "text": "Open a File " }, { "code": null, "e": 27309, "s": 27280, "text": "sudo nano docker-compose.yml" }, { "code": null, "e": 27360, "s": 27309, "text": "copy paste the above code here and save the file. " }, { "code": null, "e": 27405, "s": 27360, "text": "Step4 Run the compose file to launch pihole " }, { "code": null, "e": 27431, "s": 27405, "text": "sudo docker-compose up -d" }, { "code": null, "e": 27468, "s": 27431, "text": "Step5 Move inside pihole container " }, { "code": null, "e": 27501, "s": 27468, "text": "sudo docker exec -it pihole bash" }, { "code": null, "e": 27526, "s": 27501, "text": "Change pihole password " }, { "code": null, "e": 27539, "s": 27526, "text": "pihole -a -p" }, { "code": null, "e": 27546, "s": 27541, "text": "exit" }, { "code": null, "e": 27579, "s": 27546, "text": "Step7 Go to browser and search " }, { "code": null, "e": 27603, "s": 27579, "text": "http://localhost/admin/" }, { "code": null, "e": 27648, "s": 27603, "text": "OR Use IP and copy-paste the IP to browser " }, { "code": null, "e": 27657, "s": 27648, "text": "ifconfig" }, { "code": null, "e": 27680, "s": 27659, "text": "Ip in browser pihole" }, { "code": null, "e": 27712, "s": 27680, "text": "Step8 Login with the password " }, { "code": null, "e": 27733, "s": 27712, "text": "That’s it all set. " }, { "code": null, "e": 28059, "s": 27733, "text": "Go to dns setting in your windows... settings –> Network and Internet –> Ethernet (if you are connected to ethernet) or WiFi ( if your laptop connected to wifi) –> change adapter options –>right click on wifi or ethernet and go to properties –> select ipv4 –> properties –> change the DNS to the IP of pihole. WIFI settings " }, { "code": null, "e": 28073, "s": 28059, "text": "Select IPv4 " }, { "code": null, "e": 28221, "s": 28073, "text": "Change the DNS from obtain DNS automatically to Use following dns server and write the ip the box. In second you could write any dns like 8.8.8.8 " }, { "code": null, "e": 28277, "s": 28221, "text": "Same Pi-hole IP can be used in the home router as DNS. " }, { "code": null, "e": 28291, "s": 28277, "text": "lightningjay1" }, { "code": null, "e": 28309, "s": 28291, "text": "Computer Networks" }, { "code": null, "e": 28320, "s": 28309, "text": "Linux-Unix" }, { "code": null, "e": 28338, "s": 28320, "text": "Computer Networks" }, { "code": null, "e": 28436, "s": 28338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28466, "s": 28436, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 28498, "s": 28466, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28536, "s": 28498, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28575, "s": 28536, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 28609, "s": 28575, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 28649, "s": 28609, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 28689, "s": 28649, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 28716, "s": 28689, "text": "grep command in Unix/Linux" }, { "code": null, "e": 28751, "s": 28716, "text": "cut command in Linux with examples" } ]
Preventing Object Copy in C++ (3 Different Ways) - GeeksforGeeks
24 Sep, 2017 Many times, user wants that an instance of a C++ class should not be copied at all. So, the question is how do we achieve this ? There are three ways to achieve this : Keeping the Copy Constructor and Copy assignment operator as private in the class.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y): x(y) { }private: // Copy constructor Base(const Base& obj) : x(obj.x) { } // copy assignment operator Base& operator=(const Base& tmp_obj) { x = tmp_obj.x; return *this; }}; int main(){ Base b1(10); Base b2(b1); // calls copy constructor b2 = b1; // calls copy assignment operator return 0;}NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error.prog.cpp: In function 'int main()': prog.cpp:18:2: error: 'Base::Base(const Base&)' is private Base(const Base &obj) : x(obj.x) //Copy constructor ^ prog.cpp:33:12: error: within this context Base b2(b1); // Calls copy constructor ^ prog.cpp:22:8: error: 'Base& Base::operator=(const Base&)' is private Base& operator = (const Base& tmp_obj) // copy assignment operator ^ prog.cpp:35:5: error: within this context b2 = b1; // calls copy assignment operator ^ Inherit a Dummy class with a private copy constructor and a private copy assignment operator.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Dummy {public: Dummy() { }private: Dummy(const Dummy& temp_obj) { } Dummy& operator=(const Dummy& temp_obj) { }}; class Base : public Dummy { int x;public: Base() { } Base(int y) : x(y) { }}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()': prog.cpp:12:5: error: 'Dummy::Dummy(const Dummy&)' is private Dummy(const Dummy &temp_obj) ^ prog.cpp:22:7: error: within this context class Base: public Dummy ^ prog.cpp:16:12: error: 'Dummy& Dummy::operator=(const Dummy&)' is private Dummy& operator = (const Dummy &temp_obj) ^ prog.cpp:22:7: error: within this context class Base: public Dummy NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error.Using Deleted copy constructor and copy assignment operator: Above two ways are quite complex, C++11 has come up with a simpler solution i.e. just delete the copy constructor and assignment operator.Below is the C++ implementation to illustrate :// CPP program to demonstrate use Delete copy// constructor and delete assignment operator#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y) : x(y) { } Base(const Base& temp_obj) = delete; Base& operator=(const Base& temp_obj) = delete;}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()': prog.cpp:24:15: error: use of deleted function 'Base::Base(const Base&)' Base b2(b1); // Calls copy constructor ^ prog.cpp:16:5: note: declared here Base(const Base &temp_obj) = delete; ^ prog.cpp:26:8: error: use of deleted function 'Base& Base::operator=(const Base&)' b2 = b1; // Calls copy assignment operator ^ prog.cpp:17:11: note: declared here Base& operator = (const Base &temp_obj) = delete; ^ NOTE: This code does not work as we cannot copy the object of this class and hence it will show this error. Keeping the Copy Constructor and Copy assignment operator as private in the class.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y): x(y) { }private: // Copy constructor Base(const Base& obj) : x(obj.x) { } // copy assignment operator Base& operator=(const Base& tmp_obj) { x = tmp_obj.x; return *this; }}; int main(){ Base b1(10); Base b2(b1); // calls copy constructor b2 = b1; // calls copy assignment operator return 0;}NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error.prog.cpp: In function 'int main()': prog.cpp:18:2: error: 'Base::Base(const Base&)' is private Base(const Base &obj) : x(obj.x) //Copy constructor ^ prog.cpp:33:12: error: within this context Base b2(b1); // Calls copy constructor ^ prog.cpp:22:8: error: 'Base& Base::operator=(const Base&)' is private Base& operator = (const Base& tmp_obj) // copy assignment operator ^ prog.cpp:35:5: error: within this context b2 = b1; // calls copy assignment operator ^ Below is the C++ implementation to illustrate how this can be done. #include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y): x(y) { }private: // Copy constructor Base(const Base& obj) : x(obj.x) { } // copy assignment operator Base& operator=(const Base& tmp_obj) { x = tmp_obj.x; return *this; }}; int main(){ Base b1(10); Base b2(b1); // calls copy constructor b2 = b1; // calls copy assignment operator return 0;} NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error. prog.cpp: In function 'int main()': prog.cpp:18:2: error: 'Base::Base(const Base&)' is private Base(const Base &obj) : x(obj.x) //Copy constructor ^ prog.cpp:33:12: error: within this context Base b2(b1); // Calls copy constructor ^ prog.cpp:22:8: error: 'Base& Base::operator=(const Base&)' is private Base& operator = (const Base& tmp_obj) // copy assignment operator ^ prog.cpp:35:5: error: within this context b2 = b1; // calls copy assignment operator ^ Inherit a Dummy class with a private copy constructor and a private copy assignment operator.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Dummy {public: Dummy() { }private: Dummy(const Dummy& temp_obj) { } Dummy& operator=(const Dummy& temp_obj) { }}; class Base : public Dummy { int x;public: Base() { } Base(int y) : x(y) { }}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()': prog.cpp:12:5: error: 'Dummy::Dummy(const Dummy&)' is private Dummy(const Dummy &temp_obj) ^ prog.cpp:22:7: error: within this context class Base: public Dummy ^ prog.cpp:16:12: error: 'Dummy& Dummy::operator=(const Dummy&)' is private Dummy& operator = (const Dummy &temp_obj) ^ prog.cpp:22:7: error: within this context class Base: public Dummy NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error. Below is the C++ implementation to illustrate how this can be done. #include <iostream>using namespace std; class Dummy {public: Dummy() { }private: Dummy(const Dummy& temp_obj) { } Dummy& operator=(const Dummy& temp_obj) { }}; class Base : public Dummy { int x;public: Base() { } Base(int y) : x(y) { }}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;} prog.cpp: In function 'int main()': prog.cpp:12:5: error: 'Dummy::Dummy(const Dummy&)' is private Dummy(const Dummy &temp_obj) ^ prog.cpp:22:7: error: within this context class Base: public Dummy ^ prog.cpp:16:12: error: 'Dummy& Dummy::operator=(const Dummy&)' is private Dummy& operator = (const Dummy &temp_obj) ^ prog.cpp:22:7: error: within this context class Base: public Dummy NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error. Using Deleted copy constructor and copy assignment operator: Above two ways are quite complex, C++11 has come up with a simpler solution i.e. just delete the copy constructor and assignment operator.Below is the C++ implementation to illustrate :// CPP program to demonstrate use Delete copy// constructor and delete assignment operator#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y) : x(y) { } Base(const Base& temp_obj) = delete; Base& operator=(const Base& temp_obj) = delete;}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()': prog.cpp:24:15: error: use of deleted function 'Base::Base(const Base&)' Base b2(b1); // Calls copy constructor ^ prog.cpp:16:5: note: declared here Base(const Base &temp_obj) = delete; ^ prog.cpp:26:8: error: use of deleted function 'Base& Base::operator=(const Base&)' b2 = b1; // Calls copy assignment operator ^ prog.cpp:17:11: note: declared here Base& operator = (const Base &temp_obj) = delete; ^ NOTE: This code does not work as we cannot copy the object of this class and hence it will show this error. Below is the C++ implementation to illustrate : // CPP program to demonstrate use Delete copy// constructor and delete assignment operator#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y) : x(y) { } Base(const Base& temp_obj) = delete; Base& operator=(const Base& temp_obj) = delete;}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;} prog.cpp: In function 'int main()': prog.cpp:24:15: error: use of deleted function 'Base::Base(const Base&)' Base b2(b1); // Calls copy constructor ^ prog.cpp:16:5: note: declared here Base(const Base &temp_obj) = delete; ^ prog.cpp:26:8: error: use of deleted function 'Base& Base::operator=(const Base&)' b2 = b1; // Calls copy assignment operator ^ prog.cpp:17:11: note: declared here Base& operator = (const Base &temp_obj) = delete; ^ NOTE: This code does not work as we cannot copy the object of this class and hence it will show this error. Reference:https://ariya.io/2015/01/c-class-and-preventing-object-copy This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-advanced cpp-constructor C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Queue in C++ Standard Template Library (STL) Convert string to char array in C++
[ { "code": null, "e": 25367, "s": 25339, "text": "\n24 Sep, 2017" }, { "code": null, "e": 25496, "s": 25367, "text": "Many times, user wants that an instance of a C++ class should not be copied at all. So, the question is how do we achieve this ?" }, { "code": null, "e": 25535, "s": 25496, "text": "There are three ways to achieve this :" }, { "code": null, "e": 29123, "s": 25535, "text": "Keeping the Copy Constructor and Copy assignment operator as private in the class.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y): x(y) { }private: // Copy constructor Base(const Base& obj) : x(obj.x) { } // copy assignment operator Base& operator=(const Base& tmp_obj) { x = tmp_obj.x; return *this; }}; int main(){ Base b1(10); Base b2(b1); // calls copy constructor b2 = b1; // calls copy assignment operator return 0;}NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error.prog.cpp: In function 'int main()':\nprog.cpp:18:2: error: 'Base::Base(const Base&)' is private\n Base(const Base &obj) : x(obj.x) //Copy constructor\n ^\nprog.cpp:33:12: error: within this context\n Base b2(b1); // Calls copy constructor\n ^\nprog.cpp:22:8: error: 'Base& Base::operator=(const Base&)' is private\n Base& operator = (const Base& tmp_obj) // copy assignment operator\n ^\nprog.cpp:35:5: error: within this context\n b2 = b1; // calls copy assignment operator\n ^\nInherit a Dummy class with a private copy constructor and a private copy assignment operator.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Dummy {public: Dummy() { }private: Dummy(const Dummy& temp_obj) { } Dummy& operator=(const Dummy& temp_obj) { }}; class Base : public Dummy { int x;public: Base() { } Base(int y) : x(y) { }}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()':\n\nprog.cpp:12:5: error: \n'Dummy::Dummy(const Dummy&)' is private\n Dummy(const Dummy &temp_obj)\n ^\nprog.cpp:22:7: error: within this context\n class Base: public Dummy\n ^\nprog.cpp:16:12: error: \n'Dummy& Dummy::operator=(const Dummy&)' is private\n Dummy& operator = (const Dummy &temp_obj)\n ^\nprog.cpp:22:7: error: within this context\n class Base: public Dummy\nNOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error.Using Deleted copy constructor and copy assignment operator: Above two ways are quite complex, C++11 has come up with a simpler solution i.e. just delete the copy constructor and assignment operator.Below is the C++ implementation to illustrate :// CPP program to demonstrate use Delete copy// constructor and delete assignment operator#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y) : x(y) { } Base(const Base& temp_obj) = delete; Base& operator=(const Base& temp_obj) = delete;}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()':\nprog.cpp:24:15: error: use of deleted function\n 'Base::Base(const Base&)'\n Base b2(b1); // Calls copy constructor\n ^\nprog.cpp:16:5: note: declared here\n Base(const Base &temp_obj) = delete;\n ^\nprog.cpp:26:8: error: use of deleted function \n'Base& Base::operator=(const Base&)'\n b2 = b1; // Calls copy assignment operator\n ^\nprog.cpp:17:11: note: declared here\n Base& operator = (const Base &temp_obj) = delete;\n ^\nNOTE: This code does not work as we cannot copy the object of this class and hence it will show this error." }, { "code": null, "e": 30329, "s": 29123, "text": "Keeping the Copy Constructor and Copy assignment operator as private in the class.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y): x(y) { }private: // Copy constructor Base(const Base& obj) : x(obj.x) { } // copy assignment operator Base& operator=(const Base& tmp_obj) { x = tmp_obj.x; return *this; }}; int main(){ Base b1(10); Base b2(b1); // calls copy constructor b2 = b1; // calls copy assignment operator return 0;}NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error.prog.cpp: In function 'int main()':\nprog.cpp:18:2: error: 'Base::Base(const Base&)' is private\n Base(const Base &obj) : x(obj.x) //Copy constructor\n ^\nprog.cpp:33:12: error: within this context\n Base b2(b1); // Calls copy constructor\n ^\nprog.cpp:22:8: error: 'Base& Base::operator=(const Base&)' is private\n Base& operator = (const Base& tmp_obj) // copy assignment operator\n ^\nprog.cpp:35:5: error: within this context\n b2 = b1; // calls copy assignment operator\n ^\n" }, { "code": null, "e": 30397, "s": 30329, "text": "Below is the C++ implementation to illustrate how this can be done." }, { "code": "#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y): x(y) { }private: // Copy constructor Base(const Base& obj) : x(obj.x) { } // copy assignment operator Base& operator=(const Base& tmp_obj) { x = tmp_obj.x; return *this; }}; int main(){ Base b1(10); Base b2(b1); // calls copy constructor b2 = b1; // calls copy assignment operator return 0;}", "e": 30850, "s": 30397, "text": null }, { "code": null, "e": 30961, "s": 30850, "text": "NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error." }, { "code": null, "e": 31456, "s": 30961, "text": "prog.cpp: In function 'int main()':\nprog.cpp:18:2: error: 'Base::Base(const Base&)' is private\n Base(const Base &obj) : x(obj.x) //Copy constructor\n ^\nprog.cpp:33:12: error: within this context\n Base b2(b1); // Calls copy constructor\n ^\nprog.cpp:22:8: error: 'Base& Base::operator=(const Base&)' is private\n Base& operator = (const Base& tmp_obj) // copy assignment operator\n ^\nprog.cpp:35:5: error: within this context\n b2 = b1; // calls copy assignment operator\n ^\n" }, { "code": null, "e": 32551, "s": 31456, "text": "Inherit a Dummy class with a private copy constructor and a private copy assignment operator.Below is the C++ implementation to illustrate how this can be done.#include <iostream>using namespace std; class Dummy {public: Dummy() { }private: Dummy(const Dummy& temp_obj) { } Dummy& operator=(const Dummy& temp_obj) { }}; class Base : public Dummy { int x;public: Base() { } Base(int y) : x(y) { }}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()':\n\nprog.cpp:12:5: error: \n'Dummy::Dummy(const Dummy&)' is private\n Dummy(const Dummy &temp_obj)\n ^\nprog.cpp:22:7: error: within this context\n class Base: public Dummy\n ^\nprog.cpp:16:12: error: \n'Dummy& Dummy::operator=(const Dummy&)' is private\n Dummy& operator = (const Dummy &temp_obj)\n ^\nprog.cpp:22:7: error: within this context\n class Base: public Dummy\nNOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error." }, { "code": null, "e": 32619, "s": 32551, "text": "Below is the C++ implementation to illustrate how this can be done." }, { "code": "#include <iostream>using namespace std; class Dummy {public: Dummy() { }private: Dummy(const Dummy& temp_obj) { } Dummy& operator=(const Dummy& temp_obj) { }}; class Base : public Dummy { int x;public: Base() { } Base(int y) : x(y) { }}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}", "e": 33022, "s": 32619, "text": null }, { "code": null, "e": 33445, "s": 33022, "text": "prog.cpp: In function 'int main()':\n\nprog.cpp:12:5: error: \n'Dummy::Dummy(const Dummy&)' is private\n Dummy(const Dummy &temp_obj)\n ^\nprog.cpp:22:7: error: within this context\n class Base: public Dummy\n ^\nprog.cpp:16:12: error: \n'Dummy& Dummy::operator=(const Dummy&)' is private\n Dummy& operator = (const Dummy &temp_obj)\n ^\nprog.cpp:22:7: error: within this context\n class Base: public Dummy\n" }, { "code": null, "e": 33556, "s": 33445, "text": "NOTE: This code does not compile as we cannot copy the object of this class and hence it will show this error." }, { "code": null, "e": 34845, "s": 33556, "text": "Using Deleted copy constructor and copy assignment operator: Above two ways are quite complex, C++11 has come up with a simpler solution i.e. just delete the copy constructor and assignment operator.Below is the C++ implementation to illustrate :// CPP program to demonstrate use Delete copy// constructor and delete assignment operator#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y) : x(y) { } Base(const Base& temp_obj) = delete; Base& operator=(const Base& temp_obj) = delete;}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}prog.cpp: In function 'int main()':\nprog.cpp:24:15: error: use of deleted function\n 'Base::Base(const Base&)'\n Base b2(b1); // Calls copy constructor\n ^\nprog.cpp:16:5: note: declared here\n Base(const Base &temp_obj) = delete;\n ^\nprog.cpp:26:8: error: use of deleted function \n'Base& Base::operator=(const Base&)'\n b2 = b1; // Calls copy assignment operator\n ^\nprog.cpp:17:11: note: declared here\n Base& operator = (const Base &temp_obj) = delete;\n ^\nNOTE: This code does not work as we cannot copy the object of this class and hence it will show this error." }, { "code": null, "e": 34893, "s": 34845, "text": "Below is the C++ implementation to illustrate :" }, { "code": "// CPP program to demonstrate use Delete copy// constructor and delete assignment operator#include <iostream>using namespace std; class Base { int x;public: Base() { } Base(int y) : x(y) { } Base(const Base& temp_obj) = delete; Base& operator=(const Base& temp_obj) = delete;}; int main(){ Base b1(10); Base b2(b1); // Calls copy constructor b2 = b1; // Calls copy assignment operator return 0;}", "e": 35327, "s": 34893, "text": null }, { "code": null, "e": 35830, "s": 35327, "text": "prog.cpp: In function 'int main()':\nprog.cpp:24:15: error: use of deleted function\n 'Base::Base(const Base&)'\n Base b2(b1); // Calls copy constructor\n ^\nprog.cpp:16:5: note: declared here\n Base(const Base &temp_obj) = delete;\n ^\nprog.cpp:26:8: error: use of deleted function \n'Base& Base::operator=(const Base&)'\n b2 = b1; // Calls copy assignment operator\n ^\nprog.cpp:17:11: note: declared here\n Base& operator = (const Base &temp_obj) = delete;\n ^\n" }, { "code": null, "e": 35938, "s": 35830, "text": "NOTE: This code does not work as we cannot copy the object of this class and hence it will show this error." }, { "code": null, "e": 36008, "s": 35938, "text": "Reference:https://ariya.io/2015/01/c-class-and-preventing-object-copy" }, { "code": null, "e": 36312, "s": 36008, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 36437, "s": 36312, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36450, "s": 36437, "text": "cpp-advanced" }, { "code": null, "e": 36466, "s": 36450, "text": "cpp-constructor" }, { "code": null, "e": 36470, "s": 36466, "text": "C++" }, { "code": null, "e": 36474, "s": 36470, "text": "CPP" }, { "code": null, "e": 36572, "s": 36474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36600, "s": 36572, "text": "Operator Overloading in C++" }, { "code": null, "e": 36620, "s": 36600, "text": "Polymorphism in C++" }, { "code": null, "e": 36653, "s": 36620, "text": "Friend class and function in C++" }, { "code": null, "e": 36677, "s": 36653, "text": "Sorting a vector in C++" }, { "code": null, "e": 36702, "s": 36677, "text": "std::string class in C++" }, { "code": null, "e": 36746, "s": 36702, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 36770, "s": 36746, "text": "Inline Functions in C++" }, { "code": null, "e": 36823, "s": 36770, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 36868, "s": 36823, "text": "Queue in C++ Standard Template Library (STL)" } ]
Bootstrap - Forms
In this chapter, we will study how to create forms with ease using Bootstrap. Bootstrap makes it easy with the simple HTML markup and extended classes for different styles of forms. In this chapter we will study how to create forms with ease using Bootstrap. Bootstrap provides you with following types of form layouts − Vertical (default) form In-line form Horizontal form The basic form structure comes with Bootstrap; individual form controls automatically receive some global styling. To create a basic form do the following − Add a role form to the parent <form> element. Add a role form to the parent <form> element. Wrap labels and controls in a <div> with class .form-group. This is needed for optimum spacing. Wrap labels and controls in a <div> with class .form-group. This is needed for optimum spacing. Add a class of .form-control to all textual <input>, <textarea>, and <select> elements. Add a class of .form-control to all textual <input>, <textarea>, and <select> elements. <form role = "form"> <div class = "form-group"> <label for = "name">Name</label> <input type = "text" class = "form-control" id = "name" placeholder = "Enter Name"> </div> <div class = "form-group"> <label for = "inputfile">File input</label> <input type = "file" id = "inputfile"> <p class = "help-block">Example block-level help text here.</p> </div> <div class = "checkbox"> <label><input type = "checkbox"> Check me out</label> </div> <button type = "submit" class = "btn btn-default">Submit</button> </form> Example block-level help text here. To create a form where all of the elements are inline, left aligned and labels are alongside, add the class .form-inline to the <form> tag. <form class = "form-inline" role = "form"> <div class = "form-group"> <label class = "sr-only" for = "name">Name</label> <input type = "text" class = "form-control" id = "name" placeholder = "Enter Name"> </div> <div class = "form-group"> <label class = "sr-only" for = "inputfile">File input</label> <input type = "file" id = "inputfile"> </div> <div class = "checkbox"> <label><input type = "checkbox"> Check me out</label> </div> <button type = "submit" class = "btn btn-default">Submit</button> </form> By default inputs, selects, and textareas have 100% width in Bootstrap. You need to set a width on the form controls when using inline form. By default inputs, selects, and textareas have 100% width in Bootstrap. You need to set a width on the form controls when using inline form. Using the class .sr-only you can hide the labels of the inline forms. Using the class .sr-only you can hide the labels of the inline forms. Horizontal forms stands apart from the others not only in the amount of markup, but also in the presentation of the form. To create a form that uses the horizontal layout, do the following − Add a class of .form-horizontal to the parent <form> element. Add a class of .form-horizontal to the parent <form> element. Wrap labels and controls in a <div> with class .form-group. Wrap labels and controls in a <div> with class .form-group. Add a class of .control-label to the labels. Add a class of .control-label to the labels. <form class = "form-horizontal" role = "form"> <div class = "form-group"> <label for = "firstname" class = "col-sm-2 control-label">First Name</label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "firstname" placeholder = "Enter First Name"> </div> </div> <div class = "form-group"> <label for = "lastname" class = "col-sm-2 control-label">Last Name</label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "lastname" placeholder = "Enter Last Name"> </div> </div> <div class = "form-group"> <div class = "col-sm-offset-2 col-sm-10"> <div class = "checkbox"> <label><input type = "checkbox"> Remember me</label> </div> </div> </div> <div class = "form-group"> <div class = "col-sm-offset-2 col-sm-10"> <button type = "submit" class = "btn btn-default">Sign in</button> </div> </div> </form> Bootstrap natively supports the most common form controls mainly input, textarea, checkbox, radio, and select. The most common form text field is the input field. This is where users will enter most of the essential form data. Bootstrap offers support for all native HTML5 input types: text, password, datetime, datetime-local, date, month, time, week, number, email, url, search, tel, and color. Proper type declaration is required to make Inputs fully styled. <form role = "form"> <div class = "form-group"> <label for = "name">Label</label> <input type = "text" class = "form-control" placeholder = "Text input"> </div> </form> The textarea is used when you need multiple lines of input. Change rows attribute as necessary (fewer rows = smaller box, more rows = bigger box). <form role = "form"> <div class = "form-group"> <label for = "name">Text Area</label> <textarea class = "form-control" rows = "3"></textarea> </div> </form> Checkboxes and radio buttons are great when you want users to choose from a list of preset options. When building a form, use checkbox if you want the user to select any number of options from a list. Use radio if you want to limit the user to just one selection. When building a form, use checkbox if you want the user to select any number of options from a list. Use radio if you want to limit the user to just one selection. Use .checkbox-inline or .radio-inline class to a series of checkboxes or radios for controls appear on the same line. Use .checkbox-inline or .radio-inline class to a series of checkboxes or radios for controls appear on the same line. The following example demonstrates both (default and inline) types − <label for = "name">Example of Default Checkbox and radio button </label> <div class = "checkbox"> <label> <input type = "checkbox" value = "">Option 1 </label> </div> <div class = "checkbox"> <label> <input type = "checkbox" value = "">Option 2 </label> </div> <div class = "radio"> <label> <input type = "radio" name = "optionsRadios" id = "optionsRadios1" value = "option1" checked> Option 1 </label> </div> <div class = "radio"> <label> <input type = "radio" name = "optionsRadios" id = "optionsRadios2" value = "option2"> Option 2 - selecting it will deselect option 1 </label> </div> <label for = "name">Example of Inline Checkbox and radio button </label> <div> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox1" value = "option1"> Option 1 </label> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox2" value = "option2"> Option 2 </label> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox3" value = "option3"> Option 3 </label> <label class = "checkbox-inline"> <input type = "radio" name = "optionsRadiosinline" id = "optionsRadios3" value = "option1" checked> Option 1 </label> <label class = "checkbox-inline"> <input type = "radio" name = "optionsRadiosinline" id = "optionsRadios4" value = "option2"> Option 2 </label> </div> A select is used when you want to allow the user to pick from multiple options, but by default it only allows one. Use <select> for list options with which the user is familiar, such as states or numbers. Use <select> for list options with which the user is familiar, such as states or numbers. Use multiple = "multiple" to allow the users to select more than one option. Use multiple = "multiple" to allow the users to select more than one option. The following example demonstrates both (select and multiple) types − <form role = "form"> <div class = "form-group"> <label for = "name">Select list</label> <select class = "form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <label for = "name">Mutiple Select list</label> <select multiple class = "form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> </form> Use the class .form-control-static on a <p>, when you need to place plain text next to a form label within a horizontal form. <form class = "form-horizontal" role = "form"> <div class = "form-group"> <label class = "col-sm-2 control-label">Email</label> <div class = "col-sm-10"> <p class = "form-control-static">[email protected]</p> </div> </div> <div class = "form-group"> <label for = "inputPassword" class = "col-sm-2 control-label">Password</label> <div class = "col-sm-10"> <input type = "password" class = "form-control" id = "inputPassword" placeholder = "Password"> </div> </div> </form> [email protected] In addition to the :focus (i.e., a user clicks into the input or tabs onto it) state, Bootstrap offers styling for disabled inputs and classes for form validation. When an input receives :focus, the outline of the input is removed and a box-shadow is applied. If you need to disable an input, simply adding the disabled attribute will not only disable it; it will also change the styling and the mouse cursor when the cursor hovers over the element. Add the disabled attribute to a <fieldset> to disable all the controls within the <fieldset> at once. Bootstrap includes validation styles for errors, warnings, and success messages. To use, simply add the appropriate class (.has-warning, .has-error, or .has-success) to the parent element. The following example demonstrates all the form control states − <form class = "form-horizontal" role = "form"> <div class = "form-group"> <label class = "col-sm-2 control-label">Focused</label> <div class = "col-sm-10"> <input class = "form-control" id = "focusedInput" type = "text" value = "This is focused..."> </div> </div> <div class = "form-group"> <label for = "inputPassword" class = "col-sm-2 control-label"> Disabled </label> <div class = "col-sm-10"> <input class = "form-control" id = "disabledInput" type = "text" placeholder = "Disabled input here..." disabled> </div> </div> <fieldset disabled> <div class = "form-group"> <label for = "disabledTextInput" class = "col-sm-2 control-label"> Disabled input (Fieldset disabled) </label> <div class = "col-sm-10"> <input type = "text" id = "disabledTextInput" class = "form-control" placeholder = "Disabled input"> </div> </div> <div class = "form-group"> <label for = "disabledSelect" class = "col-sm-2 control-label"> Disabled select menu (Fieldset disabled) </label> <div class = "col-sm-10"> <select id = "disabledSelect" class = "form-control"> <option>Disabled select</option> </select> </div> </div> </fieldset> <div class = "form-group has-success"> <label class = "col-sm-2 control-label" for = "inputSuccess"> Input with success </label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "inputSuccess"> </div> </div> <div class = "form-group has-warning"> <label class = "col-sm-2 control-label" for = "inputWarning"> Input with warning </label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "inputWarning"> </div> </div> <div class = "form-group has-error"> <label class = "col-sm-2 control-label" for = "inputError"> Input with error </label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "inputError"> </div> </div> </form> You can set heights and widths of forms using classes like .input-lg and .col-lg-* respectively. The following example demonstrates this − <form role = "form"> <div class = "form-group"> <input class = "form-control input-lg" type = "text" placeholder =".input-lg"> </div> <div class = "form-group"> <input class = "form-control" type = "text" placeholder = "Default input"> </div> <div class = "form-group"> <input class = "form-control input-sm" type = "text" placeholder = ".input-sm"> </div> <div class = "form-group"></div> <div class = "form-group"> <select class = "form-control input-lg"> <option value = "">.input-lg</option> </select> </div> <div class = "form-group"> <select class = "form-control"> <option value = "">Default select</option> </select> </div> <div class = "form-group"> <select class = "form-control input-sm"> <option value = "">.input-sm</option> </select> </div> <div class = "row"> <div class = "col-lg-2"> <input type = "text" class = "form-control" placeholder = ".col-lg-2"> </div> <div class = "col-lg-3"> <input type = "text" class = "form-control" placeholder = ".col-lg-3"> </div> <div class = "col-lg-4"> <input type = "text" class = "form-control" placeholder = ".col-lg-4"> </div> </div> </form> Bootstrap form controls can have a block level help text that flows with the inputs. To add a full width block of content, use the .help-block after the <input>. The following example demonstrates this − <form role = "form"> <span>Example of Help Text</span> <input class = "form-control" type = "text" placeholder = ""> <span class = "help-block"> A longer block of help text that breaks onto a new line and may extend beyond one line. </span> </form> 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3590, "s": 3331, "text": "In this chapter, we will study how to create forms with ease using Bootstrap. Bootstrap makes it easy with the simple HTML markup and extended classes for different styles of forms. In this chapter we will study how to create forms with ease using Bootstrap." }, { "code": null, "e": 3652, "s": 3590, "text": "Bootstrap provides you with following types of form layouts −" }, { "code": null, "e": 3676, "s": 3652, "text": "Vertical (default) form" }, { "code": null, "e": 3689, "s": 3676, "text": "In-line form" }, { "code": null, "e": 3705, "s": 3689, "text": "Horizontal form" }, { "code": null, "e": 3862, "s": 3705, "text": "The basic form structure comes with Bootstrap; individual form controls automatically receive some global styling. To create a basic form do the following −" }, { "code": null, "e": 3908, "s": 3862, "text": "Add a role form to the parent <form> element." }, { "code": null, "e": 3954, "s": 3908, "text": "Add a role form to the parent <form> element." }, { "code": null, "e": 4050, "s": 3954, "text": "Wrap labels and controls in a <div> with class .form-group. This is needed for optimum spacing." }, { "code": null, "e": 4146, "s": 4050, "text": "Wrap labels and controls in a <div> with class .form-group. This is needed for optimum spacing." }, { "code": null, "e": 4234, "s": 4146, "text": "Add a class of .form-control to all textual <input>, <textarea>, and <select> elements." }, { "code": null, "e": 4322, "s": 4234, "text": "Add a class of .form-control to all textual <input>, <textarea>, and <select> elements." }, { "code": null, "e": 4905, "s": 4322, "text": "<form role = \"form\">\n\n <div class = \"form-group\">\n <label for = \"name\">Name</label>\n <input type = \"text\" class = \"form-control\" id = \"name\" placeholder = \"Enter Name\">\n </div>\n \n <div class = \"form-group\">\n <label for = \"inputfile\">File input</label>\n <input type = \"file\" id = \"inputfile\">\n <p class = \"help-block\">Example block-level help text here.</p>\n </div>\n \n <div class = \"checkbox\">\n <label><input type = \"checkbox\"> Check me out</label>\n </div>\n \n <button type = \"submit\" class = \"btn btn-default\">Submit</button>\n</form>" }, { "code": null, "e": 4941, "s": 4905, "text": "Example block-level help text here." }, { "code": null, "e": 5081, "s": 4941, "text": "To create a form where all of the elements are inline, left aligned and labels are alongside, add the class .form-inline to the <form> tag." }, { "code": null, "e": 5655, "s": 5081, "text": "<form class = \"form-inline\" role = \"form\">\n \n <div class = \"form-group\">\n <label class = \"sr-only\" for = \"name\">Name</label>\n <input type = \"text\" class = \"form-control\" id = \"name\" placeholder = \"Enter Name\">\n </div>\n \n <div class = \"form-group\">\n <label class = \"sr-only\" for = \"inputfile\">File input</label>\n <input type = \"file\" id = \"inputfile\">\n </div>\n \n <div class = \"checkbox\">\n <label><input type = \"checkbox\"> Check me out</label>\n </div>\n \n <button type = \"submit\" class = \"btn btn-default\">Submit</button>\n</form>" }, { "code": null, "e": 5796, "s": 5655, "text": "By default inputs, selects, and textareas have 100% width in Bootstrap. You need to set a width on the form controls when using inline form." }, { "code": null, "e": 5937, "s": 5796, "text": "By default inputs, selects, and textareas have 100% width in Bootstrap. You need to set a width on the form controls when using inline form." }, { "code": null, "e": 6007, "s": 5937, "text": "Using the class .sr-only you can hide the labels of the inline forms." }, { "code": null, "e": 6077, "s": 6007, "text": "Using the class .sr-only you can hide the labels of the inline forms." }, { "code": null, "e": 6268, "s": 6077, "text": "Horizontal forms stands apart from the others not only in the amount of markup, but also in the presentation of the form. To create a form that uses the horizontal layout, do the following −" }, { "code": null, "e": 6330, "s": 6268, "text": "Add a class of .form-horizontal to the parent <form> element." }, { "code": null, "e": 6392, "s": 6330, "text": "Add a class of .form-horizontal to the parent <form> element." }, { "code": null, "e": 6452, "s": 6392, "text": "Wrap labels and controls in a <div> with class .form-group." }, { "code": null, "e": 6512, "s": 6452, "text": "Wrap labels and controls in a <div> with class .form-group." }, { "code": null, "e": 6557, "s": 6512, "text": "Add a class of .control-label to the labels." }, { "code": null, "e": 6602, "s": 6557, "text": "Add a class of .control-label to the labels." }, { "code": null, "e": 7614, "s": 6602, "text": "<form class = \"form-horizontal\" role = \"form\">\n \n <div class = \"form-group\">\n <label for = \"firstname\" class = \"col-sm-2 control-label\">First Name</label>\n\t\t\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"firstname\" placeholder = \"Enter First Name\">\n </div>\n </div>\n \n <div class = \"form-group\">\n <label for = \"lastname\" class = \"col-sm-2 control-label\">Last Name</label>\n\t\t\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"lastname\" placeholder = \"Enter Last Name\">\n </div>\n </div>\n \n <div class = \"form-group\">\n <div class = \"col-sm-offset-2 col-sm-10\">\n <div class = \"checkbox\">\n <label><input type = \"checkbox\"> Remember me</label>\n </div>\n </div>\n </div>\n \n <div class = \"form-group\">\n <div class = \"col-sm-offset-2 col-sm-10\">\n <button type = \"submit\" class = \"btn btn-default\">Sign in</button>\n </div>\n </div>\n\t\n</form>" }, { "code": null, "e": 7725, "s": 7614, "text": "Bootstrap natively supports the most common form controls mainly input, textarea, checkbox, radio, and select." }, { "code": null, "e": 8076, "s": 7725, "text": "The most common form text field is the input field. This is where users will enter most of the essential form data. Bootstrap offers support for all native HTML5 input types: text, password, datetime, datetime-local, date, month, time, week, number, email, url, search, tel, and color. Proper type declaration is required to make Inputs fully styled." }, { "code": null, "e": 8270, "s": 8076, "text": "<form role = \"form\">\n \n <div class = \"form-group\">\n <label for = \"name\">Label</label>\n <input type = \"text\" class = \"form-control\" placeholder = \"Text input\">\n </div>\n \n</form>" }, { "code": null, "e": 8417, "s": 8270, "text": "The textarea is used when you need multiple lines of input. Change rows attribute as necessary (fewer rows = smaller box, more rows = bigger box)." }, { "code": null, "e": 8600, "s": 8417, "text": "<form role = \"form\">\n \n <div class = \"form-group\">\n <label for = \"name\">Text Area</label>\n <textarea class = \"form-control\" rows = \"3\"></textarea>\n </div>\n \n</form>" }, { "code": null, "e": 8700, "s": 8600, "text": "Checkboxes and radio buttons are great when you want users to choose from a list of preset options." }, { "code": null, "e": 8864, "s": 8700, "text": "When building a form, use checkbox if you want the user to select any number of options from a list. Use radio if you want to limit the user to just one selection." }, { "code": null, "e": 9028, "s": 8864, "text": "When building a form, use checkbox if you want the user to select any number of options from a list. Use radio if you want to limit the user to just one selection." }, { "code": null, "e": 9146, "s": 9028, "text": "Use .checkbox-inline or .radio-inline class to a series of checkboxes or radios for controls appear on the same line." }, { "code": null, "e": 9264, "s": 9146, "text": "Use .checkbox-inline or .radio-inline class to a series of checkboxes or radios for controls appear on the same line." }, { "code": null, "e": 9333, "s": 9264, "text": "The following example demonstrates both (default and inline) types −" }, { "code": null, "e": 10799, "s": 9333, "text": "\n<label for = \"name\">Example of Default Checkbox and radio button </label>\n\n<div class = \"checkbox\">\n <label>\n <input type = \"checkbox\" value = \"\">Option 1\n </label>\n</div>\n\n<div class = \"checkbox\">\n <label>\n <input type = \"checkbox\" value = \"\">Option 2\n </label>\n</div>\n\n<div class = \"radio\">\n <label>\n <input type = \"radio\" name = \"optionsRadios\" id = \"optionsRadios1\" value = \"option1\" checked> Option 1\n </label>\n</div>\n\n<div class = \"radio\">\n <label>\n <input type = \"radio\" name = \"optionsRadios\" id = \"optionsRadios2\" value = \"option2\">\n Option 2 - selecting it will deselect option 1\n </label>\n</div>\n\n<label for = \"name\">Example of Inline Checkbox and radio button </label>\n\n<div>\n <label class = \"checkbox-inline\">\n <input type = \"checkbox\" id = \"inlineCheckbox1\" value = \"option1\"> Option 1\n </label>\n \n <label class = \"checkbox-inline\">\n <input type = \"checkbox\" id = \"inlineCheckbox2\" value = \"option2\"> Option 2\n </label>\n \n <label class = \"checkbox-inline\">\n <input type = \"checkbox\" id = \"inlineCheckbox3\" value = \"option3\"> Option 3\n </label>\n \n <label class = \"checkbox-inline\">\n <input type = \"radio\" name = \"optionsRadiosinline\" id = \"optionsRadios3\" value = \"option1\" checked> Option 1\n </label>\n \n <label class = \"checkbox-inline\">\n <input type = \"radio\" name = \"optionsRadiosinline\" id = \"optionsRadios4\" value = \"option2\"> Option 2\n </label>\n</div>" }, { "code": null, "e": 10914, "s": 10799, "text": "A select is used when you want to allow the user to pick from multiple options, but by default it only allows one." }, { "code": null, "e": 11004, "s": 10914, "text": "Use <select> for list options with which the user is familiar, such as states or numbers." }, { "code": null, "e": 11094, "s": 11004, "text": "Use <select> for list options with which the user is familiar, such as states or numbers." }, { "code": null, "e": 11171, "s": 11094, "text": "Use multiple = \"multiple\" to allow the users to select more than one option." }, { "code": null, "e": 11248, "s": 11171, "text": "Use multiple = \"multiple\" to allow the users to select more than one option." }, { "code": null, "e": 11318, "s": 11248, "text": "The following example demonstrates both (select and multiple) types −" }, { "code": null, "e": 11912, "s": 11318, "text": "<form role = \"form\">\n \n <div class = \"form-group\">\n <label for = \"name\">Select list</label>\n \n <select class = \"form-control\">\n <option>1</option>\n <option>2</option>\n <option>3</option>\n <option>4</option>\n <option>5</option>\n </select>\n\n <label for = \"name\">Mutiple Select list</label>\n \n <select multiple class = \"form-control\">\n <option>1</option>\n <option>2</option>\n <option>3</option>\n <option>4</option>\n <option>5</option>\n </select>\n \n </div>\n\t\n</form>" }, { "code": null, "e": 12038, "s": 11912, "text": "Use the class .form-control-static on a <p>, when you need to place plain text next to a form label within a horizontal form." }, { "code": null, "e": 12608, "s": 12038, "text": "<form class = \"form-horizontal\" role = \"form\">\n <div class = \"form-group\">\n <label class = \"col-sm-2 control-label\">Email</label>\n \n <div class = \"col-sm-10\">\n <p class = \"form-control-static\">[email protected]</p>\n </div>\n \n </div>\n \n <div class = \"form-group\">\n <label for = \"inputPassword\" class = \"col-sm-2 control-label\">Password</label>\n \n <div class = \"col-sm-10\">\n <input type = \"password\" class = \"form-control\" id = \"inputPassword\" placeholder = \"Password\">\n </div>\n \n </div>\n</form>" }, { "code": null, "e": 12626, "s": 12608, "text": "[email protected]" }, { "code": null, "e": 12790, "s": 12626, "text": "In addition to the :focus (i.e., a user clicks into the input or tabs onto it) state, Bootstrap offers styling for disabled inputs and classes for form validation." }, { "code": null, "e": 12886, "s": 12790, "text": "When an input receives :focus, the outline of the input is removed and a box-shadow is applied." }, { "code": null, "e": 13076, "s": 12886, "text": "If you need to disable an input, simply adding the disabled attribute will not only disable it; it will also change the styling and the mouse cursor when the cursor hovers over the element." }, { "code": null, "e": 13178, "s": 13076, "text": "Add the disabled attribute to a <fieldset> to disable all the controls within the <fieldset> at once." }, { "code": null, "e": 13367, "s": 13178, "text": "Bootstrap includes validation styles for errors, warnings, and success messages. To use, simply add the appropriate class (.has-warning, .has-error, or .has-success) to the parent element." }, { "code": null, "e": 13432, "s": 13367, "text": "The following example demonstrates all the form control states −" }, { "code": null, "e": 15683, "s": 13432, "text": "<form class = \"form-horizontal\" role = \"form\">\n <div class = \"form-group\">\n <label class = \"col-sm-2 control-label\">Focused</label>\n <div class = \"col-sm-10\">\n <input class = \"form-control\" id = \"focusedInput\" type = \"text\" value = \"This is focused...\">\n </div>\n </div>\n \n <div class = \"form-group\">\n <label for = \"inputPassword\" class = \"col-sm-2 control-label\">\n Disabled\n </label>\n <div class = \"col-sm-10\">\n <input class = \"form-control\" id = \"disabledInput\" type = \"text\" placeholder = \"Disabled input here...\" disabled>\n </div>\n </div>\n \n <fieldset disabled>\n <div class = \"form-group\">\n <label for = \"disabledTextInput\" class = \"col-sm-2 control-label\">\n Disabled input (Fieldset disabled)\n </label>\n <div class = \"col-sm-10\">\n <input type = \"text\" id = \"disabledTextInput\" class = \"form-control\" placeholder = \"Disabled input\">\n </div> \n </div>\n \n <div class = \"form-group\">\n <label for = \"disabledSelect\" class = \"col-sm-2 control-label\"> \n Disabled select menu (Fieldset disabled)\n </label>\n <div class = \"col-sm-10\">\n <select id = \"disabledSelect\" class = \"form-control\"> \n <option>Disabled select</option>\n </select> \n </div>\n </div> \n </fieldset>\n \n <div class = \"form-group has-success\">\n <label class = \"col-sm-2 control-label\" for = \"inputSuccess\">\n Input with success\n </label>\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"inputSuccess\">\n </div>\n </div>\n \n <div class = \"form-group has-warning\">\n <label class = \"col-sm-2 control-label\" for = \"inputWarning\">\n Input with warning\n </label>\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"inputWarning\">\n </div>\n </div>\n \n <div class = \"form-group has-error\">\n <label class = \"col-sm-2 control-label\" for = \"inputError\">\n Input with error\n </label>\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"inputError\">\n </div>\n </div>\n</form>" }, { "code": null, "e": 15822, "s": 15683, "text": "You can set heights and widths of forms using classes like .input-lg and .col-lg-* respectively. The following example demonstrates this −" }, { "code": null, "e": 17151, "s": 15822, "text": "<form role = \"form\">\n\n <div class = \"form-group\">\n <input class = \"form-control input-lg\" type = \"text\" placeholder =\".input-lg\">\n </div>\n\n <div class = \"form-group\">\n <input class = \"form-control\" type = \"text\" placeholder = \"Default input\">\n </div>\n\n <div class = \"form-group\">\n <input class = \"form-control input-sm\" type = \"text\" placeholder = \".input-sm\">\n </div>\n \n <div class = \"form-group\"></div>\n \n <div class = \"form-group\">\n <select class = \"form-control input-lg\">\n <option value = \"\">.input-lg</option>\n </select>\n </div>\n \n <div class = \"form-group\">\n <select class = \"form-control\">\n <option value = \"\">Default select</option>\n </select>\n </div>\n \n <div class = \"form-group\">\n <select class = \"form-control input-sm\">\n <option value = \"\">.input-sm</option>\n </select>\n </div>\n\n <div class = \"row\">\n <div class = \"col-lg-2\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-2\">\n </div>\n \n <div class = \"col-lg-3\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-3\">\n </div>\n \n <div class = \"col-lg-4\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-4\">\n </div>\n \n </div>\n</form>" }, { "code": null, "e": 17355, "s": 17151, "text": "Bootstrap form controls can have a block level help text that flows with the inputs. To add a full width block of content, use the .help-block after the <input>. The following example demonstrates this −" }, { "code": null, "e": 17628, "s": 17355, "text": "<form role = \"form\">\n <span>Example of Help Text</span>\n <input class = \"form-control\" type = \"text\" placeholder = \"\">\n \n <span class = \"help-block\">\n A longer block of help text that breaks onto a new line and may extend beyond one line.\n </span>\n\t\n</form>" }, { "code": null, "e": 17661, "s": 17628, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 17675, "s": 17661, "text": " Anadi Sharma" }, { "code": null, "e": 17710, "s": 17675, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 17727, "s": 17710, "text": " Frahaan Hussain" }, { "code": null, "e": 17764, "s": 17727, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 17792, "s": 17764, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 17825, "s": 17792, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 17837, "s": 17825, "text": " Azaz Patel" }, { "code": null, "e": 17872, "s": 17837, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 17889, "s": 17872, "text": " Muhammad Ismail" }, { "code": null, "e": 17922, "s": 17889, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 17942, "s": 17922, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 17949, "s": 17942, "text": " Print" }, { "code": null, "e": 17960, "s": 17949, "text": " Add Notes" } ]
Program to find number of boxes that form longest chain in Python?
Suppose we have a list of boxes, here each entry has two values [start, end] (start < end). We can join two boxes if the end of one is equal to the start of another. We have to find the length of the longest chain of boxes. So, if the input is like blocks = [ [4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ], then the output will be 4, as we can form the chain: [1, 2], [2, 4], [4, 5], [5, 6] To solve this, we will follow these steps: if boxes are empty, thenreturn 0 if boxes are empty, then return 0 return 0 sort the list boxes sort the list boxes dic := an empty map dic := an empty map for each start s and end e in boxes, dodic[e] := maximum of dic[e] and dic[s] + 1 for each start s and end e in boxes, do dic[e] := maximum of dic[e] and dic[s] + 1 dic[e] := maximum of dic[e] and dic[s] + 1 return maximum of the list of all values of dic return maximum of the list of all values of dic Let us see the following implementation to get better understanding: Live Demo import collections class Solution: def solve(self, boxes): if not boxes: return 0 boxes.sort() dic = collections.defaultdict(int) for s, e in boxes: dic[e] = max(dic[e], dic[s] + 1) return max(dic.values()) ob = Solution() boxes = [ [4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ] print(ob.solve(boxes)) [[4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ] 4
[ { "code": null, "e": 1286, "s": 1062, "text": "Suppose we have a list of boxes, here each entry has two values [start, end] (start < end). We can join two boxes if the end of one is equal to the start of another. We have to find the length of the longest chain of boxes." }, { "code": null, "e": 1448, "s": 1286, "text": "So, if the input is like blocks = [ [4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ], then the output will be 4, as we can form the chain: [1, 2], [2, 4], [4, 5], [5, 6]" }, { "code": null, "e": 1491, "s": 1448, "text": "To solve this, we will follow these steps:" }, { "code": null, "e": 1524, "s": 1491, "text": "if boxes are empty, thenreturn 0" }, { "code": null, "e": 1549, "s": 1524, "text": "if boxes are empty, then" }, { "code": null, "e": 1558, "s": 1549, "text": "return 0" }, { "code": null, "e": 1567, "s": 1558, "text": "return 0" }, { "code": null, "e": 1587, "s": 1567, "text": "sort the list boxes" }, { "code": null, "e": 1607, "s": 1587, "text": "sort the list boxes" }, { "code": null, "e": 1627, "s": 1607, "text": "dic := an empty map" }, { "code": null, "e": 1647, "s": 1627, "text": "dic := an empty map" }, { "code": null, "e": 1729, "s": 1647, "text": "for each start s and end e in boxes, dodic[e] := maximum of dic[e] and dic[s] + 1" }, { "code": null, "e": 1769, "s": 1729, "text": "for each start s and end e in boxes, do" }, { "code": null, "e": 1812, "s": 1769, "text": "dic[e] := maximum of dic[e] and dic[s] + 1" }, { "code": null, "e": 1855, "s": 1812, "text": "dic[e] := maximum of dic[e] and dic[s] + 1" }, { "code": null, "e": 1903, "s": 1855, "text": "return maximum of the list of all values of dic" }, { "code": null, "e": 1951, "s": 1903, "text": "return maximum of the list of all values of dic" }, { "code": null, "e": 2020, "s": 1951, "text": "Let us see the following implementation to get better understanding:" }, { "code": null, "e": 2031, "s": 2020, "text": " Live Demo" }, { "code": null, "e": 2396, "s": 2031, "text": "import collections\n\nclass Solution:\n def solve(self, boxes):\n if not boxes:\n return 0\n boxes.sort()\n dic = collections.defaultdict(int)\n for s, e in boxes:\n dic[e] = max(dic[e], dic[s] + 1)\n return max(dic.values())\n\nob = Solution()\nboxes = [\n [4, 5],\n [5, 6],\n [4, 8],\n [1, 2],\n [2, 4]\n]\nprint(ob.solve(boxes))" }, { "code": null, "e": 2438, "s": 2396, "text": "[[4, 5],\n[5, 6],\n[4, 8],\n[1, 2],\n[2, 4] ]" }, { "code": null, "e": 2440, "s": 2438, "text": "4" } ]
Classification - Introduction
Classification may be defined as the process of predicting class or category from observed values or given data points. The categorized output can have the form such as “Black” or “White” or “spam” or “no spam”. Mathematically, classification is the task of approximating a mapping function (f) from input variables (X) to output variables (Y). It is basically belongs to the supervised machine learning in which targets are also provided along with the input data set. An example of classification problem can be the spam detection in emails. There can be only two categories of output, “spam” and “no spam”; hence this is a binary type classification. To implement this classification, we first need to train the classifier. For this example, “spam” and “no spam” emails would be used as the training data. After successfully train the classifier, it can be used to detect an unknown email. We have two types of learners in respective to classification problems − As the name suggests, such kind of learners waits for the testing data to be appeared after storing the training data. Classification is done only after getting the testing data. They spend less time on training but more time on predicting. Examples of lazy learners are K-nearest neighbor and case-based reasoning. As opposite to lazy learners, eager learners construct classification model without waiting for the testing data to be appeared after storing the training data. They spend more time on training but less time on predicting. Examples of eager learners are Decision Trees, Naïve Bayes and Artificial Neural Networks (ANN). Scikit-learn, a Python library for machine learning can be used to build a classifier in Python. The steps for building a classifier in Python are as follows − For building a classifier using scikit-learn, we need to import it. We can import it by using following script − import sklearn After importing necessary package, we need a dataset to build classification prediction model. We can import it from sklearn dataset or can use other one as per our requirement. We are going to use sklearn’s Breast Cancer Wisconsin Diagnostic Database. We can import it with the help of following script − from sklearn.datasets import load_breast_cancer The following script will load the dataset; data = load_breast_cancer() We also need to organize the data and it can be done with the help of following scripts − label_names = data['target_names'] labels = data['target'] feature_names = data['feature_names'] features = data['data'] The following command will print the name of the labels, ‘malignant’ and ‘benign’ in case of our database. print(label_names) The output of the above command is the names of the labels − ['malignant' 'benign'] These labels are mapped to binary values 0 and 1. Malignant cancer is represented by 0 and Benign cancer is represented by 1. The feature names and feature values of these labels can be seen with the help of following commands − print(feature_names[0]) The output of the above command is the names of the features for label 0 i.e. Malignant cancer − mean radius Similarly, names of the features for label can be produced as follows − print(feature_names[1]) The output of the above command is the names of the features for label 1 i.e. Benign cancer − mean texture We can print the features for these labels with the help of following command − print(features[0]) This will give the following output − [ 1.799e+01 1.038e+01 1.228e+02 1.001e+03 1.184e-01 2.776e-01 3.001e-01 1.471e-01 2.419e-01 7.871e-02 1.095e+00 9.053e-01 8.589e+00 1.534e+02 6.399e-03 4.904e-02 5.373e-02 1.587e-02 3.003e-02 6.193e-03 2.538e+01 1.733e+01 1.846e+02 2.019e+03 1.622e-01 6.656e-01 7.119e-01 2.654e-01 4.601e-01 1.189e-01 ] We can print the features for these labels with the help of following command − print(features[1]) This will give the following output − [ 2.057e+01 1.777e+01 1.329e+02 1.326e+03 8.474e-02 7.864e-02 8.690e-02 7.017e-02 1.812e-01 5.667e-02 5.435e-01 7.339e-01 3.398e+00 7.408e+01 5.225e-03 1.308e-02 1.860e-02 1.340e-02 1.389e-02 3.532e-03 2.499e+01 2.341e+01 1.588e+02 1.956e+03 1.238e-01 1.866e-01 2.416e-01 1.860e-01 2.750e-01 8.902e-02 ] As we need to test our model on unseen data, we will divide our dataset into two parts: a training set and a test set. We can use train_test_split() function of sklearn python package to split the data into sets. The following command will import the function − from sklearn.model_selection import train_test_split Now, next command will split the data into training & testing data. In this example, we are using taking 40 percent of the data for testing purpose and 60 percent of the data for training purpose − train, test, train_labels, test_labels = train_test_split( features,labels,test_size = 0.40, random_state = 42 ) After dividing the data into training and testing we need to build the model. We will be using Naïve Bayes algorithm for this purpose. The following commands will import the GaussianNB module − from sklearn.naive_bayes import GaussianNB Now, initialize the model as follows − gnb = GaussianNB() Next, with the help of following command we can train the model − model = gnb.fit(train, train_labels) Now, for evaluation purpose we need to make predictions. It can be done by using predict() function as follows − preds = gnb.predict(test) print(preds) This will give the following output − [ 1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 1 0 1 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1 ] The above series of 0s and 1s in output are the predicted values for the Malignant and Benign tumor classes. We can find the accuracy of the model build in previous step by comparing the two arrays namely test_labels and preds. We will be using the accuracy_score() function to determine the accuracy. from sklearn.metrics import accuracy_score print(accuracy_score(test_labels,preds)) 0.951754385965 The above output shows that NaïveBayes classifier is 95.17% accurate . The job is not done even if you have finished implementation of your Machine Learning application or model. We must have to find out how effective our model is? There can be different evaluation metrics, but we must choose it carefully because the choice of metrics influences how the performance of a machine learning algorithm is measured and compared. The following are some of the important classification evaluation metrics among which you can choose based upon your dataset and kind of problem − It is the easiest way to measure the performance of a classification problem where the output can be of two or more type of classes. A confusion matrix is nothing but a table with two dimensions viz. “Actual” and “Predicted” and furthermore, both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)” as shown below − The explanation of the terms associated with confusion matrix are as follows − True Positives (TP) − It is the case when both actual class & predicted class of data point is 1. True Positives (TP) − It is the case when both actual class & predicted class of data point is 1. True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0. True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0. False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1. False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1. False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0. False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0. We can find the confusion matrix with the help of confusion_matrix() function of sklearn. With the help of the following script, we can find the confusion matrix of above built binary classifier − from sklearn.metrics import confusion_matrix [ [ 73 7] [ 4 144] ] It may be defined as the number of correct predictions made by our ML model. We can easily calculate it by confusion matrix with the help of following formula − For above built binary classifier, TP + TN = 73+144 = 217 and TP+FP+FN+TN = 73+7+4+144=228. Hence, Accuracy = 217/228 = 0.951754385965 which is same as we have calculated after creating our binary classifier. Precision, used in document retrievals, may be defined as the number of correct documents returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula − For the above built binary classifier, TP = 73 and TP+FP = 73+7 = 80. Hence, Precision = 73/80 = 0.915 Recall may be defined as the number of positives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula − For above built binary classifier, TP = 73 and TP+FN = 73+4 = 77. Hence, Precision = 73/77 = 0.94805 Specificity, in contrast to recall, may be defined as the number of negatives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula − For the above built binary classifier, TN = 144 and TN+FP = 144+7 = 151. Hence, Precision = 144/151 = 0.95364 The followings are some important ML classification algorithms − Logistic Regression Logistic Regression Support Vector Machine (SVM) Support Vector Machine (SVM) Decision Tree Decision Tree Naïve Bayes Naïve Bayes Random Forest Random Forest We will be discussing all these classification algorithms in detail in further chapters. Some of the most important applications of classification algorithms are as follows − Speech Recognition Speech Recognition Handwriting Recognition Handwriting Recognition Biometric Identification Biometric Identification Document Classification Document Classification 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2516, "s": 2304, "text": "Classification may be defined as the process of predicting class or category from observed values or given data points. The categorized output can have the form such as “Black” or “White” or “spam” or “no spam”." }, { "code": null, "e": 2774, "s": 2516, "text": "Mathematically, classification is the task of approximating a mapping function (f) from input variables (X) to output variables (Y). It is basically belongs to the supervised machine learning in which targets are also provided along with the input data set." }, { "code": null, "e": 2958, "s": 2774, "text": "An example of classification problem can be the spam detection in emails. There can be only two categories of output, “spam” and “no spam”; hence this is a binary type classification." }, { "code": null, "e": 3197, "s": 2958, "text": "To implement this classification, we first need to train the classifier. For this example, “spam” and “no spam” emails would be used as the training data. After successfully train the classifier, it can be used to detect an unknown email." }, { "code": null, "e": 3270, "s": 3197, "text": "We have two types of learners in respective to classification problems −" }, { "code": null, "e": 3586, "s": 3270, "text": "As the name suggests, such kind of learners waits for the testing data to be appeared after storing the training data. Classification is done only after getting the testing data. They spend less time on training but more time on predicting. Examples of lazy learners are K-nearest neighbor and case-based reasoning." }, { "code": null, "e": 3907, "s": 3586, "text": "As opposite to lazy learners, eager learners construct classification model without waiting for the testing data to be appeared after storing the training data. They spend more time on training but less time on predicting. Examples of eager learners are Decision Trees, Naïve Bayes and Artificial Neural Networks (ANN)." }, { "code": null, "e": 4067, "s": 3907, "text": "Scikit-learn, a Python library for machine learning can be used to build a classifier in Python. The steps for building a classifier in Python are as follows −" }, { "code": null, "e": 4180, "s": 4067, "text": "For building a classifier using scikit-learn, we need to import it. We can import it by using following script −" }, { "code": null, "e": 4196, "s": 4180, "text": "import sklearn\n" }, { "code": null, "e": 4502, "s": 4196, "text": "After importing necessary package, we need a dataset to build classification prediction model. We can import it from sklearn dataset or can use other one as per our requirement. We are going to use sklearn’s Breast Cancer Wisconsin Diagnostic Database. We can import it with the help of following script −" }, { "code": null, "e": 4551, "s": 4502, "text": "from sklearn.datasets import load_breast_cancer\n" }, { "code": null, "e": 4595, "s": 4551, "text": "The following script will load the dataset;" }, { "code": null, "e": 4624, "s": 4595, "text": "data = load_breast_cancer()\n" }, { "code": null, "e": 4714, "s": 4624, "text": "We also need to organize the data and it can be done with the help of following scripts −" }, { "code": null, "e": 4844, "s": 4714, "text": "label_names = data['target_names']\n labels = data['target']\n feature_names = data['feature_names']\n features = data['data']" }, { "code": null, "e": 4951, "s": 4844, "text": "The following command will print the name of the labels, ‘malignant’ and ‘benign’ in case of our database." }, { "code": null, "e": 4971, "s": 4951, "text": "print(label_names)\n" }, { "code": null, "e": 5032, "s": 4971, "text": "The output of the above command is the names of the labels −" }, { "code": null, "e": 5056, "s": 5032, "text": "['malignant' 'benign']\n" }, { "code": null, "e": 5182, "s": 5056, "text": "These labels are mapped to binary values 0 and 1. Malignant cancer is represented by 0 and Benign cancer is represented by 1." }, { "code": null, "e": 5285, "s": 5182, "text": "The feature names and feature values of these labels can be seen with the help of following commands −" }, { "code": null, "e": 5310, "s": 5285, "text": "print(feature_names[0])\n" }, { "code": null, "e": 5407, "s": 5310, "text": "The output of the above command is the names of the features for label 0 i.e. Malignant cancer −" }, { "code": null, "e": 5420, "s": 5407, "text": "mean radius\n" }, { "code": null, "e": 5492, "s": 5420, "text": "Similarly, names of the features for label can be produced as follows −" }, { "code": null, "e": 5517, "s": 5492, "text": "print(feature_names[1])\n" }, { "code": null, "e": 5611, "s": 5517, "text": "The output of the above command is the names of the features for label 1 i.e. Benign cancer −" }, { "code": null, "e": 5625, "s": 5611, "text": "mean texture\n" }, { "code": null, "e": 5705, "s": 5625, "text": "We can print the features for these labels with the help of following command −" }, { "code": null, "e": 5725, "s": 5705, "text": "print(features[0])\n" }, { "code": null, "e": 5763, "s": 5725, "text": "This will give the following output −" }, { "code": null, "e": 6083, "s": 5763, "text": "[\n 1.799e+01 1.038e+01 1.228e+02 1.001e+03 1.184e-01 2.776e-01 3.001e-01\n 1.471e-01 2.419e-01 7.871e-02 1.095e+00 9.053e-01 8.589e+00 1.534e+02\n 6.399e-03 4.904e-02 5.373e-02 1.587e-02 3.003e-02 6.193e-03 2.538e+01\n 1.733e+01 1.846e+02 2.019e+03 1.622e-01 6.656e-01 7.119e-01 2.654e-01\n 4.601e-01 1.189e-01\n]\n" }, { "code": null, "e": 6163, "s": 6083, "text": "We can print the features for these labels with the help of following command −" }, { "code": null, "e": 6183, "s": 6163, "text": "print(features[1])\n" }, { "code": null, "e": 6221, "s": 6183, "text": "This will give the following output −" }, { "code": null, "e": 6541, "s": 6221, "text": "[\n 2.057e+01 1.777e+01 1.329e+02 1.326e+03 8.474e-02 7.864e-02 8.690e-02\n 7.017e-02 1.812e-01 5.667e-02 5.435e-01 7.339e-01 3.398e+00 7.408e+01\n 5.225e-03 1.308e-02 1.860e-02 1.340e-02 1.389e-02 3.532e-03 2.499e+01\n 2.341e+01 1.588e+02 1.956e+03 1.238e-01 1.866e-01 2.416e-01 1.860e-01\n 2.750e-01 8.902e-02\n]\n" }, { "code": null, "e": 6803, "s": 6541, "text": "As we need to test our model on unseen data, we will divide our dataset into two parts: a training set and a test set. We can use train_test_split() function of sklearn python package to split the data into sets. The following command will import the function −" }, { "code": null, "e": 6857, "s": 6803, "text": "from sklearn.model_selection import train_test_split\n" }, { "code": null, "e": 7055, "s": 6857, "text": "Now, next command will split the data into training & testing data. In this example, we are using taking 40 percent of the data for testing purpose and 60 percent of the data for training purpose −" }, { "code": null, "e": 7172, "s": 7055, "text": "train, test, train_labels, test_labels = train_test_split(\n features,labels,test_size = 0.40, random_state = 42\n)\n" }, { "code": null, "e": 7367, "s": 7172, "text": "After dividing the data into training and testing we need to build the model. We will be using Naïve Bayes algorithm for this purpose. The following commands will import the GaussianNB module −" }, { "code": null, "e": 7411, "s": 7367, "text": "from sklearn.naive_bayes import GaussianNB\n" }, { "code": null, "e": 7450, "s": 7411, "text": "Now, initialize the model as follows −" }, { "code": null, "e": 7470, "s": 7450, "text": "gnb = GaussianNB()\n" }, { "code": null, "e": 7536, "s": 7470, "text": "Next, with the help of following command we can train the model −" }, { "code": null, "e": 7574, "s": 7536, "text": "model = gnb.fit(train, train_labels)\n" }, { "code": null, "e": 7687, "s": 7574, "text": "Now, for evaluation purpose we need to make predictions. It can be done by using predict() function as follows −" }, { "code": null, "e": 7727, "s": 7687, "text": "preds = gnb.predict(test)\nprint(preds)\n" }, { "code": null, "e": 7765, "s": 7727, "text": "This will give the following output −" }, { "code": null, "e": 8252, "s": 7765, "text": "[\n 1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1\n 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1\n 1 1 1 1 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0\n 0 0 1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0 1 0 0 1 1 1 1\n 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1 0 \n 1 0 1 1 1 1 0 1 1 0 1 1 1 0 1 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 \n 1\n\n]\n" }, { "code": null, "e": 8361, "s": 8252, "text": "The above series of 0s and 1s in output are the predicted values for the Malignant and Benign tumor classes." }, { "code": null, "e": 8554, "s": 8361, "text": "We can find the accuracy of the model build in previous step by comparing the two arrays namely test_labels and preds. We will be using the accuracy_score() function to determine the accuracy." }, { "code": null, "e": 8660, "s": 8554, "text": "from sklearn.metrics import accuracy_score\n print(accuracy_score(test_labels,preds))\n 0.951754385965\n" }, { "code": null, "e": 8732, "s": 8660, "text": "The above output shows that NaïveBayes classifier is 95.17% accurate ." }, { "code": null, "e": 9087, "s": 8732, "text": "The job is not done even if you have finished implementation of your Machine Learning application or model. We must have to find out how effective our model is? There can be different evaluation metrics, but we must choose it carefully because the choice of metrics influences how the performance of a machine learning algorithm is measured and compared." }, { "code": null, "e": 9234, "s": 9087, "text": "The following are some of the important classification evaluation metrics among which you can choose based upon your dataset and kind of problem −" }, { "code": null, "e": 9611, "s": 9234, "text": "It is the easiest way to measure the performance of a classification problem where the output can be of two or more type of classes. A confusion matrix is nothing but a table with two dimensions viz. “Actual” and “Predicted” and furthermore, both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)” as shown below −" }, { "code": null, "e": 9690, "s": 9611, "text": "The explanation of the terms associated with confusion matrix are as follows −" }, { "code": null, "e": 9788, "s": 9690, "text": "True Positives (TP) − It is the case when both actual class & predicted class of data point is 1." }, { "code": null, "e": 9886, "s": 9788, "text": "True Positives (TP) − It is the case when both actual class & predicted class of data point is 1." }, { "code": null, "e": 9984, "s": 9886, "text": "True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0." }, { "code": null, "e": 10082, "s": 9984, "text": "True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0." }, { "code": null, "e": 10195, "s": 10082, "text": "False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1." }, { "code": null, "e": 10308, "s": 10195, "text": "False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1." }, { "code": null, "e": 10421, "s": 10308, "text": "False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0." }, { "code": null, "e": 10534, "s": 10421, "text": "False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0." }, { "code": null, "e": 10731, "s": 10534, "text": "We can find the confusion matrix with the help of confusion_matrix() function of sklearn. With the help of the following script, we can find the confusion matrix of above built binary classifier −" }, { "code": null, "e": 10777, "s": 10731, "text": "from sklearn.metrics import confusion_matrix\n" }, { "code": null, "e": 10808, "s": 10777, "text": "[\n [ 73 7]\n [ 4 144]\n]\n" }, { "code": null, "e": 10969, "s": 10808, "text": "It may be defined as the number of correct predictions made by our ML model. We can easily calculate it by confusion matrix with the help of following formula −" }, { "code": null, "e": 11061, "s": 10969, "text": "For above built binary classifier, TP + TN = 73+144 = 217 and TP+FP+FN+TN = 73+7+4+144=228." }, { "code": null, "e": 11178, "s": 11061, "text": "Hence, Accuracy = 217/228 = 0.951754385965 which is same as we have calculated after creating our binary classifier." }, { "code": null, "e": 11378, "s": 11178, "text": "Precision, used in document retrievals, may be defined as the number of correct documents returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −" }, { "code": null, "e": 11448, "s": 11378, "text": "For the above built binary classifier, TP = 73 and TP+FP = 73+7 = 80." }, { "code": null, "e": 11481, "s": 11448, "text": "Hence, Precision = 73/80 = 0.915" }, { "code": null, "e": 11640, "s": 11481, "text": "Recall may be defined as the number of positives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −" }, { "code": null, "e": 11706, "s": 11640, "text": "For above built binary classifier, TP = 73 and TP+FN = 73+4 = 77." }, { "code": null, "e": 11741, "s": 11706, "text": "Hence, Precision = 73/77 = 0.94805" }, { "code": null, "e": 11929, "s": 11741, "text": "Specificity, in contrast to recall, may be defined as the number of negatives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −" }, { "code": null, "e": 12002, "s": 11929, "text": "For the above built binary classifier, TN = 144 and TN+FP = 144+7 = 151." }, { "code": null, "e": 12039, "s": 12002, "text": "Hence, Precision = 144/151 = 0.95364" }, { "code": null, "e": 12104, "s": 12039, "text": "The followings are some important ML classification algorithms −" }, { "code": null, "e": 12124, "s": 12104, "text": "Logistic Regression" }, { "code": null, "e": 12144, "s": 12124, "text": "Logistic Regression" }, { "code": null, "e": 12173, "s": 12144, "text": "Support Vector Machine (SVM)" }, { "code": null, "e": 12202, "s": 12173, "text": "Support Vector Machine (SVM)" }, { "code": null, "e": 12216, "s": 12202, "text": "Decision Tree" }, { "code": null, "e": 12230, "s": 12216, "text": "Decision Tree" }, { "code": null, "e": 12243, "s": 12230, "text": "Naïve Bayes" }, { "code": null, "e": 12256, "s": 12243, "text": "Naïve Bayes" }, { "code": null, "e": 12270, "s": 12256, "text": "Random Forest" }, { "code": null, "e": 12284, "s": 12270, "text": "Random Forest" }, { "code": null, "e": 12373, "s": 12284, "text": "We will be discussing all these classification algorithms in detail in further chapters." }, { "code": null, "e": 12459, "s": 12373, "text": "Some of the most important applications of classification algorithms are as follows −" }, { "code": null, "e": 12478, "s": 12459, "text": "Speech Recognition" }, { "code": null, "e": 12497, "s": 12478, "text": "Speech Recognition" }, { "code": null, "e": 12521, "s": 12497, "text": "Handwriting Recognition" }, { "code": null, "e": 12545, "s": 12521, "text": "Handwriting Recognition" }, { "code": null, "e": 12570, "s": 12545, "text": "Biometric Identification" }, { "code": null, "e": 12595, "s": 12570, "text": "Biometric Identification" }, { "code": null, "e": 12619, "s": 12595, "text": "Document Classification" }, { "code": null, "e": 12643, "s": 12619, "text": "Document Classification" }, { "code": null, "e": 12680, "s": 12643, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 12703, "s": 12680, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 12739, "s": 12703, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 12767, "s": 12739, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12801, "s": 12767, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 12818, "s": 12801, "text": " Abhilash Nelson" }, { "code": null, "e": 12851, "s": 12818, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 12873, "s": 12851, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 12906, "s": 12873, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 12928, "s": 12906, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 12961, "s": 12928, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 12983, "s": 12961, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 12990, "s": 12983, "text": " Print" }, { "code": null, "e": 13001, "s": 12990, "text": " Add Notes" } ]
Pandas Index Explained. Pandas is a best friend to a Data... | by Manu Sharma | Towards Data Science
We spend a lot of time with methods like loc, iloc, filtering, stack/unstack, concat, merge, pivot and many more while processing and understanding our data, especially when we work on a new problem. And these methods use indexes, even most of the errors we face are indices error. Index become more important in time series data. Visualisations also need good control over pandas index. Index is like an address, that’s how any data point across the dataframe or series can be accessed. Rows and columns both have indexes, rows indices are called as index and for columns its general column names. Machine/ Deep learning algorithms has a performance limit at prediction accuracy just like their ancestors, statistical models, so how do you get a significant better accuracy? Feed a better data for learning. Data Processing & Feature Enginnering is the key Pandas have three data structures dataframe, series & panel. We mostly use dataframe and series and they both use indexes, which make them very convenient to analyse. Time to take a step back and look at the pandas' index. It empowers us to be a better data scientist. We will be using the UCI Machine Learning Adult Dataset, the following notebook has the script to download the data. Business Problem: Classification (a person earns more than 50k or less) Predictor Variable: Label ; Predictors: country, age, education, occupation, marital status etc. The following Notebook is very easy to follow and also has small tips and tricks to make daily work a little better. adult = pd.read_csv("https://archive.ics.uci.edu/ml/machine- learning-databases/adult/adult.data", names = ['age','workclass','fnlwgt', 'education', 'education_num','marital_status','occupation','relationship','race','sex','capital_gain','capital_loss', 'hours_per_week', 'native_country','label'], index_col = False)print("Shape of data{}".format(adult.shape))adult.head() Dataset has 32561 rows and 15 features, the leftmost series 0,1 2,3 ... is index. Let’s Look at some more information. Adult has rangeindex 32561 entries, an integer series from 0 to 32560. df.loc are for labels/ namesdf.iloc are for position numbers df.loc are for labels/ names df.iloc are for position numbers e.g. Lets assume Ram, Sonu & Tony are standing at positions 1, 2 & 3 respectively. If you want to call Ram you have two options, either you call him by his name or his position number. So, if you call Ram by his name “Ram”, you will use df.loc and if we will call him by his position number “1” we will use df.iloc. Before we understand loc & iloc more, let's take a sample from our data for further analysis. We are taking a sample of 10000 observations, using pandas df.sample method. Nice, now we have a dataset name df, and the leftmost series are 3,4,6,8, 11...Strange! It is because the rows will carry their original( old address ) index or index names from the adult dataset Naming our index will help us a little initially, its the indices from adult dataset.look at the rows and column indices Both rows and columns have indexes, and the name of index is ‘index_adult Let's discuss a couple of examples on loc & iloc methods In the first example of .loc, it gave us an error because we have used .loc method and df has no row who has a name ‘2’, row index looks like a number to us, but they are name/label to .loc method try replacing 2 with 3 or 4, it will work, because there are names ‘3’,’4' as position names In the second example, we are trying the same with .iloc, its a position number-based method “age” is first column so we will use its position which is 0 there will be a position 0,1,2,3 till the last row of df, so 2 will be the third row For our further analysis, let's Keep a few interesting variables only Some of the times, it’s difficult to work with random numbers in index, at that time, resetting this index will make it a column and recreate another default index `reset_index()`will recreate index column every time we run it on same data `drop = True` paramater won’t create that as column in the dataframe, look at the difference between following two dataset `inplace = True` save us from assigning it to data againwe are not using `drop = True`, now df should have its last index as a column in it df has another column index_adult, because of reset Filter on India After resetting our index, and applying a filter for India, we can see index hold itself from df, just like sampling, now the row index(4, 312, 637 ,902..) are from df and index_adult is the indices of these rows in adult Let's look at the observations with more than 50k income across the gender Even this dataframe has an index, hard to recognise by looking at the dataframe, and individual items can be accessed like Filter ind dataset for people with income more than 50K indices are intact with their rows, just like an address Very Impressive, these people are earning really good, Let's try to know their work hours since we don't have ‘hours_per_week’ in this data, we will bring it from adult with the help of indices Indices made it very easy to bring more information easily, the above formula can be understood as filtering adult[‘hours_per_week’] on the address index_adult of ind_50 mean of work hours per week for people who earn more than 50k Just with the use of index_adult, we were able to bring another column information easily Index make filtering very easy and also give you space to move forward and backwards in your data Filtering a complementary set from the data, just like train and test from the total dataset we are slicing that part of ind, which is not in ind_50, i.e. people who are earning less than 50k Nice! It looks like people who earn 50k & more, work more hours per week in this data sample Jupyter nb can be downloaded from this Github-repo. The true capability of pandas index can be realised only when we drill down our data with multi-indexing & visualisations. Visit my next exercise on stack/unstack, pivot_table & crosstab Thanks for reading. If you have liked this article, you may also like Pandas Pivot & Stacking, Scaling & Transformation When & Where For more, please follow me on Medium Let’s Connect on Linkedin
[ { "code": null, "e": 560, "s": 172, "text": "We spend a lot of time with methods like loc, iloc, filtering, stack/unstack, concat, merge, pivot and many more while processing and understanding our data, especially when we work on a new problem. And these methods use indexes, even most of the errors we face are indices error. Index become more important in time series data. Visualisations also need good control over pandas index." }, { "code": null, "e": 771, "s": 560, "text": "Index is like an address, that’s how any data point across the dataframe or series can be accessed. Rows and columns both have indexes, rows indices are called as index and for columns its general column names." }, { "code": null, "e": 1030, "s": 771, "text": "Machine/ Deep learning algorithms has a performance limit at prediction accuracy just like their ancestors, statistical models, so how do you get a significant better accuracy? Feed a better data for learning. Data Processing & Feature Enginnering is the key" }, { "code": null, "e": 1197, "s": 1030, "text": "Pandas have three data structures dataframe, series & panel. We mostly use dataframe and series and they both use indexes, which make them very convenient to analyse." }, { "code": null, "e": 1299, "s": 1197, "text": "Time to take a step back and look at the pandas' index. It empowers us to be a better data scientist." }, { "code": null, "e": 1416, "s": 1299, "text": "We will be using the UCI Machine Learning Adult Dataset, the following notebook has the script to download the data." }, { "code": null, "e": 1585, "s": 1416, "text": "Business Problem: Classification (a person earns more than 50k or less) Predictor Variable: Label ; Predictors: country, age, education, occupation, marital status etc." }, { "code": null, "e": 1702, "s": 1585, "text": "The following Notebook is very easy to follow and also has small tips and tricks to make daily work a little better." }, { "code": null, "e": 2083, "s": 1702, "text": "adult = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine- learning-databases/adult/adult.data\", names = ['age','workclass','fnlwgt', 'education', 'education_num','marital_status','occupation','relationship','race','sex','capital_gain','capital_loss', 'hours_per_week', 'native_country','label'], index_col = False)print(\"Shape of data{}\".format(adult.shape))adult.head()" }, { "code": null, "e": 2202, "s": 2083, "text": "Dataset has 32561 rows and 15 features, the leftmost series 0,1 2,3 ... is index. Let’s Look at some more information." }, { "code": null, "e": 2273, "s": 2202, "text": "Adult has rangeindex 32561 entries, an integer series from 0 to 32560." }, { "code": null, "e": 2334, "s": 2273, "text": "df.loc are for labels/ namesdf.iloc are for position numbers" }, { "code": null, "e": 2363, "s": 2334, "text": "df.loc are for labels/ names" }, { "code": null, "e": 2396, "s": 2363, "text": "df.iloc are for position numbers" }, { "code": null, "e": 2712, "s": 2396, "text": "e.g. Lets assume Ram, Sonu & Tony are standing at positions 1, 2 & 3 respectively. If you want to call Ram you have two options, either you call him by his name or his position number. So, if you call Ram by his name “Ram”, you will use df.loc and if we will call him by his position number “1” we will use df.iloc." }, { "code": null, "e": 2883, "s": 2712, "text": "Before we understand loc & iloc more, let's take a sample from our data for further analysis. We are taking a sample of 10000 observations, using pandas df.sample method." }, { "code": null, "e": 2971, "s": 2883, "text": "Nice, now we have a dataset name df, and the leftmost series are 3,4,6,8, 11...Strange!" }, { "code": null, "e": 3079, "s": 2971, "text": "It is because the rows will carry their original( old address ) index or index names from the adult dataset" }, { "code": null, "e": 3200, "s": 3079, "text": "Naming our index will help us a little initially, its the indices from adult dataset.look at the rows and column indices" }, { "code": null, "e": 3274, "s": 3200, "text": "Both rows and columns have indexes, and the name of index is ‘index_adult" }, { "code": null, "e": 3331, "s": 3274, "text": "Let's discuss a couple of examples on loc & iloc methods" }, { "code": null, "e": 3381, "s": 3331, "text": "In the first example of .loc, it gave us an error" }, { "code": null, "e": 3528, "s": 3381, "text": "because we have used .loc method and df has no row who has a name ‘2’, row index looks like a number to us, but they are name/label to .loc method" }, { "code": null, "e": 3621, "s": 3528, "text": "try replacing 2 with 3 or 4, it will work, because there are names ‘3’,’4' as position names" }, { "code": null, "e": 3714, "s": 3621, "text": "In the second example, we are trying the same with .iloc, its a position number-based method" }, { "code": null, "e": 3775, "s": 3714, "text": "“age” is first column so we will use its position which is 0" }, { "code": null, "e": 3860, "s": 3775, "text": "there will be a position 0,1,2,3 till the last row of df, so 2 will be the third row" }, { "code": null, "e": 3930, "s": 3860, "text": "For our further analysis, let's Keep a few interesting variables only" }, { "code": null, "e": 4094, "s": 3930, "text": "Some of the times, it’s difficult to work with random numbers in index, at that time, resetting this index will make it a column and recreate another default index" }, { "code": null, "e": 4293, "s": 4094, "text": "`reset_index()`will recreate index column every time we run it on same data `drop = True` paramater won’t create that as column in the dataframe, look at the difference between following two dataset" }, { "code": null, "e": 4433, "s": 4293, "text": "`inplace = True` save us from assigning it to data againwe are not using `drop = True`, now df should have its last index as a column in it" }, { "code": null, "e": 4485, "s": 4433, "text": "df has another column index_adult, because of reset" }, { "code": null, "e": 4501, "s": 4485, "text": "Filter on India" }, { "code": null, "e": 4723, "s": 4501, "text": "After resetting our index, and applying a filter for India, we can see index hold itself from df, just like sampling, now the row index(4, 312, 637 ,902..) are from df and index_adult is the indices of these rows in adult" }, { "code": null, "e": 4798, "s": 4723, "text": "Let's look at the observations with more than 50k income across the gender" }, { "code": null, "e": 4921, "s": 4798, "text": "Even this dataframe has an index, hard to recognise by looking at the dataframe, and individual items can be accessed like" }, { "code": null, "e": 4977, "s": 4921, "text": "Filter ind dataset for people with income more than 50K" }, { "code": null, "e": 5034, "s": 4977, "text": "indices are intact with their rows, just like an address" }, { "code": null, "e": 5228, "s": 5034, "text": "Very Impressive, these people are earning really good, Let's try to know their work hours since we don't have ‘hours_per_week’ in this data, we will bring it from adult with the help of indices" }, { "code": null, "e": 5398, "s": 5228, "text": "Indices made it very easy to bring more information easily, the above formula can be understood as filtering adult[‘hours_per_week’] on the address index_adult of ind_50" }, { "code": null, "e": 5460, "s": 5398, "text": "mean of work hours per week for people who earn more than 50k" }, { "code": null, "e": 5550, "s": 5460, "text": "Just with the use of index_adult, we were able to bring another column information easily" }, { "code": null, "e": 5648, "s": 5550, "text": "Index make filtering very easy and also give you space to move forward and backwards in your data" }, { "code": null, "e": 5741, "s": 5648, "text": "Filtering a complementary set from the data, just like train and test from the total dataset" }, { "code": null, "e": 5840, "s": 5741, "text": "we are slicing that part of ind, which is not in ind_50, i.e. people who are earning less than 50k" }, { "code": null, "e": 5933, "s": 5840, "text": "Nice! It looks like people who earn 50k & more, work more hours per week in this data sample" }, { "code": null, "e": 5985, "s": 5933, "text": "Jupyter nb can be downloaded from this Github-repo." }, { "code": null, "e": 6172, "s": 5985, "text": "The true capability of pandas index can be realised only when we drill down our data with multi-indexing & visualisations. Visit my next exercise on stack/unstack, pivot_table & crosstab" }, { "code": null, "e": 6305, "s": 6172, "text": "Thanks for reading. If you have liked this article, you may also like Pandas Pivot & Stacking, Scaling & Transformation When & Where" }, { "code": null, "e": 6342, "s": 6305, "text": "For more, please follow me on Medium" } ]
Fleury’s Algorithm
Fleury’s Algorithm is used to display the Euler path or Euler circuit from a given graph. In this algorithm, starting from one edge, it tries to move other adjacent vertices by removing the previous vertices. Using this trick, the graph becomes simpler in each step to find the Euler path or circuit. We have to check some rules to get the path or circuit − The graph must be a Euler Graph. The graph must be a Euler Graph. When there are two edges, one is bridge, another one is non-bridge, we have to choose non-bridge at first. When there are two edges, one is bridge, another one is non-bridge, we have to choose non-bridge at first. Choosing of starting vertex is also tricky, we cannot use any vertex as starting vertex, if the graph has no odd degree vertices, we can choose any vertex as start point, otherwise when one vertex has odd degree, we have to choose that one first. findStartVert(graph) Input: The given graph. Output: Find the starting vertex to start algorithm. Begin for all vertex i, in the graph, do deg := 0 for all vertex j, which are adjacent with i, do deg := deg + 1 done if deg is odd, then return i done when all degree is even return 0 End dfs(prev, start, visited) Input: The pervious and start vertex to perform DFS, and visited list. Output: Count the number of nodes after DFS. Begin count := 1 visited[start] := true for all vertex b, in the graph, do if prev is not u, then if u is not visited, then if start and u are connected, then count := count + dfs(start, u, visited) end if end if end if done return count End isBridge(u, v) Input: The start and end node. Output: True when u and v are forming a bridge. Begin deg := 0 for all vertex i which are adjacent with v, do deg := deg + 1 done if deg > 1, then return false return true End fleuryAlgorithm(start) Input: The starting vertex. Output: Display the Euler path or circuit. Begin edge := get the number of edges in the graph //it will not initialize in next recursion call v_count = number of nodes //this will not initialize in next recursion call for all vertex v, which are adjacent with start, do make visited array and will with false value if isBridge(start, v), then decrease v_count by 1 cnt = dfs(start, v, visited) if difference between cnt and v_count <= 2, then print the edge (start →‡ v) if isBridge(v, start), then decrease v_count by 1 remove edge from start and v decrease edge by 1 fleuryAlgorithm(v) end if done End #include<iostream> #include<vector> #include<cmath> #define NODE 8 using namespace std; int graph[NODE][NODE] = { {0,1,1,0,0,0,0,0}, {1,0,1,1,1,0,0,0}, {1,1,0,1,0,1,0,0}, {0,1,1,0,0,0,0,0}, {0,1,0,0,0,1,1,1}, {0,0,1,0,1,0,1,1}, {0,0,0,0,1,1,0,0}, {0,0,0,0,1,1,0,0} }; int tempGraph[NODE][NODE]; int findStartVert() { for(int i = 0; i<NODE; i++) { int deg = 0; for(int j = 0; j<NODE; j++) { if(tempGraph[i][j]) deg++; //increase degree, when connected edge found } if(deg % 2 != 0) //when degree of vertices are odd return i; //i is node with odd degree } return 0; //when all vertices have even degree, start from 0 } int dfs(int prev, int start, bool visited[]){ int count = 1; visited[start] = true; for(int u = 0; u<NODE; u++){ if(prev != u){ if(!visited[u]){ if(tempGraph[start][u]){ count += dfs(start, u, visited); } } } } return count; } bool isBridge(int u, int v) { int deg = 0; for(int i = 0; i<NODE; i++) if(tempGraph[v][i]) deg++; if(deg>1) { return false; //the edge is not forming bridge } return true; //edge forming a bridge } int edgeCount() { int count = 0; for(int i = 0; i<NODE; i++) for(int j = i; j<NODE; j++) if(tempGraph[i][j]) count++; return count; } void fleuryAlgorithm(int start) { static int edge = edgeCount(); static int v_count = NODE; for(int v = 0; v<NODE; v++) { if(tempGraph[start][v]) { bool visited[NODE] = {false}; if(isBridge(start, v)){ v_count--; } int cnt = dfs(start, v, visited); if(abs(v_count-cnt) <= 2){ cout << start << "--" << v << " "; if(isBridge(v, start)){ v_count--; } tempGraph[start][v] = tempGraph[v][start] = 0; //remove edge from graph edge--; fleuryAlgorithm(v); } } } } int main() { for(int i = 0; i<NODE; i++) //copy main graph to tempGraph for(int j = 0; j<NODE; j++) tempGraph[i][j] = graph[i][j]; cout << "Euler Path Or Circuit: "; fleuryAlgorithm(findStartVert()); } Euler Path Or Circuit: 0--1 1--2 2--3 3--1 1--4 4--5 5--6 6--4 4--7 7--5 5--2 2--0
[ { "code": null, "e": 1363, "s": 1062, "text": "Fleury’s Algorithm is used to display the Euler path or Euler circuit from a given graph. In this algorithm, starting from one edge, it tries to move other adjacent vertices by removing the previous vertices. Using this trick, the graph becomes simpler in each step to find the Euler path or circuit." }, { "code": null, "e": 1420, "s": 1363, "text": "We have to check some rules to get the path or circuit −" }, { "code": null, "e": 1453, "s": 1420, "text": "The graph must be a Euler Graph." }, { "code": null, "e": 1486, "s": 1453, "text": "The graph must be a Euler Graph." }, { "code": null, "e": 1593, "s": 1486, "text": "When there are two edges, one is bridge, another one is non-bridge, we have to choose non-bridge at first." }, { "code": null, "e": 1700, "s": 1593, "text": "When there are two edges, one is bridge, another one is non-bridge, we have to choose non-bridge at first." }, { "code": null, "e": 1947, "s": 1700, "text": "Choosing of starting vertex is also tricky, we cannot use any vertex as starting vertex, if the graph has no odd degree vertices, we can choose any vertex as start point, otherwise when one vertex has odd degree, we have to choose that one first." }, { "code": null, "e": 3756, "s": 1947, "text": "findStartVert(graph)\nInput: The given graph.\nOutput: Find the starting vertex to start algorithm.\nBegin\n for all vertex i, in the graph, do\n deg := 0\n for all vertex j, which are adjacent with i, do\n deg := deg + 1\n done\n if deg is odd, then\n return i\n done\n when all degree is even return 0\nEnd\n\ndfs(prev, start, visited)\nInput: The pervious and start vertex to perform DFS, and visited list.\nOutput: Count the number of nodes after DFS.\nBegin\n count := 1\n visited[start] := true\n for all vertex b, in the graph, do\n if prev is not u, then\n if u is not visited, then\n if start and u are connected, then\n count := count + dfs(start, u, visited)\n end if\n end if\n end if\n done\n return count\nEnd\n\nisBridge(u, v)\nInput: The start and end node.\nOutput: True when u and v are forming a bridge.\nBegin\n deg := 0\n for all vertex i which are adjacent with v, do\n deg := deg + 1\n done\n if deg > 1, then\n return false\n return true\nEnd\n\nfleuryAlgorithm(start)\nInput: The starting vertex.\nOutput: Display the Euler path or circuit.\nBegin\n edge := get the number of edges in the graph\n //it will not initialize in next\n recursion call\n v_count = number of nodes\n //this will not initialize in next recursion call\n for all vertex v, which are adjacent with start, do\n make visited array and will with false value\n if isBridge(start, v), then decrease v_count by 1\n cnt = dfs(start, v, visited)\n if difference between cnt and v_count <= 2, then\n print the edge (start →‡ v)\n if isBridge(v, start), then decrease v_count by 1\n remove edge from start and v\n decrease edge by 1\n fleuryAlgorithm(v)\n end if\n done\nEnd" }, { "code": null, "e": 6012, "s": 3756, "text": "#include<iostream>\n#include<vector>\n#include<cmath>\n#define NODE 8\n\nusing namespace std;\nint graph[NODE][NODE] = {\n {0,1,1,0,0,0,0,0},\n {1,0,1,1,1,0,0,0},\n {1,1,0,1,0,1,0,0},\n {0,1,1,0,0,0,0,0},\n {0,1,0,0,0,1,1,1},\n {0,0,1,0,1,0,1,1},\n {0,0,0,0,1,1,0,0},\n {0,0,0,0,1,1,0,0}\n};\nint tempGraph[NODE][NODE];\nint findStartVert() {\n for(int i = 0; i<NODE; i++) {\n int deg = 0;\n for(int j = 0; j<NODE; j++) {\n if(tempGraph[i][j])\n deg++; //increase degree, when connected edge found\n }\n if(deg % 2 != 0) //when degree of vertices are odd\n return i; //i is node with odd degree\n }\n return 0; //when all vertices have even degree, start from 0\n}\nint dfs(int prev, int start, bool visited[]){\n int count = 1;\n visited[start] = true;\n for(int u = 0; u<NODE; u++){\n if(prev != u){\n if(!visited[u]){\n if(tempGraph[start][u]){\n count += dfs(start, u, visited);\n }\n }\n }\n }\n return count;\n}\nbool isBridge(int u, int v) {\n int deg = 0;\n for(int i = 0; i<NODE; i++)\n if(tempGraph[v][i])\n deg++;\n if(deg>1) {\n return false; //the edge is not forming bridge\n }\n return true; //edge forming a bridge\n}\nint edgeCount() {\n int count = 0;\n for(int i = 0; i<NODE; i++)\n for(int j = i; j<NODE; j++)\n if(tempGraph[i][j])\n count++;\n return count;\n}\nvoid fleuryAlgorithm(int start) {\n static int edge = edgeCount();\n static int v_count = NODE;\n for(int v = 0; v<NODE; v++) {\n if(tempGraph[start][v]) {\n bool visited[NODE] = {false};\n if(isBridge(start, v)){\n v_count--;\n }\n int cnt = dfs(start, v, visited);\n if(abs(v_count-cnt) <= 2){\n cout << start << \"--\" << v << \" \";\n if(isBridge(v, start)){\n v_count--;\n }\n tempGraph[start][v] = tempGraph[v][start] = 0; //remove edge from graph\n edge--;\n fleuryAlgorithm(v);\n }\n }\n }\n}\nint main() {\n for(int i = 0; i<NODE; i++) //copy main graph to tempGraph\n for(int j = 0; j<NODE; j++)\n tempGraph[i][j] = graph[i][j];\n cout << \"Euler Path Or Circuit: \";\n fleuryAlgorithm(findStartVert());\n}" }, { "code": null, "e": 6095, "s": 6012, "text": "Euler Path Or Circuit: 0--1 1--2 2--3 3--1 1--4 4--5 5--6 6--4 4--7 7--5 5--2 2--0" } ]
How to load and show image in OpenCV using C++?
In this topic, we will determine how to load and show images using OpenCV in C++. There are the following functions required for loading and showing an image in OpenCV. Mat: Mat is not a function. It is a data structure, a type of variable. Like int, char, string variable types in C++, Mat is a variable of OpenCV, which creates a matrix data structure to load images inside it. In this program, we wrote 'Mat myImage;'. That means we are declaring a matrix variable named 'myImage'. namedWindow(): It allocates some memory and creates a window to show the image. It works like a photo frame. In OpenCV, we have to make the function as 'namedWindow("name of the window",flag)'. 3. imread(): This function reads an image from a defined location. This program reads the image from 'C:' drive. To use this function, you have to write it as 'imread("location of the image/name of the image with the extension", flag)'. imshow(): This function shows the image in the defined window. To use this function you have to write as 'imshow(name of the window", name of the matrix)'. waitKey(): This is a vital function of OpenCV. To process images and executes operations, we must allow the system some time. If we don't do it, we will not This function waits for a certain period before closing the program. If you use waitKey(10000), it will close the program after 10 seconds. If you write waitKey(0), it will get the desired output. This function will enable us to give the system the required time to operate. wait for the keystroke from the user. When the user clicks any key from the keyboard, the program will stop. This function has to be written as 'waitKey(milliseconds)'. destroyWindows(): This function closes all windows. When we create windows, we allocate some memory. destroyWindow() function releases that memory to the system. The following program shows how to load and show an image using OpenCV Libraries. #include<iostream> #include<opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; int main() { Mat myImage;//declaring a matrix named myImage// namedWindow("PhotoFrame");//declaring the window to show the image// myImage = imread("lakshmi.jpg");//loading the image named lakshme in the matrix// if (myImage.empty()) {//If the image is not loaded, show an error message// cout << "Couldn't load the image." << endl; system("pause");//pause the system and wait for users to press any key// return-1; } imshow("PhotoFrame", myImage);//display the image which is stored in the 'myImage' in the "myWindow" window// destroyWindow("Photoframe");//close the window and release allocate memory// waitKey(0);//wait till user press any key return 0; } On executing the above program, we get the following output −
[ { "code": null, "e": 1231, "s": 1062, "text": "In this topic, we will determine how to load and show images using OpenCV in C++. There are the following functions required for loading and showing an image in OpenCV." }, { "code": null, "e": 1548, "s": 1231, "text": " Mat: Mat is not a function. It is a data structure, a type of variable. Like int, char, string variable types in C++, Mat is a variable of OpenCV, which creates a matrix data structure to load images inside it. In this program, we wrote 'Mat myImage;'. That means we are declaring a matrix variable named 'myImage'." }, { "code": null, "e": 1743, "s": 1548, "text": " namedWindow(): It allocates some memory and creates a window to show the image. It works like a photo frame. In OpenCV, we have to make the function as 'namedWindow(\"name of the window\",flag)'." }, { "code": null, "e": 1980, "s": 1743, "text": "3. imread(): This function reads an image from a defined location. This program reads the image from 'C:' drive. To use this function, you have to write it as 'imread(\"location of the image/name of the image with the extension\", flag)'." }, { "code": null, "e": 2137, "s": 1980, "text": " imshow(): This function shows the image in the defined window. To use this function you have to write as 'imshow(name of the window\", name of the matrix)'." }, { "code": null, "e": 2295, "s": 2137, "text": " waitKey(): This is a vital function of OpenCV. To process images and executes operations, we must allow the system some time. If we don't do it, we will not" }, { "code": null, "e": 2739, "s": 2295, "text": "This function waits for a certain period before closing the program. If you use waitKey(10000), it will close the program after 10 seconds. If you write waitKey(0), it will get the desired output. This function will enable us to give the system the required time to operate. wait for the keystroke from the user. When the user clicks any key from the keyboard, the program will stop. This function has to be written as 'waitKey(milliseconds)'." }, { "code": null, "e": 2902, "s": 2739, "text": " destroyWindows(): This function closes all windows. When we create windows, we allocate some memory. destroyWindow() function releases that memory to the system." }, { "code": null, "e": 2984, "s": 2902, "text": "The following program shows how to load and show an image using OpenCV Libraries." }, { "code": null, "e": 3788, "s": 2984, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\nusing namespace cv;\nusing namespace std;\nint main() {\n Mat myImage;//declaring a matrix named myImage//\n namedWindow(\"PhotoFrame\");//declaring the window to show the image//\n myImage = imread(\"lakshmi.jpg\");//loading the image named lakshme in the matrix//\n if (myImage.empty()) {//If the image is not loaded, show an error message//\n cout << \"Couldn't load the image.\" << endl;\n system(\"pause\");//pause the system and wait for users to press any key//\n return-1;\n }\n imshow(\"PhotoFrame\", myImage);//display the image which is stored in the 'myImage' in the \"myWindow\" window// \n destroyWindow(\"Photoframe\");//close the window and release allocate memory//\n waitKey(0);//wait till user press any key\n return 0;\n}" }, { "code": null, "e": 3850, "s": 3788, "text": "On executing the above program, we get the following output −" } ]
What are string and String data types in C#?
String stands for System.String whereas string is an alias in C# for System.String − For example − string str = "Welcome!"; It’s not essential, but generally String is used when you work with classes − string str = String.Format("Welcome! {0}!", user); Since string is an alias for System.String. The alias for other datatypes are − object: System.Object string: System.String bool: System.Boolean float: System.Single double: System.Double decimal: System.Decimal byte: System.Byte sbyte: System.SByte short: System.Int16 ushort: System.UInt16 int: System.Int32 uint: System.UInt32 long: System.Int64 ulong: System.UInt64 char: System.Char The String type in C# allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms − quoted and @quoted. String str = "Okay!";
[ { "code": null, "e": 1147, "s": 1062, "text": "String stands for System.String whereas string is an alias in C# for System.String −" }, { "code": null, "e": 1161, "s": 1147, "text": "For example −" }, { "code": null, "e": 1186, "s": 1161, "text": "string str = \"Welcome!\";" }, { "code": null, "e": 1264, "s": 1186, "text": "It’s not essential, but generally String is used when you work with classes −" }, { "code": null, "e": 1315, "s": 1264, "text": "string str = String.Format(\"Welcome! {0}!\", user);" }, { "code": null, "e": 1395, "s": 1315, "text": "Since string is an alias for System.String. The alias for other datatypes are −" }, { "code": null, "e": 1703, "s": 1395, "text": "object: System.Object\nstring: System.String\nbool: System.Boolean\nfloat: System.Single\ndouble: System.Double\ndecimal: System.Decimal\nbyte: System.Byte\nsbyte: System.SByte\nshort: System.Int16\nushort: System.UInt16\nint: System.Int32\nuint: System.UInt32\nlong: System.Int64\nulong: System.UInt64\nchar: System.Char" }, { "code": null, "e": 1969, "s": 1703, "text": "The String type in C# allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms − quoted and @quoted." }, { "code": null, "e": 1991, "s": 1969, "text": "String str = \"Okay!\";" } ]
Perl symlink Function
This function creates a symbolic link between OLDFILE and NEWFILE. On systems that don't support symbolic links, causes a fatal error. Following is the simple syntax for this function − symlink ( OLDFILE, NEWFILE ) This function returns 0 on failure and 1 on success. Following is the example code showing its basic usage, first create one file test.txt in /tmp directory and then try out following example it will create a symbolic link in the same directory:: #!/usr/bin/perl -w symlink("/tmp/text.txt", "/tmp/symlink_to_text.txt"); When above code is executed, it produces the following result − Symbolic link gets created 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": 2355, "s": 2220, "text": "This function creates a symbolic link between OLDFILE and NEWFILE. On systems that don't support symbolic links, causes a fatal error." }, { "code": null, "e": 2406, "s": 2355, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2436, "s": 2406, "text": "symlink ( OLDFILE, NEWFILE )\n" }, { "code": null, "e": 2489, "s": 2436, "text": "This function returns 0 on failure and 1 on success." }, { "code": null, "e": 2683, "s": 2489, "text": "Following is the example code showing its basic usage, first create one file test.txt in /tmp directory and then try out following example it will create a symbolic link in the same directory::" }, { "code": null, "e": 2757, "s": 2683, "text": "#!/usr/bin/perl -w\n\nsymlink(\"/tmp/text.txt\", \"/tmp/symlink_to_text.txt\");" }, { "code": null, "e": 2821, "s": 2757, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 2849, "s": 2821, "text": "Symbolic link gets created\n" }, { "code": null, "e": 2884, "s": 2849, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2898, "s": 2884, "text": " Devi Killada" }, { "code": null, "e": 2933, "s": 2898, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2953, "s": 2933, "text": " Harshit Srivastava" }, { "code": null, "e": 2986, "s": 2953, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3002, "s": 2986, "text": " TELCOMA Global" }, { "code": null, "e": 3035, "s": 3002, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3052, "s": 3035, "text": " Mohammad Nauman" }, { "code": null, "e": 3085, "s": 3052, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3108, "s": 3085, "text": " Stone River ELearning" }, { "code": null, "e": 3143, "s": 3108, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3166, "s": 3143, "text": " Stone River ELearning" }, { "code": null, "e": 3173, "s": 3166, "text": " Print" }, { "code": null, "e": 3184, "s": 3173, "text": " Add Notes" } ]
Get Standard Deviation of a Column in R dataframe - GeeksforGeeks
07 Apr, 2021 In this article, we are going to find the standard deviation of a column in a dataframe in R Programming Language. To select the desired column of a dataframe $ is used. Syntax: dataframe$column_name Formula for variance: where n is the total number of observations and x bar is the mean Formula for standard deviation: In the R programming language, for finding standard deviation on set of data, the method used is sd() Syntax: sd(data_values) Where data-values are a vector input or data frame input. Given below are some examples to help you understand this better Example 1: R # data1 with vector of elementsdata1=c(1,2,3,4,5) # data2 with vector of elementsdata2=c("sravan",'bobby','rohith','gnanu','ojaswi') # give input to the data which is a dataframedata=data.frame(a1=data1,a2=data2) # finding standard deviation of dataframe# column 1print(sd(data$a1)) Output: [1] 1.581139 Example 2: R # data1 with vector of elementsdata1=c(1,2,3,4,5) # data2 with vector of elementsdata2=c(10,20,30,40,50) # give input to the data which is a# dataframedata=data.frame(a1=data1,a2=data2) # finding standard deviation of dataframe# column 1print(sd(data$a1)) # finding standard deviation of dataframe# column 2print(sd(data$a2)) Output: [1] 1.581139 [1] 15.81139 Example 3: R # data1 with vector of elements (float# values)data1=c(1.0,2,3,4,5,8) # data2 with vector of elements(float# values)data2=c(10,20.5,30.3,40,50,67.89) # give input to the data which is a # dataframedata=data.frame(a1=data1,a2=data2) # finding standard deviation of dataframe # column 1print(sd(data$a1)) # finding standard deviation of dataframe # column 2print(sd(data$a2)) Output: [1] 2.483277 [1] 20.86387 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Logistic Regression in R Programming How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25358, "s": 25242, "text": "In this article, we are going to find the standard deviation of a column in a dataframe in R Programming Language. " }, { "code": null, "e": 25413, "s": 25358, "text": "To select the desired column of a dataframe $ is used." }, { "code": null, "e": 25421, "s": 25413, "text": "Syntax:" }, { "code": null, "e": 25443, "s": 25421, "text": "dataframe$column_name" }, { "code": null, "e": 25465, "s": 25443, "text": "Formula for variance:" }, { "code": null, "e": 25531, "s": 25465, "text": "where n is the total number of observations and x bar is the mean" }, { "code": null, "e": 25563, "s": 25531, "text": "Formula for standard deviation:" }, { "code": null, "e": 25665, "s": 25563, "text": "In the R programming language, for finding standard deviation on set of data, the method used is sd()" }, { "code": null, "e": 25673, "s": 25665, "text": "Syntax:" }, { "code": null, "e": 25689, "s": 25673, "text": "sd(data_values)" }, { "code": null, "e": 25747, "s": 25689, "text": "Where data-values are a vector input or data frame input." }, { "code": null, "e": 25812, "s": 25747, "text": "Given below are some examples to help you understand this better" }, { "code": null, "e": 25823, "s": 25812, "text": "Example 1:" }, { "code": null, "e": 25825, "s": 25823, "text": "R" }, { "code": "# data1 with vector of elementsdata1=c(1,2,3,4,5) # data2 with vector of elementsdata2=c(\"sravan\",'bobby','rohith','gnanu','ojaswi') # give input to the data which is a dataframedata=data.frame(a1=data1,a2=data2) # finding standard deviation of dataframe# column 1print(sd(data$a1))", "e": 26111, "s": 25825, "text": null }, { "code": null, "e": 26119, "s": 26111, "text": "Output:" }, { "code": null, "e": 26132, "s": 26119, "text": "[1] 1.581139" }, { "code": null, "e": 26143, "s": 26132, "text": "Example 2:" }, { "code": null, "e": 26145, "s": 26143, "text": "R" }, { "code": "# data1 with vector of elementsdata1=c(1,2,3,4,5) # data2 with vector of elementsdata2=c(10,20,30,40,50) # give input to the data which is a# dataframedata=data.frame(a1=data1,a2=data2) # finding standard deviation of dataframe# column 1print(sd(data$a1)) # finding standard deviation of dataframe# column 2print(sd(data$a2))", "e": 26475, "s": 26145, "text": null }, { "code": null, "e": 26483, "s": 26475, "text": "Output:" }, { "code": null, "e": 26496, "s": 26483, "text": "[1] 1.581139" }, { "code": null, "e": 26509, "s": 26496, "text": "[1] 15.81139" }, { "code": null, "e": 26520, "s": 26509, "text": "Example 3:" }, { "code": null, "e": 26522, "s": 26520, "text": "R" }, { "code": "# data1 with vector of elements (float# values)data1=c(1.0,2,3,4,5,8) # data2 with vector of elements(float# values)data2=c(10,20.5,30.3,40,50,67.89) # give input to the data which is a # dataframedata=data.frame(a1=data1,a2=data2) # finding standard deviation of dataframe # column 1print(sd(data$a1)) # finding standard deviation of dataframe # column 2print(sd(data$a2))", "e": 26900, "s": 26522, "text": null }, { "code": null, "e": 26908, "s": 26900, "text": "Output:" }, { "code": null, "e": 26921, "s": 26908, "text": "[1] 2.483277" }, { "code": null, "e": 26934, "s": 26921, "text": "[1] 20.86387" }, { "code": null, "e": 26941, "s": 26934, "text": "Picked" }, { "code": null, "e": 26962, "s": 26941, "text": "R DataFrame-Programs" }, { "code": null, "e": 26974, "s": 26962, "text": "R-DataFrame" }, { "code": null, "e": 26985, "s": 26974, "text": "R Language" }, { "code": null, "e": 26996, "s": 26985, "text": "R Programs" }, { "code": null, "e": 27094, "s": 26996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27103, "s": 27094, "text": "Comments" }, { "code": null, "e": 27116, "s": 27103, "text": "Old Comments" }, { "code": null, "e": 27168, "s": 27116, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27206, "s": 27168, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27241, "s": 27206, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27299, "s": 27241, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27336, "s": 27299, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27394, "s": 27336, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27443, "s": 27394, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27493, "s": 27443, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27536, "s": 27493, "text": "Replace Specific Characters in String in R" } ]
Combinatoric Iterators in Python - GeeksforGeeks
12 Dec, 2019 An iterator is an object that can be traversed through all its values. Simply put, iterators are data type that can be looped upon. Generators are iterators but as they cannot return values instead they yield results when they are executed, using the ‘yield’ function. Generators can be recursive just like functions. These recursive generators which are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products are called combinatoric iterators. In python there are 4 combinatoric iterators: Product()This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function are tuples in sorted order.Syntax:product(iterables*, repeat=1)Examples:# import the product function from itertools modulefrom itertools import product print("The cartesian product using repeat:")print(list(product([1, 2], repeat=2)))print() print("The cartesian product of the containers:")print(list(product(['geeks', 'for', 'geeks'], '2')))print() print("The cartesian product of the containers:")print(list(product('AB', [3,4])))Output:The cartesian product using repeat: [(1, 1), (1, 2), (2, 1), (2, 2)] The cartesian product of the containers: [('geeks', '2'), ('for', '2'), ('geeks', '2')] The cartesian product of the containers: [('A', 3), ('A', 4), ('B', 3), ('B', 4)] Permutations()Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable.Syntax:permutations(iterables*, group_size=None)Example:# import the product function from itertools modulefrom itertools import permutations print ("All the permutations of the given list is:") print (list(permutations([1, 'geeks'], 2)))print() print ("All the permutations of the given string is:") print (list(permutations('AB')))print() print ("All the permutations of the given container is:") print(list(permutations(range(3), 2)))Output:All the permutations of the given list is: [(1, 'geeks'), ('geeks', 1)] All the permutations of the given string is: [('A', 'B'), ('B', 'A')] All the permutations of the given container is: [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] Combinations():This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order.Syntax:combinations(iterables*, group_size)Examples:# import combinations from itertools module from itertools import combinations print ("All the combination of list in sorted order(without replacement) is:") print(list(combinations(['A', 2], 2)))print() print ("All the combination of string in sorted order(without replacement) is:")print(list(combinations('AB', 2)))print() print ("All the combination of list in sorted order(without replacement) is:")print(list(combinations(range(2),1)))Output:All the combination of list in sorted order(without replacement) is: [('A', 2)] All the combination of string in sorted order(without replacement) is: [('A', 'B')] All the combination of list in sorted order(without replacement) is: [(0,), (1,)] Combinations_with_replacement():This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function.Syntax:combinations_with_replacement(iterables*, n=None)Examples:# import combinations from itertools module from itertools import combinations_with_replacement print ("All the combination of string in sorted order(with replacement) is:")print(list(combinations_with_replacement("AB", 2)))print() print ("All the combination of list in sorted order(with replacement) is:")print(list(combinations_with_replacement([1, 2], 2)))print() print ("All the combination of container in sorted order(with replacement) is:")print(list(combinations_with_replacement(range(2), 1)))Output:All the combination of string in sorted order(with replacement) is: [('A', 'A'), ('A', 'B'), ('B', 'B')] All the combination of list in sorted order(with replacement) is: [(1, 1), (1, 2), (2, 2)] All the combination of container in sorted order(with replacement) is: [(0,), (1,)] Product()This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function are tuples in sorted order.Syntax:product(iterables*, repeat=1)Examples:# import the product function from itertools modulefrom itertools import product print("The cartesian product using repeat:")print(list(product([1, 2], repeat=2)))print() print("The cartesian product of the containers:")print(list(product(['geeks', 'for', 'geeks'], '2')))print() print("The cartesian product of the containers:")print(list(product('AB', [3,4])))Output:The cartesian product using repeat: [(1, 1), (1, 2), (2, 1), (2, 2)] The cartesian product of the containers: [('geeks', '2'), ('for', '2'), ('geeks', '2')] The cartesian product of the containers: [('A', 3), ('A', 4), ('B', 3), ('B', 4)] This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function are tuples in sorted order. Syntax: product(iterables*, repeat=1) Examples: # import the product function from itertools modulefrom itertools import product print("The cartesian product using repeat:")print(list(product([1, 2], repeat=2)))print() print("The cartesian product of the containers:")print(list(product(['geeks', 'for', 'geeks'], '2')))print() print("The cartesian product of the containers:")print(list(product('AB', [3,4]))) Output: The cartesian product using repeat: [(1, 1), (1, 2), (2, 1), (2, 2)] The cartesian product of the containers: [('geeks', '2'), ('for', '2'), ('geeks', '2')] The cartesian product of the containers: [('A', 3), ('A', 4), ('B', 3), ('B', 4)] Permutations()Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable.Syntax:permutations(iterables*, group_size=None)Example:# import the product function from itertools modulefrom itertools import permutations print ("All the permutations of the given list is:") print (list(permutations([1, 'geeks'], 2)))print() print ("All the permutations of the given string is:") print (list(permutations('AB')))print() print ("All the permutations of the given container is:") print(list(permutations(range(3), 2)))Output:All the permutations of the given list is: [(1, 'geeks'), ('geeks', 1)] All the permutations of the given string is: [('A', 'B'), ('B', 'A')] All the permutations of the given container is: [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable. Syntax: permutations(iterables*, group_size=None) Example: # import the product function from itertools modulefrom itertools import permutations print ("All the permutations of the given list is:") print (list(permutations([1, 'geeks'], 2)))print() print ("All the permutations of the given string is:") print (list(permutations('AB')))print() print ("All the permutations of the given container is:") print(list(permutations(range(3), 2))) Output: All the permutations of the given list is: [(1, 'geeks'), ('geeks', 1)] All the permutations of the given string is: [('A', 'B'), ('B', 'A')] All the permutations of the given container is: [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] Combinations():This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order.Syntax:combinations(iterables*, group_size)Examples:# import combinations from itertools module from itertools import combinations print ("All the combination of list in sorted order(without replacement) is:") print(list(combinations(['A', 2], 2)))print() print ("All the combination of string in sorted order(without replacement) is:")print(list(combinations('AB', 2)))print() print ("All the combination of list in sorted order(without replacement) is:")print(list(combinations(range(2),1)))Output:All the combination of list in sorted order(without replacement) is: [('A', 2)] All the combination of string in sorted order(without replacement) is: [('A', 'B')] All the combination of list in sorted order(without replacement) is: [(0,), (1,)] This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order. Syntax: combinations(iterables*, group_size) Examples: # import combinations from itertools module from itertools import combinations print ("All the combination of list in sorted order(without replacement) is:") print(list(combinations(['A', 2], 2)))print() print ("All the combination of string in sorted order(without replacement) is:")print(list(combinations('AB', 2)))print() print ("All the combination of list in sorted order(without replacement) is:")print(list(combinations(range(2),1))) Output: All the combination of list in sorted order(without replacement) is: [('A', 2)] All the combination of string in sorted order(without replacement) is: [('A', 'B')] All the combination of list in sorted order(without replacement) is: [(0,), (1,)] Combinations_with_replacement():This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function.Syntax:combinations_with_replacement(iterables*, n=None)Examples:# import combinations from itertools module from itertools import combinations_with_replacement print ("All the combination of string in sorted order(with replacement) is:")print(list(combinations_with_replacement("AB", 2)))print() print ("All the combination of list in sorted order(with replacement) is:")print(list(combinations_with_replacement([1, 2], 2)))print() print ("All the combination of container in sorted order(with replacement) is:")print(list(combinations_with_replacement(range(2), 1)))Output:All the combination of string in sorted order(with replacement) is: [('A', 'A'), ('A', 'B'), ('B', 'B')] All the combination of list in sorted order(with replacement) is: [(1, 1), (1, 2), (2, 2)] All the combination of container in sorted order(with replacement) is: [(0,), (1,)] This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function. Syntax: combinations_with_replacement(iterables*, n=None) Examples: # import combinations from itertools module from itertools import combinations_with_replacement print ("All the combination of string in sorted order(with replacement) is:")print(list(combinations_with_replacement("AB", 2)))print() print ("All the combination of list in sorted order(with replacement) is:")print(list(combinations_with_replacement([1, 2], 2)))print() print ("All the combination of container in sorted order(with replacement) is:")print(list(combinations_with_replacement(range(2), 1))) Output: All the combination of string in sorted order(with replacement) is: [('A', 'A'), ('A', 'B'), ('B', 'B')] All the combination of list in sorted order(with replacement) is: [(1, 1), (1, 2), (2, 2)] All the combination of container in sorted order(with replacement) is: [(0,), (1,)] Python-itertools Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions 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 Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n12 Dec, 2019" }, { "code": null, "e": 24783, "s": 24292, "text": "An iterator is an object that can be traversed through all its values. Simply put, iterators are data type that can be looped upon. Generators are iterators but as they cannot return values instead they yield results when they are executed, using the ‘yield’ function. Generators can be recursive just like functions. These recursive generators which are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products are called combinatoric iterators." }, { "code": null, "e": 24829, "s": 24783, "text": "In python there are 4 combinatoric iterators:" }, { "code": null, "e": 28902, "s": 24829, "text": "Product()This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function are tuples in sorted order.Syntax:product(iterables*, repeat=1)Examples:# import the product function from itertools modulefrom itertools import product print(\"The cartesian product using repeat:\")print(list(product([1, 2], repeat=2)))print() print(\"The cartesian product of the containers:\")print(list(product(['geeks', 'for', 'geeks'], '2')))print() print(\"The cartesian product of the containers:\")print(list(product('AB', [3,4])))Output:The cartesian product using repeat:\n[(1, 1), (1, 2), (2, 1), (2, 2)]\n\nThe cartesian product of the containers:\n[('geeks', '2'), ('for', '2'), ('geeks', '2')]\n\nThe cartesian product of the containers:\n[('A', 3), ('A', 4), ('B', 3), ('B', 4)]\nPermutations()Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable.Syntax:permutations(iterables*, group_size=None)Example:# import the product function from itertools modulefrom itertools import permutations print (\"All the permutations of the given list is:\") print (list(permutations([1, 'geeks'], 2)))print() print (\"All the permutations of the given string is:\") print (list(permutations('AB')))print() print (\"All the permutations of the given container is:\") print(list(permutations(range(3), 2)))Output:All the permutations of the given list is:\n[(1, 'geeks'), ('geeks', 1)]\n\nAll the permutations of the given string is:\n[('A', 'B'), ('B', 'A')]\n\nAll the permutations of the given container is:\n[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]\nCombinations():This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order.Syntax:combinations(iterables*, group_size)Examples:# import combinations from itertools module from itertools import combinations print (\"All the combination of list in sorted order(without replacement) is:\") print(list(combinations(['A', 2], 2)))print() print (\"All the combination of string in sorted order(without replacement) is:\")print(list(combinations('AB', 2)))print() print (\"All the combination of list in sorted order(without replacement) is:\")print(list(combinations(range(2),1)))Output:All the combination of list in sorted order(without replacement) is:\n[('A', 2)]\n\nAll the combination of string in sorted order(without replacement) is:\n[('A', 'B')]\n\nAll the combination of list in sorted order(without replacement) is:\n[(0,), (1,)]\n\nCombinations_with_replacement():This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function.Syntax:combinations_with_replacement(iterables*, n=None)Examples:# import combinations from itertools module from itertools import combinations_with_replacement print (\"All the combination of string in sorted order(with replacement) is:\")print(list(combinations_with_replacement(\"AB\", 2)))print() print (\"All the combination of list in sorted order(with replacement) is:\")print(list(combinations_with_replacement([1, 2], 2)))print() print (\"All the combination of container in sorted order(with replacement) is:\")print(list(combinations_with_replacement(range(2), 1)))Output:All the combination of string in sorted order(with replacement) is:\n[('A', 'A'), ('A', 'B'), ('B', 'B')]\n\nAll the combination of list in sorted order(with replacement) is:\n[(1, 1), (1, 2), (2, 2)]\n\nAll the combination of container in sorted order(with replacement) is:\n[(0,), (1,)]\n" }, { "code": null, "e": 29819, "s": 28902, "text": "Product()This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function are tuples in sorted order.Syntax:product(iterables*, repeat=1)Examples:# import the product function from itertools modulefrom itertools import product print(\"The cartesian product using repeat:\")print(list(product([1, 2], repeat=2)))print() print(\"The cartesian product of the containers:\")print(list(product(['geeks', 'for', 'geeks'], '2')))print() print(\"The cartesian product of the containers:\")print(list(product('AB', [3,4])))Output:The cartesian product using repeat:\n[(1, 1), (1, 2), (2, 1), (2, 2)]\n\nThe cartesian product of the containers:\n[('geeks', '2'), ('for', '2'), ('geeks', '2')]\n\nThe cartesian product of the containers:\n[('A', 3), ('A', 4), ('B', 3), ('B', 4)]\n" }, { "code": null, "e": 30069, "s": 29819, "text": "This tool computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function are tuples in sorted order." }, { "code": null, "e": 30077, "s": 30069, "text": "Syntax:" }, { "code": null, "e": 30107, "s": 30077, "text": "product(iterables*, repeat=1)" }, { "code": null, "e": 30117, "s": 30107, "text": "Examples:" }, { "code": "# import the product function from itertools modulefrom itertools import product print(\"The cartesian product using repeat:\")print(list(product([1, 2], repeat=2)))print() print(\"The cartesian product of the containers:\")print(list(product(['geeks', 'for', 'geeks'], '2')))print() print(\"The cartesian product of the containers:\")print(list(product('AB', [3,4])))", "e": 30483, "s": 30117, "text": null }, { "code": null, "e": 30491, "s": 30483, "text": "Output:" }, { "code": null, "e": 30733, "s": 30491, "text": "The cartesian product using repeat:\n[(1, 1), (1, 2), (2, 1), (2, 2)]\n\nThe cartesian product of the containers:\n[('geeks', '2'), ('for', '2'), ('geeks', '2')]\n\nThe cartesian product of the containers:\n[('A', 3), ('A', 4), ('B', 3), ('B', 4)]\n" }, { "code": null, "e": 31796, "s": 30733, "text": "Permutations()Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable.Syntax:permutations(iterables*, group_size=None)Example:# import the product function from itertools modulefrom itertools import permutations print (\"All the permutations of the given list is:\") print (list(permutations([1, 'geeks'], 2)))print() print (\"All the permutations of the given string is:\") print (list(permutations('AB')))print() print (\"All the permutations of the given container is:\") print(list(permutations(range(3), 2)))Output:All the permutations of the given list is:\n[(1, 'geeks'), ('geeks', 1)]\n\nAll the permutations of the given string is:\n[('A', 'B'), ('B', 'A')]\n\nAll the permutations of the given container is:\n[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]\n" }, { "code": null, "e": 32157, "s": 31796, "text": "Permutations() as the name speaks for itself is used to generate all possible permutations of an iterable. All elements are treated as unique based on their position and not their values. This function takes an iterable and group_size, if the value of group_size is not specified or is equal to None then the value of group_size becomes length of the iterable." }, { "code": null, "e": 32165, "s": 32157, "text": "Syntax:" }, { "code": null, "e": 32207, "s": 32165, "text": "permutations(iterables*, group_size=None)" }, { "code": null, "e": 32216, "s": 32207, "text": "Example:" }, { "code": "# import the product function from itertools modulefrom itertools import permutations print (\"All the permutations of the given list is:\") print (list(permutations([1, 'geeks'], 2)))print() print (\"All the permutations of the given string is:\") print (list(permutations('AB')))print() print (\"All the permutations of the given container is:\") print(list(permutations(range(3), 2)))", "e": 32601, "s": 32216, "text": null }, { "code": null, "e": 32609, "s": 32601, "text": "Output:" }, { "code": null, "e": 32851, "s": 32609, "text": "All the permutations of the given list is:\n[(1, 'geeks'), ('geeks', 1)]\n\nAll the permutations of the given string is:\n[('A', 'B'), ('B', 'A')]\n\nAll the permutations of the given container is:\n[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]\n" }, { "code": null, "e": 33773, "s": 32851, "text": "Combinations():This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order.Syntax:combinations(iterables*, group_size)Examples:# import combinations from itertools module from itertools import combinations print (\"All the combination of list in sorted order(without replacement) is:\") print(list(combinations(['A', 2], 2)))print() print (\"All the combination of string in sorted order(without replacement) is:\")print(list(combinations('AB', 2)))print() print (\"All the combination of list in sorted order(without replacement) is:\")print(list(combinations(range(2),1)))Output:All the combination of list in sorted order(without replacement) is:\n[('A', 2)]\n\nAll the combination of string in sorted order(without replacement) is:\n[('A', 'B')]\n\nAll the combination of list in sorted order(without replacement) is:\n[(0,), (1,)]\n\n" }, { "code": null, "e": 33927, "s": 33773, "text": "This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order." }, { "code": null, "e": 33935, "s": 33927, "text": "Syntax:" }, { "code": null, "e": 33972, "s": 33935, "text": "combinations(iterables*, group_size)" }, { "code": null, "e": 33982, "s": 33972, "text": "Examples:" }, { "code": "# import combinations from itertools module from itertools import combinations print (\"All the combination of list in sorted order(without replacement) is:\") print(list(combinations(['A', 2], 2)))print() print (\"All the combination of string in sorted order(without replacement) is:\")print(list(combinations('AB', 2)))print() print (\"All the combination of list in sorted order(without replacement) is:\")print(list(combinations(range(2),1)))", "e": 34428, "s": 33982, "text": null }, { "code": null, "e": 34436, "s": 34428, "text": "Output:" }, { "code": null, "e": 34686, "s": 34436, "text": "All the combination of list in sorted order(without replacement) is:\n[('A', 2)]\n\nAll the combination of string in sorted order(without replacement) is:\n[('A', 'B')]\n\nAll the combination of list in sorted order(without replacement) is:\n[(0,), (1,)]\n\n" }, { "code": null, "e": 35860, "s": 34686, "text": "Combinations_with_replacement():This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function.Syntax:combinations_with_replacement(iterables*, n=None)Examples:# import combinations from itertools module from itertools import combinations_with_replacement print (\"All the combination of string in sorted order(with replacement) is:\")print(list(combinations_with_replacement(\"AB\", 2)))print() print (\"All the combination of list in sorted order(with replacement) is:\")print(list(combinations_with_replacement([1, 2], 2)))print() print (\"All the combination of container in sorted order(with replacement) is:\")print(list(combinations_with_replacement(range(2), 1)))Output:All the combination of string in sorted order(with replacement) is:\n[('A', 'A'), ('A', 'B'), ('B', 'B')]\n\nAll the combination of list in sorted order(with replacement) is:\n[(1, 1), (1, 2), (2, 2)]\n\nAll the combination of container in sorted order(with replacement) is:\n[(0,), (1,)]\n" }, { "code": null, "e": 36141, "s": 35860, "text": "This function returns a subsequence of length n from the elements of the iterable where n is the argument that the function takes determining the length of the subsequences generated by the function. Individual elements may repeat itself in combinations_with_replacement function." }, { "code": null, "e": 36149, "s": 36141, "text": "Syntax:" }, { "code": null, "e": 36199, "s": 36149, "text": "combinations_with_replacement(iterables*, n=None)" }, { "code": null, "e": 36209, "s": 36199, "text": "Examples:" }, { "code": "# import combinations from itertools module from itertools import combinations_with_replacement print (\"All the combination of string in sorted order(with replacement) is:\")print(list(combinations_with_replacement(\"AB\", 2)))print() print (\"All the combination of list in sorted order(with replacement) is:\")print(list(combinations_with_replacement([1, 2], 2)))print() print (\"All the combination of container in sorted order(with replacement) is:\")print(list(combinations_with_replacement(range(2), 1)))", "e": 36717, "s": 36209, "text": null }, { "code": null, "e": 36725, "s": 36717, "text": "Output:" }, { "code": null, "e": 37008, "s": 36725, "text": "All the combination of string in sorted order(with replacement) is:\n[('A', 'A'), ('A', 'B'), ('B', 'B')]\n\nAll the combination of list in sorted order(with replacement) is:\n[(1, 1), (1, 2), (2, 2)]\n\nAll the combination of container in sorted order(with replacement) is:\n[(0,), (1,)]\n" }, { "code": null, "e": 37025, "s": 37008, "text": "Python-itertools" }, { "code": null, "e": 37032, "s": 37025, "text": "Python" }, { "code": null, "e": 37051, "s": 37032, "text": "Technical Scripter" }, { "code": null, "e": 37149, "s": 37051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37158, "s": 37149, "text": "Comments" }, { "code": null, "e": 37171, "s": 37158, "text": "Old Comments" }, { "code": null, "e": 37203, "s": 37171, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 37258, "s": 37203, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 37314, "s": 37258, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 37356, "s": 37314, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 37398, "s": 37356, "text": "Check if element exists in list in Python" }, { "code": null, "e": 37437, "s": 37398, "text": "Python | Get unique values from a list" }, { "code": null, "e": 37459, "s": 37437, "text": "Defaultdict in Python" }, { "code": null, "e": 37480, "s": 37459, "text": "Python OOPs Concepts" }, { "code": null, "e": 37511, "s": 37480, "text": "Python | os.path.join() method" } ]
Java Examples - Format Text in PDF
How to format the text in a PDF using Java. Following is the program to format the text in a PDF using Java. import com.itextpdf.io.font.FontConstants; import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.element.Text; public class FormatTextInPdf { public static void main(String args[]) throws Exception { String file = "C:/EXAMPLES/itextExamples/formatingTextInPDF.pdf"; //Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); //Creating a Document object Document doc = new Document(pdfDoc); //Adding text to the document Text text1 = new Text("Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms."); //Setting color to the text text1.setFontColor(Color.RED); //Setting font to the text text1.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); //Creating a paragraph 1 Paragraph para1 = new Paragraph(text1); Text text2 = new Text("The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more."); //Setting color to the text text2.setFontColor(Color.RED); //Setting font to the text text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); //Creating a paragraph 2 Paragraph para2 = new Paragraph(text2); //Adding paragraphs to the document doc.add(para1); doc.add(para2); //Closing the document doc.close(); System.out.println("Text added successfully.."); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2112, "s": 2068, "text": "How to format the text in a PDF using Java." }, { "code": null, "e": 2177, "s": 2112, "text": "Following is the program to format the text in a PDF using Java." }, { "code": null, "e": 4342, "s": 2177, "text": "import com.itextpdf.io.font.FontConstants; \n\nimport com.itextpdf.kernel.color.Color; \nimport com.itextpdf.kernel.font.PdfFontFactory; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \n\nimport com.itextpdf.layout.Document;\nimport com.itextpdf.layout.element.Paragraph; \nimport com.itextpdf.layout.element.Text; \n\npublic class FormatTextInPdf { \n public static void main(String args[]) throws Exception { \n String file = \"C:/EXAMPLES/itextExamples/formatingTextInPDF.pdf\"; \n \n //Creating a PdfDocument object \n PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); \n\n //Creating a Document object \n Document doc = new Document(pdfDoc); \n\n //Adding text to the document \n Text text1 = new Text(\"Tutorials Point originated from the idea that there exists\n a class of readers who respond better to online content and prefer to\n learn new skills at their own pace from the comforts of their drawing rooms.\");\n\n //Setting color to the text \n text1.setFontColor(Color.RED); \n\n //Setting font to the text \n text1.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); \n \n //Creating a paragraph 1 \n Paragraph para1 = new Paragraph(text1); \n\n Text text2 = new Text(\"The journey commenced with a single tutorial on HTML in 2006\n and elated by the response it generated, we worked our way to adding fresh\n tutorials to our repository which now proudly flaunts a wealth of tutorials and\n allied articles on topics ranging from programming languages to web designing to\n academics and much more.\"); \n \n //Setting color to the text \n text2.setFontColor(Color.RED);\n \n //Setting font to the text \n text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); \n\n //Creating a paragraph 2 \n Paragraph para2 = new Paragraph(text2); \n\n //Adding paragraphs to the document \n doc.add(para1); \n doc.add(para2); \n\n //Closing the document \n doc.close(); \n System.out.println(\"Text added successfully..\"); \n } \n} " }, { "code": null, "e": 4349, "s": 4342, "text": " Print" }, { "code": null, "e": 4360, "s": 4349, "text": " Add Notes" } ]
VBA - Arrays
We know very well that a variable is a container to store a value. Sometimes, developers are in a position to hold more than one value in a single variable at a time. When a series of values are stored in a single variable, then it is known as an array variable. Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the following example, the size of the array is mentioned in the brackets. 'Method 1 : Using Dim Dim arr1() 'Without Size 'Method 2 : Mentioning the Size Dim arr2(5) 'Declared with size of 5 'Method 3 : using 'Array' Parameter Dim arr3 arr3 = Array("apple","Orange","Grapes") Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO. Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO. Array Index cannot be negative. Array Index cannot be negative. VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable. VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable. The values are assigned to the array by specifying an array index value against each one of the values to be assigned. It can be a string. Add a button and add the following function. Private Sub Constant_demo_Click() Dim arr(5) arr(0) = "1" 'Number as String arr(1) = "VBScript" 'String arr(2) = 100 'Number arr(3) = 2.45 'Decimal Number arr(4) = #10/07/2013# 'Date arr(5) = #12.45 PM# 'Time msgbox("Value stored in Array index 0 : " & arr(0)) msgbox("Value stored in Array index 1 : " & arr(1)) msgbox("Value stored in Array index 2 : " & arr(2)) msgbox("Value stored in Array index 3 : " & arr(3)) msgbox("Value stored in Array index 4 : " & arr(4)) msgbox("Value stored in Array index 5 : " & arr(5)) End Sub When you execute the above function, it produces the following output. Value stored in Array index 0 : 1 Value stored in Array index 1 : VBScript Value stored in Array index 2 : 100 Value stored in Array index 3 : 2.45 Value stored in Array index 4 : 7/10/2013 Value stored in Array index 5 : 12:45:00 PM Arrays are not just limited to a single dimension, however, they can have a maximum of 60 dimensions. Two-dimensional arrays are the most commonly used ones. In the following example, a multi-dimensional array is declared with 3 rows and 4 columns. Private Sub Constant_demo_Click() Dim arr(2,3) as Variant ' Which has 3 rows and 4 columns arr(0,0) = "Apple" arr(0,1) = "Orange" arr(0,2) = "Grapes" arr(0,3) = "pineapple" arr(1,0) = "cucumber" arr(1,1) = "beans" arr(1,2) = "carrot" arr(1,3) = "tomato" arr(2,0) = "potato" arr(2,1) = "sandwitch" arr(2,2) = "coffee" arr(2,3) = "nuts" msgbox("Value in Array index 0,1 : " & arr(0,1)) msgbox("Value in Array index 2,2 : " & arr(2,2)) End Sub When you execute the above function, it produces the following output. Value stored in Array index : 0 , 1 : Orange Value stored in Array index : 2 , 2 : coffee ReDim statement is used to declare dynamic-array variables and allocate or reallocate storage space. ReDim [Preserve] varname(subscripts) [, varname(subscripts)] Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension. Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension. Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions. Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions. Subscripts − A required parameter, which indicates the size of the array. Subscripts − A required parameter, which indicates the size of the array. In the following example, an array has been redefined and then the values preserved when the existing size of the array is changed. Note − Upon resizing an array smaller than it was originally, the data in the eliminated elements will be lost. Private Sub Constant_demo_Click() Dim a() as variant i = 0 redim a(5) a(0) = "XYZ" a(1) = 41.25 a(2) = 22 REDIM PRESERVE a(7) For i = 3 to 7 a(i) = i Next 'to Fetch the output For i = 0 to ubound(a) Msgbox a(i) Next End Sub When you execute the above function, it produces the following output. XYZ 41.25 22 3 4 5 6 7 There are various inbuilt functions within VBScript which help the developers to handle arrays effectively. All the methods that are used in conjunction with arrays are listed below. Please click on the method name to know about it in detail. A Function, which returns an integer that corresponds to the smallest subscript of the given arrays. A Function, which returns an integer that corresponds to the largest subscript of the given arrays. A Function, which returns an array that contains a specified number of values. Split based on a delimiter. A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method. A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria. A Function, which returns a boolean value that indicates whether or not the input variable is an array. A Function, which recovers the allocated memory for the array variables. 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2198, "s": 1935, "text": "We know very well that a variable is a container to store a value. Sometimes, developers are in a position to hold more than one value in a single variable at a time. When a series of values are stored in a single variable, then it is known as an array variable." }, { "code": null, "e": 2405, "s": 2198, "text": "Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the following example, the size of the array is mentioned in the brackets." }, { "code": null, "e": 2609, "s": 2405, "text": "'Method 1 : Using Dim\nDim arr1()\t'Without Size\n\n'Method 2 : Mentioning the Size\nDim arr2(5) 'Declared with size of 5\n\n'Method 3 : using 'Array' Parameter\nDim arr3\narr3 = Array(\"apple\",\"Orange\",\"Grapes\")" }, { "code": null, "e": 2707, "s": 2609, "text": "Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO." }, { "code": null, "e": 2805, "s": 2707, "text": "Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO." }, { "code": null, "e": 2837, "s": 2805, "text": "Array Index cannot be negative." }, { "code": null, "e": 2869, "s": 2837, "text": "Array Index cannot be negative." }, { "code": null, "e": 3017, "s": 2869, "text": "VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable." }, { "code": null, "e": 3165, "s": 3017, "text": "VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable." }, { "code": null, "e": 3304, "s": 3165, "text": "The values are assigned to the array by specifying an array index value against each one of the values to be assigned. It can be a string." }, { "code": null, "e": 3349, "s": 3304, "text": "Add a button and add the following function." }, { "code": null, "e": 3951, "s": 3349, "text": "Private Sub Constant_demo_Click()\n Dim arr(5)\n arr(0) = \"1\" 'Number as String\n arr(1) = \"VBScript\" 'String\n arr(2) = 100 \t\t 'Number\n arr(3) = 2.45 \t\t 'Decimal Number\n arr(4) = #10/07/2013# 'Date\n arr(5) = #12.45 PM# 'Time\n \n msgbox(\"Value stored in Array index 0 : \" & arr(0))\n msgbox(\"Value stored in Array index 1 : \" & arr(1))\n msgbox(\"Value stored in Array index 2 : \" & arr(2))\n msgbox(\"Value stored in Array index 3 : \" & arr(3))\n msgbox(\"Value stored in Array index 4 : \" & arr(4))\n msgbox(\"Value stored in Array index 5 : \" & arr(5))\nEnd Sub" }, { "code": null, "e": 4022, "s": 3951, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 4257, "s": 4022, "text": "Value stored in Array index 0 : 1\nValue stored in Array index 1 : VBScript\nValue stored in Array index 2 : 100\nValue stored in Array index 3 : 2.45\nValue stored in Array index 4 : 7/10/2013\nValue stored in Array index 5 : 12:45:00 PM\n" }, { "code": null, "e": 4415, "s": 4257, "text": "Arrays are not just limited to a single dimension, however, they can have a maximum of 60 dimensions. Two-dimensional arrays are the most commonly used ones." }, { "code": null, "e": 4506, "s": 4415, "text": "In the following example, a multi-dimensional array is declared with 3 rows and 4 columns." }, { "code": null, "e": 5113, "s": 4506, "text": "Private Sub Constant_demo_Click()\n Dim arr(2,3) as Variant\t' Which has 3 rows and 4 columns\n arr(0,0) = \"Apple\" \n arr(0,1) = \"Orange\"\n arr(0,2) = \"Grapes\" \n arr(0,3) = \"pineapple\" \n arr(1,0) = \"cucumber\" \n arr(1,1) = \"beans\" \n arr(1,2) = \"carrot\" \n arr(1,3) = \"tomato\" \n arr(2,0) = \"potato\" \n arr(2,1) = \"sandwitch\" \n arr(2,2) = \"coffee\" \n arr(2,3) = \"nuts\" \n \n msgbox(\"Value in Array index 0,1 : \" & arr(0,1))\n msgbox(\"Value in Array index 2,2 : \" & arr(2,2))\nEnd Sub" }, { "code": null, "e": 5184, "s": 5113, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 5275, "s": 5184, "text": "Value stored in Array index : 0 , 1 : Orange\nValue stored in Array index : 2 , 2 : coffee\n" }, { "code": null, "e": 5376, "s": 5275, "text": "ReDim statement is used to declare dynamic-array variables and allocate or reallocate storage space." }, { "code": null, "e": 5438, "s": 5376, "text": "ReDim [Preserve] varname(subscripts) [, varname(subscripts)]\n" }, { "code": null, "e": 5566, "s": 5438, "text": "Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension." }, { "code": null, "e": 5694, "s": 5566, "text": "Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension." }, { "code": null, "e": 5828, "s": 5694, "text": "Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions." }, { "code": null, "e": 5962, "s": 5828, "text": "Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions." }, { "code": null, "e": 6036, "s": 5962, "text": "Subscripts − A required parameter, which indicates the size of the array." }, { "code": null, "e": 6110, "s": 6036, "text": "Subscripts − A required parameter, which indicates the size of the array." }, { "code": null, "e": 6242, "s": 6110, "text": "In the following example, an array has been redefined and then the values preserved when the existing size of the array is changed." }, { "code": null, "e": 6354, "s": 6242, "text": "Note − Upon resizing an array smaller than it was originally, the data in the eliminated elements will be lost." }, { "code": null, "e": 6629, "s": 6354, "text": "Private Sub Constant_demo_Click()\n Dim a() as variant\n i = 0\n redim a(5)\n a(0) = \"XYZ\"\n a(1) = 41.25\n a(2) = 22\n \n REDIM PRESERVE a(7)\n For i = 3 to 7\n a(i) = i\n Next\n \n 'to Fetch the output\n For i = 0 to ubound(a)\n Msgbox a(i)\n Next\nEnd Sub" }, { "code": null, "e": 6700, "s": 6629, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 6724, "s": 6700, "text": "XYZ\n41.25\n22\n3\n4\n5\n6\n7\n" }, { "code": null, "e": 6967, "s": 6724, "text": "There are various inbuilt functions within VBScript which help the developers to handle arrays effectively. All the methods that are used in conjunction with arrays are listed below. Please click on the method name to know about it in detail." }, { "code": null, "e": 7068, "s": 6967, "text": "A Function, which returns an integer that corresponds to the smallest subscript of the given arrays." }, { "code": null, "e": 7168, "s": 7068, "text": "A Function, which returns an integer that corresponds to the largest subscript of the given arrays." }, { "code": null, "e": 7275, "s": 7168, "text": "A Function, which returns an array that contains a specified number of values. Split based on a delimiter." }, { "code": null, "e": 7422, "s": 7275, "text": "A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method." }, { "code": null, "e": 7545, "s": 7422, "text": "A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria." }, { "code": null, "e": 7649, "s": 7545, "text": "A Function, which returns a boolean value that indicates whether or not the input variable is an array." }, { "code": null, "e": 7722, "s": 7649, "text": "A Function, which recovers the allocated memory for the array variables." }, { "code": null, "e": 7756, "s": 7722, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 7771, "s": 7756, "text": " Pavan Lalwani" }, { "code": null, "e": 7804, "s": 7771, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 7819, "s": 7804, "text": " Arnold Higuit" }, { "code": null, "e": 7854, "s": 7819, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7872, "s": 7854, "text": " Prashant Panchal" }, { "code": null, "e": 7905, "s": 7872, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 7923, "s": 7905, "text": " Prashant Panchal" }, { "code": null, "e": 7956, "s": 7923, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 7971, "s": 7956, "text": " Arnold Higuit" }, { "code": null, "e": 8007, "s": 7971, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 8035, "s": 8007, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 8042, "s": 8035, "text": " Print" }, { "code": null, "e": 8053, "s": 8042, "text": " Add Notes" } ]
Difference Between Django and Node.js - GeeksforGeeks
22 Feb, 2022 In this article, we will describe Django & Node.js so that we may establish a foundation on which we may describe their differences. Django is an open-source web framework written in Python that allows you to create web applications. Django was created in 2003 by Adrian Holovaty and Simon Willison while working at the Lawrence Journal-World newspaper company, and it was later released for public use in 2005. Django development is now supported by an independent foundation, the Django Software Foundation. Django is self-described as “The web framework for perfectionists with deadlines”. It encourages rapid development and clean, pragmatic design, so you can focus on writing your app without needing to reinvent the wheel. Django is one of the top Python web frameworks, and consistently takes the lead as the most recommended framework to learn when creating web applications with Python. Django takes care of user authentication, content administration, site maps, RSS feeds, and many more tasks — right out of the box. Django takes security seriously and helps developers avoid many common security mistakes, such as SQL injection, cross-site scripting, cross-site request forgery and clickjacking. Its user authentication system provides a secure way to manage user accounts and passwords. Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale to meet the heaviest traffic demands. Companies, organizations and governments have used Django to build all sorts of things — from content management systems to social networks to scientific computing platforms. Django follows the MVT (Model-View-Template) software design pattern, a variation of the MVC (Model-View-Controller) pattern. The difference is that Django takes ownership of the Controller aspect of the pattern, which leaves the template for a developer to design and implement. Django implements the Model, which defines the basic layer of the web application, and is implemented through the use of a database, such as PostgreSQL. The View implements the logic that is applied when a user navigates to a URL within the website or application. The Template system allows developers to generate dynamic HTML by containing static HTML as well as Python syntax in templates that control how static and dynamic content will be rendered on a page. Features of Django: Versatile: Django can build almost any type of website. It can also work with any client-side framework and can deliver content in any format such as HTML, JSON, XML, etc. Some sites which can be built using Django are wikis, social networks, new sites, etc. Security: Since the Django framework is made for making web development easy, it has been engineered in such a way that it automatically does the right things to protect the website. For instance, in the Django framework instead of putting a password in cookies, the hashed password is stored in it so that it can’t be fetched easily by hackers. Scalability: Django web nodes have no stored state, they scale horizontally – just fire up more of them when you need them. Being able to do this is the essence of good scalability. Instagram and Disqus are two Django-based products. Portability: All the codes of the Django framework are written in Python, which runs on many platforms, such as Linux, Windows, and Mac OS. Example: A Django Template which demonstrates looping through different pages in a Django project Python3 {% for page in pages %}{# Do something... #}{% endfor %} Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. It was developed by Ryan Dahl in 2009. It was composed in C, C++, and JavaScript. In other words, Node.js could be a JavaScript stage that capacities like a web server that permits engineers to compose total and exceedingly versatile web applications utilizing JavaScript. Node.js was built on the Google V8 JavaScript motor. There are thousands of open-source libraries to back Node.js You need to remember that NodeJS is not a framework and it’s not a programming language. Most people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. It’s used in production by large companies such as Paypal, Uber, Netflix, Walmart, and so on. Features of NodeJS: Easy to get started and can be used for prototyping and agile development. Provides fast and highly scalable services. Easy for a JavaScript programmer to build back-end services using Node.js, as it uses javascript. Source code cleaner and consistent. Huge open source library. It has asynchronous or Non-blocking nature. Example: This example create a Hello World web-based application using Node.js. Create a firstprogram.js file containing the following code. Javascript // Require http headervar http = require('http'); // Create serverhttp.createServer(function (req, res) { // HTTP Status: 200 : OK // Content Type: text/html res.writeHead(200, {'Content-Type': 'text/html'}); // Send the response body as "Hello World!" res.end('Hello World!'); }).listen(8080); Difference Between Django and Node.js: It is an open-source Python-based web framework to design web applications It is an open-source and JS runtime environment to develop web applications Django is programmed in Python Node.js is written in C, C++, and JavaScript Django is less scalable for small apps Node.js is more scalable than Django for small apps Django follows Model View Template architecture Node.js follows event-driven programming Django is more complex than node.js Node.js is less complex than Django It is modern and behind Node.js in utilization It is utilized broadly in numerous nations and ahead comparatively Django web development is more stable than node.js Node.js web development is less stable than Django ashushrma378 bhaskargeeksforgeeks ledv93 Django-basics NodeJS-Questions Node.js Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.readFile() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Express.js express.Router() Function Difference between promise and async await in Node.js Read JSON file using Python Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python
[ { "code": null, "e": 25417, "s": 25389, "text": "\n22 Feb, 2022" }, { "code": null, "e": 25550, "s": 25417, "text": "In this article, we will describe Django & Node.js so that we may establish a foundation on which we may describe their differences." }, { "code": null, "e": 26315, "s": 25550, "text": "Django is an open-source web framework written in Python that allows you to create web applications. Django was created in 2003 by Adrian Holovaty and Simon Willison while working at the Lawrence Journal-World newspaper company, and it was later released for public use in 2005. Django development is now supported by an independent foundation, the Django Software Foundation. Django is self-described as “The web framework for perfectionists with deadlines”. It encourages rapid development and clean, pragmatic design, so you can focus on writing your app without needing to reinvent the wheel. Django is one of the top Python web frameworks, and consistently takes the lead as the most recommended framework to learn when creating web applications with Python. " }, { "code": null, "e": 27023, "s": 26315, "text": "Django takes care of user authentication, content administration, site maps, RSS feeds, and many more tasks — right out of the box. Django takes security seriously and helps developers avoid many common security mistakes, such as SQL injection, cross-site scripting, cross-site request forgery and clickjacking. Its user authentication system provides a secure way to manage user accounts and passwords. Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale to meet the heaviest traffic demands. Companies, organizations and governments have used Django to build all sorts of things — from content management systems to social networks to scientific computing platforms." }, { "code": null, "e": 27304, "s": 27023, "text": "Django follows the MVT (Model-View-Template) software design pattern, a variation of the MVC (Model-View-Controller) pattern. The difference is that Django takes ownership of the Controller aspect of the pattern, which leaves the template for a developer to design and implement. " }, { "code": null, "e": 27768, "s": 27304, "text": "Django implements the Model, which defines the basic layer of the web application, and is implemented through the use of a database, such as PostgreSQL. The View implements the logic that is applied when a user navigates to a URL within the website or application. The Template system allows developers to generate dynamic HTML by containing static HTML as well as Python syntax in templates that control how static and dynamic content will be rendered on a page." }, { "code": null, "e": 27788, "s": 27768, "text": "Features of Django:" }, { "code": null, "e": 28047, "s": 27788, "text": "Versatile: Django can build almost any type of website. It can also work with any client-side framework and can deliver content in any format such as HTML, JSON, XML, etc. Some sites which can be built using Django are wikis, social networks, new sites, etc." }, { "code": null, "e": 28393, "s": 28047, "text": "Security: Since the Django framework is made for making web development easy, it has been engineered in such a way that it automatically does the right things to protect the website. For instance, in the Django framework instead of putting a password in cookies, the hashed password is stored in it so that it can’t be fetched easily by hackers." }, { "code": null, "e": 28627, "s": 28393, "text": "Scalability: Django web nodes have no stored state, they scale horizontally – just fire up more of them when you need them. Being able to do this is the essence of good scalability. Instagram and Disqus are two Django-based products." }, { "code": null, "e": 28767, "s": 28627, "text": "Portability: All the codes of the Django framework are written in Python, which runs on many platforms, such as Linux, Windows, and Mac OS." }, { "code": null, "e": 28865, "s": 28767, "text": "Example: A Django Template which demonstrates looping through different pages in a Django project" }, { "code": null, "e": 28873, "s": 28865, "text": "Python3" }, { "code": "{% for page in pages %}{# Do something... #}{% endfor %}", "e": 28930, "s": 28873, "text": null }, { "code": null, "e": 29791, "s": 28932, "text": "Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. It was developed by Ryan Dahl in 2009. It was composed in C, C++, and JavaScript. In other words, Node.js could be a JavaScript stage that capacities like a web server that permits engineers to compose total and exceedingly versatile web applications utilizing JavaScript. Node.js was built on the Google V8 JavaScript motor. There are thousands of open-source libraries to back Node.js You need to remember that NodeJS is not a framework and it’s not a programming language. Most people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. It’s used in production by large companies such as Paypal, Uber, Netflix, Walmart, and so on. " }, { "code": null, "e": 29811, "s": 29791, "text": "Features of NodeJS:" }, { "code": null, "e": 29886, "s": 29811, "text": "Easy to get started and can be used for prototyping and agile development." }, { "code": null, "e": 29930, "s": 29886, "text": "Provides fast and highly scalable services." }, { "code": null, "e": 30028, "s": 29930, "text": "Easy for a JavaScript programmer to build back-end services using Node.js, as it uses javascript." }, { "code": null, "e": 30064, "s": 30028, "text": "Source code cleaner and consistent." }, { "code": null, "e": 30090, "s": 30064, "text": "Huge open source library." }, { "code": null, "e": 30134, "s": 30090, "text": "It has asynchronous or Non-blocking nature." }, { "code": null, "e": 30275, "s": 30134, "text": "Example: This example create a Hello World web-based application using Node.js. Create a firstprogram.js file containing the following code." }, { "code": null, "e": 30286, "s": 30275, "text": "Javascript" }, { "code": "// Require http headervar http = require('http'); // Create serverhttp.createServer(function (req, res) { // HTTP Status: 200 : OK // Content Type: text/html res.writeHead(200, {'Content-Type': 'text/html'}); // Send the response body as \"Hello World!\" res.end('Hello World!'); }).listen(8080);", "e": 30612, "s": 30286, "text": null }, { "code": null, "e": 30651, "s": 30612, "text": "Difference Between Django and Node.js:" }, { "code": null, "e": 30728, "s": 30653, "text": "It is an open-source Python-based web framework to design web applications" }, { "code": null, "e": 30804, "s": 30728, "text": "It is an open-source and JS runtime environment to develop web applications" }, { "code": null, "e": 30835, "s": 30804, "text": "Django is programmed in Python" }, { "code": null, "e": 30880, "s": 30835, "text": "Node.js is written in C, C++, and JavaScript" }, { "code": null, "e": 30919, "s": 30880, "text": "Django is less scalable for small apps" }, { "code": null, "e": 30971, "s": 30919, "text": "Node.js is more scalable than Django for small apps" }, { "code": null, "e": 31019, "s": 30971, "text": "Django follows Model View Template architecture" }, { "code": null, "e": 31060, "s": 31019, "text": "Node.js follows event-driven programming" }, { "code": null, "e": 31096, "s": 31060, "text": "Django is more complex than node.js" }, { "code": null, "e": 31132, "s": 31096, "text": "Node.js is less complex than Django" }, { "code": null, "e": 31179, "s": 31132, "text": "It is modern and behind Node.js in utilization" }, { "code": null, "e": 31246, "s": 31179, "text": "It is utilized broadly in numerous nations and ahead comparatively" }, { "code": null, "e": 31297, "s": 31246, "text": "Django web development is more stable than node.js" }, { "code": null, "e": 31348, "s": 31297, "text": "Node.js web development is less stable than Django" }, { "code": null, "e": 31363, "s": 31350, "text": "ashushrma378" }, { "code": null, "e": 31384, "s": 31363, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 31391, "s": 31384, "text": "ledv93" }, { "code": null, "e": 31405, "s": 31391, "text": "Django-basics" }, { "code": null, "e": 31422, "s": 31405, "text": "NodeJS-Questions" }, { "code": null, "e": 31430, "s": 31422, "text": "Node.js" }, { "code": null, "e": 31437, "s": 31430, "text": "Python" }, { "code": null, "e": 31454, "s": 31437, "text": "Web Technologies" }, { "code": null, "e": 31552, "s": 31454, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31561, "s": 31552, "text": "Comments" }, { "code": null, "e": 31574, "s": 31561, "text": "Old Comments" }, { "code": null, "e": 31603, "s": 31574, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 31633, "s": 31603, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 31690, "s": 31633, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 31727, "s": 31690, "text": "Express.js express.Router() Function" }, { "code": null, "e": 31781, "s": 31727, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 31809, "s": 31781, "text": "Read JSON file using Python" }, { "code": null, "e": 31831, "s": 31809, "text": "Python map() function" }, { "code": null, "e": 31875, "s": 31831, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 31893, "s": 31875, "text": "Python Dictionary" } ]
Ruby | String insert Method - GeeksforGeeks
09 Dec, 2019 insert is a String class method in Ruby which is used to inserts the specified string before the character at the given index, modifying the given one. Negative indices count from the end of the string, and insert after the given character. Syntax: str.insert(index, other_str) Parameters: Here, str is the given string. Returns: A modified string. Example 1: # Ruby program to demonstrate # the insert method # Taking a string and # using the methodputs "Ruby".insert(0, 'Z') puts "Program".insert(3, 'Z') Output: ZRuby ProZgram Example 2: # Ruby program to demonstrate # the insert method # Taking a string and # using the methodputs "Sample".insert(-4, 'Z') puts "Articles".insert(-5, 'Z') Output: SamZple ArtiZcles Ruby String-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Array select() function Ruby | Enumerator each_with_index function Ruby | Hash delete() function Global Variable in Ruby Ruby | Case Statement Ruby | String gsub! Method Include v/s Extend in Ruby Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | Enumerable find() function Ruby | Numeric round() function
[ { "code": null, "e": 23664, "s": 23636, "text": "\n09 Dec, 2019" }, { "code": null, "e": 23905, "s": 23664, "text": "insert is a String class method in Ruby which is used to inserts the specified string before the character at the given index, modifying the given one. Negative indices count from the end of the string, and insert after the given character." }, { "code": null, "e": 23942, "s": 23905, "text": "Syntax: str.insert(index, other_str)" }, { "code": null, "e": 23985, "s": 23942, "text": "Parameters: Here, str is the given string." }, { "code": null, "e": 24013, "s": 23985, "text": "Returns: A modified string." }, { "code": null, "e": 24024, "s": 24013, "text": "Example 1:" }, { "code": "# Ruby program to demonstrate # the insert method # Taking a string and # using the methodputs \"Ruby\".insert(0, 'Z') puts \"Program\".insert(3, 'Z') ", "e": 24182, "s": 24024, "text": null }, { "code": null, "e": 24190, "s": 24182, "text": "Output:" }, { "code": null, "e": 24206, "s": 24190, "text": "ZRuby\nProZgram\n" }, { "code": null, "e": 24217, "s": 24206, "text": "Example 2:" }, { "code": "# Ruby program to demonstrate # the insert method # Taking a string and # using the methodputs \"Sample\".insert(-4, 'Z') puts \"Articles\".insert(-5, 'Z') ", "e": 24380, "s": 24217, "text": null }, { "code": null, "e": 24388, "s": 24380, "text": "Output:" }, { "code": null, "e": 24407, "s": 24388, "text": "SamZple\nArtiZcles\n" }, { "code": null, "e": 24425, "s": 24407, "text": "Ruby String-class" }, { "code": null, "e": 24438, "s": 24425, "text": "Ruby-Methods" }, { "code": null, "e": 24443, "s": 24438, "text": "Ruby" }, { "code": null, "e": 24541, "s": 24443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24550, "s": 24541, "text": "Comments" }, { "code": null, "e": 24563, "s": 24550, "text": "Old Comments" }, { "code": null, "e": 24594, "s": 24563, "text": "Ruby | Array select() function" }, { "code": null, "e": 24637, "s": 24594, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 24667, "s": 24637, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 24691, "s": 24667, "text": "Global Variable in Ruby" }, { "code": null, "e": 24713, "s": 24691, "text": "Ruby | Case Statement" }, { "code": null, "e": 24740, "s": 24713, "text": "Ruby | String gsub! Method" }, { "code": null, "e": 24767, "s": 24740, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 24835, "s": 24767, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" }, { "code": null, "e": 24869, "s": 24835, "text": "Ruby | Enumerable find() function" } ]
Who’s The MVP of NBA This Season? | by Yufeng | Towards Data Science
Don’t tell me it will be Giannis. Let’s find the answer from the data. I will frame this problem to a machine learning project and finish the project using the general working flow of machine learning similar to that introduced by DEEP LEARNING with Python [1]. Let’s get started. The question we want to ask is “Who is the MVP of this season in NBA?” Who is or is not, which seems like a binary classification problem. So, my first attempt is to build a classifier to differentiate MVP players and non-MVP players. However, I found building a classifier is not practical because I will face the problem of sample bias. Specifically, the number of non-MVP players is much larger than that of MVP players, which will result in the difficulties of training and evaluating the model. Therefore, I frame it to a regression problem and the output is defined as the MVP voting share each year. To note, I use my domain knowledge (I am very familiar with the NBA as a big fan) here to choose the correct direction for the project. To make full use of your domain knowledge is very important in conceiving a doable project. Then, let’s look at the data we have in terms of the input X and output y. The X part of the data is the statistics of the players who have got votes for MVP from the season of 1989–1990 to the season of 2018–2019. The y part of the data is the voting share. Then the data is separated to train and test dataset. And the test dataset will never be touched until we have our final model. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) This is an important step of a project, which defines the success of the model. In this regression problem, I use the mean squared error (MSE) as the evaluation metric. Specifically, the model is trying to minimize the MSE in the training process. Since the sample size is small, I use the K-fold cross-validation instead of a one-time train-validation-test split as my evaluation process. When the sample size is small, the splitting of data can actually affect the performance of the model. K-fold cross-validation is usually used to solve the problem. The preparation of the data includes missing value imputation and feature normalization. my_imputer = SimpleImputer(strategy="median")my_scaler = StandardScaler() The feature normalization is essential in regression problems, the different scale of features will be a disaster for the model training if pooled raw to the engine. In the modeling part, it’s easy to forget to set a baseline model no matter you are a beginner or experienced data scientist. Here we use a simple linear model as our baseline model and pack it together with the preprocessing of the data into a pipeline. For those who are interested in the pipeline usage, please refer to the Pipeline function in sklearn. from sklearn.linear_model import LinearRegressionmodel_base = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('ln_model',LinearRegression())])model_base.fit(X_train, y_train) The baseline model now is ready to be compared with. Next, we are going to develop a model that should perform better than the simple linear regression. I select three candidates, Elastic Net, Random Forest Regressor, and Deep Learning regression. Elastic Net is the combination of LASSO and Ridge, which penalizes the complexity of the model. If interested, please refer to one of my previous posts below. towardsdatascience.com For the hyperparameter tuning process of these three candidates, I write a function that combines preprocessing, hyperparameter space definition and cross-validation process. def train_hyper_tune(X,y): # create the pre-processing component my_scaler = StandardScaler() my_imputer = SimpleImputer(strategy="median") # define regressors ## regressors 1: Logistic Regression rgs_EN = ElasticNet(random_state=0) ## regressors 2: Random Forest regressors rgs_RF = RandomForestRegressor(random_state=0) ## regressors 3: Deep Learning rgs_DL = KerasRegressor(build_fn=my_DL) # define pipeline for three regressors ## rgs_LR pipe1 = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('en_model',rgs_EN)]) ## rgs_RF pipe2 = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('rf_model',rgs_RF)]) ## rgs_DL pipe3 = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('dl_model',rgs_DL)]) # create hyperparameter space of the three models ## rgs_LR param_grid1 = { 'en_model__alpha' : [1e-1,1,10], 'en_model__l1_ratio' : [0,0.5,1] } ## rgs_RF param_grid2 = { 'rf_model__n_estimators' : [50,100], 'rf_model__max_features' : [0.8,"auto"], 'rf_model__max_depth' : [4,5] } ## rgs_DL param_grid3 = { 'dl_model__epochs' : [6,12,18,24], 'dl_model__batchsize' : [256,512] } # set GridSearch via 5-fold cross-validation ## rgs_LR grid1 = GridSearchCV(pipe1, cv=5, param_grid=param_grid1) ## rgs_RF grid2 = GridSearchCV(pipe2, cv=5, param_grid=param_grid2) ## rgs_DL grid3 = GridSearchCV(pipe3, cv=5, param_grid=param_grid3) # run the hyperparameter tunning grid1.fit(X,y) grid2.fit(X,y) grid3.fit(X,y) # return results of the tunning process return grid1,grid2,grid3,pipe1,pipe2,pipe3 where the deep learning model my_DL is defined as below: def my_DL(epochs=6,batchsize=512): model = Sequential() model.add(Dense(32,activation='relu')) model.add(Dense(16,activation='relu')) model.add(Dense(1)) model.compile(loss='mse',optimizer='rmsprop', metrics=['mae']) return model The classification and regression model in a neural network are usually different in the last layer. Here, for the regression modeling, we don’t use any activation function in the last layer: model.add(Dense(1)). However, if it’s a classification problem, you need to add an activation function, such as sigmoid in the last layer. I have written some similar function in one of my other posts as below: towardsdatascience.com We then run the function of the hyperparameter tuning. my_grid1,my_grid2,my_grid3,my_pipe1,my_pipe2,my_pipe3 = train_hyper_tune(X_train, y_train) Now we’ve got the best set of hyperparameters for each of the three models. We then need to refit on the entire training dataset using the trained hyperparameters. def train_on_entire(X,y,pipe,grid_res): # fit pipeline pipe.set_params(**grid_res.best_params_).fit(X, y) # return the newly trained pipeline return pipemodel1 = train_on_entire(X_train,y_train,my_pipe1,my_grid1)model2 = train_on_entire(X_train,y_train,my_pipe2,my_grid2)model3 = train_on_entire(X_train,y_train,my_pipe3,my_grid3) We cannot say a model is better than the baseline model (linear regression) based on the training data performance. So, we need one more step evaluation on the test data that we have never touched before. Now, we have the conclusion that model3 (the deep learning regressor) outperforms the other models by achieving the lowest MSE on the test dataset. So, model3 is our final model. Usually, a machine learning model project ends here by having a model with pretty good performance. However, in our project, this step is not sufficient yet to answer the question, “Who is the MVP?” That’s why we are going further. We are going to apply our trained model to the target question, predicting the MVP. So, I extract the same feature space as our training data from the players’ stats in this season (before the NBA suspension due to COVID19). We are only interested in the top players who have the chance to win the MVP. They are Giannis, Anthony, Luka, James (Harden), Lebron, and Kawhi. If you are a basketball fan, you must know these people. If not, you don’t need to know them to understand this machine learning project. Either way, I will not waste time introducing them. This is the prediction of their MVP vote share. We got a different answer from the media, our predicted MVP is James Harden! No like, no hate, but all from data. (But personally I do agree with this result. 😀) After predicting the result, I need to dig deeper into the data to interpret the result or to support the result. So, I compare these players’ stats (our feature space of the model) using the CoxComb Chart. We can see clearly that James Harden’s stats are all among the best (Game played, points per game, field goal percentage, steal, and so on). That’s why the model predicts him as the MVP for this season. For those who are interested in generating the CoxComb Chart, please refer to the following post. towardsdatascience.com That’s it. A question-driven machine learning project from the beginning to the end. Applying domain knowledge is important to project design and data collection.Use K-fold Cross-validation when sample size is small.Don’t forget to normalize your features before modeling.Use the performance on the test data to evaluate your model.Use graphics to make sense of your prediction results.James Harden is the MVP. Applying domain knowledge is important to project design and data collection. Use K-fold Cross-validation when sample size is small. Don’t forget to normalize your features before modeling. Use the performance on the test data to evaluate your model. Use graphics to make sense of your prediction results. James Harden is the MVP. François Chollet. Deep Learning with Python.
[ { "code": null, "e": 117, "s": 46, "text": "Don’t tell me it will be Giannis. Let’s find the answer from the data." }, { "code": null, "e": 308, "s": 117, "text": "I will frame this problem to a machine learning project and finish the project using the general working flow of machine learning similar to that introduced by DEEP LEARNING with Python [1]." }, { "code": null, "e": 327, "s": 308, "text": "Let’s get started." }, { "code": null, "e": 398, "s": 327, "text": "The question we want to ask is “Who is the MVP of this season in NBA?”" }, { "code": null, "e": 562, "s": 398, "text": "Who is or is not, which seems like a binary classification problem. So, my first attempt is to build a classifier to differentiate MVP players and non-MVP players." }, { "code": null, "e": 827, "s": 562, "text": "However, I found building a classifier is not practical because I will face the problem of sample bias. Specifically, the number of non-MVP players is much larger than that of MVP players, which will result in the difficulties of training and evaluating the model." }, { "code": null, "e": 934, "s": 827, "text": "Therefore, I frame it to a regression problem and the output is defined as the MVP voting share each year." }, { "code": null, "e": 1162, "s": 934, "text": "To note, I use my domain knowledge (I am very familiar with the NBA as a big fan) here to choose the correct direction for the project. To make full use of your domain knowledge is very important in conceiving a doable project." }, { "code": null, "e": 1421, "s": 1162, "text": "Then, let’s look at the data we have in terms of the input X and output y. The X part of the data is the statistics of the players who have got votes for MVP from the season of 1989–1990 to the season of 2018–2019. The y part of the data is the voting share." }, { "code": null, "e": 1549, "s": 1421, "text": "Then the data is separated to train and test dataset. And the test dataset will never be touched until we have our final model." }, { "code": null, "e": 1639, "s": 1549, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)" }, { "code": null, "e": 1887, "s": 1639, "text": "This is an important step of a project, which defines the success of the model. In this regression problem, I use the mean squared error (MSE) as the evaluation metric. Specifically, the model is trying to minimize the MSE in the training process." }, { "code": null, "e": 2194, "s": 1887, "text": "Since the sample size is small, I use the K-fold cross-validation instead of a one-time train-validation-test split as my evaluation process. When the sample size is small, the splitting of data can actually affect the performance of the model. K-fold cross-validation is usually used to solve the problem." }, { "code": null, "e": 2283, "s": 2194, "text": "The preparation of the data includes missing value imputation and feature normalization." }, { "code": null, "e": 2357, "s": 2283, "text": "my_imputer = SimpleImputer(strategy=\"median\")my_scaler = StandardScaler()" }, { "code": null, "e": 2523, "s": 2357, "text": "The feature normalization is essential in regression problems, the different scale of features will be a disaster for the model training if pooled raw to the engine." }, { "code": null, "e": 2649, "s": 2523, "text": "In the modeling part, it’s easy to forget to set a baseline model no matter you are a beginner or experienced data scientist." }, { "code": null, "e": 2880, "s": 2649, "text": "Here we use a simple linear model as our baseline model and pack it together with the preprocessing of the data into a pipeline. For those who are interested in the pipeline usage, please refer to the Pipeline function in sklearn." }, { "code": null, "e": 3066, "s": 2880, "text": "from sklearn.linear_model import LinearRegressionmodel_base = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('ln_model',LinearRegression())])model_base.fit(X_train, y_train)" }, { "code": null, "e": 3119, "s": 3066, "text": "The baseline model now is ready to be compared with." }, { "code": null, "e": 3314, "s": 3119, "text": "Next, we are going to develop a model that should perform better than the simple linear regression. I select three candidates, Elastic Net, Random Forest Regressor, and Deep Learning regression." }, { "code": null, "e": 3473, "s": 3314, "text": "Elastic Net is the combination of LASSO and Ridge, which penalizes the complexity of the model. If interested, please refer to one of my previous posts below." }, { "code": null, "e": 3496, "s": 3473, "text": "towardsdatascience.com" }, { "code": null, "e": 3671, "s": 3496, "text": "For the hyperparameter tuning process of these three candidates, I write a function that combines preprocessing, hyperparameter space definition and cross-validation process." }, { "code": null, "e": 5378, "s": 3671, "text": "def train_hyper_tune(X,y): # create the pre-processing component my_scaler = StandardScaler() my_imputer = SimpleImputer(strategy=\"median\") # define regressors ## regressors 1: Logistic Regression rgs_EN = ElasticNet(random_state=0) ## regressors 2: Random Forest regressors rgs_RF = RandomForestRegressor(random_state=0) ## regressors 3: Deep Learning rgs_DL = KerasRegressor(build_fn=my_DL) # define pipeline for three regressors ## rgs_LR pipe1 = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('en_model',rgs_EN)]) ## rgs_RF pipe2 = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('rf_model',rgs_RF)]) ## rgs_DL pipe3 = Pipeline([('imputer', my_imputer), ('scaler', my_scaler), ('dl_model',rgs_DL)]) # create hyperparameter space of the three models ## rgs_LR param_grid1 = { 'en_model__alpha' : [1e-1,1,10], 'en_model__l1_ratio' : [0,0.5,1] } ## rgs_RF param_grid2 = { 'rf_model__n_estimators' : [50,100], 'rf_model__max_features' : [0.8,\"auto\"], 'rf_model__max_depth' : [4,5] } ## rgs_DL param_grid3 = { 'dl_model__epochs' : [6,12,18,24], 'dl_model__batchsize' : [256,512] } # set GridSearch via 5-fold cross-validation ## rgs_LR grid1 = GridSearchCV(pipe1, cv=5, param_grid=param_grid1) ## rgs_RF grid2 = GridSearchCV(pipe2, cv=5, param_grid=param_grid2) ## rgs_DL grid3 = GridSearchCV(pipe3, cv=5, param_grid=param_grid3) # run the hyperparameter tunning grid1.fit(X,y) grid2.fit(X,y) grid3.fit(X,y) # return results of the tunning process return grid1,grid2,grid3,pipe1,pipe2,pipe3" }, { "code": null, "e": 5435, "s": 5378, "text": "where the deep learning model my_DL is defined as below:" }, { "code": null, "e": 5683, "s": 5435, "text": "def my_DL(epochs=6,batchsize=512): model = Sequential() model.add(Dense(32,activation='relu')) model.add(Dense(16,activation='relu')) model.add(Dense(1)) model.compile(loss='mse',optimizer='rmsprop', metrics=['mae']) return model" }, { "code": null, "e": 5896, "s": 5683, "text": "The classification and regression model in a neural network are usually different in the last layer. Here, for the regression modeling, we don’t use any activation function in the last layer: model.add(Dense(1))." }, { "code": null, "e": 6086, "s": 5896, "text": "However, if it’s a classification problem, you need to add an activation function, such as sigmoid in the last layer. I have written some similar function in one of my other posts as below:" }, { "code": null, "e": 6109, "s": 6086, "text": "towardsdatascience.com" }, { "code": null, "e": 6164, "s": 6109, "text": "We then run the function of the hyperparameter tuning." }, { "code": null, "e": 6255, "s": 6164, "text": "my_grid1,my_grid2,my_grid3,my_pipe1,my_pipe2,my_pipe3 = train_hyper_tune(X_train, y_train)" }, { "code": null, "e": 6419, "s": 6255, "text": "Now we’ve got the best set of hyperparameters for each of the three models. We then need to refit on the entire training dataset using the trained hyperparameters." }, { "code": null, "e": 6762, "s": 6419, "text": "def train_on_entire(X,y,pipe,grid_res): # fit pipeline pipe.set_params(**grid_res.best_params_).fit(X, y) # return the newly trained pipeline return pipemodel1 = train_on_entire(X_train,y_train,my_pipe1,my_grid1)model2 = train_on_entire(X_train,y_train,my_pipe2,my_grid2)model3 = train_on_entire(X_train,y_train,my_pipe3,my_grid3)" }, { "code": null, "e": 6967, "s": 6762, "text": "We cannot say a model is better than the baseline model (linear regression) based on the training data performance. So, we need one more step evaluation on the test data that we have never touched before." }, { "code": null, "e": 7146, "s": 6967, "text": "Now, we have the conclusion that model3 (the deep learning regressor) outperforms the other models by achieving the lowest MSE on the test dataset. So, model3 is our final model." }, { "code": null, "e": 7246, "s": 7146, "text": "Usually, a machine learning model project ends here by having a model with pretty good performance." }, { "code": null, "e": 7378, "s": 7246, "text": "However, in our project, this step is not sufficient yet to answer the question, “Who is the MVP?” That’s why we are going further." }, { "code": null, "e": 7603, "s": 7378, "text": "We are going to apply our trained model to the target question, predicting the MVP. So, I extract the same feature space as our training data from the players’ stats in this season (before the NBA suspension due to COVID19)." }, { "code": null, "e": 7749, "s": 7603, "text": "We are only interested in the top players who have the chance to win the MVP. They are Giannis, Anthony, Luka, James (Harden), Lebron, and Kawhi." }, { "code": null, "e": 7939, "s": 7749, "text": "If you are a basketball fan, you must know these people. If not, you don’t need to know them to understand this machine learning project. Either way, I will not waste time introducing them." }, { "code": null, "e": 7987, "s": 7939, "text": "This is the prediction of their MVP vote share." }, { "code": null, "e": 8149, "s": 7987, "text": "We got a different answer from the media, our predicted MVP is James Harden! No like, no hate, but all from data. (But personally I do agree with this result. 😀)" }, { "code": null, "e": 8356, "s": 8149, "text": "After predicting the result, I need to dig deeper into the data to interpret the result or to support the result. So, I compare these players’ stats (our feature space of the model) using the CoxComb Chart." }, { "code": null, "e": 8559, "s": 8356, "text": "We can see clearly that James Harden’s stats are all among the best (Game played, points per game, field goal percentage, steal, and so on). That’s why the model predicts him as the MVP for this season." }, { "code": null, "e": 8657, "s": 8559, "text": "For those who are interested in generating the CoxComb Chart, please refer to the following post." }, { "code": null, "e": 8680, "s": 8657, "text": "towardsdatascience.com" }, { "code": null, "e": 8765, "s": 8680, "text": "That’s it. A question-driven machine learning project from the beginning to the end." }, { "code": null, "e": 9091, "s": 8765, "text": "Applying domain knowledge is important to project design and data collection.Use K-fold Cross-validation when sample size is small.Don’t forget to normalize your features before modeling.Use the performance on the test data to evaluate your model.Use graphics to make sense of your prediction results.James Harden is the MVP." }, { "code": null, "e": 9169, "s": 9091, "text": "Applying domain knowledge is important to project design and data collection." }, { "code": null, "e": 9224, "s": 9169, "text": "Use K-fold Cross-validation when sample size is small." }, { "code": null, "e": 9281, "s": 9224, "text": "Don’t forget to normalize your features before modeling." }, { "code": null, "e": 9342, "s": 9281, "text": "Use the performance on the test data to evaluate your model." }, { "code": null, "e": 9397, "s": 9342, "text": "Use graphics to make sense of your prediction results." }, { "code": null, "e": 9422, "s": 9397, "text": "James Harden is the MVP." } ]
How to create a new directory by using File object in Java?
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories. The mkdir() method of this class creates a directory with the path represented by the current object. Therefore, to create a directory − Instantiate the File class by passing the path of the directory you need to create, as a parameter (String). Invoke the mkdir() method using the above created file object. Following Java example reads the path and name of the directory to be created, from the user, and creates it. import java.io.File; import java.util.Scanner; public class CreateDirectory { public static void main(String args[]) { System.out.println("Enter the path to create a directory: "); Scanner sc = new Scanner(System.in); String path = sc.next(); System.out.println("Enter the name of the desired a directory: "); path = path+sc.next(); //Creating a File object File file = new File(path); //Creating the directory boolean bool = file.mkdir(); if(bool){ System.out.println("Directory created successfully"); }else{ System.out.println("Sorry couldn’t create specified directory"); } } } Enter the path to create a directory: D:\ Enter the name of the desired a directory: sample_directory Directory created successfully If you verify, you can observe see the created directory as − But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory. For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as − D:\test\myDirectories\sample_directory Where the test and myDirectories folders doesn’t exist, the mkdir() method will not create it. To create a hierarchy of new directories you can using the method mkdirs() of the same class. This method creates the directory with the path represented by the current object, including non-existing parent directories. import java.io.File; import java.util.Scanner; public class CreateDirectory { public static void main(String args[]) { System.out.println("Enter the path to create a directory: "); Scanner sc = new Scanner(System.in); String path = sc.next(); System.out.println("Enter the name of the desired a directory: "); path = path+sc.next(); //Creating a File object File file = new File(path); //Creating the directory boolean bool = file.mkdirs(); if(bool){ System.out.println("Directory created successfully"); }else{ System.out.println("Sorry couldnt create specified directory"); } } } Enter the path to create a directory: D:\test\myDirectories\ Enter the name of the desired a directory: sample_directory Directory created successfully If you verify you can observe see the created directory as −
[ { "code": null, "e": 1253, "s": 1062, "text": "The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories." }, { "code": null, "e": 1355, "s": 1253, "text": "The mkdir() method of this class creates a directory with the path represented by the current object." }, { "code": null, "e": 1390, "s": 1355, "text": "Therefore, to create a directory −" }, { "code": null, "e": 1499, "s": 1390, "text": "Instantiate the File class by passing the path of the directory you need to create, as a parameter (String)." }, { "code": null, "e": 1562, "s": 1499, "text": "Invoke the mkdir() method using the above created file object." }, { "code": null, "e": 1672, "s": 1562, "text": "Following Java example reads the path and name of the directory to be created, from the user, and creates it." }, { "code": null, "e": 2350, "s": 1672, "text": "import java.io.File;\nimport java.util.Scanner;\npublic class CreateDirectory {\n public static void main(String args[]) {\n System.out.println(\"Enter the path to create a directory: \");\n Scanner sc = new Scanner(System.in);\n String path = sc.next();\n System.out.println(\"Enter the name of the desired a directory: \");\n path = path+sc.next();\n //Creating a File object\n File file = new File(path);\n //Creating the directory\n boolean bool = file.mkdir();\n if(bool){\n System.out.println(\"Directory created successfully\");\n }else{\n System.out.println(\"Sorry couldn’t create specified directory\");\n }\n }\n}" }, { "code": null, "e": 2483, "s": 2350, "text": "Enter the path to create a directory:\nD:\\\nEnter the name of the desired a directory:\nsample_directory\nDirectory created successfully" }, { "code": null, "e": 2545, "s": 2483, "text": "If you verify, you can observe see the created directory as −" }, { "code": null, "e": 2655, "s": 2545, "text": "But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory." }, { "code": null, "e": 2777, "s": 2655, "text": "For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as −" }, { "code": null, "e": 2816, "s": 2777, "text": "D:\\test\\myDirectories\\sample_directory" }, { "code": null, "e": 2911, "s": 2816, "text": "Where the test and myDirectories folders doesn’t exist, the mkdir() method will not create it." }, { "code": null, "e": 3131, "s": 2911, "text": "To create a hierarchy of new directories you can using the method mkdirs() of the same class. This method creates the directory with the path represented by the current object, including non-existing parent directories." }, { "code": null, "e": 3809, "s": 3131, "text": "import java.io.File;\nimport java.util.Scanner;\npublic class CreateDirectory {\n public static void main(String args[]) {\n System.out.println(\"Enter the path to create a directory: \");\n Scanner sc = new Scanner(System.in);\n String path = sc.next();\n System.out.println(\"Enter the name of the desired a directory: \");\n path = path+sc.next();\n //Creating a File object\n File file = new File(path);\n //Creating the directory\n boolean bool = file.mkdirs();\n if(bool){\n System.out.println(\"Directory created successfully\");\n }else{\n System.out.println(\"Sorry couldnt create specified directory\");\n }\n }\n}" }, { "code": null, "e": 3961, "s": 3809, "text": "Enter the path to create a directory:\nD:\\test\\myDirectories\\\nEnter the name of the desired a directory:\nsample_directory\nDirectory created successfully" }, { "code": null, "e": 4022, "s": 3961, "text": "If you verify you can observe see the created directory as −" } ]
How to pass Command line Arguments in Python - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Hi everyone, in this tutorial, we will see different ways to use command line arguments in Python using various examples. These are the arguments that we passed along with the executing command of Python Program in the Command-line Interface (CLI) or shell. The typical syntax for this is python script_name.py arg1 arg2 ... In Python, we have several ways to use the command line arguments. The sys module is an in-built Module that provides us with the ability to interact with the Python interpreter on any platform using some variables and functions. One of the ways to interact with command line arguments is by using the variable sys.argv, which is a list of all the arguments passed during execution and having 1st element as the script name. Let’s write a sample program that will take all the arguments from the command line and return their summation. # importing the sys module import sys def summation(): sum_cla = 0 # loop over all command line arguments for i in sys.argv[1:]: sum_cla = sum_cla + int(i) # printing the results print("No. of command line arguments are: ",len(sys.argv[1:])) print("Sum of command line arguments is:",sum_cla) return if __name__ == "__main__": summation() Output: No. of command line arguments are: 4 Sum of command line arguments is: 16 Using the argparse module gives us a lot more flexibility than using the sys.argv to interact with the command line arguments as using this we can specify the positional arguments, the default value for arguments, help message etc. argparse is the recommended command-line parsing module in the Python standard library. The basic code to use the argeparse module is below which does nothing if no single argument is passed and will give some sort of information if it parses the argument that is known to it like -h for help. import argparse parser = argparse.ArgumentParser() parser.parse_args() Output: python .\cla.py -h usage: cla.py [-h] optional arguments: -h, --help show this help message and exit We can add our own custom positional arguments when using the command line arguments. These type of arguments are mandatory to be passed during the execution otherwise we will get an error. import argparse parser = argparse.ArgumentParser() parser.add_argument("sum",help = "It will sum the integer list passed as argument") args = parser.parse_args() Output: python .\cla.py --help usage: cla.py [-h] sum positional arguments: sum It will sum the integer list passed as an argument optional arguments: -h, --help show this help message and exit We can add our own custom optional arguments when using the command line arguments. These type of arguments are not mandatory to be passed during the execution and are generally used to provide extra optional functionalities to the user. import argparse parser = argparse.ArgumentParser() parser.add_argument("weight",help = "Return -ve is integer is negative else +ve",type=int) parser.add_argument("--verbose", action="store_true",help="negative/ positive integer") args = parser.parse_args() if args.verbose: print("Weight=", '-ve' if args.weight<0 else '+ve') elif args.weight <0: print('Integer is -ve') else: print('Integer is +ve') Output: python .\cla.py -9 --verbose Weight= -ve python .\cla.py 5 Integer is +ve The getopt module is a parser for command-line options whose API is similar to users of the C language getopt() function. If we want to write less code and get better help and error messages, we should consider using the argparse module that we have discussed above. This module provides a methodgetopt()which parses the command line options and the parameter list. The first element of command-line arguments while using sys.argv is generally skipped. he basic syntax of this method is. getopt.getopt(args, shortopts, longopts=[]) args – The argument list usually from the second element of Command-line interface example sys.argv[1:] shortopts – The string of option letters that the script wants to recognize, with options that require an argument followed by a colon (:) longopts – The list of strings with the names of the long options which should be supported. # importing modules import sys import getopt # Defining arguments and options arguments = sys.argv[1:] shortopts= "svo" longopts = ["script-name ","verbose", "output="] # Printing different options and arguments options, args = getopt.getopt(arguments, shortopts,longopts) print('Options are :',options) print('Arguments are :',args) # Setting behaviour for options for opt, val in options: if opt in ("-s", "--script-name"): print ("Script name is", sys.argv[0]) elif opt in ("-o", "--output"): print ("Output saved in file named", val) elif opt in ("-v", "--verbose"): print ("Verbosity is ON") Output 1: python .\cla.py -v --output=abc.xyz a b Options are : [('-v', ''), ('--output', 'abc.xyz')] Arguments are : ['a', 'b'] Verbosity is ON Output saved in file named abc.xyz Output 2: python .\cla.py -s --verbose --output=opfile.txt a b Options are : [('-s', ''), ('--verbose', ''), ('--output', 'opfile.txt')] Arguments are : ['a', 'b'] Script name is .\cla.py Verbosity is ON Output saved in file named opfile.txt So we learned how to use command-line arguments in Python and if you have any doubts or queries please ask in the comment section below. Modes of Python Program Shell Script How to write logs in a Separate File How to install Maven on windows 7 command line Happy Learning 🙂 Different ways to use Lambdas in Python How to use *args and **kwargs in Python Modes of Python Program How to Export MySQL Tables to a file from command line Python String to int Conversion Example How to get the size of a Directory in Python ? How to Delete a File or Directory in Python Python How to read input from keyboard How to check whether a file exists python ? How to Handle Exceptions in Python What are the different ways to Sort Objects in Python ? How to Create or Delete Directories in Python ? How to Remove Spaces from String in Python How to install Maven on windows 7 command line How to access for loop index in Python Different ways to use Lambdas in Python How to use *args and **kwargs in Python Modes of Python Program How to Export MySQL Tables to a file from command line Python String to int Conversion Example How to get the size of a Directory in Python ? How to Delete a File or Directory in Python Python How to read input from keyboard How to check whether a file exists python ? How to Handle Exceptions in Python What are the different ways to Sort Objects in Python ? How to Create or Delete Directories in Python ? How to Remove Spaces from String in Python How to install Maven on windows 7 command line How to access for loop index in Python Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 520, "s": 398, "text": "Hi everyone, in this tutorial, we will see different ways to use command line arguments in Python using various examples." }, { "code": null, "e": 687, "s": 520, "text": "These are the arguments that we passed along with the executing command of Python Program in the Command-line Interface (CLI) or shell. The typical syntax for this is" }, { "code": null, "e": 723, "s": 687, "text": "python script_name.py arg1 arg2 ..." }, { "code": null, "e": 790, "s": 723, "text": "In Python, we have several ways to use the command line arguments." }, { "code": null, "e": 1148, "s": 790, "text": "The sys module is an in-built Module that provides us with the ability to interact with the Python interpreter on any platform using some variables and functions. One of the ways to interact with command line arguments is by using the variable sys.argv, which is a list of all the arguments passed during execution and having 1st element as the script name." }, { "code": null, "e": 1260, "s": 1148, "text": "Let’s write a sample program that will take all the arguments from the command line and return their summation." }, { "code": null, "e": 1648, "s": 1260, "text": "# importing the sys module\nimport sys\n\ndef summation(): \n sum_cla = 0\n # loop over all command line arguments\n for i in sys.argv[1:]: \n sum_cla = sum_cla + int(i)\n # printing the results \n print(\"No. of command line arguments are: \",len(sys.argv[1:])) \n print(\"Sum of command line arguments is:\",sum_cla)\n return\n\nif __name__ == \"__main__\":\n summation()" }, { "code": null, "e": 1656, "s": 1648, "text": "Output:" }, { "code": null, "e": 1730, "s": 1656, "text": "No. of command line arguments are: 4\nSum of command line arguments is: 16" }, { "code": null, "e": 1962, "s": 1730, "text": "Using the argparse module gives us a lot more flexibility than using the sys.argv to interact with the command line arguments as using this we can specify the positional arguments, the default value for arguments, help message etc." }, { "code": null, "e": 2050, "s": 1962, "text": "argparse is the recommended command-line parsing module in the Python standard library." }, { "code": null, "e": 2256, "s": 2050, "text": "The basic code to use the argeparse module is below which does nothing if no single argument is passed and will give some sort of information if it parses the argument that is known to it like -h for help." }, { "code": null, "e": 2327, "s": 2256, "text": "import argparse\nparser = argparse.ArgumentParser()\nparser.parse_args()" }, { "code": null, "e": 2335, "s": 2327, "text": "Output:" }, { "code": null, "e": 2437, "s": 2335, "text": "python .\\cla.py -h\nusage: cla.py [-h]\n\noptional arguments:\n-h, --help show this help message and exit" }, { "code": null, "e": 2627, "s": 2437, "text": "We can add our own custom positional arguments when using the command line arguments. These type of arguments are mandatory to be passed during the execution otherwise we will get an error." }, { "code": null, "e": 2789, "s": 2627, "text": "import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"sum\",help = \"It will sum the integer list passed as argument\")\nargs = parser.parse_args()" }, { "code": null, "e": 2797, "s": 2789, "text": "Output:" }, { "code": null, "e": 2985, "s": 2797, "text": "python .\\cla.py --help\nusage: cla.py [-h] sum\n\npositional arguments:\nsum It will sum the integer list passed as an argument\n\noptional arguments:\n-h, --help show this help message and exit" }, { "code": null, "e": 3223, "s": 2985, "text": "We can add our own custom optional arguments when using the command line arguments. These type of arguments are not mandatory to be passed during the execution and are generally used to provide extra optional functionalities to the user." }, { "code": null, "e": 3637, "s": 3223, "text": "import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"weight\",help = \"Return -ve is integer is negative else +ve\",type=int)\nparser.add_argument(\"--verbose\", action=\"store_true\",help=\"negative/ positive integer\")\nargs = parser.parse_args()\n\nif args.verbose:\n print(\"Weight=\", '-ve' if args.weight<0 else '+ve')\nelif args.weight <0:\n print('Integer is -ve')\nelse:\n print('Integer is +ve')" }, { "code": null, "e": 3645, "s": 3637, "text": "Output:" }, { "code": null, "e": 3720, "s": 3645, "text": "python .\\cla.py -9 --verbose\nWeight= -ve\n\npython .\\cla.py 5\nInteger is +ve" }, { "code": null, "e": 3987, "s": 3720, "text": "The getopt module is a parser for command-line options whose API is similar to users of the C language getopt() function. If we want to write less code and get better help and error messages, we should consider using the argparse module that we have discussed above." }, { "code": null, "e": 4208, "s": 3987, "text": "This module provides a methodgetopt()which parses the command line options and the parameter list. The first element of command-line arguments while using sys.argv is generally skipped. he basic syntax of this method is." }, { "code": null, "e": 4252, "s": 4208, "text": "getopt.getopt(args, shortopts, longopts=[])" }, { "code": null, "e": 4356, "s": 4252, "text": "args – The argument list usually from the second element of Command-line interface example sys.argv[1:]" }, { "code": null, "e": 4495, "s": 4356, "text": "shortopts – The string of option letters that the script wants to recognize, with options that require an argument followed by a colon (:)" }, { "code": null, "e": 4588, "s": 4495, "text": "longopts – The list of strings with the names of the long options which should be supported." }, { "code": null, "e": 5225, "s": 4588, "text": "# importing modules\nimport sys\nimport getopt\n\n# Defining arguments and options\narguments = sys.argv[1:]\nshortopts= \"svo\"\nlongopts = [\"script-name \",\"verbose\", \"output=\"]\n\n# Printing different options and arguments\noptions, args = getopt.getopt(arguments, shortopts,longopts)\nprint('Options are :',options)\nprint('Arguments are :',args)\n\n# Setting behaviour for options\nfor opt, val in options: \n if opt in (\"-s\", \"--script-name\"):\n print (\"Script name is\", sys.argv[0])\n elif opt in (\"-o\", \"--output\"):\n print (\"Output saved in file named\", val)\n elif opt in (\"-v\", \"--verbose\"):\n print (\"Verbosity is ON\")" }, { "code": null, "e": 5235, "s": 5225, "text": "Output 1:" }, { "code": null, "e": 5405, "s": 5235, "text": "python .\\cla.py -v --output=abc.xyz a b\nOptions are : [('-v', ''), ('--output', 'abc.xyz')]\nArguments are : ['a', 'b']\nVerbosity is ON\nOutput saved in file named abc.xyz" }, { "code": null, "e": 5415, "s": 5405, "text": "Output 2:" }, { "code": null, "e": 5647, "s": 5415, "text": "python .\\cla.py -s --verbose --output=opfile.txt a b\nOptions are : [('-s', ''), ('--verbose', ''), ('--output', 'opfile.txt')]\nArguments are : ['a', 'b']\nScript name is .\\cla.py\nVerbosity is ON\nOutput saved in file named opfile.txt" }, { "code": null, "e": 5784, "s": 5647, "text": "So we learned how to use command-line arguments in Python and if you have any doubts or queries please ask in the comment section below." }, { "code": null, "e": 5808, "s": 5784, "text": "Modes of Python Program" }, { "code": null, "e": 5858, "s": 5808, "text": "Shell Script How to write logs in a Separate File" }, { "code": null, "e": 5905, "s": 5858, "text": "How to install Maven on windows 7 command line" }, { "code": null, "e": 5922, "s": 5905, "text": "Happy Learning 🙂" }, { "code": null, "e": 6565, "s": 5922, "text": "\nDifferent ways to use Lambdas in Python\nHow to use *args and **kwargs in Python\nModes of Python Program\nHow to Export MySQL Tables to a file from command line\nPython String to int Conversion Example\nHow to get the size of a Directory in Python ?\nHow to Delete a File or Directory in Python\nPython How to read input from keyboard\nHow to check whether a file exists python ?\nHow to Handle Exceptions in Python\nWhat are the different ways to Sort Objects in Python ?\nHow to Create or Delete Directories in Python ?\nHow to Remove Spaces from String in Python\nHow to install Maven on windows 7 command line\nHow to access for loop index in Python\n" }, { "code": null, "e": 6605, "s": 6565, "text": "Different ways to use Lambdas in Python" }, { "code": null, "e": 6645, "s": 6605, "text": "How to use *args and **kwargs in Python" }, { "code": null, "e": 6669, "s": 6645, "text": "Modes of Python Program" }, { "code": null, "e": 6724, "s": 6669, "text": "How to Export MySQL Tables to a file from command line" }, { "code": null, "e": 6764, "s": 6724, "text": "Python String to int Conversion Example" }, { "code": null, "e": 6811, "s": 6764, "text": "How to get the size of a Directory in Python ?" }, { "code": null, "e": 6855, "s": 6811, "text": "How to Delete a File or Directory in Python" }, { "code": null, "e": 6894, "s": 6855, "text": "Python How to read input from keyboard" }, { "code": null, "e": 6938, "s": 6894, "text": "How to check whether a file exists python ?" }, { "code": null, "e": 6973, "s": 6938, "text": "How to Handle Exceptions in Python" }, { "code": null, "e": 7029, "s": 6973, "text": "What are the different ways to Sort Objects in Python ?" }, { "code": null, "e": 7077, "s": 7029, "text": "How to Create or Delete Directories in Python ?" }, { "code": null, "e": 7120, "s": 7077, "text": "How to Remove Spaces from String in Python" }, { "code": null, "e": 7167, "s": 7120, "text": "How to install Maven on windows 7 command line" }, { "code": null, "e": 7206, "s": 7167, "text": "How to access for loop index in Python" }, { "code": null, "e": 7212, "s": 7210, "text": "Δ" }, { "code": null, "e": 7235, "s": 7212, "text": " Python – Introduction" }, { "code": null, "e": 7254, "s": 7235, "text": " Python – Features" }, { "code": null, "e": 7283, "s": 7254, "text": " Python – Install on Windows" }, { "code": null, "e": 7310, "s": 7283, "text": " Python – Modes of Program" }, { "code": null, "e": 7334, "s": 7310, "text": " Python – Number System" }, { "code": null, "e": 7356, "s": 7334, "text": " Python – Identifiers" }, { "code": null, "e": 7376, "s": 7356, "text": " Python – Operators" }, { "code": null, "e": 7403, "s": 7376, "text": " Python – Ternary Operator" }, { "code": null, "e": 7436, "s": 7403, "text": " Python – Command Line Arguments" }, { "code": null, "e": 7455, "s": 7436, "text": " Python – Keywords" }, { "code": null, "e": 7476, "s": 7455, "text": " Python – Data Types" }, { "code": null, "e": 7505, "s": 7476, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 7535, "s": 7505, "text": " Python – Virtual Environment" }, { "code": null, "e": 7558, "s": 7535, "text": " Pyhton – Type Casting" }, { "code": null, "e": 7582, "s": 7558, "text": " Python – String to Int" }, { "code": null, "e": 7615, "s": 7582, "text": " Python – Conditional Statements" }, { "code": null, "e": 7638, "s": 7615, "text": " Python – if statement" }, { "code": null, "e": 7667, "s": 7638, "text": " Python – *args and **kwargs" }, { "code": null, "e": 7693, "s": 7667, "text": " Python – Date Formatting" }, { "code": null, "e": 7728, "s": 7693, "text": " Python – Read input from keyboard" }, { "code": null, "e": 7748, "s": 7728, "text": " Python – raw_input" }, { "code": null, "e": 7772, "s": 7748, "text": " Python – List In Depth" }, { "code": null, "e": 7801, "s": 7772, "text": " Python – List Comprehension" }, { "code": null, "e": 7824, "s": 7801, "text": " Python – Set in Depth" }, { "code": null, "e": 7854, "s": 7824, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 7879, "s": 7854, "text": " Python – Tuple in Depth" }, { "code": null, "e": 7909, "s": 7879, "text": " Python – Stack Datastructure" }, { "code": null, "e": 7939, "s": 7909, "text": " Python – Classes and Objects" }, { "code": null, "e": 7962, "s": 7939, "text": " Python – Constructors" }, { "code": null, "e": 7993, "s": 7962, "text": " Python – Object Introspection" }, { "code": null, "e": 8015, "s": 7993, "text": " Python – Inheritance" }, { "code": null, "e": 8036, "s": 8015, "text": " Python – Decorators" }, { "code": null, "e": 8072, "s": 8036, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 8102, "s": 8072, "text": " Python – Exceptions Handling" }, { "code": null, "e": 8136, "s": 8102, "text": " Python – User defined Exceptions" }, { "code": null, "e": 8162, "s": 8136, "text": " Python – Multiprocessing" }, { "code": null, "e": 8200, "s": 8162, "text": " Python – Default function parameters" }, { "code": null, "e": 8228, "s": 8200, "text": " Python – Lambdas Functions" }, { "code": null, "e": 8252, "s": 8228, "text": " Python – NumPy Library" }, { "code": null, "e": 8278, "s": 8252, "text": " Python – MySQL Connector" }, { "code": null, "e": 8310, "s": 8278, "text": " Python – MySQL Create Database" }, { "code": null, "e": 8336, "s": 8310, "text": " Python – MySQL Read Data" }, { "code": null, "e": 8364, "s": 8336, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 8395, "s": 8364, "text": " Python – MySQL Update Records" }, { "code": null, "e": 8426, "s": 8395, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 8459, "s": 8426, "text": " Python – String Case Conversion" }, { "code": null, "e": 8494, "s": 8459, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 8531, "s": 8494, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 8569, "s": 8531, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 8595, "s": 8569, "text": " Howto – Merge two Lists" }, { "code": null, "e": 8620, "s": 8595, "text": " Howto – Merge two dicts" }, { "code": null, "e": 8660, "s": 8620, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 8695, "s": 8660, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 8730, "s": 8695, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 8759, "s": 8730, "text": " Howto – Read Env variables" }, { "code": null, "e": 8785, "s": 8759, "text": " Howto – Read a text File" }, { "code": null, "e": 8811, "s": 8785, "text": " Howto – Read a JSON File" }, { "code": null, "e": 8843, "s": 8811, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 8871, "s": 8843, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 8911, "s": 8871, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 8945, "s": 8911, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 8970, "s": 8945, "text": " Howto – create Zip File" }, { "code": null, "e": 8991, "s": 8970, "text": " Howto – Get OS info" }, { "code": null, "e": 9022, "s": 8991, "text": " Howto – Get size of Directory" }, { "code": null, "e": 9059, "s": 9022, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 9096, "s": 9059, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 9118, "s": 9096, "text": " Howto – Sort Objects" }, { "code": null, "e": 9156, "s": 9118, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 9179, "s": 9156, "text": " Howto – Read CSV File" }, { "code": null, "e": 9217, "s": 9179, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 9248, "s": 9217, "text": " Howto – Access for loop index" }, { "code": null, "e": 9286, "s": 9248, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 9326, "s": 9286, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 9373, "s": 9326, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 9405, "s": 9373, "text": " Howto – Sort dictionary by key" } ]
jQuery | hasClass() with Examples - GeeksforGeeks
13 Feb, 2019 The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not.Syntax: $(selector).hasClass(className); Parameter: It accepts a “className” parameter which specifies the class name need to search in the selected element. Return Value: It returns true if the search is successful otherwise false.jQuery code to show the working of this method: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("button").click(function() { alert($("p").hasClass("find")); }); }); </script> <style> .find { font-size: 120%; color: green; } body { width: 50%; height: 200px; border: 2px solid green; padding: 20px; } </style></head> <body> <h1>Heading 1</h1> <p class="find">Geeks for Geeks !.</p> <p>This is normal paragraph.</p> <button>Click me!</button> </body> </html> Output:Before clicking the “Click me!” button- After clicking the “Click me!” button- jQuery-HTML/CSS JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 40723, "s": 40695, "text": "\n13 Feb, 2019" }, { "code": null, "e": 40854, "s": 40723, "text": "The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not.Syntax:" }, { "code": null, "e": 40888, "s": 40854, "text": "$(selector).hasClass(className);\n" }, { "code": null, "e": 41005, "s": 40888, "text": "Parameter: It accepts a “className” parameter which specifies the class name need to search in the selected element." }, { "code": null, "e": 41127, "s": 41005, "text": "Return Value: It returns true if the search is successful otherwise false.jQuery code to show the working of this method:" }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"button\").click(function() { alert($(\"p\").hasClass(\"find\")); }); }); </script> <style> .find { font-size: 120%; color: green; } body { width: 50%; height: 200px; border: 2px solid green; padding: 20px; } </style></head> <body> <h1>Heading 1</h1> <p class=\"find\">Geeks for Geeks !.</p> <p>This is normal paragraph.</p> <button>Click me!</button> </body> </html>", "e": 41833, "s": 41127, "text": null }, { "code": null, "e": 41880, "s": 41833, "text": "Output:Before clicking the “Click me!” button-" }, { "code": null, "e": 41919, "s": 41880, "text": "After clicking the “Click me!” button-" }, { "code": null, "e": 41935, "s": 41919, "text": "jQuery-HTML/CSS" }, { "code": null, "e": 41946, "s": 41935, "text": "JavaScript" }, { "code": null, "e": 41953, "s": 41946, "text": "JQuery" }, { "code": null, "e": 42051, "s": 41953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42096, "s": 42051, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42157, "s": 42096, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42226, "s": 42157, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42298, "s": 42226, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42350, "s": 42298, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 42396, "s": 42350, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 42459, "s": 42396, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 42488, "s": 42459, "text": "Form validation using jQuery" }, { "code": null, "e": 42565, "s": 42488, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Add a title to any heading element in the Bootstrap 4 card
To add a title to any heading element in Bootstrap card, use the card-title class − <h4 class="card-title"> Top Universities </h4> The card-title class comes inside the card class in Bootstrap − <div class="card-body"> <h4 class="card-title">Top Universities</h4> <p class="card-text">Stanford</p> <p class="card-text">Oxford</p> </div> Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="card"> <div class="card-body"> <h4 class="card-title">Top Universities</h4> <p class="card-text">Stanford</p> <p class="card-text">Oxford</p> </div> </div> </div> </body> </html>
[ { "code": null, "e": 1146, "s": 1062, "text": "To add a title to any heading element in Bootstrap card, use the card-title class −" }, { "code": null, "e": 1195, "s": 1146, "text": "<h4 class=\"card-title\">\n Top Universities\n</h4>" }, { "code": null, "e": 1259, "s": 1195, "text": "The card-title class comes inside the card class in Bootstrap −" }, { "code": null, "e": 1407, "s": 1259, "text": "<div class=\"card-body\">\n <h4 class=\"card-title\">Top Universities</h4>\n <p class=\"card-text\">Stanford</p>\n <p class=\"card-text\">Oxford</p>\n</div>" }, { "code": null, "e": 1417, "s": 1407, "text": "Live Demo" }, { "code": null, "e": 2172, "s": 1417, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <div class=\"card\">\n <div class=\"card-body\">\n <h4 class=\"card-title\">Top Universities</h4>\n <p class=\"card-text\">Stanford</p>\n <p class=\"card-text\">Oxford</p>\n </div>\n </div>\n </div>\n\n</body>\n</html>" } ]
NumPy Joining Array
Joining means putting contents of two or more arrays in a single array. In SQL we join tables based on a key, whereas in NumPy we join arrays by axes. We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0. Join two arrays Join two 2-D arrays along rows (axis=1): Stacking is same as concatenation, the only difference is that stacking is done along a new axis. We can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis. If axis is not explicitly passed it is taken as 0. NumPy provides a helper function: hstack() to stack along rows. NumPy provides a helper function: vstack() to stack along columns. NumPy provides a helper function: dstack() to stack along height, which is the same as depth. Use a correct NumPy method to join two arrays into a single array. arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) arr = np.((arr1, arr2)) Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 72, "s": 0, "text": "Joining means putting contents of two or more arrays in a single array." }, { "code": null, "e": 151, "s": 72, "text": "In SQL we join tables based on a key, whereas in NumPy we join arrays by axes." }, { "code": null, "e": 305, "s": 151, "text": "We pass a sequence of arrays that we want to join to the\nconcatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0." }, { "code": null, "e": 321, "s": 305, "text": "Join two arrays" }, { "code": null, "e": 362, "s": 321, "text": "Join two 2-D arrays along rows (axis=1):" }, { "code": null, "e": 460, "s": 362, "text": "Stacking is same as concatenation, the only difference is that stacking is done along a new axis." }, { "code": null, "e": 586, "s": 460, "text": "We can concatenate two 1-D arrays along the second axis which would result in putting them one over \nthe other, ie. stacking." }, { "code": null, "e": 730, "s": 586, "text": "We pass a sequence of arrays that we want to join to the\nstack() method along with the axis. If axis is not explicitly passed it is taken as 0." }, { "code": null, "e": 795, "s": 730, "text": "NumPy provides a helper function: hstack() \nto stack along rows." }, { "code": null, "e": 863, "s": 795, "text": "NumPy provides a helper function: vstack() to stack along columns." }, { "code": null, "e": 958, "s": 863, "text": "NumPy provides a helper function: dstack() \nto stack along height, which is the same as depth." }, { "code": null, "e": 1025, "s": 958, "text": "Use a correct NumPy method to join two arrays into a single array." }, { "code": null, "e": 1106, "s": 1025, "text": "arr1 = np.array([1, 2, 3])\n\narr2 = np.array([4, 5, 6])\n\narr = np.((arr1, arr2))\n" }, { "code": null, "e": 1125, "s": 1106, "text": "Start the Exercise" }, { "code": null, "e": 1158, "s": 1125, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1200, "s": 1158, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1307, "s": 1200, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1326, "s": 1307, "text": "[email protected]" } ]
Python | Pandas DataFrame.where() - GeeksforGeeks
17 Sep, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas where() method is used to check a data frame for one or more condition and return the result accordingly. By default, The rows not satisfying the condition are filled with NaN value. Syntax:DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None) Parameters: cond: One or more condition to check data frame for.other: Replace rows which don’t satisfy the condition with user defined object, Default is NaNinplace: Boolean value, Makes changes in data frame itself if Trueaxis: axis to check( row or columns) For link to the CSV file used, Click here. Example #1: Single Condition operation In this example, rows having particular Team name will be shown and rest will be replaced by NaN using .where() method. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # sorting dataframedata.sort_values("Team", inplace = True) # making boolean series for a team namefilter = data["Team"]=="Atlanta Hawks" # filtering datadata.where(filter, inplace = True) # displaydata Output: As shown in the output image, every row which doesn’t have Team = Atlanta Hawks is replaced with NaN. Example #2: Multi-condition Operations Data is filtered on the basis of both Team and Age. Only the rows having Team name “Atlanta Hawks” and players having age above 24 will be displayed. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # sorting dataframedata.sort_values("Team", inplace = True) # making boolean series for a team namefilter1 = data["Team"]=="Atlanta Hawks" # making boolean series for agefilter2 = data["Age"]>24 # filtering data on basis of both filtersdata.where(filter1 & filter2, inplace = True) # displaydata Output:As shown in the output image, Only the rows having Team name “Atlanta Hawks” and players having age above 24 are displayed. 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. How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON? isupper(), islower(), lower(), upper() in Python and their applications sum() function in Python
[ { "code": null, "e": 24930, "s": 24902, "text": "\n17 Sep, 2018" }, { "code": null, "e": 25144, "s": 24930, "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": 25334, "s": 25144, "text": "Pandas where() method is used to check a data frame for one or more condition and return the result accordingly. By default, The rows not satisfying the condition are filled with NaN value." }, { "code": null, "e": 25466, "s": 25334, "text": "Syntax:DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None) " }, { "code": null, "e": 25478, "s": 25466, "text": "Parameters:" }, { "code": null, "e": 25727, "s": 25478, "text": "cond: One or more condition to check data frame for.other: Replace rows which don’t satisfy the condition with user defined object, Default is NaNinplace: Boolean value, Makes changes in data frame itself if Trueaxis: axis to check( row or columns)" }, { "code": null, "e": 25770, "s": 25727, "text": "For link to the CSV file used, Click here." }, { "code": null, "e": 25809, "s": 25770, "text": "Example #1: Single Condition operation" }, { "code": null, "e": 25929, "s": 25809, "text": "In this example, rows having particular Team name will be shown and rest will be replaced by NaN using .where() method." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # sorting dataframedata.sort_values(\"Team\", inplace = True) # making boolean series for a team namefilter = data[\"Team\"]==\"Atlanta Hawks\" # filtering datadata.where(filter, inplace = True) # displaydata", "e": 26246, "s": 25929, "text": null }, { "code": null, "e": 26254, "s": 26246, "text": "Output:" }, { "code": null, "e": 26356, "s": 26254, "text": "As shown in the output image, every row which doesn’t have Team = Atlanta Hawks is replaced with NaN." }, { "code": null, "e": 26397, "s": 26358, "text": "Example #2: Multi-condition Operations" }, { "code": null, "e": 26547, "s": 26397, "text": "Data is filtered on the basis of both Team and Age. Only the rows having Team name “Atlanta Hawks” and players having age above 24 will be displayed." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # sorting dataframedata.sort_values(\"Team\", inplace = True) # making boolean series for a team namefilter1 = data[\"Team\"]==\"Atlanta Hawks\" # making boolean series for agefilter2 = data[\"Age\"]>24 # filtering data on basis of both filtersdata.where(filter1 & filter2, inplace = True) # displaydata", "e": 26958, "s": 26547, "text": null }, { "code": null, "e": 27089, "s": 26958, "text": "Output:As shown in the output image, Only the rows having Team name “Atlanta Hawks” and players having age above 24 are displayed." }, { "code": null, "e": 27113, "s": 27089, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27145, "s": 27113, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 27159, "s": 27145, "text": "Python-pandas" }, { "code": null, "e": 27166, "s": 27159, "text": "Python" }, { "code": null, "e": 27264, "s": 27166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27296, "s": 27264, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27338, "s": 27296, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27360, "s": 27338, "text": "Enumerate() in Python" }, { "code": null, "e": 27397, "s": 27360, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27426, "s": 27397, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27468, "s": 27426, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27504, "s": 27468, "text": "Convert integer to string in Python" }, { "code": null, "e": 27546, "s": 27504, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27618, "s": 27546, "text": "isupper(), islower(), lower(), upper() in Python and their applications" } ]
Python - Combinations of sum with tuples in tuple list - GeeksforGeeks
17 Dec, 2019 Sometimes, while working with data, we can have a problem in which we need to perform tuple addition among all the tuples in list. This can have application in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using combinations() + list comprehensionThis problem can be solved using combinations of above functions. In this, we use combinations() to generate all possible combination among tuples and list comprehension is used to feed addition logic. # Python3 code to demonstrate working of# Summation combination in tuple lists# Using list comprehension + combinationsfrom itertools import combinations # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10)] # printing original list print("The original list : " + str(test_list)) # Summation combination in tuple lists# Using list comprehension + combinationsres = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(test_list, 2)] # printing resultprint("The Summation combinations are : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10)] The Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)] Method #2 : Using list comprehension + zip() + operator.add + combinations()The combinations of above methods can also solve this problem. In this, we perform the task of addition using add() and the like indexed elements are linked using zip(). # Python3 code to demonstrate working of# Summation combination in tuple lists# Using list comprehension + zip() + operator.add + combinations()from itertools import combinationsimport operator # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10)] # printing original list print("The original list : " + str(test_list)) # Summation combination in tuple lists# Using list comprehension + zip() + operator.add + combinations()res = [(operator.add(*a), operator.add(*b))\ for a, b in (zip(y, x) for x, y in combinations(test_list, 2))] # printing resultprint("The Summation combinations are : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10)] The Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)] Python list-programs Python tuple-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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26227, "s": 26199, "text": "\n17 Dec, 2019" }, { "code": null, "e": 26465, "s": 26227, "text": "Sometimes, while working with data, we can have a problem in which we need to perform tuple addition among all the tuples in list. This can have application in many domains. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26720, "s": 26465, "text": "Method #1 : Using combinations() + list comprehensionThis problem can be solved using combinations of above functions. In this, we use combinations() to generate all possible combination among tuples and list comprehension is used to feed addition logic." }, { "code": "# Python3 code to demonstrate working of# Summation combination in tuple lists# Using list comprehension + combinationsfrom itertools import combinations # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10)] # printing original list print(\"The original list : \" + str(test_list)) # Summation combination in tuple lists# Using list comprehension + combinationsres = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(test_list, 2)] # printing resultprint(\"The Summation combinations are : \" + str(res))", "e": 27245, "s": 26720, "text": null }, { "code": null, "e": 27389, "s": 27245, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10)]\nThe Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)]\n" }, { "code": null, "e": 27637, "s": 27391, "text": "Method #2 : Using list comprehension + zip() + operator.add + combinations()The combinations of above methods can also solve this problem. In this, we perform the task of addition using add() and the like indexed elements are linked using zip()." }, { "code": "# Python3 code to demonstrate working of# Summation combination in tuple lists# Using list comprehension + zip() + operator.add + combinations()from itertools import combinationsimport operator # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10)] # printing original list print(\"The original list : \" + str(test_list)) # Summation combination in tuple lists# Using list comprehension + zip() + operator.add + combinations()res = [(operator.add(*a), operator.add(*b))\\ for a, b in (zip(y, x) for x, y in combinations(test_list, 2))] # printing resultprint(\"The Summation combinations are : \" + str(res))", "e": 28258, "s": 27637, "text": null }, { "code": null, "e": 28402, "s": 28258, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10)]\nThe Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)]\n" }, { "code": null, "e": 28423, "s": 28402, "text": "Python list-programs" }, { "code": null, "e": 28445, "s": 28423, "text": "Python tuple-programs" }, { "code": null, "e": 28452, "s": 28445, "text": "Python" }, { "code": null, "e": 28468, "s": 28452, "text": "Python Programs" }, { "code": null, "e": 28566, "s": 28468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28584, "s": 28566, "text": "Python Dictionary" }, { "code": null, "e": 28619, "s": 28584, "text": "Read a file line by line in Python" }, { "code": null, "e": 28651, "s": 28619, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28673, "s": 28651, "text": "Enumerate() in Python" }, { "code": null, "e": 28715, "s": 28673, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28758, "s": 28715, "text": "Python program to convert a list to string" }, { "code": null, "e": 28780, "s": 28758, "text": "Defaultdict in Python" }, { "code": null, "e": 28819, "s": 28780, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28865, "s": 28819, "text": "Python | Split string into list of characters" } ]
as_integer_ratio() in Python for reduced fraction of a given rational - GeeksforGeeks
30 Nov, 2021 Given a rational number d, print the reduced fraction which gives d.Examples: Input : d = 2.5 Output : 5/2 Explanation: 5/2 gives 2.5 which is the reduced form of any fraction that gives 2.5 Input : d = 1.5 Output : 3/2 as_integer_ratio() function Python: Returns a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Syntax: float. as_integer_ratio() Return Value: Tuple (a pair of integers) Errors: Raises OverflowError on infinities and a ValueError on NaNs. In Python we have an inbuilt function as_integer_ratio() which prints the reduced fraction form of any given rational number d. We need to store that in any variable and then print the 0th index and 1st index of the stored fraction. Python3 # function to print the fraction of# a given rational numberdef reducedfraction(d): # function that converts a rational number # to the reduced fraction b = d.as_integer_ratio() # reduced the list that contains the fraction return b # driver codeb = reducedfraction(2.5)print (b[0], "/", b[1]) Output: 5 / 2 simmytarika5 Fraction Python-Library rational-numbers Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python
[ { "code": null, "e": 24910, "s": 24882, "text": "\n30 Nov, 2021" }, { "code": null, "e": 24989, "s": 24910, "text": "Given a rational number d, print the reduced fraction which gives d.Examples: " }, { "code": null, "e": 25149, "s": 24989, "text": "Input : d = 2.5 \nOutput : 5/2\nExplanation: 5/2 gives 2.5 which is the reduced form\n of any fraction that gives 2.5 \n\nInput : d = 1.5 \nOutput : 3/2 " }, { "code": null, "e": 25299, "s": 25151, "text": "as_integer_ratio() function Python: Returns a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. " }, { "code": null, "e": 25443, "s": 25299, "text": "Syntax: float. as_integer_ratio() Return Value: Tuple (a pair of integers) Errors: Raises OverflowError on infinities and a ValueError on NaNs." }, { "code": null, "e": 25676, "s": 25443, "text": "In Python we have an inbuilt function as_integer_ratio() which prints the reduced fraction form of any given rational number d. We need to store that in any variable and then print the 0th index and 1st index of the stored fraction." }, { "code": null, "e": 25684, "s": 25676, "text": "Python3" }, { "code": "# function to print the fraction of# a given rational numberdef reducedfraction(d): # function that converts a rational number # to the reduced fraction b = d.as_integer_ratio() # reduced the list that contains the fraction return b # driver codeb = reducedfraction(2.5)print (b[0], \"/\", b[1])", "e": 25999, "s": 25684, "text": null }, { "code": null, "e": 26008, "s": 25999, "text": "Output: " }, { "code": null, "e": 26015, "s": 26008, "text": "5 / 2 " }, { "code": null, "e": 26028, "s": 26015, "text": "simmytarika5" }, { "code": null, "e": 26037, "s": 26028, "text": "Fraction" }, { "code": null, "e": 26052, "s": 26037, "text": "Python-Library" }, { "code": null, "e": 26069, "s": 26052, "text": "rational-numbers" }, { "code": null, "e": 26076, "s": 26069, "text": "Python" }, { "code": null, "e": 26174, "s": 26076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26192, "s": 26174, "text": "Python Dictionary" }, { "code": null, "e": 26227, "s": 26192, "text": "Read a file line by line in Python" }, { "code": null, "e": 26259, "s": 26227, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26301, "s": 26259, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26323, "s": 26301, "text": "Enumerate() in Python" }, { "code": null, "e": 26353, "s": 26323, "text": "Iterate over a list in Python" }, { "code": null, "e": 26379, "s": 26353, "text": "Python String | replace()" }, { "code": null, "e": 26423, "s": 26379, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26460, "s": 26423, "text": "Create a Pandas DataFrame from Lists" } ]
ReactJS UI Ant Design AutoComplete Component - GeeksforGeeks
21 May, 2021 Ant Design Library has this component pre-built, and it is very easy to integrate as well. AutoComplete Component is used for auto-completing the free text value with the option value. We can use the following approach in ReactJS to use the Ant Design AutoComplete Component. AutoComplete Methods: blur(): This method is used to remove the focus from the element. focus(): This method is used to get the focus on the element. AutoComplete Props: allowClear: It is used to show the clear button. autoFocus: It is used to get the focus when the component is mounted. backfill: If this value is true, then it back fills the selected item the input when using the keyboard. children(for customize input element): It is used to customize the input element. children(for dataSource): It is used for the data source to auto-complete. defaultActiveFirstOption: It is used to denote whether the first option is to be active by default or not. defaultOpen: It is used to indicate the initial open state of the dropdown. defaultValue: It is used to indicate the initially selected option. disabled: It is used to disable the select. dropdownClassName: It is used to pass the class name for the styling of the dropdown menu. dropdownMatchSelectWidth: It is used to determine whether the select input and the dropdown menu are of the same width or not. filterOption: It is used to apply the filter options against it if this is set to true. notFoundContent: It is used to show the content when no result matches. open: It is used to control the open state of the dropdown. options: It is used to pass the select options. placeholder: It is used to indicate the placeholder of input. value: It is used to denote the selected option value. onBlur: It is a callback function that is triggered on leaving the component. onChange: It is a callback function that is triggered on the selection of an option or input value change. onDropdownVisibleChange: It is a callback function that is triggered when the dropdown is open. onFocus: It is a callback function that is triggered when entering the component. onSearch: It is a callback function that is triggered when searching items. onSelect: It is a callback function that is triggered on the selection of an option. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd Step 3: After creating the ReactJS application, Install the required module using the following command: npm install antd Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React, { useState } from 'react'import "antd/dist/antd.css";import { AutoComplete } from 'antd'; export default function App() { const [currentValue, setCurrentValue] = useState('') const options = [ {label: 'One', value: 'One'}, {label: 'Two', value: 'Two'}, {label: 'Three', value: 'Three'}, {label: 'Four', value: 'Four'}, {label: 'Five', value: 'Five'} ] return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design AutoComplete Component</h4> <AutoComplete options={options} style={{ width: 200 }} onSelect={(value)=> { setCurrentValue(value) }} placeholder="Enter your text" /> <br /> <p>Selected Value {`${currentValue}`} </p> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://ant.design/components/auto-complete/ ReactJS-Ant Design ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? Create a Responsive Navbar using ReactJS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 35593, "s": 35565, "text": "\n21 May, 2021" }, { "code": null, "e": 35869, "s": 35593, "text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. AutoComplete Component is used for auto-completing the free text value with the option value. We can use the following approach in ReactJS to use the Ant Design AutoComplete Component." }, { "code": null, "e": 35891, "s": 35869, "text": "AutoComplete Methods:" }, { "code": null, "e": 35957, "s": 35891, "text": "blur(): This method is used to remove the focus from the element." }, { "code": null, "e": 36019, "s": 35957, "text": "focus(): This method is used to get the focus on the element." }, { "code": null, "e": 36039, "s": 36019, "text": "AutoComplete Props:" }, { "code": null, "e": 36088, "s": 36039, "text": "allowClear: It is used to show the clear button." }, { "code": null, "e": 36158, "s": 36088, "text": "autoFocus: It is used to get the focus when the component is mounted." }, { "code": null, "e": 36263, "s": 36158, "text": "backfill: If this value is true, then it back fills the selected item the input when using the keyboard." }, { "code": null, "e": 36345, "s": 36263, "text": "children(for customize input element): It is used to customize the input element." }, { "code": null, "e": 36420, "s": 36345, "text": "children(for dataSource): It is used for the data source to auto-complete." }, { "code": null, "e": 36527, "s": 36420, "text": "defaultActiveFirstOption: It is used to denote whether the first option is to be active by default or not." }, { "code": null, "e": 36603, "s": 36527, "text": "defaultOpen: It is used to indicate the initial open state of the dropdown." }, { "code": null, "e": 36671, "s": 36603, "text": "defaultValue: It is used to indicate the initially selected option." }, { "code": null, "e": 36715, "s": 36671, "text": "disabled: It is used to disable the select." }, { "code": null, "e": 36806, "s": 36715, "text": "dropdownClassName: It is used to pass the class name for the styling of the dropdown menu." }, { "code": null, "e": 36933, "s": 36806, "text": "dropdownMatchSelectWidth: It is used to determine whether the select input and the dropdown menu are of the same width or not." }, { "code": null, "e": 37021, "s": 36933, "text": "filterOption: It is used to apply the filter options against it if this is set to true." }, { "code": null, "e": 37093, "s": 37021, "text": "notFoundContent: It is used to show the content when no result matches." }, { "code": null, "e": 37153, "s": 37093, "text": "open: It is used to control the open state of the dropdown." }, { "code": null, "e": 37201, "s": 37153, "text": "options: It is used to pass the select options." }, { "code": null, "e": 37263, "s": 37201, "text": "placeholder: It is used to indicate the placeholder of input." }, { "code": null, "e": 37318, "s": 37263, "text": "value: It is used to denote the selected option value." }, { "code": null, "e": 37396, "s": 37318, "text": "onBlur: It is a callback function that is triggered on leaving the component." }, { "code": null, "e": 37503, "s": 37396, "text": "onChange: It is a callback function that is triggered on the selection of an option or input value change." }, { "code": null, "e": 37599, "s": 37503, "text": "onDropdownVisibleChange: It is a callback function that is triggered when the dropdown is open." }, { "code": null, "e": 37681, "s": 37599, "text": "onFocus: It is a callback function that is triggered when entering the component." }, { "code": null, "e": 37757, "s": 37681, "text": "onSearch: It is a callback function that is triggered when searching items." }, { "code": null, "e": 37842, "s": 37757, "text": "onSelect: It is a callback function that is triggered on the selection of an option." }, { "code": null, "e": 37892, "s": 37842, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 37987, "s": 37892, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 38051, "s": 37987, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 38083, "s": 38051, "text": "npx create-react-app foldername" }, { "code": null, "e": 38196, "s": 38083, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 38296, "s": 38196, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 38310, "s": 38296, "text": "cd foldername" }, { "code": null, "e": 38431, "s": 38310, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd" }, { "code": null, "e": 38536, "s": 38431, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 38553, "s": 38536, "text": "npm install antd" }, { "code": null, "e": 38605, "s": 38553, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 38623, "s": 38605, "text": "Project Structure" }, { "code": null, "e": 38753, "s": 38623, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 38760, "s": 38753, "text": "App.js" }, { "code": "import React, { useState } from 'react'import \"antd/dist/antd.css\";import { AutoComplete } from 'antd'; export default function App() { const [currentValue, setCurrentValue] = useState('') const options = [ {label: 'One', value: 'One'}, {label: 'Two', value: 'Two'}, {label: 'Three', value: 'Three'}, {label: 'Four', value: 'Four'}, {label: 'Five', value: 'Five'} ] return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design AutoComplete Component</h4> <AutoComplete options={options} style={{ width: 200 }} onSelect={(value)=> { setCurrentValue(value) }} placeholder=\"Enter your text\" /> <br /> <p>Selected Value {`${currentValue}`} </p> </div> );}", "e": 39563, "s": 38760, "text": null }, { "code": null, "e": 39676, "s": 39563, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 39686, "s": 39676, "text": "npm start" }, { "code": null, "e": 39785, "s": 39686, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 39841, "s": 39785, "text": "Reference: https://ant.design/components/auto-complete/" }, { "code": null, "e": 39860, "s": 39841, "text": "ReactJS-Ant Design" }, { "code": null, "e": 39868, "s": 39860, "text": "ReactJS" }, { "code": null, "e": 39885, "s": 39868, "text": "Web Technologies" }, { "code": null, "e": 39983, "s": 39885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40026, "s": 39983, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 40071, "s": 40026, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 40136, "s": 40071, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 40204, "s": 40136, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 40245, "s": 40204, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 40285, "s": 40245, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40318, "s": 40285, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40363, "s": 40318, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40406, "s": 40363, "text": "How to fetch data from an API in ReactJS ?" } ]
Tryit Editor v3.7
CSS Image Reflection Tryit: Image reflection - add gradient
[ { "code": null, "e": 30, "s": 9, "text": "CSS Image Reflection" } ]
Find Maximum and Minimum element in a Set in C++ STL - GeeksforGeeks
21 Jun, 2019 Given a Set, the task is to find the maximum and minimum element of this set in C++ STL. Examples: Input: set={1, 6, 15, 10, 5} Output: max = 15, min = 1 Input: set={10, 20, 30, 40, 50, 60} Output: max = 60, min = 10 Using set.begin() and set.end() methodsApproach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.begin() and set.end() methods respectively.Program:#include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << "Set: "; for (auto i : my_set) cout << i << " "; cout << '\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *(my_set.rbegin()); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *my_set.begin(); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << "Minimum element: " << findMin(my_set) << endl; // Get the maximum element cout << "Maximum element: " << findMax(my_set) << endl;}Output:Set: 1 5 6 10 15 Minimum element: 1 Maximum element: 15 Approach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.begin() and set.end() methods respectively. Program: #include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << "Set: "; for (auto i : my_set) cout << i << " "; cout << '\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *(my_set.rbegin()); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *my_set.begin(); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << "Minimum element: " << findMin(my_set) << endl; // Get the maximum element cout << "Maximum element: " << findMax(my_set) << endl;} Set: 1 5 6 10 15 Minimum element: 1 Maximum element: 15 Using set.rbegin() and set.rend() methodsApproach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.rend() and set.rbegin() methods respectively.Program:#include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << "Set: "; for (auto i : my_set) cout << i << " "; cout << '\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *my_set.rbegin(); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *(--my_set.rend()); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << "Minimum element: " << findMin(my_set) << endl; // Get the maximum element cout << "Maximum element: " << findMax(my_set) << endl;}Output:Set: 1 5 6 10 15 Minimum element: 1 Maximum element: 15 My Personal Notes arrow_drop_upSave Approach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.rend() and set.rbegin() methods respectively. Program: #include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << "Set: "; for (auto i : my_set) cout << i << " "; cout << '\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *my_set.rbegin(); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *(--my_set.rend()); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << "Minimum element: " << findMin(my_set) << endl; // Get the maximum element cout << "Maximum element: " << findMax(my_set) << endl;} Set: 1 5 6 10 15 Minimum element: 1 Maximum element: 15 klakshmanan6499 cpp-set STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 25369, "s": 25341, "text": "\n21 Jun, 2019" }, { "code": null, "e": 25458, "s": 25369, "text": "Given a Set, the task is to find the maximum and minimum element of this set in C++ STL." }, { "code": null, "e": 25468, "s": 25458, "text": "Examples:" }, { "code": null, "e": 25588, "s": 25468, "text": "Input: set={1, 6, 15, 10, 5}\nOutput: max = 15, min = 1\n\nInput: set={10, 20, 30, 40, 50, 60}\nOutput: max = 60, min = 10\n" }, { "code": null, "e": 27146, "s": 25588, "text": "Using set.begin() and set.end() methodsApproach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.begin() and set.end() methods respectively.Program:#include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << \"Set: \"; for (auto i : my_set) cout << i << \" \"; cout << '\\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *(my_set.rbegin()); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *my_set.begin(); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << \"Minimum element: \" << findMin(my_set) << endl; // Get the maximum element cout << \"Maximum element: \" << findMax(my_set) << endl;}Output:Set: 1 5 6 10 15 \nMinimum element: 1\nMaximum element: 15\n" }, { "code": null, "e": 27433, "s": 27146, "text": "Approach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.begin() and set.end() methods respectively." }, { "code": null, "e": 27442, "s": 27433, "text": "Program:" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << \"Set: \"; for (auto i : my_set) cout << i << \" \"; cout << '\\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *(my_set.rbegin()); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *my_set.begin(); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << \"Minimum element: \" << findMin(my_set) << endl; // Get the maximum element cout << \"Maximum element: \" << findMax(my_set) << endl;}", "e": 28603, "s": 27442, "text": null }, { "code": null, "e": 28661, "s": 28603, "text": "Set: 1 5 6 10 15 \nMinimum element: 1\nMaximum element: 15\n" }, { "code": null, "e": 30259, "s": 28661, "text": "Using set.rbegin() and set.rend() methodsApproach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.rend() and set.rbegin() methods respectively.Program:#include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << \"Set: \"; for (auto i : my_set) cout << i << \" \"; cout << '\\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *my_set.rbegin(); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *(--my_set.rend()); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << \"Minimum element: \" << findMin(my_set) << endl; // Get the maximum element cout << \"Maximum element: \" << findMax(my_set) << endl;}Output:Set: 1 5 6 10 15 \nMinimum element: 1\nMaximum element: 15\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30548, "s": 30259, "text": "Approach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set.rend() and set.rbegin() methods respectively." }, { "code": null, "e": 30557, "s": 30548, "text": "Program:" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to print the setvoid printSet(set<int> my_set){ // Print the set cout << \"Set: \"; for (auto i : my_set) cout << i << \" \"; cout << '\\n';} // Function to find the maximum elementint findMax(set<int> my_set){ // Get the maximum element int max_element; if (!my_set.empty()) max_element = *my_set.rbegin(); // return the maximum element return max_element;} // Function to find the minimum elementint findMin(set<int> my_set){ // Get the minimum element int min_element; if (!my_set.empty()) min_element = *(--my_set.rend()); // return the minimum element return min_element;} int main(){ // Get the set set<int> my_set; // Add the elements in the set my_set.insert(1); my_set.insert(6); my_set.insert(15); my_set.insert(10); my_set.insert(5); // Print the set printSet(my_set); // Get the minimum element cout << \"Minimum element: \" << findMin(my_set) << endl; // Get the maximum element cout << \"Maximum element: \" << findMax(my_set) << endl;}", "e": 31719, "s": 30557, "text": null }, { "code": null, "e": 31777, "s": 31719, "text": "Set: 1 5 6 10 15 \nMinimum element: 1\nMaximum element: 15\n" }, { "code": null, "e": 31793, "s": 31777, "text": "klakshmanan6499" }, { "code": null, "e": 31801, "s": 31793, "text": "cpp-set" }, { "code": null, "e": 31805, "s": 31801, "text": "STL" }, { "code": null, "e": 31809, "s": 31805, "text": "C++" }, { "code": null, "e": 31822, "s": 31809, "text": "C++ Programs" }, { "code": null, "e": 31826, "s": 31822, "text": "STL" }, { "code": null, "e": 31830, "s": 31826, "text": "CPP" }, { "code": null, "e": 31928, "s": 31830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31956, "s": 31928, "text": "Operator Overloading in C++" }, { "code": null, "e": 31976, "s": 31956, "text": "Polymorphism in C++" }, { "code": null, "e": 32009, "s": 31976, "text": "Friend class and function in C++" }, { "code": null, "e": 32033, "s": 32009, "text": "Sorting a vector in C++" }, { "code": null, "e": 32058, "s": 32033, "text": "std::string class in C++" }, { "code": null, "e": 32093, "s": 32058, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 32137, "s": 32093, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 32163, "s": 32137, "text": "C++ Program for QuickSort" }, { "code": null, "e": 32222, "s": 32163, "text": "How to return multiple values from a function in C or C++?" } ]
Print all possible strings | Practice | GeeksforGeeks
Given a string str your task is to complete the function spaceString which takes only one argument the string str and finds all possible strings that can be made by placing spaces (zero or one) in between them. For eg . for the string abc all valid strings will be abc ab c a bc a b c Example 1: Input: str = abc Output: abc$ab c$a bc$a b c$ Example 2: Input: str = xy Output: xy$x y$ Your Task: Complete the function spaceString() which takes a character array as an input parameter and returns list of all possible answers. The driver code will print the all possible answer '$' separated Expected Time Complexity: O(N * 2N) Expected Auxiliary Space: O(N) Constraints: 1<= length of string str <=10 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 mestryruturaj3 weeks ago //JAVA class GfG { ArrayList<String> spaceString(String str) { ArrayList<String> res = new ArrayList<String>(); helper(str, str, "", res); return res; } void helper(String str, String ip, String op, ArrayList<String> res) { if (str.length() == ip.length()) { op = "" + str.charAt(0); ip = str.substring(1); helper(str, ip, op, res); } else { if (ip.length() == 0) { res.add(op); return; } String op1 = op + " " + ip.charAt(0); String op2 = op + ip.charAt(0); ip = ip.substring(1); helper(str, ip, op2, res); helper(str, ip, op1, res); } } } 0 shrustis1761 month ago C++ solution void solve(string ip, string op, vector<string> &v){ if(ip.length() == 0) { v.push_back(op); return; } string op1=op; string op2=op; op1.push_back(' '); op1.push_back(ip[0]); op2.push_back(ip[0]); ip.erase(ip.begin()+0); solve(ip,op1,v); solve(ip,op2,v); } vector<string> spaceString(char str[]){//Your code here string ip,op; vector<string>v; // int l=str.length(); ip=str; op.push_back(ip[0]); ip.erase(ip.begin()+0); solve(ip,op,v); reverse(v.begin(), v.end()); return v;} +1 akanksha00122 months ago void recString(string S,int i, string s, vector<string>& a){ if(S.size()<=i){ a.push_back(s); return; } recString(S,i+1,s+S[i],a);//no space recString(S,i+1,s+" "+S[i],a);//add space } vector<string> spaceString(char str[]) { //Your code here vector<string> ans; string S=""; for(int i=0;str[i]!='\0';i++) S+=str[i]; string s; s+=S[0];//initailize with S[0] recString(S,1,s,ans);//start from index 1 return ans; } 0 blank551k2 months ago // int n=1;void storestring(vector<string>& a,string s,int i){ // cout<<n<<" "; // ++n; if(i>=s.size()){ // cout<<s<<endl; a.push_back(s); return ; } storestring(a,s,i+1); storestring(a,(s.substr(0,i)+" "+s.substr(i)),i+2);} vector<string> spaceString(char str[]){ string s=""; vector<string> a; for(int i=0;str[i]!='\0';++i){ s.push_back(str[i]); } storestring(a,s,1); return a;} 0 madhumita1310002 months ago void recur(vector<string>&s,string st,char str[],int i,int l){ if(i==l) { s.push_back(st); //s.push_back("$"); return; } else { recur(s,st+str[i],str,i+1,l); if(i<l-1) { recur(s,st+str[i]+" ",str,i+1,l); } }} vector<string> spaceString(char str[]){//Your code hereint i=0;//int l=str.length();int j=0,l=0;/*while(str[j]){ j++; l++;}*/vector<string> s;string st="";recur(s,st,str,i,l);return s;} 0 ppt892 months ago Java Solution Recursive Approach class GfG { ArrayList<String> spaceString(String str) { // Your code here ArrayList<String> res = new ArrayList<>(); if(str.length() == 0) return res; String op = ""+str.charAt(0); str = str.substring(1); return solve(str, op, res); } ArrayList<String> solve(String ip, String op, ArrayList<String> res){ if(ip.length() == 0){ res.add(op); return res; } String op1 = op; String op2 = op; op1 += " "+ip.charAt(0); op2 += ip.charAt(0); ip = ip.substring(1); solve(ip, op2, res); solve(ip, op1, res); return res; } } 0 ankurjeesingh3102 months ago My JavaScript Code:::::---→ class Solution { spaceString(str){ if(str.length===1){ return [str]; } let ch = str.charAt(0); let res = str.substring(1); let subStr = this.spaceString(res); let myres = []; for(let i =0; i<subStr.length; i++){ myres.push(ch+subStr[i]); } for(let i =0; i<subStr.length; i++){ myres.push(ch+" "+subStr[i]); } return myres; }} +2 pranavtripathi20013 months ago void subsets(string input,int index,string output,vector<string> &v){ if(index==input.size()){ v.push_back(output); return; } //Dont pick the space string op1=output+input[index]; string op2=output+" "+ input[index]; subsets(input,index+1,op1,v); //pick the space subsets(input,index+1,op2,v); } vector<string> spaceString(char str[]){ string input = str; vector<string>v; string output=""; output+=input[0]; subsets(input,1,output,v); return v; } +1 sachinkartik1663 months ago class GfG{ ArrayList<String> spaceString(String str) { ArrayList<String> list=new ArrayList<>(); rec(list,str,0,""); return list; } public void rec(ArrayList<String> list,String str,int i,String s){ if(str.length()==i){ list.add(s); return; } rec(list,str,i+1,s+str.charAt(i)); if(i==0){ return; } rec(list,str,i+1,s+" "+str.charAt(i)); } } 0 alexluthner77 This comment was deleted. 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": 603, "s": 238, "text": "Given a string str your task is to complete the function spaceString which takes only one argument the string str and finds all possible strings that can be made by placing spaces (zero or one) in between them. \n\nFor eg . for the string abc all valid strings will be\n abc\n ab c\n a bc\n a b c\n\nExample 1:" }, { "code": null, "e": 650, "s": 603, "text": "Input:\nstr = abc\nOutput: abc$ab c$a bc$a b c$\n" }, { "code": null, "e": 661, "s": 650, "text": "Example 2:" }, { "code": null, "e": 695, "s": 661, "text": "Input:\nstr = xy\nOutput: xy$x y$\n\n" }, { "code": null, "e": 901, "s": 695, "text": "Your Task:\nComplete the function spaceString() which takes a character array as an input parameter and returns list of all possible answers. The driver code will print the all possible answer '$' separated" }, { "code": null, "e": 968, "s": 901, "text": "Expected Time Complexity: O(N * 2N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1322, "s": 968, "text": "\nConstraints:\n1<= length of string str <=10\n\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1324, "s": 1322, "text": "0" }, { "code": null, "e": 1349, "s": 1324, "text": "mestryruturaj3 weeks ago" }, { "code": null, "e": 2158, "s": 1349, "text": "//JAVA\nclass GfG {\n ArrayList<String> spaceString(String str) {\n ArrayList<String> res = new ArrayList<String>();\n helper(str, str, \"\", res);\n return res;\n }\n \n void helper(String str, String ip, String op, ArrayList<String> res) {\n if (str.length() == ip.length()) {\n op = \"\" + str.charAt(0);\n ip = str.substring(1);\n \n helper(str, ip, op, res);\n }\n else {\n if (ip.length() == 0) {\n res.add(op);\n return;\n }\n \n String op1 = op + \" \" + ip.charAt(0);\n String op2 = op + ip.charAt(0);\n ip = ip.substring(1);\n \n helper(str, ip, op2, res);\n helper(str, ip, op1, res);\n }\n }\n}" }, { "code": null, "e": 2160, "s": 2158, "text": "0" }, { "code": null, "e": 2183, "s": 2160, "text": "shrustis1761 month ago" }, { "code": null, "e": 2196, "s": 2183, "text": "C++ solution" }, { "code": null, "e": 2505, "s": 2198, "text": "void solve(string ip, string op, vector<string> &v){ if(ip.length() == 0) { v.push_back(op); return; } string op1=op; string op2=op; op1.push_back(' '); op1.push_back(ip[0]); op2.push_back(ip[0]); ip.erase(ip.begin()+0); solve(ip,op1,v); solve(ip,op2,v); }" }, { "code": null, "e": 2750, "s": 2505, "text": "vector<string> spaceString(char str[]){//Your code here string ip,op; vector<string>v; // int l=str.length(); ip=str; op.push_back(ip[0]); ip.erase(ip.begin()+0); solve(ip,op,v); reverse(v.begin(), v.end()); return v;}" }, { "code": null, "e": 2753, "s": 2750, "text": "+1" }, { "code": null, "e": 2778, "s": 2753, "text": "akanksha00122 months ago" }, { "code": null, "e": 3263, "s": 2778, "text": "void recString(string S,int i, string s, vector<string>& a){\n if(S.size()<=i){\n a.push_back(s);\n return;\n }\n recString(S,i+1,s+S[i],a);//no space\n recString(S,i+1,s+\" \"+S[i],a);//add space\n}\n\nvector<string> spaceString(char str[])\n{\n//Your code here\n vector<string> ans;\n string S=\"\";\n for(int i=0;str[i]!='\\0';i++)\n S+=str[i];\n string s;\n s+=S[0];//initailize with S[0]\n recString(S,1,s,ans);//start from index 1\n return ans;\n} " }, { "code": null, "e": 3265, "s": 3263, "text": "0" }, { "code": null, "e": 3287, "s": 3265, "text": "blank551k2 months ago" }, { "code": null, "e": 3548, "s": 3287, "text": "// int n=1;void storestring(vector<string>& a,string s,int i){ // cout<<n<<\" \"; // ++n; if(i>=s.size()){ // cout<<s<<endl; a.push_back(s); return ; } storestring(a,s,i+1); storestring(a,(s.substr(0,i)+\" \"+s.substr(i)),i+2);}" }, { "code": null, "e": 3723, "s": 3548, "text": "vector<string> spaceString(char str[]){ string s=\"\"; vector<string> a; for(int i=0;str[i]!='\\0';++i){ s.push_back(str[i]); } storestring(a,s,1); return a;}" }, { "code": null, "e": 3725, "s": 3723, "text": "0" }, { "code": null, "e": 3753, "s": 3725, "text": "madhumita1310002 months ago" }, { "code": null, "e": 4037, "s": 3753, "text": "void recur(vector<string>&s,string st,char str[],int i,int l){ if(i==l) { s.push_back(st); //s.push_back(\"$\"); return; } else { recur(s,st+str[i],str,i+1,l); if(i<l-1) { recur(s,st+str[i]+\" \",str,i+1,l); } }}" }, { "code": null, "e": 4228, "s": 4037, "text": "vector<string> spaceString(char str[]){//Your code hereint i=0;//int l=str.length();int j=0,l=0;/*while(str[j]){ j++; l++;}*/vector<string> s;string st=\"\";recur(s,st,str,i,l);return s;}" }, { "code": null, "e": 4230, "s": 4228, "text": "0" }, { "code": null, "e": 4248, "s": 4230, "text": "ppt892 months ago" }, { "code": null, "e": 4281, "s": 4248, "text": "Java Solution Recursive Approach" }, { "code": null, "e": 4994, "s": 4283, "text": "class GfG\n{\n ArrayList<String> spaceString(String str)\n {\n // Your code here\n ArrayList<String> res = new ArrayList<>();\n if(str.length() == 0) return res;\n \n String op = \"\"+str.charAt(0);\n str = str.substring(1);\n return solve(str, op, res);\n \n }\n ArrayList<String> solve(String ip, String op, ArrayList<String> res){\n if(ip.length() == 0){\n res.add(op);\n return res;\n }\n String op1 = op;\n String op2 = op;\n op1 += \" \"+ip.charAt(0);\n op2 += ip.charAt(0);\n \n ip = ip.substring(1);\n \n solve(ip, op2, res);\n solve(ip, op1, res);\n \n \n return res;\n }\n}" }, { "code": null, "e": 4996, "s": 4994, "text": "0" }, { "code": null, "e": 5025, "s": 4996, "text": "ankurjeesingh3102 months ago" }, { "code": null, "e": 5053, "s": 5025, "text": "My JavaScript Code:::::---→" }, { "code": null, "e": 5292, "s": 5053, "text": "class Solution { spaceString(str){ if(str.length===1){ return [str]; } let ch = str.charAt(0); let res = str.substring(1); let subStr = this.spaceString(res); let myres = [];" }, { "code": null, "e": 5530, "s": 5292, "text": " for(let i =0; i<subStr.length; i++){ myres.push(ch+subStr[i]); } for(let i =0; i<subStr.length; i++){ myres.push(ch+\" \"+subStr[i]); } return myres; }}" }, { "code": null, "e": 5537, "s": 5534, "text": "+2" }, { "code": null, "e": 5568, "s": 5537, "text": "pranavtripathi20013 months ago" }, { "code": null, "e": 5946, "s": 5568, "text": "void subsets(string input,int index,string output,vector<string> &v){ if(index==input.size()){ v.push_back(output); return; } //Dont pick the space string op1=output+input[index]; string op2=output+\" \"+ input[index]; subsets(input,index+1,op1,v); //pick the space subsets(input,index+1,op2,v); }" }, { "code": null, "e": 6130, "s": 5946, "text": "vector<string> spaceString(char str[]){ string input = str; vector<string>v; string output=\"\"; output+=input[0]; subsets(input,1,output,v); return v; } " }, { "code": null, "e": 6133, "s": 6130, "text": "+1" }, { "code": null, "e": 6161, "s": 6133, "text": "sachinkartik1663 months ago" }, { "code": null, "e": 6652, "s": 6161, "text": "class GfG{ ArrayList<String> spaceString(String str) { ArrayList<String> list=new ArrayList<>(); rec(list,str,0,\"\"); return list; } public void rec(ArrayList<String> list,String str,int i,String s){ if(str.length()==i){ list.add(s); return; } rec(list,str,i+1,s+str.charAt(i)); if(i==0){ return; } rec(list,str,i+1,s+\" \"+str.charAt(i)); } } " }, { "code": null, "e": 6654, "s": 6652, "text": "0" }, { "code": null, "e": 6668, "s": 6654, "text": "alexluthner77" }, { "code": null, "e": 6694, "s": 6668, "text": "This comment was deleted." }, { "code": null, "e": 6840, "s": 6694, "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": 6876, "s": 6840, "text": " Login to access your submissions. " }, { "code": null, "e": 6886, "s": 6876, "text": "\nProblem\n" }, { "code": null, "e": 6896, "s": 6886, "text": "\nContest\n" }, { "code": null, "e": 6959, "s": 6896, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7107, "s": 6959, "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": 7315, "s": 7107, "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": 7421, "s": 7315, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
dos2unix and unix2dos commands - GeeksforGeeks
15 May, 2019 Sometimes, you will need to move files between windows and unix systems. Window files use the same format as Dos, where the end of line is signified by two characters, Carriage Return or CR or \r followed by Line Feed or LF or \n.Unix files, on the other hand, use only Line Feed (\n). unix2dos is a tool to convert line breaks in a text file from Unix format (Line feed) to DOS format (carriage return + Line feed) and vice versa. dos2unix command : converts a DOS text file to UNIX format. Unix2dos command : converts a Unix text file to DOS formatExampleTask : Create a file in DOS or in notepad with following contents hello everybody welcome to unix unix is easy now copy this file in unix /home/geeks directory$od –bc myfile.txt 0000000 150 145 154 154 157 040 145 166 145 162 171 142 157 144 171 015 h e l l o e v e r y b o d y \r 0000020 012 167 145 154 143 157 155 145 040 164 157 040 165 156 151 170 \n w e l c o m e t o u n i x 0000040 015 012 165 156 151 170 040 151 163 040 145 141 163 171 015 012 \r \n u n i x i s e a s y \r \n 0000060 The CR-LF combination is represented by the octal values 015-012 and the escape sequence \r\n.Note: The above output shows that this is a DOS format file.Now convert DOS file to UNIX format by using dos2unix command$dos2unix myfile.txt $od –bc myfile.txt Conversion of this file to UNIX is just a simple matter of removing the \r.We can also convert UNIX file to DOS format by using unixsdos command$unix2dos myfile.txt $od –bc myfile.txt After Conversion of this file to DOS, \r is added in DOS file.This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Example Task : Create a file in DOS or in notepad with following contents hello everybody welcome to unix unix is easy now copy this file in unix /home/geeks directory $od –bc myfile.txt 0000000 150 145 154 154 157 040 145 166 145 162 171 142 157 144 171 015 h e l l o e v e r y b o d y \r 0000020 012 167 145 154 143 157 155 145 040 164 157 040 165 156 151 170 \n w e l c o m e t o u n i x 0000040 015 012 165 156 151 170 040 151 163 040 145 141 163 171 015 012 \r \n u n i x i s e a s y \r \n 0000060 The CR-LF combination is represented by the octal values 015-012 and the escape sequence \r\n. Note: The above output shows that this is a DOS format file.Now convert DOS file to UNIX format by using dos2unix command $dos2unix myfile.txt $od –bc myfile.txt Conversion of this file to UNIX is just a simple matter of removing the \r.We can also convert UNIX file to DOS format by using unixsdos command $unix2dos myfile.txt $od –bc myfile.txt After Conversion of this file to DOS, \r is added in DOS file. This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. linux-command Linux-system-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples UDP Server-Client implementation in C Cat command in Linux with examples touch command in Linux with Examples scp command in Linux with Examples echo command in Linux with Examples
[ { "code": null, "e": 25347, "s": 25319, "text": "\n15 May, 2019" }, { "code": null, "e": 25633, "s": 25347, "text": "Sometimes, you will need to move files between windows and unix systems. Window files use the same format as Dos, where the end of line is signified by two characters, Carriage Return or CR or \\r followed by Line Feed or LF or \\n.Unix files, on the other hand, use only Line Feed (\\n)." }, { "code": null, "e": 25779, "s": 25633, "text": "unix2dos is a tool to convert line breaks in a text file from Unix format (Line feed) to DOS format (carriage return + Line feed) and vice versa." }, { "code": null, "e": 25839, "s": 25779, "text": "dos2unix command : converts a DOS text file to UNIX format." }, { "code": null, "e": 27482, "s": 25839, "text": "Unix2dos command : converts a Unix text file to DOS formatExampleTask : Create a file in DOS or in notepad with following contents\nhello everybody\nwelcome to unix\nunix is easy\nnow copy this file in unix /home/geeks directory$od –bc myfile.txt\n0000000 150 145 154 154 157 040 145 166 145 162 171 142 157 144 171 015\n h e l l o e v e r y b o d y \\r\n0000020 012 167 145 154 143 157 155 145 040 164 157 040 165 156 151 170\n \\n w e l c o m e t o u n i x\n0000040 015 012 165 156 151 170 040 151 163 040 145 141 163 171 015 012\n \\r \\n u n i x i s e a s y \\r \\n\n0000060\nThe CR-LF combination is represented by the octal values 015-012 and the escape sequence \\r\\n.Note: The above output shows that this is a DOS format file.Now convert DOS file to UNIX format by using dos2unix command$dos2unix myfile.txt\n$od –bc myfile.txt\nConversion of this file to UNIX is just a simple matter of removing the \\r.We can also convert UNIX file to DOS format by using unixsdos command$unix2dos myfile.txt\n$od –bc myfile.txt\nAfter Conversion of this file to DOS, \\r is added in DOS file.This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27490, "s": 27482, "text": "Example" }, { "code": null, "e": 27602, "s": 27490, "text": "Task : Create a file in DOS or in notepad with following contents\nhello everybody\nwelcome to unix\nunix is easy\n" }, { "code": null, "e": 27651, "s": 27602, "text": "now copy this file in unix /home/geeks directory" }, { "code": null, "e": 28111, "s": 27651, "text": "$od –bc myfile.txt\n0000000 150 145 154 154 157 040 145 166 145 162 171 142 157 144 171 015\n h e l l o e v e r y b o d y \\r\n0000020 012 167 145 154 143 157 155 145 040 164 157 040 165 156 151 170\n \\n w e l c o m e t o u n i x\n0000040 015 012 165 156 151 170 040 151 163 040 145 141 163 171 015 012\n \\r \\n u n i x i s e a s y \\r \\n\n0000060\n" }, { "code": null, "e": 28206, "s": 28111, "text": "The CR-LF combination is represented by the octal values 015-012 and the escape sequence \\r\\n." }, { "code": null, "e": 28328, "s": 28206, "text": "Note: The above output shows that this is a DOS format file.Now convert DOS file to UNIX format by using dos2unix command" }, { "code": null, "e": 28369, "s": 28328, "text": "$dos2unix myfile.txt\n$od –bc myfile.txt\n" }, { "code": null, "e": 28514, "s": 28369, "text": "Conversion of this file to UNIX is just a simple matter of removing the \\r.We can also convert UNIX file to DOS format by using unixsdos command" }, { "code": null, "e": 28555, "s": 28514, "text": "$unix2dos myfile.txt\n$od –bc myfile.txt\n" }, { "code": null, "e": 28618, "s": 28555, "text": "After Conversion of this file to DOS, \\r is added in DOS file." }, { "code": null, "e": 28918, "s": 28618, "text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29043, "s": 28918, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29057, "s": 29043, "text": "linux-command" }, { "code": null, "e": 29079, "s": 29057, "text": "Linux-system-commands" }, { "code": null, "e": 29090, "s": 29079, "text": "Linux-Unix" }, { "code": null, "e": 29188, "s": 29090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29226, "s": 29188, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 29261, "s": 29226, "text": "tar command in Linux with examples" }, { "code": null, "e": 29297, "s": 29261, "text": "curl command in Linux with Examples" }, { "code": null, "e": 29335, "s": 29297, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 29371, "s": 29335, "text": "Tail command in Linux with examples" }, { "code": null, "e": 29409, "s": 29371, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 29444, "s": 29409, "text": "Cat command in Linux with examples" }, { "code": null, "e": 29481, "s": 29444, "text": "touch command in Linux with Examples" }, { "code": null, "e": 29516, "s": 29481, "text": "scp command in Linux with Examples" } ]
LocalDate getMonth() method in Java
The month name for a particular LocalDate can be obtained using the getMonth() method in the LocalDate class in Java. This method requires no parameters and it returns the month name in the year. A program that demonstrates this is given as follows Live Demo import java.time.*; public class Demo { public static void main(String[] args) { LocalDate ld = LocalDate.parse("2019-02-14"); System.out.println("The LocalDate is: " + ld); System.out.println("The month is: " + ld.getMonth()); } } The LocalDate is: 2019-02-14 The month is: FEBRUARY Now let us understand the above program. First the LocalDate is displayed. Then the month name for the LocalDate is displayed using the getMonth() method. A code snippet that demonstrates this is as follows: LocalDate ld = LocalDate.parse("2019-02-14"); System.out.println("The LocalDate is: " + ld); System.out.println("The month is: " + ld.getMonth());
[ { "code": null, "e": 1258, "s": 1062, "text": "The month name for a particular LocalDate can be obtained using the getMonth() method in the LocalDate class in Java. This method requires no parameters and it returns the month name in the year." }, { "code": null, "e": 1311, "s": 1258, "text": "A program that demonstrates this is given as follows" }, { "code": null, "e": 1322, "s": 1311, "text": " Live Demo" }, { "code": null, "e": 1578, "s": 1322, "text": "import java.time.*;\npublic class Demo {\n public static void main(String[] args) {\n LocalDate ld = LocalDate.parse(\"2019-02-14\");\n System.out.println(\"The LocalDate is: \" + ld);\n System.out.println(\"The month is: \" + ld.getMonth());\n }\n}" }, { "code": null, "e": 1630, "s": 1578, "text": "The LocalDate is: 2019-02-14\nThe month is: FEBRUARY" }, { "code": null, "e": 1671, "s": 1630, "text": "Now let us understand the above program." }, { "code": null, "e": 1838, "s": 1671, "text": "First the LocalDate is displayed. Then the month name for the LocalDate is displayed using the getMonth() method. A code snippet that demonstrates this is as follows:" }, { "code": null, "e": 1985, "s": 1838, "text": "LocalDate ld = LocalDate.parse(\"2019-02-14\");\nSystem.out.println(\"The LocalDate is: \" + ld);\nSystem.out.println(\"The month is: \" + ld.getMonth());" } ]
Building Simulations in Python — A Step by Step Walkthrough | by Terence Shin | Towards Data Science
Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more! IntroductionThe Most Basic SimulationAdding More Variables to the SimulationAdding EVEN MORE complexityFull Code Introduction The Most Basic Simulation Adding More Variables to the Simulation Adding EVEN MORE complexity Full Code Computer-generated simulations are one of the fastest-growing technologies today, and it’s never been more important with COVID-19 around. You might have wondered how governments and agencies make decisions when it comes to enforcing lockdowns, closing schools, banning indoor dining, etc... These decisions aren’t blindly made. They’re made through simulations. A simulation is simply an imitation of a situation or a process. In the case of this pandemic, governments use simulations to see how different factors, like the ones listed above, impact the spread of COVID-19. Simulations are useful for a number of reasons: They can turn into powerful visualizations that make it easier to communicate insights and findings. They can be used for predictions and forecasting, but we’ll talk more about this later. They can help you understand the most important factors in a simulation. (Eg. How does a 1% change in factor A affect the output vs a 1% change in factor B?) A big misconception about simulations is that they’re really complicated, and that’s not necessarily the case! Simulations can end up being very complex, but they can also be very simple. In this article, you’ll learn how to build a very simple simulation/model of population growth, as well as how it can be improved. Note: In this article, the terms “model” and “simulation” will be used synonymously. Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more! The most basic human population simulator that we could possibly create would be something like this, where the initial population is 50 and we want to see how the population grows to 1,000,000: totalPopulation = 50 growthFactor = 1.00005dayCount = 0 #Every 2 months the population is reportedwhile totalPopulation < 1000000: totalPopulation *= growthFactor #Every 56th day, population is reported dayCount += 1 if dayCount == 56: dayCount = 0 print(totalPopulation) If you can tell, this program is simply an exponential function and is too basic of a model to be able to simulate population growth. As you might have already thought, the total number of people in an environment won’t increase by a set percentage every cycle, and there are many factors that affect the population that aren’t included. This is okay! This is how a simulation starts. It starts off simple and gets more advanced. Let’s see how we can improve on this. If we want to run a more realistic simulation of the human population, we’ll need to establish some factors and use them to control when people are born, reproduce, and die. So, let’s set up a more complicated simulation. Although there are millions of variables that can change population, we’ll stick with just a few major ones. Once these are set up, we can program them to fluctuate, and they can be tinkered with to imitate different scenarios. I’ve chosen eight very simple factors: Starting populationInfant mortalityFoodFertility x & Fertility yHealthcareAgricultureChance of disasterAge of death. Starting population Infant mortality Food Fertility x & Fertility y Healthcare Agriculture Chance of disaster Age of death. I’ll explain how each of these works as I go. Let’s create a new Python script in the IDLE. We’ll use the random function quite a lot, so import that first: import random Now we assign a value to the variable startingPopulation. This can be virtually whatever you want, but I’m using fifty. startingPopulation = 50 Realistically it would be impossible to grow a population significantly from just fifty people, and inbreeding would cause endless genetic diseases, but let’s keep it simple. Our next variable is infantMortality. This is the chance of a child dying in their first year of life. Our World in Data estimates an average infant mortality rate of ~25% over the past two millennia. I’ll use that because it can give us a good historical simulation. infantMortality = 25 The variable, agriculture, will be how many “units” of food each person produces. One unit of food feeds a person for a single year. In our simulation, each person must eat one unit of food every year or they will die. Therefore, if agriculture is exactly 1 in a given year, everyone eats. If it is 0.5, fifty percent of the population dies. If it is 1.5, there is a fifty percent excess of food, and this can be stored and used as a backup if the agriculture in the next year is not enough to support the population. Explained simply, if the agriculture value is not above 1, the population cannot grow, because the population would starve. To start, I’ll use a value of 5, meaning each person produces enough food for themselves, plus four more people: agriculture = 5 Then we have disasterChance. This is the probability every year that some natural disaster comes along and damages the population. It will affect the population by a random percentage, from 5–10%. To start with, I’ll leave the disasterChance at 10%, meaning on average every ten years a disaster will come along. disasterChance = 10 food is pretty self-explanatory. Every year we will run a “harvest” function and the output of that harvest will be the population multiplied by agriculture. Even if your agriculture is below 1, if you have stocks of food, you can theoretically maintain your population. food = 0 Finally, we have fertilityx and fertilityy. These are the ages at which a women can become pregnant in our simulation. For my program, I’m using the range of ages 18 to 35. fertilityx = 18fertilityy = 35 Now, we need a way for these factors to control our population on a year by year basis. We could do this a mathematical way and use all sorts of percentages, but I think it’d be more intuitive and versatile if we used object-based programming to simulate each person. Each person will be an object with a few factors, and every cycle (that is, one year of our simulation) that person will be affected in some way — at the least, their age will increase by 1. We need something to store all these people, so let’s create a list: peopleDictionary = [] That’s where each object will be stored and we can use a for loop to cycle through each person year by year and alter them. If you are not familiar with Python classes and objects, I would probably read up on them. But if you’re already up to scratch, let’s define a class which we can use for every human: class Person: def __init__(self, age): self.gender = random.randint(0,1) self.age = age This is the way we’ll “spawn” a person. As you can see, each person has a gender and age. You may notice that when we “spawn” a person, their age is not set to 0. The reason for this is because when we initiate the simulation, we’ll use this class to create a group of people with random ages, so we don’t want to immediately set every person to 0 years old. There are several functions we need to include in this program. For now, we want the program to simulate a population that exponentially increases over time — just like our very simple demo program from the start of this article. Therefore, the following must happen: All “able” people, that is, anyone over 8 years old, works in the fields to produce food. This includes both men and women for simplicity.A certain number of women in the fertility band give birth to babies every year.Anyone over eighty years old dies. All “able” people, that is, anyone over 8 years old, works in the fields to produce food. This includes both men and women for simplicity. A certain number of women in the fertility band give birth to babies every year. Anyone over eighty years old dies. With this model, the population should increase exponentially, because enough infants are born every year to outweigh the number of people dying from old age, and as these infants reach 8+ years of age, they produce food to support the civilization. Let’s create the harvest function: def harvest(food, agriculture): ablePeople = 0 for person in peopleDictionary: if person.age > 8: ablePeople +=1 food += ablePeople * agriculture if food < len(peopleDictionary): del peopleDictionary[0:int(len(peopleDictionary)-food)] food = 0 else: food -= len(peopleDictionary) Every year of the simulation there is a “harvest”. The function takes the food and agriculture values. It calculates how many “able” people there are to produce food by counting those over 8 years of age. Of course, we multiply the number of able people by agriculture to get the total food produced for the year. If the food is not enough for each person to eat 1 unit of food, then the dictionary of people is limited to the amount of food available, and the excess die from starvation. This ensures that if there is not enough food to go around, people who cannot eat die, and the population is effectively limited. But if there is excess food, each person consumes 1 unit, and whatever is left is stored for the next year! To grow our population, we need a reproduce function: def reproduce(fertilityx, fertilityy): for person in peopleDictionary: if person.gender == 1: if person.age > fertilityx: if person.age < fertilityy: if random.randint(0,5)==1: peopleDictionary.append(Person(0)) Here I have assumed that 1 in 5 women will become pregnant every year. Of course that figure isn’t exactly accurate to real life, but it’ll work fine for our simulation! The reproduce function cycles through every person in the dictionary of people. If any person is female and between the ages of 18 and 35, they have a 20% chance of giving birth, and a new person of age 0 is appended to the dictionary of people. Fantastic, we have our very basic functions laid out. Although this could be done more simply using maths, setting our code out as an object-based script allows for more flexibility; if you wanted to expand the program and make it more realistic, you could add various characteristics to each person, such as medical conditions or social class. We need a way to initiate our simulation. To get the ball rolling, we spawn fifty people, with random ages between 18 and 50. This is our beginSim function: def beginSim(): for x in range(startPopulation): peopleDictionary.append(Person(random.randint(18,50))) As you can see, we add fifty people to our people dictionary, each of which has a random age. We can call this function at the bottom of our script, like this: beginSim() After starting the program and creating these people, we need a system to cycle through each year, and perform the harvest and reproduce functions. We’ll call this function runYear: def runYear(food, agriculture, fertilityx, fertilityy): harvest(food, agriculture) reproduce(fertilityx, fertilityy) for person in peopleDictionary: if person.age > 80: peopleDictionary.remove(person) else: person.age +=1 print(len(peopleDictionary)) Let’s see what is going on here. The runYear function takes agriculture, food, fertilityx and fertilityy. It runs the harvest function to find out if the food will leave some people to starve to death, or if there is enough to be stored. We then perform the reproduce function, so that 20% of women between 18–35 give birth to a baby. Next, we cycle through the people dictionary and remove anyone who is over 80. The rest of the population increases by 1 year of age. If you wanted to improve the simulator, you could make it more random which age you die at. Finally, we print out the total population. To keep the runYear function going, we’ll include this line just below where we initiated the program through beginSim: while len(peopleDictionary)<100000 and len(peopleDictionary) > 1: runYear(food, agriculture, fertilityx, fertilityy) This just ensures that the program stops when the population reaches 0 or 100,000. Congratulations! We have population growth, the basis for our simulator. If you import this data into Excel, we get this graph: This looks just like our graph from the simple first program of the article. It makes sense based on the current code, but it’s not very interesting. Let’s spice it up a little. Remember those variables, infantMortality and disasterChance we talked about? Let’s factor those in. 20% of women give birth every year, according to our simulation, but 25% of those infants die. So let’s update our reproduce function and include this: if random.randint(0,5)==1: if random.randint(0,100)>infantMortality: peopleDictionary.append(Person(0)) Note: You’ll also want to update the runYear function, and also the line where we call it, so it can accept the infantMortality variable. Otherwise, you will get the error “infantMortality is not defined”. As you can see, instead of giving each woman a 1 in 5 chance of giving birth, even if she does give birth, there is a 25% chance of the baby dying. You can see from our random clause that any random numbers generated between 0–100 that are below 25% = baby dies, any above = baby lives. If infantMortality is high, then very few of the infants will survive. Ideally, you want to get it down from 1% to 2%. When we run the simulation with a 25% infant mortality rate, the results are quite gloomy and inaccurate: Instead, let’s allow infant mortality rates to decrease over time, as healthcare gets better. You’d think after a hundred years they would make some advances, right? To keep the infantMortality variable updated, we’ll make this change to where we call the runYear function: infantMortality = runYear(food, agriculture, fertilityx, fertilityy, infantMortality) That way, we can make a change to the infantMortality rate every year, and it’ll be returned from the runYear function so it can be used for the next year! We’ll then add these two lines to the runYear function: infantMortality *= 0.985return infantMortality This is also really simple. We’re decreasing the infantMortality by 1.5% every year, and returning it so the updated mortality rate can be put into the function for the subsequent year. Run the program and we get these results from the data in Excel: Last but not least, we’ll add in our disasterChance. I feel like the 25% initial infant mortality rate will be a bit unreasonable for this simulation, so I’m setting it to 5%, and then we’re ready to add in disasterChance, right above where we print out the population: if random.randint(0,100)<disasterChance: del peopleDictionary[0:int(random.uniform(0.05,0.2)*len(peopleDictionary))] This is a rather long clause, but I’ll try to explain it. If the random number between 0 and 100 falls within the disasterChance range (for us, that is 10%), then a disaster is initiated. We generate a random number to figure out how much damage we’ll do. It’ll fall between 5% and 20%. We’ll multiply this by the length of the people dictionary to get a 5–20% slice of the population. We’ll then cut that slice out (effectively killing 5–20% of our population). Once again, you’ll want to update the line where we call the runYears function so it sends the disasterChance to the function. Those are all the remaining changes and updates you must make to finish the simple population simulator! Let’s run it: It’s complete! You can see that about every ten years, there is some kind of significant disaster that kills 5–20% of the population. These disasters are barely noticeable for the first seven hundred years, but they get very exaggerated thereafter. import randomstartPopulation = 50infantMortality = 5youthMortality = 45agriculture = 5disasterChance = 10fertilityx = 18fertilityy = 35food = 0peopleDictionary = []class Person: def __init__(self, age): self.gender = random.randint(0,1) self.age = age self.pregnant = 0def harvest(food, agriculture): ablePeople = 0 for person in peopleDictionary: if person.age > 8: ablePeople +=1food += ablePeople * agricultureif food < len(peopleDictionary): del peopleDictionary[0:int(len(peopleDictionary)-food)] food = 0 else: food -= len(peopleDictionary)def reproduce(fertilityx, fertilityy, infantMortality): for person in peopleDictionary: if person.gender == 1: if person.age > fertilityx: if person.age < fertilityy: if random.randint(0,5)==1: if random.randint(0,100)>infantMortality: peopleDictionary.append(Person(0))def beginSim(): for x in range(startPopulation): peopleDictionary.append(Person(random.randint(18,50)))def runYear(food, agriculture, fertilityx, fertilityy, infantMortality, disasterChance): harvest(food, agriculture) for person in peopleDictionary: if person.age > 80: peopleDictionary.remove(person) else: person.age +=1 reproduce(fertilityx, fertilityy, infantMortality)if random.randint(0,100)<disasterChance: del peopleDictionary[0:int(random.uniform(0.05,0.2)*len(peopleDictionary))] print(len(peopleDictionary)) infantMortality *= 0.985 return infantMortalitybeginSim()while len(peopleDictionary)<100000 and len(peopleDictionary) > 1: infantMortality = runYear(food, agriculture, fertilityx, fertilityy, infantMortality, disasterChance) While this is a simple and incomplete model, you now know how to build a simulation! To take this to the next level, you can update and advance this program to include way more factors like health conditions, social class, urbanization, healthcare, various kinds of disasters, geolocation, etc. Overall, I hope this inspires you to build your own simulations for the pandemic, population growth, or whatever else you can think of! Not sure what to read next? I’ve picked another article for you: towardsdatascience.com If you enjoyed this, follow me on Medium for more Sign up for my email list here! Let’s connect on LinkedIn Interested in collaborating? Check out my website. Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. See our Reader Terms for details. To learn about the coronavirus pandemic, you can click here.
[ { "code": null, "e": 322, "s": 172, "text": "Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 435, "s": 322, "text": "IntroductionThe Most Basic SimulationAdding More Variables to the SimulationAdding EVEN MORE complexityFull Code" }, { "code": null, "e": 448, "s": 435, "text": "Introduction" }, { "code": null, "e": 474, "s": 448, "text": "The Most Basic Simulation" }, { "code": null, "e": 514, "s": 474, "text": "Adding More Variables to the Simulation" }, { "code": null, "e": 542, "s": 514, "text": "Adding EVEN MORE complexity" }, { "code": null, "e": 552, "s": 542, "text": "Full Code" }, { "code": null, "e": 915, "s": 552, "text": "Computer-generated simulations are one of the fastest-growing technologies today, and it’s never been more important with COVID-19 around. You might have wondered how governments and agencies make decisions when it comes to enforcing lockdowns, closing schools, banning indoor dining, etc... These decisions aren’t blindly made. They’re made through simulations." }, { "code": null, "e": 1127, "s": 915, "text": "A simulation is simply an imitation of a situation or a process. In the case of this pandemic, governments use simulations to see how different factors, like the ones listed above, impact the spread of COVID-19." }, { "code": null, "e": 1175, "s": 1127, "text": "Simulations are useful for a number of reasons:" }, { "code": null, "e": 1276, "s": 1175, "text": "They can turn into powerful visualizations that make it easier to communicate insights and findings." }, { "code": null, "e": 1364, "s": 1276, "text": "They can be used for predictions and forecasting, but we’ll talk more about this later." }, { "code": null, "e": 1522, "s": 1364, "text": "They can help you understand the most important factors in a simulation. (Eg. How does a 1% change in factor A affect the output vs a 1% change in factor B?)" }, { "code": null, "e": 1710, "s": 1522, "text": "A big misconception about simulations is that they’re really complicated, and that’s not necessarily the case! Simulations can end up being very complex, but they can also be very simple." }, { "code": null, "e": 1841, "s": 1710, "text": "In this article, you’ll learn how to build a very simple simulation/model of population growth, as well as how it can be improved." }, { "code": null, "e": 1926, "s": 1841, "text": "Note: In this article, the terms “model” and “simulation” will be used synonymously." }, { "code": null, "e": 2076, "s": 1926, "text": "Be sure to subscribe here or to my personal newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 2271, "s": 2076, "text": "The most basic human population simulator that we could possibly create would be something like this, where the initial population is 50 and we want to see how the population grows to 1,000,000:" }, { "code": null, "e": 2570, "s": 2271, "text": "totalPopulation = 50 growthFactor = 1.00005dayCount = 0 #Every 2 months the population is reportedwhile totalPopulation < 1000000: totalPopulation *= growthFactor #Every 56th day, population is reported dayCount += 1 if dayCount == 56: dayCount = 0 print(totalPopulation)" }, { "code": null, "e": 2908, "s": 2570, "text": "If you can tell, this program is simply an exponential function and is too basic of a model to be able to simulate population growth. As you might have already thought, the total number of people in an environment won’t increase by a set percentage every cycle, and there are many factors that affect the population that aren’t included." }, { "code": null, "e": 3038, "s": 2908, "text": "This is okay! This is how a simulation starts. It starts off simple and gets more advanced. Let’s see how we can improve on this." }, { "code": null, "e": 3212, "s": 3038, "text": "If we want to run a more realistic simulation of the human population, we’ll need to establish some factors and use them to control when people are born, reproduce, and die." }, { "code": null, "e": 3488, "s": 3212, "text": "So, let’s set up a more complicated simulation. Although there are millions of variables that can change population, we’ll stick with just a few major ones. Once these are set up, we can program them to fluctuate, and they can be tinkered with to imitate different scenarios." }, { "code": null, "e": 3527, "s": 3488, "text": "I’ve chosen eight very simple factors:" }, { "code": null, "e": 3644, "s": 3527, "text": "Starting populationInfant mortalityFoodFertility x & Fertility yHealthcareAgricultureChance of disasterAge of death." }, { "code": null, "e": 3664, "s": 3644, "text": "Starting population" }, { "code": null, "e": 3681, "s": 3664, "text": "Infant mortality" }, { "code": null, "e": 3686, "s": 3681, "text": "Food" }, { "code": null, "e": 3712, "s": 3686, "text": "Fertility x & Fertility y" }, { "code": null, "e": 3723, "s": 3712, "text": "Healthcare" }, { "code": null, "e": 3735, "s": 3723, "text": "Agriculture" }, { "code": null, "e": 3754, "s": 3735, "text": "Chance of disaster" }, { "code": null, "e": 3768, "s": 3754, "text": "Age of death." }, { "code": null, "e": 3925, "s": 3768, "text": "I’ll explain how each of these works as I go. Let’s create a new Python script in the IDLE. We’ll use the random function quite a lot, so import that first:" }, { "code": null, "e": 3939, "s": 3925, "text": "import random" }, { "code": null, "e": 4059, "s": 3939, "text": "Now we assign a value to the variable startingPopulation. This can be virtually whatever you want, but I’m using fifty." }, { "code": null, "e": 4083, "s": 4059, "text": "startingPopulation = 50" }, { "code": null, "e": 4258, "s": 4083, "text": "Realistically it would be impossible to grow a population significantly from just fifty people, and inbreeding would cause endless genetic diseases, but let’s keep it simple." }, { "code": null, "e": 4526, "s": 4258, "text": "Our next variable is infantMortality. This is the chance of a child dying in their first year of life. Our World in Data estimates an average infant mortality rate of ~25% over the past two millennia. I’ll use that because it can give us a good historical simulation." }, { "code": null, "e": 4547, "s": 4526, "text": "infantMortality = 25" }, { "code": null, "e": 5065, "s": 4547, "text": "The variable, agriculture, will be how many “units” of food each person produces. One unit of food feeds a person for a single year. In our simulation, each person must eat one unit of food every year or they will die. Therefore, if agriculture is exactly 1 in a given year, everyone eats. If it is 0.5, fifty percent of the population dies. If it is 1.5, there is a fifty percent excess of food, and this can be stored and used as a backup if the agriculture in the next year is not enough to support the population." }, { "code": null, "e": 5302, "s": 5065, "text": "Explained simply, if the agriculture value is not above 1, the population cannot grow, because the population would starve. To start, I’ll use a value of 5, meaning each person produces enough food for themselves, plus four more people:" }, { "code": null, "e": 5318, "s": 5302, "text": "agriculture = 5" }, { "code": null, "e": 5631, "s": 5318, "text": "Then we have disasterChance. This is the probability every year that some natural disaster comes along and damages the population. It will affect the population by a random percentage, from 5–10%. To start with, I’ll leave the disasterChance at 10%, meaning on average every ten years a disaster will come along." }, { "code": null, "e": 5651, "s": 5631, "text": "disasterChance = 10" }, { "code": null, "e": 5922, "s": 5651, "text": "food is pretty self-explanatory. Every year we will run a “harvest” function and the output of that harvest will be the population multiplied by agriculture. Even if your agriculture is below 1, if you have stocks of food, you can theoretically maintain your population." }, { "code": null, "e": 5931, "s": 5922, "text": "food = 0" }, { "code": null, "e": 6104, "s": 5931, "text": "Finally, we have fertilityx and fertilityy. These are the ages at which a women can become pregnant in our simulation. For my program, I’m using the range of ages 18 to 35." }, { "code": null, "e": 6135, "s": 6104, "text": "fertilityx = 18fertilityy = 35" }, { "code": null, "e": 6403, "s": 6135, "text": "Now, we need a way for these factors to control our population on a year by year basis. We could do this a mathematical way and use all sorts of percentages, but I think it’d be more intuitive and versatile if we used object-based programming to simulate each person." }, { "code": null, "e": 6663, "s": 6403, "text": "Each person will be an object with a few factors, and every cycle (that is, one year of our simulation) that person will be affected in some way — at the least, their age will increase by 1. We need something to store all these people, so let’s create a list:" }, { "code": null, "e": 6685, "s": 6663, "text": "peopleDictionary = []" }, { "code": null, "e": 6992, "s": 6685, "text": "That’s where each object will be stored and we can use a for loop to cycle through each person year by year and alter them. If you are not familiar with Python classes and objects, I would probably read up on them. But if you’re already up to scratch, let’s define a class which we can use for every human:" }, { "code": null, "e": 7097, "s": 6992, "text": "class Person: def __init__(self, age): self.gender = random.randint(0,1) self.age = age" }, { "code": null, "e": 7456, "s": 7097, "text": "This is the way we’ll “spawn” a person. As you can see, each person has a gender and age. You may notice that when we “spawn” a person, their age is not set to 0. The reason for this is because when we initiate the simulation, we’ll use this class to create a group of people with random ages, so we don’t want to immediately set every person to 0 years old." }, { "code": null, "e": 7724, "s": 7456, "text": "There are several functions we need to include in this program. For now, we want the program to simulate a population that exponentially increases over time — just like our very simple demo program from the start of this article. Therefore, the following must happen:" }, { "code": null, "e": 7977, "s": 7724, "text": "All “able” people, that is, anyone over 8 years old, works in the fields to produce food. This includes both men and women for simplicity.A certain number of women in the fertility band give birth to babies every year.Anyone over eighty years old dies." }, { "code": null, "e": 8116, "s": 7977, "text": "All “able” people, that is, anyone over 8 years old, works in the fields to produce food. This includes both men and women for simplicity." }, { "code": null, "e": 8197, "s": 8116, "text": "A certain number of women in the fertility band give birth to babies every year." }, { "code": null, "e": 8232, "s": 8197, "text": "Anyone over eighty years old dies." }, { "code": null, "e": 8482, "s": 8232, "text": "With this model, the population should increase exponentially, because enough infants are born every year to outweigh the number of people dying from old age, and as these infants reach 8+ years of age, they produce food to support the civilization." }, { "code": null, "e": 8517, "s": 8482, "text": "Let’s create the harvest function:" }, { "code": null, "e": 8851, "s": 8517, "text": "def harvest(food, agriculture): ablePeople = 0 for person in peopleDictionary: if person.age > 8: ablePeople +=1 food += ablePeople * agriculture if food < len(peopleDictionary): del peopleDictionary[0:int(len(peopleDictionary)-food)] food = 0 else: food -= len(peopleDictionary)" }, { "code": null, "e": 9165, "s": 8851, "text": "Every year of the simulation there is a “harvest”. The function takes the food and agriculture values. It calculates how many “able” people there are to produce food by counting those over 8 years of age. Of course, we multiply the number of able people by agriculture to get the total food produced for the year." }, { "code": null, "e": 9578, "s": 9165, "text": "If the food is not enough for each person to eat 1 unit of food, then the dictionary of people is limited to the amount of food available, and the excess die from starvation. This ensures that if there is not enough food to go around, people who cannot eat die, and the population is effectively limited. But if there is excess food, each person consumes 1 unit, and whatever is left is stored for the next year!" }, { "code": null, "e": 9632, "s": 9578, "text": "To grow our population, we need a reproduce function:" }, { "code": null, "e": 9922, "s": 9632, "text": "def reproduce(fertilityx, fertilityy): for person in peopleDictionary: if person.gender == 1: if person.age > fertilityx: if person.age < fertilityy: if random.randint(0,5)==1: peopleDictionary.append(Person(0))" }, { "code": null, "e": 10338, "s": 9922, "text": "Here I have assumed that 1 in 5 women will become pregnant every year. Of course that figure isn’t exactly accurate to real life, but it’ll work fine for our simulation! The reproduce function cycles through every person in the dictionary of people. If any person is female and between the ages of 18 and 35, they have a 20% chance of giving birth, and a new person of age 0 is appended to the dictionary of people." }, { "code": null, "e": 10683, "s": 10338, "text": "Fantastic, we have our very basic functions laid out. Although this could be done more simply using maths, setting our code out as an object-based script allows for more flexibility; if you wanted to expand the program and make it more realistic, you could add various characteristics to each person, such as medical conditions or social class." }, { "code": null, "e": 10840, "s": 10683, "text": "We need a way to initiate our simulation. To get the ball rolling, we spawn fifty people, with random ages between 18 and 50. This is our beginSim function:" }, { "code": null, "e": 10954, "s": 10840, "text": "def beginSim(): for x in range(startPopulation): peopleDictionary.append(Person(random.randint(18,50)))" }, { "code": null, "e": 11114, "s": 10954, "text": "As you can see, we add fifty people to our people dictionary, each of which has a random age. We can call this function at the bottom of our script, like this:" }, { "code": null, "e": 11125, "s": 11114, "text": "beginSim()" }, { "code": null, "e": 11307, "s": 11125, "text": "After starting the program and creating these people, we need a system to cycle through each year, and perform the harvest and reproduce functions. We’ll call this function runYear:" }, { "code": null, "e": 11610, "s": 11307, "text": "def runYear(food, agriculture, fertilityx, fertilityy): harvest(food, agriculture) reproduce(fertilityx, fertilityy) for person in peopleDictionary: if person.age > 80: peopleDictionary.remove(person) else: person.age +=1 print(len(peopleDictionary))" }, { "code": null, "e": 11945, "s": 11610, "text": "Let’s see what is going on here. The runYear function takes agriculture, food, fertilityx and fertilityy. It runs the harvest function to find out if the food will leave some people to starve to death, or if there is enough to be stored. We then perform the reproduce function, so that 20% of women between 18–35 give birth to a baby." }, { "code": null, "e": 12171, "s": 11945, "text": "Next, we cycle through the people dictionary and remove anyone who is over 80. The rest of the population increases by 1 year of age. If you wanted to improve the simulator, you could make it more random which age you die at." }, { "code": null, "e": 12335, "s": 12171, "text": "Finally, we print out the total population. To keep the runYear function going, we’ll include this line just below where we initiated the program through beginSim:" }, { "code": null, "e": 12455, "s": 12335, "text": "while len(peopleDictionary)<100000 and len(peopleDictionary) > 1: runYear(food, agriculture, fertilityx, fertilityy)" }, { "code": null, "e": 12538, "s": 12455, "text": "This just ensures that the program stops when the population reaches 0 or 100,000." }, { "code": null, "e": 12666, "s": 12538, "text": "Congratulations! We have population growth, the basis for our simulator. If you import this data into Excel, we get this graph:" }, { "code": null, "e": 12844, "s": 12666, "text": "This looks just like our graph from the simple first program of the article. It makes sense based on the current code, but it’s not very interesting. Let’s spice it up a little." }, { "code": null, "e": 12945, "s": 12844, "text": "Remember those variables, infantMortality and disasterChance we talked about? Let’s factor those in." }, { "code": null, "e": 13097, "s": 12945, "text": "20% of women give birth every year, according to our simulation, but 25% of those infants die. So let’s update our reproduce function and include this:" }, { "code": null, "e": 13215, "s": 13097, "text": "if random.randint(0,5)==1: if random.randint(0,100)>infantMortality: peopleDictionary.append(Person(0))" }, { "code": null, "e": 13421, "s": 13215, "text": "Note: You’ll also want to update the runYear function, and also the line where we call it, so it can accept the infantMortality variable. Otherwise, you will get the error “infantMortality is not defined”." }, { "code": null, "e": 13827, "s": 13421, "text": "As you can see, instead of giving each woman a 1 in 5 chance of giving birth, even if she does give birth, there is a 25% chance of the baby dying. You can see from our random clause that any random numbers generated between 0–100 that are below 25% = baby dies, any above = baby lives. If infantMortality is high, then very few of the infants will survive. Ideally, you want to get it down from 1% to 2%." }, { "code": null, "e": 13933, "s": 13827, "text": "When we run the simulation with a 25% infant mortality rate, the results are quite gloomy and inaccurate:" }, { "code": null, "e": 14099, "s": 13933, "text": "Instead, let’s allow infant mortality rates to decrease over time, as healthcare gets better. You’d think after a hundred years they would make some advances, right?" }, { "code": null, "e": 14207, "s": 14099, "text": "To keep the infantMortality variable updated, we’ll make this change to where we call the runYear function:" }, { "code": null, "e": 14293, "s": 14207, "text": "infantMortality = runYear(food, agriculture, fertilityx, fertilityy, infantMortality)" }, { "code": null, "e": 14449, "s": 14293, "text": "That way, we can make a change to the infantMortality rate every year, and it’ll be returned from the runYear function so it can be used for the next year!" }, { "code": null, "e": 14505, "s": 14449, "text": "We’ll then add these two lines to the runYear function:" }, { "code": null, "e": 14552, "s": 14505, "text": "infantMortality *= 0.985return infantMortality" }, { "code": null, "e": 14738, "s": 14552, "text": "This is also really simple. We’re decreasing the infantMortality by 1.5% every year, and returning it so the updated mortality rate can be put into the function for the subsequent year." }, { "code": null, "e": 14803, "s": 14738, "text": "Run the program and we get these results from the data in Excel:" }, { "code": null, "e": 15073, "s": 14803, "text": "Last but not least, we’ll add in our disasterChance. I feel like the 25% initial infant mortality rate will be a bit unreasonable for this simulation, so I’m setting it to 5%, and then we’re ready to add in disasterChance, right above where we print out the population:" }, { "code": null, "e": 15197, "s": 15073, "text": "if random.randint(0,100)<disasterChance: del peopleDictionary[0:int(random.uniform(0.05,0.2)*len(peopleDictionary))]" }, { "code": null, "e": 15660, "s": 15197, "text": "This is a rather long clause, but I’ll try to explain it. If the random number between 0 and 100 falls within the disasterChance range (for us, that is 10%), then a disaster is initiated. We generate a random number to figure out how much damage we’ll do. It’ll fall between 5% and 20%. We’ll multiply this by the length of the people dictionary to get a 5–20% slice of the population. We’ll then cut that slice out (effectively killing 5–20% of our population)." }, { "code": null, "e": 15892, "s": 15660, "text": "Once again, you’ll want to update the line where we call the runYears function so it sends the disasterChance to the function. Those are all the remaining changes and updates you must make to finish the simple population simulator!" }, { "code": null, "e": 15906, "s": 15892, "text": "Let’s run it:" }, { "code": null, "e": 16155, "s": 15906, "text": "It’s complete! You can see that about every ten years, there is some kind of significant disaster that kills 5–20% of the population. These disasters are barely noticeable for the first seven hundred years, but they get very exaggerated thereafter." }, { "code": null, "e": 17971, "s": 16155, "text": "import randomstartPopulation = 50infantMortality = 5youthMortality = 45agriculture = 5disasterChance = 10fertilityx = 18fertilityy = 35food = 0peopleDictionary = []class Person: def __init__(self, age): self.gender = random.randint(0,1) self.age = age self.pregnant = 0def harvest(food, agriculture): ablePeople = 0 for person in peopleDictionary: if person.age > 8: ablePeople +=1food += ablePeople * agricultureif food < len(peopleDictionary): del peopleDictionary[0:int(len(peopleDictionary)-food)] food = 0 else: food -= len(peopleDictionary)def reproduce(fertilityx, fertilityy, infantMortality): for person in peopleDictionary: if person.gender == 1: if person.age > fertilityx: if person.age < fertilityy: if random.randint(0,5)==1: if random.randint(0,100)>infantMortality: peopleDictionary.append(Person(0))def beginSim(): for x in range(startPopulation): peopleDictionary.append(Person(random.randint(18,50)))def runYear(food, agriculture, fertilityx, fertilityy, infantMortality, disasterChance): harvest(food, agriculture) for person in peopleDictionary: if person.age > 80: peopleDictionary.remove(person) else: person.age +=1 reproduce(fertilityx, fertilityy, infantMortality)if random.randint(0,100)<disasterChance: del peopleDictionary[0:int(random.uniform(0.05,0.2)*len(peopleDictionary))] print(len(peopleDictionary)) infantMortality *= 0.985 return infantMortalitybeginSim()while len(peopleDictionary)<100000 and len(peopleDictionary) > 1: infantMortality = runYear(food, agriculture, fertilityx, fertilityy, infantMortality, disasterChance)" }, { "code": null, "e": 18402, "s": 17971, "text": "While this is a simple and incomplete model, you now know how to build a simulation! To take this to the next level, you can update and advance this program to include way more factors like health conditions, social class, urbanization, healthcare, various kinds of disasters, geolocation, etc. Overall, I hope this inspires you to build your own simulations for the pandemic, population growth, or whatever else you can think of!" }, { "code": null, "e": 18467, "s": 18402, "text": "Not sure what to read next? I’ve picked another article for you:" }, { "code": null, "e": 18490, "s": 18467, "text": "towardsdatascience.com" }, { "code": null, "e": 18540, "s": 18490, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 18572, "s": 18540, "text": "Sign up for my email list here!" }, { "code": null, "e": 18598, "s": 18572, "text": "Let’s connect on LinkedIn" }, { "code": null, "e": 18649, "s": 18598, "text": "Interested in collaborating? Check out my website." } ]
AWK - Built-in Variables
AWK provides several built-in variables. They play an important role while writing AWK scripts. This chapter demonstrates the usage of built-in variables. The standard AWK variables are discussed below. It implies the number of arguments provided at the command line. Example [jerry]$ awk 'BEGIN {print "Arguments =", ARGC}' One Two Three Four On executing this code, you get the following result − Output Arguments = 5 But why AWK shows 5 when you passed only 4 arguments? Just check the following example to clear your doubt. It is an array that stores the command-line arguments. The array's valid index ranges from 0 to ARGC-1. Example [jerry]$ awk 'BEGIN { for (i = 0; i < ARGC - 1; ++i) { printf "ARGV[%d] = %s\n", i, ARGV[i] } }' one two three four On executing this code, you get the following result − Output ARGV[0] = awk ARGV[1] = one ARGV[2] = two ARGV[3] = three It represents the conversion format for numbers. Its default value is %.6g. Example [jerry]$ awk 'BEGIN { print "Conversion Format =", CONVFMT }' On executing this code, you get the following result − Output Conversion Format = %.6g It is an associative array of environment variables. Example [jerry]$ awk 'BEGIN { print ENVIRON["USER"] }' On executing this code, you get the following result − Output jerry To find names of other environment variables, use env command. It represents the current file name. Example [jerry]$ awk 'END {print FILENAME}' marks.txt On executing this code, you get the following result − Output marks.txt Please note that FILENAME is undefined in the BEGIN block. It represents the (input) field separator and its default value is space. You can also change this by using -F command line option. Example [jerry]$ awk 'BEGIN {print "FS = " FS}' | cat -vte On executing this code, you get the following result − Output FS = $ It represents the number of fields in the current record. For instance, the following example prints only those lines that contain more than two fields. Example [jerry]$ echo -e "One Two\nOne Two Three\nOne Two Three Four" | awk 'NF > 2' On executing this code, you get the following result − Output One Two Three One Two Three Four It represents the number of the current record. For instance, the following example prints the record if the current record number is less than three. Example [jerry]$ echo -e "One Two\nOne Two Three\nOne Two Three Four" | awk 'NR < 3' On executing this code, you get the following result − Output One Two One Two Three It is similar to NR, but relative to the current file. It is useful when AWK is operating on multiple files. Value of FNR resets with new file. It represents the output format number and its default value is %.6g. Example [jerry]$ awk 'BEGIN {print "OFMT = " OFMT}' On executing this code, you get the following result − Output OFMT = %.6g It represents the output field separator and its default value is space. Example [jerry]$ awk 'BEGIN {print "OFS = " OFS}' | cat -vte On executing this code, you get the following result − Output OFS = $ It represents the output record separator and its default value is newline. Example [jerry]$ awk 'BEGIN {print "ORS = " ORS}' | cat -vte On executing the above code, you get the following result − Output ORS = $ $ It represents the length of the string matched by match function. AWK's match function searches for a given string in the input-string. Example [jerry]$ awk 'BEGIN { if (match("One Two Three", "re")) { print RLENGTH } }' On executing this code, you get the following result − Output 2 It represents (input) record separator and its default value is newline. Example [jerry]$ awk 'BEGIN {print "RS = " RS}' | cat -vte On executing this code, you get the following result − Output RS = $ $ It represents the first position in the string matched by match function. Example [jerry]$ awk 'BEGIN { if (match("One Two Three", "Thre")) { print RSTART } }' On executing this code, you get the following result − Output 9 It represents the separator character for array subscripts and its default value is \034. Example [jerry]$ awk 'BEGIN { print "SUBSEP = " SUBSEP }' | cat -vte On executing this code, you get the following result − Output SUBSEP = ^\$ It represents the entire input record. Example [jerry]$ awk '{print $0}' marks.txt On executing this code, you get the following result − Output 1) Amit Physics 80 2) Rahul Maths 90 3) Shyam Biology 87 4) Kedar English 85 5) Hari History 89 It represents the nth field in the current record where the fields are separated by FS. Example [jerry]$ awk '{print $3 "\t" $4}' marks.txt On executing this code, you get the following result − Output Physics 80 Maths 90 Biology 87 English 85 History 89 GNU AWK specific variables are as follows − It represents the index in ARGV of the current file being processed. Example [jerry]$ awk '{ print "ARGIND = ", ARGIND; print "Filename = ", ARGV[ARGIND] }' junk1 junk2 junk3 On executing this code, you get the following result − Output ARGIND = 1 Filename = junk1 ARGIND = 2 Filename = junk2 ARGIND = 3 Filename = junk3 It is used to specify binary mode for all file I/O on non-POSIX systems. Numeric values of 1, 2, or 3 specify that input files, output files, or all files, respectively, should use binary I/O. String values of r or w specify that input files or output files, respectively, should use binary I/O. String values of rw or wr specify that all files should use binary I/O. A string indicates an error when a redirection fails for getline or if close call fails. Example [jerry]$ awk 'BEGIN { ret = getline < "junk.txt"; if (ret == -1) print "Error:", ERRNO }' On executing this code, you get the following result − Output Error: No such file or directory A space separated list of field widths variable is set, GAWK parses the input into fields of fixed width, instead of using the value of the FS variable as the field separator. When this variable is set, GAWK becomes case-insensitive. The following example demonstrates this − Example [jerry]$ awk 'BEGIN{IGNORECASE = 1} /amit/' marks.txt On executing this code, you get the following result − Output 1) Amit Physics 80 It provides dynamic control of the --lint option from the GAWK program. When this variable is set, GAWK prints lint warnings. When assigned the string value fatal, lint warnings become fatal errors, exactly like --lint=fatal. Example [jerry]$ awk 'BEGIN {LINT = 1; a}' On executing this code, you get the following result − Output awk: cmd. line:1: warning: reference to uninitialized variable `a' awk: cmd. line:1: warning: statement has no effect This is an associative array containing information about the process, such as real and effective UID numbers, process ID number, and so on. Example [jerry]$ awk 'BEGIN { print PROCINFO["pid"] }' On executing this code, you get the following result − Output 4316 It represents the text domain of the AWK program. It is used to find the localized translations for the program's strings. Example [jerry]$ awk 'BEGIN { print TEXTDOMAIN }' On executing this code, you get the following result − Output messages The above output shows English text due to en_IN locale Print Add Notes Bookmark this page
[ { "code": null, "e": 2012, "s": 1857, "text": "AWK provides several built-in variables. They play an important role while writing AWK scripts. This chapter demonstrates the usage of built-in variables." }, { "code": null, "e": 2060, "s": 2012, "text": "The standard AWK variables are discussed below." }, { "code": null, "e": 2125, "s": 2060, "text": "It implies the number of arguments provided at the command line." }, { "code": null, "e": 2133, "s": 2125, "text": "Example" }, { "code": null, "e": 2201, "s": 2133, "text": "[jerry]$ awk 'BEGIN {print \"Arguments =\", ARGC}' One Two Three Four" }, { "code": null, "e": 2256, "s": 2201, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2263, "s": 2256, "text": "Output" }, { "code": null, "e": 2278, "s": 2263, "text": "Arguments = 5\n" }, { "code": null, "e": 2386, "s": 2278, "text": "But why AWK shows 5 when you passed only 4 arguments? Just check the following example to clear your doubt." }, { "code": null, "e": 2490, "s": 2386, "text": "It is an array that stores the command-line arguments. The array's valid index ranges from 0 to ARGC-1." }, { "code": null, "e": 2498, "s": 2490, "text": "Example" }, { "code": null, "e": 2630, "s": 2498, "text": "[jerry]$ awk 'BEGIN { \n for (i = 0; i < ARGC - 1; ++i) { \n printf \"ARGV[%d] = %s\\n\", i, ARGV[i] \n } \n}' one two three four" }, { "code": null, "e": 2685, "s": 2630, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2692, "s": 2685, "text": "Output" }, { "code": null, "e": 2751, "s": 2692, "text": "ARGV[0] = awk\nARGV[1] = one\nARGV[2] = two\nARGV[3] = three\n" }, { "code": null, "e": 2827, "s": 2751, "text": "It represents the conversion format for numbers. Its default value is %.6g." }, { "code": null, "e": 2835, "s": 2827, "text": "Example" }, { "code": null, "e": 2897, "s": 2835, "text": "[jerry]$ awk 'BEGIN { print \"Conversion Format =\", CONVFMT }'" }, { "code": null, "e": 2952, "s": 2897, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2959, "s": 2952, "text": "Output" }, { "code": null, "e": 2985, "s": 2959, "text": "Conversion Format = %.6g\n" }, { "code": null, "e": 3038, "s": 2985, "text": "It is an associative array of environment variables." }, { "code": null, "e": 3046, "s": 3038, "text": "Example" }, { "code": null, "e": 3093, "s": 3046, "text": "[jerry]$ awk 'BEGIN { print ENVIRON[\"USER\"] }'" }, { "code": null, "e": 3148, "s": 3093, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3155, "s": 3148, "text": "Output" }, { "code": null, "e": 3162, "s": 3155, "text": "jerry\n" }, { "code": null, "e": 3225, "s": 3162, "text": "To find names of other environment variables, use env command." }, { "code": null, "e": 3262, "s": 3225, "text": "It represents the current file name." }, { "code": null, "e": 3270, "s": 3262, "text": "Example" }, { "code": null, "e": 3316, "s": 3270, "text": "[jerry]$ awk 'END {print FILENAME}' marks.txt" }, { "code": null, "e": 3371, "s": 3316, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3378, "s": 3371, "text": "Output" }, { "code": null, "e": 3389, "s": 3378, "text": "marks.txt\n" }, { "code": null, "e": 3448, "s": 3389, "text": "Please note that FILENAME is undefined in the BEGIN block." }, { "code": null, "e": 3580, "s": 3448, "text": "It represents the (input) field separator and its default value is space. You can also change this by using -F command line option." }, { "code": null, "e": 3588, "s": 3580, "text": "Example" }, { "code": null, "e": 3639, "s": 3588, "text": "[jerry]$ awk 'BEGIN {print \"FS = \" FS}' | cat -vte" }, { "code": null, "e": 3694, "s": 3639, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3701, "s": 3694, "text": "Output" }, { "code": null, "e": 3710, "s": 3701, "text": "FS = $\n" }, { "code": null, "e": 3863, "s": 3710, "text": "It represents the number of fields in the current record. For instance, the following example prints only those lines that contain more than two fields." }, { "code": null, "e": 3871, "s": 3863, "text": "Example" }, { "code": null, "e": 3948, "s": 3871, "text": "[jerry]$ echo -e \"One Two\\nOne Two Three\\nOne Two Three Four\" | awk 'NF > 2'" }, { "code": null, "e": 4003, "s": 3948, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 4010, "s": 4003, "text": "Output" }, { "code": null, "e": 4044, "s": 4010, "text": "One Two Three\nOne Two Three Four\n" }, { "code": null, "e": 4195, "s": 4044, "text": "It represents the number of the current record. For instance, the following example prints the record if the current record number is less than three." }, { "code": null, "e": 4203, "s": 4195, "text": "Example" }, { "code": null, "e": 4280, "s": 4203, "text": "[jerry]$ echo -e \"One Two\\nOne Two Three\\nOne Two Three Four\" | awk 'NR < 3'" }, { "code": null, "e": 4335, "s": 4280, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 4342, "s": 4335, "text": "Output" }, { "code": null, "e": 4365, "s": 4342, "text": "One Two\nOne Two Three\n" }, { "code": null, "e": 4509, "s": 4365, "text": "It is similar to NR, but relative to the current file. It is useful when AWK is operating on multiple files. Value of FNR resets with new file." }, { "code": null, "e": 4579, "s": 4509, "text": "It represents the output format number and its default value is %.6g." }, { "code": null, "e": 4587, "s": 4579, "text": "Example" }, { "code": null, "e": 4631, "s": 4587, "text": "[jerry]$ awk 'BEGIN {print \"OFMT = \" OFMT}'" }, { "code": null, "e": 4686, "s": 4631, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 4693, "s": 4686, "text": "Output" }, { "code": null, "e": 4706, "s": 4693, "text": "OFMT = %.6g\n" }, { "code": null, "e": 4779, "s": 4706, "text": "It represents the output field separator and its default value is space." }, { "code": null, "e": 4787, "s": 4779, "text": "Example" }, { "code": null, "e": 4840, "s": 4787, "text": "[jerry]$ awk 'BEGIN {print \"OFS = \" OFS}' | cat -vte" }, { "code": null, "e": 4895, "s": 4840, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 4902, "s": 4895, "text": "Output" }, { "code": null, "e": 4912, "s": 4902, "text": "OFS = $\n" }, { "code": null, "e": 4988, "s": 4912, "text": "It represents the output record separator and its default value is newline." }, { "code": null, "e": 4996, "s": 4988, "text": "Example" }, { "code": null, "e": 5049, "s": 4996, "text": "[jerry]$ awk 'BEGIN {print \"ORS = \" ORS}' | cat -vte" }, { "code": null, "e": 5109, "s": 5049, "text": "On executing the above code, you get the following result −" }, { "code": null, "e": 5116, "s": 5109, "text": "Output" }, { "code": null, "e": 5127, "s": 5116, "text": "ORS = $\n$\n" }, { "code": null, "e": 5263, "s": 5127, "text": "It represents the length of the string matched by match function. AWK's match function searches for a given string in the input-string." }, { "code": null, "e": 5271, "s": 5263, "text": "Example" }, { "code": null, "e": 5348, "s": 5271, "text": "[jerry]$ awk 'BEGIN { if (match(\"One Two Three\", \"re\")) { print RLENGTH } }'" }, { "code": null, "e": 5403, "s": 5348, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 5410, "s": 5403, "text": "Output" }, { "code": null, "e": 5413, "s": 5410, "text": "2\n" }, { "code": null, "e": 5486, "s": 5413, "text": "It represents (input) record separator and its default value is newline." }, { "code": null, "e": 5494, "s": 5486, "text": "Example" }, { "code": null, "e": 5545, "s": 5494, "text": "[jerry]$ awk 'BEGIN {print \"RS = \" RS}' | cat -vte" }, { "code": null, "e": 5600, "s": 5545, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 5607, "s": 5600, "text": "Output" }, { "code": null, "e": 5617, "s": 5607, "text": "RS = $\n$\n" }, { "code": null, "e": 5691, "s": 5617, "text": "It represents the first position in the string matched by match function." }, { "code": null, "e": 5699, "s": 5691, "text": "Example" }, { "code": null, "e": 5777, "s": 5699, "text": "[jerry]$ awk 'BEGIN { if (match(\"One Two Three\", \"Thre\")) { print RSTART } }'" }, { "code": null, "e": 5832, "s": 5777, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 5839, "s": 5832, "text": "Output" }, { "code": null, "e": 5842, "s": 5839, "text": "9\n" }, { "code": null, "e": 5932, "s": 5842, "text": "It represents the separator character for array subscripts and its default value is \\034." }, { "code": null, "e": 5940, "s": 5932, "text": "Example" }, { "code": null, "e": 6001, "s": 5940, "text": "[jerry]$ awk 'BEGIN { print \"SUBSEP = \" SUBSEP }' | cat -vte" }, { "code": null, "e": 6056, "s": 6001, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 6063, "s": 6056, "text": "Output" }, { "code": null, "e": 6077, "s": 6063, "text": "SUBSEP = ^\\$\n" }, { "code": null, "e": 6116, "s": 6077, "text": "It represents the entire input record." }, { "code": null, "e": 6124, "s": 6116, "text": "Example" }, { "code": null, "e": 6160, "s": 6124, "text": "[jerry]$ awk '{print $0}' marks.txt" }, { "code": null, "e": 6215, "s": 6160, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 6222, "s": 6215, "text": "Output" }, { "code": null, "e": 6348, "s": 6222, "text": "1) Amit Physics 80\n2) Rahul Maths 90\n3) Shyam Biology 87\n4) Kedar English 85\n5) Hari History 89\n" }, { "code": null, "e": 6436, "s": 6348, "text": "It represents the nth field in the current record where the fields are separated by FS." }, { "code": null, "e": 6444, "s": 6436, "text": "Example" }, { "code": null, "e": 6488, "s": 6444, "text": "[jerry]$ awk '{print $3 \"\\t\" $4}' marks.txt" }, { "code": null, "e": 6543, "s": 6488, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 6550, "s": 6543, "text": "Output" }, { "code": null, "e": 6616, "s": 6550, "text": "Physics 80\nMaths 90\nBiology 87\nEnglish 85\nHistory 89\n" }, { "code": null, "e": 6660, "s": 6616, "text": "GNU AWK specific variables are as follows −" }, { "code": null, "e": 6729, "s": 6660, "text": "It represents the index in ARGV of the current file being processed." }, { "code": null, "e": 6737, "s": 6729, "text": "Example" }, { "code": null, "e": 6842, "s": 6737, "text": "[jerry]$ awk '{ \n print \"ARGIND = \", ARGIND; print \"Filename = \", ARGV[ARGIND] \n}' junk1 junk2 junk3" }, { "code": null, "e": 6897, "s": 6842, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 6904, "s": 6897, "text": "Output" }, { "code": null, "e": 7001, "s": 6904, "text": "ARGIND = 1\nFilename = junk1\nARGIND = 2\nFilename = junk2\nARGIND = 3\nFilename = junk3\n" }, { "code": null, "e": 7369, "s": 7001, "text": "It is used to specify binary mode for all file I/O on non-POSIX systems. Numeric values of 1, 2, or 3 specify that input files, output files, or all files, respectively, should use binary I/O. String values of r or w specify that input files or output files, respectively, should use binary I/O. String values of rw or wr specify that all files should use binary I/O." }, { "code": null, "e": 7458, "s": 7369, "text": "A string indicates an error when a redirection fails for getline or if close call fails." }, { "code": null, "e": 7466, "s": 7458, "text": "Example" }, { "code": null, "e": 7556, "s": 7466, "text": "[jerry]$ awk 'BEGIN { ret = getline < \"junk.txt\"; if (ret == -1) print \"Error:\", ERRNO }'" }, { "code": null, "e": 7611, "s": 7556, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 7618, "s": 7611, "text": "Output" }, { "code": null, "e": 7652, "s": 7618, "text": "Error: No such file or directory\n" }, { "code": null, "e": 7828, "s": 7652, "text": "A space separated list of field widths variable is set, GAWK parses the input into fields of fixed width, instead of using the value of the FS variable as the field separator." }, { "code": null, "e": 7928, "s": 7828, "text": "When this variable is set, GAWK becomes case-insensitive. The following example demonstrates this −" }, { "code": null, "e": 7936, "s": 7928, "text": "Example" }, { "code": null, "e": 7990, "s": 7936, "text": "[jerry]$ awk 'BEGIN{IGNORECASE = 1} /amit/' marks.txt" }, { "code": null, "e": 8045, "s": 7990, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 8052, "s": 8045, "text": "Output" }, { "code": null, "e": 8075, "s": 8052, "text": "1) Amit Physics 80\n" }, { "code": null, "e": 8301, "s": 8075, "text": "It provides dynamic control of the --lint option from the GAWK program. When this variable is set, GAWK prints lint warnings. When assigned the string value fatal, lint warnings become fatal errors, exactly like --lint=fatal." }, { "code": null, "e": 8309, "s": 8301, "text": "Example" }, { "code": null, "e": 8344, "s": 8309, "text": "[jerry]$ awk 'BEGIN {LINT = 1; a}'" }, { "code": null, "e": 8399, "s": 8344, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 8406, "s": 8399, "text": "Output" }, { "code": null, "e": 8525, "s": 8406, "text": "awk: cmd. line:1: warning: reference to uninitialized variable `a'\nawk: cmd. line:1: warning: statement has no effect\n" }, { "code": null, "e": 8666, "s": 8525, "text": "This is an associative array containing information about the process, such as real and effective UID numbers, process ID number, and so on." }, { "code": null, "e": 8674, "s": 8666, "text": "Example" }, { "code": null, "e": 8721, "s": 8674, "text": "[jerry]$ awk 'BEGIN { print PROCINFO[\"pid\"] }'" }, { "code": null, "e": 8776, "s": 8721, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 8783, "s": 8776, "text": "Output" }, { "code": null, "e": 8789, "s": 8783, "text": "4316\n" }, { "code": null, "e": 8912, "s": 8789, "text": "It represents the text domain of the AWK program. It is used to find the localized translations for the program's strings." }, { "code": null, "e": 8920, "s": 8912, "text": "Example" }, { "code": null, "e": 8962, "s": 8920, "text": "[jerry]$ awk 'BEGIN { print TEXTDOMAIN }'" }, { "code": null, "e": 9017, "s": 8962, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 9024, "s": 9017, "text": "Output" }, { "code": null, "e": 9034, "s": 9024, "text": "messages\n" }, { "code": null, "e": 9090, "s": 9034, "text": "The above output shows English text due to en_IN locale" }, { "code": null, "e": 9097, "s": 9090, "text": " Print" }, { "code": null, "e": 9108, "s": 9097, "text": " Add Notes" } ]
AWT Font Class
The Font class states fonts, which are used to render text in a visible way. Following is the declaration for java.awt.Font class: public class Font extends Object implements Serializable Following are the fields for java.awt.geom.Arc2D class: static int BOLD -- The bold style constant. static int BOLD -- The bold style constant. static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese, Japanese, and Korean when laying out text. static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese, Japanese, and Korean when laying out text. static String DIALOG --A String constant for the canonical family name of the logical font "Dialog". static String DIALOG --A String constant for the canonical family name of the logical font "Dialog". static String DIALOG_INPUT --A String constant for the canonical family name of the logical font "DialogInput". static String DIALOG_INPUT --A String constant for the canonical family name of the logical font "DialogInput". static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts when laying out text. static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts when laying out text. static int ITALIC -- The italicized style constant. static int ITALIC -- The italicized style constant. static int LAYOUT_LEFT_TO_RIGHT -- A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis. static int LAYOUT_LEFT_TO_RIGHT -- A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis. static int LAYOUT_NO_LIMIT_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined. static int LAYOUT_NO_LIMIT_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined. static int LAYOUT_NO_START_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined. static int LAYOUT_NO_START_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined. static int LAYOUT_RIGHT_TO_LEFT -- A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis. static int LAYOUT_RIGHT_TO_LEFT -- A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis. static String MONOSPACED -- A String constant for the canonical family name of the logical font "Monospaced". static String MONOSPACED -- A String constant for the canonical family name of the logical font "Monospaced". protected String name -- The logical name of this Font, as passed to the constructor. protected String name -- The logical name of this Font, as passed to the constructor. static int PLAIN --The plain style constant. static int PLAIN --The plain style constant. protected float pointSize -- The point size of this Font in float. protected float pointSize -- The point size of this Font in float. static int ROMAN_BASELINE --The baseline used in most Roman scripts when laying out text. static int ROMAN_BASELINE --The baseline used in most Roman scripts when laying out text. static String SANS_SERIF -- A String constant for the canonical family name of the logical font "SansSerif". static String SANS_SERIF -- A String constant for the canonical family name of the logical font "SansSerif". static String SERIF -- A String constant for the canonical family name of the logical font "Serif". static String SERIF -- A String constant for the canonical family name of the logical font "Serif". protected int size --The point size of this Font, rounded to integer. protected int size --The point size of this Font, rounded to integer. protected int style -- The style of this Font, as passed to the constructor. protected int style -- The style of this Font, as passed to the constructor. static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE. static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE. static int TYPE1_FONT -- Identify a font resource of type TYPE1. static int TYPE1_FONT -- Identify a font resource of type TYPE1. protected Font() () Creates a new Font from the specified font. Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) Creates a new Font from the specified font. Font(String name, int style, int size) Creates a new Font from the specified font. boolean canDisplay(char c) Checks if this Font has a glyph for the specified character. boolean canDisplay(int codePoint) Checks if this Font has a glyph for the specified character. int canDisplayUpTo(char[] text, int start, int limit) Indicates whether or not this Font can display the characters in the specified text starting at start and ending at limit. int canDisplayUpTo(CharacterIterator iter, int start, int limit) Indicates whether or not this Font can display the text specified by the iter starting at start and ending at limit. int canDisplayUpTo(String str) Indicates whether or not this Font can display a specified String. static Font createFont(int fontFormat, File fontFile) Returns a new Font using the specified font type and the specified font file. static Font createFont(int fontFormat, InputStream fontStream) Returns a new Font using the specified font type and input data. GlyphVector createGlyphVector(FontRenderContext frc, char[] chars) Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font. GlyphVector createGlyphVector(FontRenderContext frc, CharacterIterator ci) Creates a GlyphVector by mapping the specified characters to glyphs one-to-one based on the Unicode cmap in this Font. GlyphVector createGlyphVector(FontRenderContext frc, int[] glyphCodes) Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font. GlyphVector createGlyphVector(FontRenderContext frc, String str) Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font. static Font decode(String str) Returns the Font that the str argument describes. Font deriveFont(AffineTransform trans) Creates a new Font object by replicating the current Font object and applying a new transform to it. Font deriveFont(float size) Creates a new Font object by replicating the current Font object and applying a new size to it. Font deriveFont(int style) Creates a new Font object by replicating the current Font object and applying a new style to it. Font deriveFont(int style, AffineTransform trans) Creates a new Font object by replicating this Font object and applying a new style and transform. Font deriveFont(int style, float size) Creates a new Font object by replicating this Font object and applying a new style and size. Font deriveFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) Creates a new Font object by replicating the current Font object and applying a new set of font attributes to it. boolean equals(Object obj) Compares this Font object to the specified Object. protected void finalize() Disposes the native Font object. Map<TextAttribute,?> getAttributes() Returns a map of font attributes available in this Font. AttributedCharacterIterator.Attribute[] getAvailableAttributes() Returns the keys of all the attributes supported by this Font. byte getBaselineFor(char c) Returns the baseline appropriate for displaying this character. String getFamily() Returns the family name of this Font. String getFamily(Locale l) Returns the family name of this Font, localized for the specified locale. static Font getFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) Returns a Font appropriate to the attributes. static Font getFont(String nm) Returns a Font object fom the system properties list. static Font getFont(String nm, Font font) Gets the specified Font from the system properties list. String getFontName() Returns the font face name of this Font. String getFontName(Locale l) Returns the font face name of the Font, localized for the specified locale. float getItalicAngle() Returns the italic angle of this Font. LineMetrics getLineMetrics(char[] chars, int beginIndex, int limit, FontRenderContext frc) Returns a LineMetrics object created with the specified arguments. LineMetrics getLineMetrics(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc) Returns a LineMetrics object created with the specified arguments. LineMetrics getLineMetrics(String str, FontRenderContext frc) Returns a LineMetrics object created with the specified String and FontRenderContext. LineMetrics getLineMetrics(String str, int beginIndex, int limit, FontRenderContext frc) Returns a LineMetrics object created with the specified arguments. Rectangle2D getMaxCharBounds(FontRenderContext frc) Returns the bounds for the character with the maximum bounds as defined in the specified FontRenderContext. int getMissingGlyphCode() Returns the glyphCode which is used when this Font does not have a glyph for a specified unicode code point. String getName() Returns the logical name of this Font. int getNumGlyphs() Returns the number of glyphs in this Font. java.awt.peer.FontPeer getPeer() Deprecated. Font rendering is now platform independent. String getPSName() Returns the postscript name of this Font. int getSize() Returns the point size of this Font, rounded to an integer. float getSize2D() Returns the point size of this Font in float value. Rectangle2D getStringBounds(char[] chars, int beginIndex, int limit, FontRenderContext frc) Returns the logical bounds of the specified array of characters in the specified FontRenderContext. Rectangle2D getStringBounds(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc) Returns the logical bounds of the characters indexed in the specified CharacterIterator in the specified FontRenderContext. Rectangle2D getStringBounds(String str, FontRenderContext frc) Returns the logical bounds of the specified String in the specified FontRenderContext. Rectangle2D getStringBounds(String str, int beginIndex, int limit, FontRenderContext frc) Returns the logical bounds of the specified String in the specified FontRenderContext. int getStyle() Returns the style of this Font. AffineTransform getTransform() Returns a copy of the transform associated with this Font. int hashCode() Returns a hashcode for this Font. boolean hasLayoutAttributes() Return true if this Font contains attributes that require extra layout processing. boolean hasUniformLineMetrics() Checks whether or not this Font has uniform line metrics. boolean isBold() Indicates whether or not this Font object's style is BOLD. boolean isItalic() Indicates whether or not this Font object's style is ITALIC. boolean isPlain() Indicates whether or not this Font object's style is PLAIN. boolean isTransformed() Indicates whether or not this Font object has a transform that affects its size in addition to the Size attribute. GlyphVector layoutGlyphVector(FontRenderContext frc, char[] text, int start, int limit, int flags) Returns a new GlyphVector object, performing full layout of the text if possible. String toString() Converts this Font object to a String representation. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class AWTGraphicsDemo extends Frame { public AWTGraphicsDemo(){ super("Java AWT Examples"); prepareGUI(); } public static void main(String[] args){ AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); awtGraphicsDemo.setVisible(true); } private void prepareGUI(){ setSize(400,400); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); } @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; Font plainFont = new Font("Serif", Font.PLAIN, 24); g2.setFont(plainFont); g2.drawString("Welcome to TutorialsPoint", 50, 70); Font italicFont = new Font("Serif", Font.ITALIC, 24); g2.setFont(italicFont); g2.drawString("Welcome to TutorialsPoint", 50, 120); Font boldFont = new Font("Serif", Font.BOLD, 24); g2.setFont(boldFont); g2.drawString("Welcome to TutorialsPoint", 50, 170); Font boldItalicFont = new Font("Serif", Font.BOLD+Font.ITALIC, 24); g2.setFont(boldItalicFont); g2.drawString("Welcome to TutorialsPoint", 50, 220); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1824, "s": 1747, "text": "The Font class states fonts, which are used to render text in a visible way." }, { "code": null, "e": 1878, "s": 1824, "text": "Following is the declaration for java.awt.Font class:" }, { "code": null, "e": 1944, "s": 1878, "text": "public class Font\n extends Object\n implements Serializable" }, { "code": null, "e": 2000, "s": 1944, "text": "Following are the fields for java.awt.geom.Arc2D class:" }, { "code": null, "e": 2045, "s": 2000, "text": "static int BOLD -- The bold style constant." }, { "code": null, "e": 2090, "s": 2045, "text": "static int BOLD -- The bold style constant." }, { "code": null, "e": 2218, "s": 2090, "text": "static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese, Japanese, and Korean when laying out text." }, { "code": null, "e": 2346, "s": 2218, "text": "static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese, Japanese, and Korean when laying out text." }, { "code": null, "e": 2448, "s": 2346, "text": "static String\tDIALOG --A String constant for the canonical family name of the logical font \"Dialog\"." }, { "code": null, "e": 2550, "s": 2448, "text": "static String\tDIALOG --A String constant for the canonical family name of the logical font \"Dialog\"." }, { "code": null, "e": 2663, "s": 2550, "text": "static String\tDIALOG_INPUT --A String constant for the canonical family name of the logical font \"DialogInput\"." }, { "code": null, "e": 2776, "s": 2663, "text": "static String\tDIALOG_INPUT --A String constant for the canonical family name of the logical font \"DialogInput\"." }, { "code": null, "e": 2882, "s": 2776, "text": "static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts when laying out text." }, { "code": null, "e": 2988, "s": 2882, "text": "static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts when laying out text." }, { "code": null, "e": 3041, "s": 2988, "text": "static int ITALIC -- The italicized style constant." }, { "code": null, "e": 3094, "s": 3041, "text": "static int ITALIC -- The italicized style constant." }, { "code": null, "e": 3228, "s": 3094, "text": "static int LAYOUT_LEFT_TO_RIGHT -- A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis." }, { "code": null, "e": 3362, "s": 3228, "text": "static int LAYOUT_LEFT_TO_RIGHT -- A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis." }, { "code": null, "e": 3518, "s": 3362, "text": "static int LAYOUT_NO_LIMIT_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined." }, { "code": null, "e": 3674, "s": 3518, "text": "static int LAYOUT_NO_LIMIT_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined." }, { "code": null, "e": 3831, "s": 3674, "text": "static int LAYOUT_NO_START_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined." }, { "code": null, "e": 3988, "s": 3831, "text": "static int LAYOUT_NO_START_CONTEXT -- A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined." }, { "code": null, "e": 4122, "s": 3988, "text": "static int LAYOUT_RIGHT_TO_LEFT -- A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis." }, { "code": null, "e": 4256, "s": 4122, "text": "static int LAYOUT_RIGHT_TO_LEFT -- A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis." }, { "code": null, "e": 4367, "s": 4256, "text": "static String\tMONOSPACED -- A String constant for the canonical family name of the logical font \"Monospaced\"." }, { "code": null, "e": 4478, "s": 4367, "text": "static String\tMONOSPACED -- A String constant for the canonical family name of the logical font \"Monospaced\"." }, { "code": null, "e": 4566, "s": 4478, "text": "protected String\tname -- The logical name of this Font, as passed to the constructor." }, { "code": null, "e": 4654, "s": 4566, "text": "protected String\tname -- The logical name of this Font, as passed to the constructor." }, { "code": null, "e": 4700, "s": 4654, "text": "static int PLAIN --The plain style constant." }, { "code": null, "e": 4746, "s": 4700, "text": "static int PLAIN --The plain style constant." }, { "code": null, "e": 4815, "s": 4746, "text": "protected float\tpointSize -- The point size of this Font in float." }, { "code": null, "e": 4884, "s": 4815, "text": "protected float\tpointSize -- The point size of this Font in float." }, { "code": null, "e": 4975, "s": 4884, "text": "static int ROMAN_BASELINE --The baseline used in most Roman scripts when laying out text." }, { "code": null, "e": 5066, "s": 4975, "text": "static int ROMAN_BASELINE --The baseline used in most Roman scripts when laying out text." }, { "code": null, "e": 5177, "s": 5066, "text": "static String\tSANS_SERIF -- A String constant for the canonical family name of the logical font \"SansSerif\"." }, { "code": null, "e": 5288, "s": 5177, "text": "static String\tSANS_SERIF -- A String constant for the canonical family name of the logical font \"SansSerif\"." }, { "code": null, "e": 5389, "s": 5288, "text": "static String\tSERIF -- A String constant for the canonical family name of the logical font \"Serif\"." }, { "code": null, "e": 5490, "s": 5389, "text": "static String\tSERIF -- A String constant for the canonical family name of the logical font \"Serif\"." }, { "code": null, "e": 5562, "s": 5490, "text": "protected int size --The point size of this Font, rounded to integer." }, { "code": null, "e": 5634, "s": 5562, "text": "protected int size --The point size of this Font, rounded to integer." }, { "code": null, "e": 5713, "s": 5634, "text": "protected int style -- The style of this Font, as passed to the constructor." }, { "code": null, "e": 5792, "s": 5713, "text": "protected int style -- The style of this Font, as passed to the constructor." }, { "code": null, "e": 5864, "s": 5792, "text": "static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE." }, { "code": null, "e": 5936, "s": 5864, "text": "static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE." }, { "code": null, "e": 6003, "s": 5936, "text": "static int TYPE1_FONT -- Identify a font resource of type TYPE1." }, { "code": null, "e": 6070, "s": 6003, "text": "static int TYPE1_FONT -- Identify a font resource of type TYPE1." }, { "code": null, "e": 6091, "s": 6070, "text": "protected Font() () " }, { "code": null, "e": 6136, "s": 6091, "text": " Creates a new Font from the specified font." }, { "code": null, "e": 6208, "s": 6136, "text": "Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)" }, { "code": null, "e": 6253, "s": 6208, "text": " Creates a new Font from the specified font." }, { "code": null, "e": 6293, "s": 6253, "text": "Font(String name, int style, int size) " }, { "code": null, "e": 6338, "s": 6293, "text": " Creates a new Font from the specified font." }, { "code": null, "e": 6367, "s": 6338, "text": "boolean canDisplay(char c) " }, { "code": null, "e": 6428, "s": 6367, "text": "Checks if this Font has a glyph for the specified character." }, { "code": null, "e": 6464, "s": 6428, "text": "boolean canDisplay(int codePoint) " }, { "code": null, "e": 6525, "s": 6464, "text": "Checks if this Font has a glyph for the specified character." }, { "code": null, "e": 6581, "s": 6525, "text": "int canDisplayUpTo(char[] text, int start, int limit) " }, { "code": null, "e": 6704, "s": 6581, "text": "Indicates whether or not this Font can display the characters in the specified text starting at start and ending at limit." }, { "code": null, "e": 6771, "s": 6704, "text": "int canDisplayUpTo(CharacterIterator iter, int start, int limit) " }, { "code": null, "e": 6888, "s": 6771, "text": "Indicates whether or not this Font can display the text specified by the iter starting at start and ending at limit." }, { "code": null, "e": 6921, "s": 6888, "text": "int canDisplayUpTo(String str) " }, { "code": null, "e": 6988, "s": 6921, "text": "Indicates whether or not this Font can display a specified String." }, { "code": null, "e": 7044, "s": 6988, "text": "static Font createFont(int fontFormat, File fontFile) " }, { "code": null, "e": 7122, "s": 7044, "text": "Returns a new Font using the specified font type and the specified font file." }, { "code": null, "e": 7187, "s": 7122, "text": "static Font createFont(int fontFormat, InputStream fontStream) " }, { "code": null, "e": 7253, "s": 7187, "text": " Returns a new Font using the specified font type and input data." }, { "code": null, "e": 7322, "s": 7253, "text": "GlyphVector createGlyphVector(FontRenderContext frc, char[] chars) " }, { "code": null, "e": 7427, "s": 7322, "text": "Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font." }, { "code": null, "e": 7504, "s": 7427, "text": "GlyphVector createGlyphVector(FontRenderContext frc, CharacterIterator ci) " }, { "code": null, "e": 7623, "s": 7504, "text": "Creates a GlyphVector by mapping the specified characters to glyphs one-to-one based on the Unicode cmap in this Font." }, { "code": null, "e": 7694, "s": 7623, "text": "GlyphVector createGlyphVector(FontRenderContext frc, int[] glyphCodes)" }, { "code": null, "e": 7799, "s": 7694, "text": "Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font." }, { "code": null, "e": 7866, "s": 7799, "text": "GlyphVector createGlyphVector(FontRenderContext frc, String str) " }, { "code": null, "e": 7972, "s": 7866, "text": " Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font." }, { "code": null, "e": 8008, "s": 7972, "text": "static Font decode(String str) " }, { "code": null, "e": 8059, "s": 8008, "text": " Returns the Font that the str argument describes." }, { "code": null, "e": 8100, "s": 8059, "text": "Font deriveFont(AffineTransform trans) " }, { "code": null, "e": 8201, "s": 8100, "text": "Creates a new Font object by replicating the current Font object and applying a new transform to it." }, { "code": null, "e": 8230, "s": 8201, "text": "Font deriveFont(float size) " }, { "code": null, "e": 8327, "s": 8230, "text": " Creates a new Font object by replicating the current Font object and applying a new size to it." }, { "code": null, "e": 8356, "s": 8327, "text": "Font deriveFont(int style) " }, { "code": null, "e": 8453, "s": 8356, "text": "Creates a new Font object by replicating the current Font object and applying a new style to it." }, { "code": null, "e": 8505, "s": 8453, "text": "Font deriveFont(int style, AffineTransform trans) " }, { "code": null, "e": 8603, "s": 8505, "text": "Creates a new Font object by replicating this Font object and applying a new style and transform." }, { "code": null, "e": 8644, "s": 8603, "text": "Font deriveFont(int style, float size) " }, { "code": null, "e": 8737, "s": 8644, "text": "Creates a new Font object by replicating this Font object and applying a new style and size." }, { "code": null, "e": 8822, "s": 8737, "text": "Font deriveFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) " }, { "code": null, "e": 8936, "s": 8822, "text": "Creates a new Font object by replicating the current Font object and applying a new set of font attributes to it." }, { "code": null, "e": 8965, "s": 8936, "text": "boolean equals(Object obj) " }, { "code": null, "e": 9016, "s": 8965, "text": "Compares this Font object to the specified Object." }, { "code": null, "e": 9045, "s": 9016, "text": "protected void finalize() " }, { "code": null, "e": 9079, "s": 9045, "text": " Disposes the native Font object." }, { "code": null, "e": 9118, "s": 9079, "text": "Map<TextAttribute,?>\tgetAttributes() " }, { "code": null, "e": 9175, "s": 9118, "text": "Returns a map of font attributes available in this Font." }, { "code": null, "e": 9242, "s": 9175, "text": "AttributedCharacterIterator.Attribute[]\tgetAvailableAttributes() " }, { "code": null, "e": 9305, "s": 9242, "text": "Returns the keys of all the attributes supported by this Font." }, { "code": null, "e": 9335, "s": 9305, "text": "byte getBaselineFor(char c) " }, { "code": null, "e": 9399, "s": 9335, "text": "Returns the baseline appropriate for displaying this character." }, { "code": null, "e": 9421, "s": 9399, "text": "String getFamily() " }, { "code": null, "e": 9460, "s": 9421, "text": " Returns the family name of this Font." }, { "code": null, "e": 9490, "s": 9460, "text": "String getFamily(Locale l) " }, { "code": null, "e": 9564, "s": 9490, "text": "Returns the family name of this Font, localized for the specified locale." }, { "code": null, "e": 9651, "s": 9564, "text": "static Font getFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)" }, { "code": null, "e": 9698, "s": 9651, "text": " Returns a Font appropriate to the attributes." }, { "code": null, "e": 9731, "s": 9698, "text": "static Font getFont(String nm) " }, { "code": null, "e": 9785, "s": 9731, "text": "Returns a Font object fom the system properties list." }, { "code": null, "e": 9827, "s": 9785, "text": "static Font getFont(String nm, Font font)" }, { "code": null, "e": 9885, "s": 9827, "text": " Gets the specified Font from the system properties list." }, { "code": null, "e": 9909, "s": 9885, "text": "String getFontName() " }, { "code": null, "e": 9950, "s": 9909, "text": "Returns the font face name of this Font." }, { "code": null, "e": 9982, "s": 9950, "text": "String getFontName(Locale l) " }, { "code": null, "e": 10058, "s": 9982, "text": "Returns the font face name of the Font, localized for the specified locale." }, { "code": null, "e": 10083, "s": 10058, "text": "float\tgetItalicAngle() " }, { "code": null, "e": 10122, "s": 10083, "text": "Returns the italic angle of this Font." }, { "code": null, "e": 10214, "s": 10122, "text": "LineMetrics getLineMetrics(char[] chars, int beginIndex, int limit, FontRenderContext frc) " }, { "code": null, "e": 10283, "s": 10214, "text": " Returns a LineMetrics object created with the specified arguments." }, { "code": null, "e": 10384, "s": 10283, "text": "LineMetrics getLineMetrics(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc) " }, { "code": null, "e": 10452, "s": 10384, "text": " Returns a LineMetrics object created with the specified arguments." }, { "code": null, "e": 10516, "s": 10452, "text": "LineMetrics getLineMetrics(String str, FontRenderContext frc) " }, { "code": null, "e": 10603, "s": 10516, "text": " Returns a LineMetrics object created with the specified String and FontRenderContext." }, { "code": null, "e": 10692, "s": 10603, "text": "LineMetrics getLineMetrics(String str, int beginIndex, int limit, FontRenderContext frc)" }, { "code": null, "e": 10759, "s": 10692, "text": "Returns a LineMetrics object created with the specified arguments." }, { "code": null, "e": 10813, "s": 10759, "text": "Rectangle2D getMaxCharBounds(FontRenderContext frc) " }, { "code": null, "e": 10921, "s": 10813, "text": "Returns the bounds for the character with the maximum bounds as defined in the specified FontRenderContext." }, { "code": null, "e": 10949, "s": 10921, "text": "int getMissingGlyphCode() " }, { "code": null, "e": 11058, "s": 10949, "text": "Returns the glyphCode which is used when this Font does not have a glyph for a specified unicode code point." }, { "code": null, "e": 11077, "s": 11058, "text": "String getName() " }, { "code": null, "e": 11116, "s": 11077, "text": "Returns the logical name of this Font." }, { "code": null, "e": 11137, "s": 11116, "text": "int getNumGlyphs() " }, { "code": null, "e": 11180, "s": 11137, "text": "Returns the number of glyphs in this Font." }, { "code": null, "e": 11215, "s": 11180, "text": "java.awt.peer.FontPeer\tgetPeer() " }, { "code": null, "e": 11272, "s": 11215, "text": " Deprecated. Font rendering is now platform independent." }, { "code": null, "e": 11294, "s": 11272, "text": "String getPSName() " }, { "code": null, "e": 11336, "s": 11294, "text": "Returns the postscript name of this Font." }, { "code": null, "e": 11352, "s": 11336, "text": "int getSize() " }, { "code": null, "e": 11413, "s": 11352, "text": " Returns the point size of this Font, rounded to an integer." }, { "code": null, "e": 11433, "s": 11413, "text": "float\tgetSize2D() " }, { "code": null, "e": 11485, "s": 11433, "text": "Returns the point size of this Font in float value." }, { "code": null, "e": 11579, "s": 11485, "text": "Rectangle2D getStringBounds(char[] chars, int beginIndex, int limit, FontRenderContext frc) " }, { "code": null, "e": 11679, "s": 11579, "text": "Returns the logical bounds of the specified array of characters in the specified FontRenderContext." }, { "code": null, "e": 11781, "s": 11679, "text": "Rectangle2D getStringBounds(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc) " }, { "code": null, "e": 11906, "s": 11781, "text": " Returns the logical bounds of the characters indexed in the specified CharacterIterator in the specified FontRenderContext." }, { "code": null, "e": 11971, "s": 11906, "text": "Rectangle2D getStringBounds(String str, FontRenderContext frc) " }, { "code": null, "e": 12059, "s": 11971, "text": " Returns the logical bounds of the specified String in the specified FontRenderContext." }, { "code": null, "e": 12151, "s": 12059, "text": "Rectangle2D getStringBounds(String str, int beginIndex, int limit, FontRenderContext frc) " }, { "code": null, "e": 12238, "s": 12151, "text": "Returns the logical bounds of the specified String in the specified FontRenderContext." }, { "code": null, "e": 12255, "s": 12238, "text": "int getStyle() " }, { "code": null, "e": 12288, "s": 12255, "text": " Returns the style of this Font." }, { "code": null, "e": 12321, "s": 12288, "text": "AffineTransform getTransform() " }, { "code": null, "e": 12380, "s": 12321, "text": "Returns a copy of the transform associated with this Font." }, { "code": null, "e": 12397, "s": 12380, "text": "int hashCode() " }, { "code": null, "e": 12431, "s": 12397, "text": "Returns a hashcode for this Font." }, { "code": null, "e": 12463, "s": 12431, "text": "boolean hasLayoutAttributes() " }, { "code": null, "e": 12546, "s": 12463, "text": "Return true if this Font contains attributes that require extra layout processing." }, { "code": null, "e": 12580, "s": 12546, "text": "boolean hasUniformLineMetrics() " }, { "code": null, "e": 12638, "s": 12580, "text": "Checks whether or not this Font has uniform line metrics." }, { "code": null, "e": 12657, "s": 12638, "text": "boolean isBold() " }, { "code": null, "e": 12716, "s": 12657, "text": "Indicates whether or not this Font object's style is BOLD." }, { "code": null, "e": 12737, "s": 12716, "text": "boolean isItalic() " }, { "code": null, "e": 12798, "s": 12737, "text": "Indicates whether or not this Font object's style is ITALIC." }, { "code": null, "e": 12818, "s": 12798, "text": "boolean isPlain() " }, { "code": null, "e": 12878, "s": 12818, "text": "Indicates whether or not this Font object's style is PLAIN." }, { "code": null, "e": 12904, "s": 12878, "text": "boolean isTransformed() " }, { "code": null, "e": 13019, "s": 12904, "text": "Indicates whether or not this Font object has a transform that affects its size in addition to the Size attribute." }, { "code": null, "e": 13120, "s": 13019, "text": "GlyphVector layoutGlyphVector(FontRenderContext frc, char[] text, int start, int limit, int flags) " }, { "code": null, "e": 13202, "s": 13120, "text": "Returns a new GlyphVector object, performing full layout of the text if possible." }, { "code": null, "e": 13223, "s": 13202, "text": "String toString() " }, { "code": null, "e": 13277, "s": 13223, "text": "Converts this Font object to a String representation." }, { "code": null, "e": 13333, "s": 13277, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 13350, "s": 13333, "text": "java.lang.Object" }, { "code": null, "e": 13367, "s": 13350, "text": "java.lang.Object" }, { "code": null, "e": 13481, "s": 13367, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 14849, "s": 13481, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.awt.geom.*;\n\npublic class AWTGraphicsDemo extends Frame {\n \n public AWTGraphicsDemo(){\n super(\"Java AWT Examples\");\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); \n awtGraphicsDemo.setVisible(true);\n }\n\n private void prepareGUI(){\n setSize(400,400);\n addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n } \n\n @Override\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D)g; \n Font plainFont = new Font(\"Serif\", Font.PLAIN, 24); \n g2.setFont(plainFont);\n g2.drawString(\"Welcome to TutorialsPoint\", 50, 70); \n Font italicFont = new Font(\"Serif\", Font.ITALIC, 24); \n g2.setFont(italicFont);\n g2.drawString(\"Welcome to TutorialsPoint\", 50, 120); \n Font boldFont = new Font(\"Serif\", Font.BOLD, 24); \n g2.setFont(boldFont);\n g2.drawString(\"Welcome to TutorialsPoint\", 50, 170); \n Font boldItalicFont = new Font(\"Serif\", Font.BOLD+Font.ITALIC, 24); \n g2.setFont(boldItalicFont);\n g2.drawString(\"Welcome to TutorialsPoint\", 50, 220); \n }\n}" }, { "code": null, "e": 14940, "s": 14849, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 14997, "s": 14940, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTGraphicsDemo.java" }, { "code": null, "e": 15094, "s": 14997, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 15145, "s": 15094, "text": "D:\\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo" }, { "code": null, "e": 15173, "s": 15145, "text": "Verify the following output" }, { "code": null, "e": 15206, "s": 15173, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 15214, "s": 15206, "text": " EduOLC" }, { "code": null, "e": 15221, "s": 15214, "text": " Print" }, { "code": null, "e": 15232, "s": 15221, "text": " Add Notes" } ]
Python | Reverse an array upto a given position - GeeksforGeeks
21 Nov, 2018 Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k). Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} k = 4 Output: arr[] = {4, 3, 2, 1, 5, 6} This problem has existing solution please refer Reverse an array upto a given position link. We will solve this problem quickly in Python. # Program to Reverse an array # upto a given position def reverseArrayUptoK(input, k): # reverse list starting from k-1 position # and split remaining list after k # concat both parts and print # input[k-1::-1] --> generate list starting # from k-1 position element till first # element in reverse order print (input[k-1::-1] + input[k:]) # Driver programif __name__ == "__main__": input = [1, 2, 3, 4, 5, 6] k = 4 reverseArrayUptoK(input, k) Output: [4, 3, 2, 1, 5, 6] Python list-programs python-list Python python-list 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": 24238, "s": 24210, "text": "\n21 Nov, 2018" }, { "code": null, "e": 24438, "s": 24238, "text": "Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k)." }, { "code": null, "e": 24448, "s": 24438, "text": "Examples:" }, { "code": null, "e": 24534, "s": 24448, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6}\n k = 4\n\nOutput: arr[] = {4, 3, 2, 1, 5, 6} \n" }, { "code": null, "e": 24673, "s": 24534, "text": "This problem has existing solution please refer Reverse an array upto a given position link. We will solve this problem quickly in Python." }, { "code": "# Program to Reverse an array # upto a given position def reverseArrayUptoK(input, k): # reverse list starting from k-1 position # and split remaining list after k # concat both parts and print # input[k-1::-1] --> generate list starting # from k-1 position element till first # element in reverse order print (input[k-1::-1] + input[k:]) # Driver programif __name__ == \"__main__\": input = [1, 2, 3, 4, 5, 6] k = 4 reverseArrayUptoK(input, k)", "e": 25153, "s": 24673, "text": null }, { "code": null, "e": 25161, "s": 25153, "text": "Output:" }, { "code": null, "e": 25181, "s": 25161, "text": "[4, 3, 2, 1, 5, 6]\n" }, { "code": null, "e": 25202, "s": 25181, "text": "Python list-programs" }, { "code": null, "e": 25214, "s": 25202, "text": "python-list" }, { "code": null, "e": 25221, "s": 25214, "text": "Python" }, { "code": null, "e": 25233, "s": 25221, "text": "python-list" }, { "code": null, "e": 25331, "s": 25233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25340, "s": 25331, "text": "Comments" }, { "code": null, "e": 25353, "s": 25340, "text": "Old Comments" }, { "code": null, "e": 25374, "s": 25353, "text": "Python OOPs Concepts" }, { "code": null, "e": 25406, "s": 25374, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25429, "s": 25406, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25451, "s": 25429, "text": "Defaultdict in Python" }, { "code": null, "e": 25478, "s": 25451, "text": "Python Classes and Objects" }, { "code": null, "e": 25494, "s": 25478, "text": "Deque in Python" }, { "code": null, "e": 25536, "s": 25494, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25592, "s": 25536, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25637, "s": 25592, "text": "Python - Ways to remove duplicates from list" } ]
JavaScript Switch Statement
The switch statement is used to perform different actions based on different conditions. Use the switch statement to select one of many code blocks to be executed. This is how it works: The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. If there is no match, the default code block is executed. The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0, Monday=1, Tuesday=2 ..) This example uses the weekday number to calculate the weekday name: The result of day will be: When JavaScript reaches a break keyword, it breaks out of the switch block. This will stop the execution inside the switch block. It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway. Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case. The default keyword specifies the code to run if there is no case match: The getDay() method returns the weekday as a number between 0 and 6. If today is neither Saturday (6) nor Sunday (0), write a default message: The result of text will be: The default case does not have to be the last case in a switch block: If default is not the last case in the switch block, remember to end the default case with a break. Sometimes you will want different switch cases to use the same code. In this example case 4 and 5 share the same code block, and 0 and 6 share another code block: If multiple cases matches a case value, the first case is selected. If no matching cases are found, the program continues to the default label. If no default label is found, the program continues to the statement(s) after the switch. Switch cases use strict comparison (===). The values must be of the same type to match. A strict comparison can only be true if the operands are of the same type. In this example there will be no match for x: Create a switch statement that will alert "Hello" if fruits is "banana", and "Welcome" if fruits is "apple". (fruits) { "Banana": alert("Hello") break; "Apple": alert("Welcome") break; } Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 89, "s": 0, "text": "The switch statement is used to perform different actions based on different conditions." }, { "code": null, "e": 164, "s": 89, "text": "Use the switch statement to select one of many code blocks to be executed." }, { "code": null, "e": 186, "s": 164, "text": "This is how it works:" }, { "code": null, "e": 227, "s": 186, "text": "The switch expression is evaluated once." }, { "code": null, "e": 297, "s": 227, "text": "The value of the expression is compared with the values of each case." }, { "code": null, "e": 360, "s": 297, "text": "If there is a match, the associated block of code is executed." }, { "code": null, "e": 418, "s": 360, "text": "If there is no match, the default code block is executed." }, { "code": null, "e": 489, "s": 418, "text": "The getDay() method returns the weekday as a number between \n 0 and 6." }, { "code": null, "e": 524, "s": 489, "text": "(Sunday=0, Monday=1, Tuesday=2 ..)" }, { "code": null, "e": 592, "s": 524, "text": "This example uses the weekday number to calculate the weekday name:" }, { "code": null, "e": 619, "s": 592, "text": "The result of day will be:" }, { "code": null, "e": 696, "s": 619, "text": "When JavaScript reaches a break \nkeyword, it breaks out of the switch block." }, { "code": null, "e": 750, "s": 696, "text": "This will stop the execution inside the switch block." }, { "code": null, "e": 850, "s": 750, "text": "It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway." }, { "code": null, "e": 969, "s": 850, "text": "Note: If you omit the break statement, the next case will be executed even if \nthe evaluation does not match the case." }, { "code": null, "e": 1043, "s": 969, "text": "The default keyword specifies the code to run if there is no \ncase match:" }, { "code": null, "e": 1114, "s": 1043, "text": "The getDay() method returns the weekday as a number between \n 0 and 6." }, { "code": null, "e": 1188, "s": 1114, "text": "If today is neither Saturday (6) nor Sunday (0), write a default message:" }, { "code": null, "e": 1216, "s": 1188, "text": "The result of text will be:" }, { "code": null, "e": 1287, "s": 1216, "text": "The default case does not have to be the last case in a switch \nblock:" }, { "code": null, "e": 1387, "s": 1287, "text": "If default is not the last case in the switch block, remember to end the default case with a break." }, { "code": null, "e": 1459, "s": 1387, "text": "\nSometimes you will want different \nswitch cases to use the same \ncode." }, { "code": null, "e": 1555, "s": 1459, "text": "\nIn this example case 4 and 5 share the same code block, and 0 and 6 share \nanother code block:" }, { "code": null, "e": 1624, "s": 1555, "text": "\nIf multiple cases matches a case value, the first case is selected." }, { "code": null, "e": 1701, "s": 1624, "text": "\nIf no matching cases are found, the program continues to the default label." }, { "code": null, "e": 1792, "s": 1701, "text": "\nIf no default label is found, the program continues to the statement(s) after the switch." }, { "code": null, "e": 1834, "s": 1792, "text": "Switch cases use strict comparison (===)." }, { "code": null, "e": 1880, "s": 1834, "text": "The values must be of the same type to match." }, { "code": null, "e": 1955, "s": 1880, "text": "A strict comparison can only be true if the operands are of the same type." }, { "code": null, "e": 2002, "s": 1955, "text": "In this example there will be no match for x: " }, { "code": null, "e": 2111, "s": 2002, "text": "Create a switch statement that will alert \"Hello\" if fruits is \"banana\", and \"Welcome\" if fruits is \"apple\"." }, { "code": null, "e": 2214, "s": 2111, "text": "(fruits) {\n \"Banana\":\n alert(\"Hello\")\n break;\n \"Apple\":\n alert(\"Welcome\")\n break; \n}\n" }, { "code": null, "e": 2233, "s": 2214, "text": "Start the Exercise" }, { "code": null, "e": 2266, "s": 2233, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2308, "s": 2266, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2415, "s": 2308, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2434, "s": 2415, "text": "[email protected]" } ]
sudoedit - Unix, Linux Command
sudo [-bEHPS] [-p prompt] [-u username|#uid] [VAR=value] {-i | -s | command} sudoedit [-S] [-p prompt] [-u username|#uid] file ... When invoked as sudoedit, the -e option (described below), is implied. sudo determines who is an authorized user by consulting the file /etc/sudoers. By giving sudo the -v flag, a user can update the time stamp without running a command. The password prompt itself will also time out if the user’s password is not entered within 5 minutes (unless overridden via sudoers). If a user who is not listed in the sudoers file tries to run a command via sudo, mail is sent to the proper authorities, as defined at configure time or in the sudoers file (defaults to root). Note that the mail will not be sent if an unauthorized user tries to run sudo with the -l or -v flags. This allows users to determine for themselves whether or not they are allowed to use sudo. If sudo is run by root and the SUDO_USER environment variable is set, sudo will use this value to determine who the actual user is. This can be used by a user to log commands through sudo even when a root shell has been invoked. It also allows the -e flag to remain useful even when being run via a sudo-run script or program. Note however, that the sudoers lookup is still done for root, not the user specified by SUDO_USER. sudo can log both successful and unsuccessful attempts (as well as errors) to syslog(3), a log file, or both. By default sudo will log via syslog(3) but this is changeable at configure time or via the sudoers file. If the specified file does not exist, it will be created. Note that unlike most commands run by sudo, the editor is run with the invoking user’s environment unmodified. If, for some reason, sudo is unable to update a file with its edited version, the user will receive a warning and the edited copy will remain in a temporary file. Otherwise, sudo quits with an exit value of 1 if there is a configuration/permission problem or if sudo cannot execute the given command. In the latter case the error string is printed to stderr. If sudo cannot stat(2) one or more entries in the user’s PATH an error is printed on stderr. (If the directory does not exist or if it is not really a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances. The most common reason for stat(2) to return permission denied is if you are running an automounter and one of the directories in your PATH is on a machine that is currently unreachable. There are two distinct ways to deal with environment variables. By default, the env_reset sudoers option is enabled. This causes commands to be executed with a minimal environment containing TERM, PATH, HOME, SHELL, LOGNAME, USER and USERNAME in addition to variables from the invoking process permitted by the env_check and env_keep sudoers options. There is effectively a whitelist for environment variables. If, however, the env_reset option is disabled in sudoers, any variables not explicitly denied by the env_check and env_delete options are inherited from the invoking process. In this case, env_check and env_delete behave like a blacklist. Since it is not possible to blacklist all potentially dangerous environment variables, use of the default env_reset behavior is encouraged. In all cases, environment variables with a value beginning with () are removed as they could be interpreted as bash functions. The list of environment variables that sudo allows or denies is contained in the output of sudo -V when run as root. Note that the dynamic linker on most operating systems will remove variables that can control dynamic linking from the environment of setuid executables, including sudo. Depending on the operating system this may include _RLD*, DYLD_*, LD_*, LDR_*, LIBPATH, SHLIB_PATH, and others. These type of variables are removed from the environment before sudo even begins execution and, as such, it is not possible for sudo to preserve them. To prevent command spoofing, sudo checks . and "" (both denoting current directory) last when searching for a command in the user’s PATH (if one or both are in the PATH). Note, however, that the actual PATH environment variable is not modified and is passed unchanged to the program that sudo executes. sudo will check the ownership of its timestamp directory (/var/run/sudo by default) and ignore the directory’s contents if it is not owned by root or if it is writable by a user other than root. On systems that allow non-root users to give away files via chown(2), if the timestamp directory is located in a directory writable by anyone (e.g., /tmp), it is possible for a user to create the timestamp directory before sudo is run. However, because sudo checks the ownership and mode of the directory and its contents, the only damage that can be done is to hide files by putting them in the timestamp dir. This is unlikely to happen since once the timestamp dir is owned by root and inaccessible by any other user, the user placing files there would be unable to get them back out. To get around this issue you can use a directory that is not world-writable for the timestamps (/var/adm/sudo for instance) or create /var/run/sudo with the appropriate owner (root) and permissions (0700) in the system startup files. sudo will not honor timestamps set far in the future. Timestamps with a date greater than current_time + 2 * TIMEOUT will be ignored and sudo will log and complain. This is done to keep a user from creating his/her own timestamp with a bogus date on systems that allow users to give away files. Please note that sudo will normally only log the command it explicitly runs. If a user runs a command such as sudo su or sudo sh, subsequent commands run from that shell will not be logged, nor will sudo’s access control affect them. The same is true for commands that offer shell escapes (including most editors). Because of this, care must be taken when giving users access to commands via sudo to verify that the command does not inadvertently give the user an effective root shell. For more information, please see the PREVENTING SHELL ESCAPES section in sudoers(5). To get a file listing of an unreadable directory: $ sudo ls /usr/local/protected To list the home directory of user yazza on a machine where the file system holding ~yazza is not exported as root: $ sudo -u yazza ls ~yazza To edit the index.html file as user www: $ sudo -u www vi ~www/htdocs/index.html To shutdown a machine: $ sudo shutdown -r +15 "quick reboot" To make a usage listing of the directories in the /home partition. Note that this runs the commands in a sub-shell to make the cd and file redirection work. $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE" Todd C. Miller Chris Jepeway See the HISTORY file in the sudo distribution or visit http://www.sudo.ws/sudo/history.html for a short history of sudo. It is not meaningful to run the cd command directly via sudo, e.g., $ sudo cd /usr/local/protected since when the command exits the parent process (your shell) will still be the same. Please see the EXAMPLES section for more information. If users have sudo ALL there is nothing to prevent them from creating their own program that gives them a root shell regardless of any ’!’ elements in the user specification. Running shell scripts via sudo can expose the same kernel bugs that make setuid shell scripts unsafe on some operating systems (if your OS has a /dev/fd/ directory, setuid shell scripts are generally safe). Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10656, "s": 10577, "text": "\nsudo [-bEHPS]\n[-p prompt]\n[-u username|#uid]\n[VAR=value] {-i | -s | command}\n" }, { "code": null, "e": 10712, "s": 10656, "text": "\nsudoedit [-S]\n[-p prompt] [-u username|#uid]\nfile ...\n" }, { "code": null, "e": 10785, "s": 10712, "text": "\nWhen invoked as sudoedit, the -e option (described below),\nis implied.\n" }, { "code": null, "e": 11089, "s": 10785, "text": "\nsudo determines who is an authorized user by consulting the file\n/etc/sudoers. By giving sudo the -v flag, a user\ncan update the time stamp without running a command. The password\nprompt itself will also time out if the user’s password is not\nentered within 5 minutes (unless overridden via\nsudoers).\n" }, { "code": null, "e": 11480, "s": 11089, "text": "\nIf a user who is not listed in the sudoers file tries to run a\ncommand via sudo, mail is sent to the proper authorities, as\ndefined at configure time or in the sudoers file (defaults to\nroot). Note that the mail will not be sent if an unauthorized\nuser tries to run sudo with the -l or -v flags. This allows\nusers to determine for themselves whether or not they are allowed\nto use sudo.\n" }, { "code": null, "e": 11911, "s": 11480, "text": "\nIf sudo is run by root and the SUDO_USER environment variable\nis set, sudo will use this value to determine who the actual\nuser is. This can be used by a user to log commands through sudo\neven when a root shell has been invoked. It also allows the -e\nflag to remain useful even when being run via a sudo-run script or\nprogram. Note however, that the sudoers lookup is still done for\nroot, not the user specified by SUDO_USER.\n" }, { "code": null, "e": 12129, "s": 11911, "text": "\nsudo can log both successful and unsuccessful attempts (as well\nas errors) to syslog(3), a log file, or both. By default sudo\nwill log via syslog(3) but this is changeable at configure time\nor via the sudoers file.\n" }, { "code": null, "e": 12466, "s": 12129, "text": "\n\nIf the specified file does not exist, it will be created. Note\nthat unlike most commands run by sudo, the editor is run with\nthe invoking user’s environment unmodified. If, for some reason,\nsudo is unable to update a file with its edited version, the\nuser will receive a warning and the edited copy will remain in a\ntemporary file.\n" }, { "code": null, "e": 13116, "s": 12466, "text": "\nOtherwise, sudo quits with an exit value of 1 if there is a\nconfiguration/permission problem or if sudo cannot execute the\ngiven command. In the latter case the error string is printed to\nstderr. If sudo cannot stat(2) one or more entries in the user’s\nPATH an error is printed on stderr. (If the directory does not\nexist or if it is not really a directory, the entry is ignored and\nno error is printed.) This should not happen under normal\ncircumstances. The most common reason for stat(2) to return\npermission denied is if you are running an automounter and one\nof the directories in your PATH is on a machine that is currently\nunreachable.\n" }, { "code": null, "e": 13529, "s": 13116, "text": "\nThere are two distinct ways to deal with environment variables.\nBy default, the env_reset sudoers option is enabled.\nThis causes commands to be executed with a minimal environment\ncontaining TERM, PATH, HOME, SHELL, LOGNAME, USER\nand USERNAME in addition to variables from the invoking process\npermitted by the env_check and env_keep sudoers options.\nThere is effectively a whitelist for environment variables.\n" }, { "code": null, "e": 13912, "s": 13529, "text": "\nIf, however, the env_reset option is disabled in sudoers, any\nvariables not explicitly denied by the env_check and env_delete\noptions are inherited from the invoking process. In this case,\nenv_check and env_delete behave like a blacklist. Since it\nis not possible to blacklist all potentially dangerous environment\nvariables, use of the default env_reset behavior is encouraged.\n" }, { "code": null, "e": 14158, "s": 13912, "text": "\nIn all cases, environment variables with a value beginning with\n() are removed as they could be interpreted as bash functions.\nThe list of environment variables that sudo allows or denies is\ncontained in the output of sudo -V when run as root.\n" }, { "code": null, "e": 14595, "s": 14158, "text": "\nNote that the dynamic linker on most operating systems will remove\nvariables that can control dynamic linking from the environment of\nsetuid executables, including sudo. Depending on the operating\nsystem this may include _RLD*, DYLD_*, LD_*, LDR_*,\nLIBPATH, SHLIB_PATH, and others. These type of variables are\nremoved from the environment before sudo even begins execution\nand, as such, it is not possible for sudo to preserve them.\n" }, { "code": null, "e": 14901, "s": 14595, "text": "\nTo prevent command spoofing, sudo checks . and \"\" (both denoting\ncurrent directory) last when searching for a command in the user’s\nPATH (if one or both are in the PATH). Note, however, that the\nactual PATH environment variable is not modified and is passed\nunchanged to the program that sudo executes.\n" }, { "code": null, "e": 15923, "s": 14901, "text": "\nsudo will check the ownership of its timestamp directory\n(/var/run/sudo by default) and ignore the directory’s contents if\nit is not owned by root or if it is writable by a user other than\nroot. On systems that allow non-root users to give away files via\nchown(2), if the timestamp directory is located in a directory\nwritable by anyone (e.g., /tmp), it is possible for a user to\ncreate the timestamp directory before sudo is run. However,\nbecause sudo checks the ownership and mode of the directory and\nits contents, the only damage that can be done is to hide files\nby putting them in the timestamp dir. This is unlikely to happen\nsince once the timestamp dir is owned by root and inaccessible by\nany other user, the user placing files there would be unable to get\nthem back out. To get around this issue you can use a directory\nthat is not world-writable for the timestamps (/var/adm/sudo for\ninstance) or create /var/run/sudo with the appropriate owner (root)\nand permissions (0700) in the system startup files.\n" }, { "code": null, "e": 16221, "s": 15923, "text": "\nsudo will not honor timestamps set far in the future.\nTimestamps with a date greater than current_time + 2 * TIMEOUT\nwill be ignored and sudo will log and complain. This is done to\nkeep a user from creating his/her own timestamp with a bogus\ndate on systems that allow users to give away files.\n" }, { "code": null, "e": 16798, "s": 16221, "text": "\nPlease note that sudo will normally only log the command it\nexplicitly runs. If a user runs a command such as sudo su or\nsudo sh, subsequent commands run from that shell will not be\nlogged, nor will sudo’s access control affect them. The same\nis true for commands that offer shell escapes (including most\neditors). Because of this, care must be taken when giving users\naccess to commands via sudo to verify that the command does not\ninadvertently give the user an effective root shell. For more\ninformation, please see the PREVENTING SHELL ESCAPES section in\nsudoers(5).\n" }, { "code": null, "e": 16850, "s": 16798, "text": "\nTo get a file listing of an unreadable directory:\n" }, { "code": null, "e": 16886, "s": 16852, "text": "\n $ sudo ls /usr/local/protected\n" }, { "code": null, "e": 17004, "s": 16886, "text": "\nTo list the home directory of user yazza on a machine where the\nfile system holding ~yazza is not exported as root:\n" }, { "code": null, "e": 17035, "s": 17006, "text": "\n $ sudo -u yazza ls ~yazza\n" }, { "code": null, "e": 17078, "s": 17035, "text": "\nTo edit the index.html file as user www:\n" }, { "code": null, "e": 17123, "s": 17080, "text": "\n $ sudo -u www vi ~www/htdocs/index.html\n" }, { "code": null, "e": 17148, "s": 17123, "text": "\nTo shutdown a machine:\n" }, { "code": null, "e": 17191, "s": 17150, "text": "\n $ sudo shutdown -r +15 \"quick reboot\"\n" }, { "code": null, "e": 17351, "s": 17191, "text": "\nTo make a usage listing of the directories in the /home\npartition. Note that this runs the commands in a sub-shell\nto make the cd and file redirection work.\n" }, { "code": null, "e": 17409, "s": 17353, "text": "\n $ sudo sh -c \"cd /home ; du -s * | sort -rn > USAGE\"\n" }, { "code": null, "e": 17458, "s": 17411, "text": "\n Todd C. Miller\n Chris Jepeway\n" }, { "code": null, "e": 17581, "s": 17458, "text": "\nSee the HISTORY file in the sudo distribution or visit\nhttp://www.sudo.ws/sudo/history.html for a short history\nof sudo.\n" }, { "code": null, "e": 17651, "s": 17581, "text": "\nIt is not meaningful to run the cd command directly via sudo, e.g.,\n" }, { "code": null, "e": 17687, "s": 17653, "text": "\n $ sudo cd /usr/local/protected\n" }, { "code": null, "e": 17829, "s": 17687, "text": "\nsince when the command exits the parent process (your shell) will\nstill be the same. Please see the EXAMPLES section for more information.\n" }, { "code": null, "e": 18006, "s": 17829, "text": "\nIf users have sudo ALL there is nothing to prevent them from\ncreating their own program that gives them a root shell regardless\nof any ’!’ elements in the user specification.\n" }, { "code": null, "e": 18215, "s": 18006, "text": "\nRunning shell scripts via sudo can expose the same kernel bugs that\nmake setuid shell scripts unsafe on some operating systems (if your OS\nhas a /dev/fd/ directory, setuid shell scripts are generally safe).\n" }, { "code": null, "e": 18232, "s": 18215, "text": "\nAdvertisements\n" }, { "code": null, "e": 18267, "s": 18232, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 18295, "s": 18267, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 18329, "s": 18295, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 18346, "s": 18329, "text": " Frahaan Hussain" }, { "code": null, "e": 18379, "s": 18346, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 18390, "s": 18379, "text": " Pradeep D" }, { "code": null, "e": 18425, "s": 18390, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 18441, "s": 18425, "text": " Musab Zayadneh" }, { "code": null, "e": 18474, "s": 18441, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 18486, "s": 18474, "text": " GUHARAJANM" }, { "code": null, "e": 18518, "s": 18486, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 18526, "s": 18518, "text": " Uplatz" }, { "code": null, "e": 18533, "s": 18526, "text": " Print" }, { "code": null, "e": 18544, "s": 18533, "text": " Add Notes" } ]
ipcalc - Unix, Linux Command
Erik Troan <[email protected]> Preston Brown <[email protected]> Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10663, "s": 10599, "text": "Erik Troan <[email protected]>\nPreston Brown <[email protected]>\n\n" }, { "code": null, "e": 10682, "s": 10665, "text": "\nAdvertisements\n" }, { "code": null, "e": 10717, "s": 10682, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 10745, "s": 10717, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10779, "s": 10745, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10796, "s": 10779, "text": " Frahaan Hussain" }, { "code": null, "e": 10829, "s": 10796, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 10840, "s": 10829, "text": " Pradeep D" }, { "code": null, "e": 10875, "s": 10840, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10891, "s": 10875, "text": " Musab Zayadneh" }, { "code": null, "e": 10924, "s": 10891, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 10936, "s": 10924, "text": " GUHARAJANM" }, { "code": null, "e": 10968, "s": 10936, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 10976, "s": 10968, "text": " Uplatz" }, { "code": null, "e": 10983, "s": 10976, "text": " Print" }, { "code": null, "e": 10994, "s": 10983, "text": " Add Notes" } ]
Count distinct elements in an array in C++
We are given an unsorted array of any size containing repetitive elements and the task is to calculate the count of distinct elements in an array. Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Input− int arr[] = {1, 1, 2, 3, 3, 4, 4} Output − count is 4 Explanation − In the given array there are 4 distinct elements and those are 1, 2, 3, 4 but the size of array is 7 as it contains repetitive elements and our task was to remove the duplicates and then count the array elements. Input − int arr[] = {1, 2, 3, 4, 5, 5, 5, 5} Output − count is 5 Explanation − In the given array there are 5 distinct elements and those are 1, 2, 3, 4 and 5 but the size of array is 8 as it contains repetitive elements and our task was to remove the duplicates and then count the array elements. Create an array of let’s say, arr[] Create an array of let’s say, arr[] Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements. Take a temporary variable that will store the count of distinct elements. Start a loop for with i to 0 till i is less than the size of an array Start a loop for with i to 0 till i is less than the size of an array Inside the loop, run while i < size-1 and arr[i] = arr[i+1] Inside the loop, run while i < size-1 and arr[i] = arr[i+1] Inside the while, increment the value of i Inside the while, increment the value of i And inside for, increment the value of count And inside for, increment the value of count Return count Return count Print the result. Print the result. Create an array of let’s say, arr[] Create an array of let’s say, arr[] Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Take a temporary variable that will store the count of distinct elements. Take a temporary variable that will store the count of distinct elements. Start a loop for with i to 1 till i is less than the size of an array Start a loop for with i to 1 till i is less than the size of an array Inside the loop, set j to 0 and start another loop for with j to 0 and j less than i and increment j wth 1 Inside the loop, set j to 0 and start another loop for with j to 0 and j less than i and increment j wth 1 Inside this loop, check if arr[i] = arr[j] then break Inside this loop, check if arr[i] = arr[j] then break Inside this loop, check if i = j then increment the count by 1 Inside this loop, check if i = j then increment the count by 1 Return count Return count Print the result.r Print the result.r Live Demo #include <algorithm> #include <iostream> using namespace std; int distinct_elements(int arr[], int n){ // Sorting the array sort(arr, arr + n); // Traverse the sorted array int count = 0; for (int i = 0; i < n; i++){ // Moving the index when duplicate is found while (i < n - 1 && arr[i] == arr[i + 1]){ i++; } count++; } return count; } // Main Function int main(){ int arr[] = { 3, 6, 5, 8, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout <<"count is "<<distinct_elements(arr, n); return 0; } If we run the above code we will get the following output − count is 6 Live Demo #include <iostream> using namespace std; int countDistinct(int a[], int size){ int i, j, count = 1; for (i = 1; i < size; i++){ for (j = 0; j < i; j++){ if (a[i] == a[j]){ break; } } if (i == j){ count++; } } return count; } // Main function int main(){ int a[] = { 3, 6, 5, 8, 2, 3, 4 }; int size = sizeof(a) / sizeof(a[0]); cout << "count is "<<countDistinct(a, size); return 0; } If we run the above code we will get the following output − count is 6
[ { "code": null, "e": 1209, "s": 1062, "text": "We are given an unsorted array of any size containing repetitive elements and the task is to calculate the count of distinct elements in an array." }, { "code": null, "e": 1465, "s": 1209, "text": "Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." }, { "code": null, "e": 1526, "s": 1465, "text": "Input− int arr[] = {1, 1, 2, 3, 3, 4, 4}\nOutput − count is 4" }, { "code": null, "e": 1753, "s": 1526, "text": "Explanation − In the given array there are 4 distinct elements and those are 1, 2, 3, 4 but the size of array is 7 as it contains repetitive elements and our task was to remove the duplicates and then count the array elements." }, { "code": null, "e": 1818, "s": 1753, "text": "Input − int arr[] = {1, 2, 3, 4, 5, 5, 5, 5}\nOutput − count is 5" }, { "code": null, "e": 2051, "s": 1818, "text": "Explanation − In the given array there are 5 distinct elements and those are 1, 2, 3, 4 and 5 but the size of array is 8 as it contains repetitive elements and our task was to remove the duplicates and then count the array elements." }, { "code": null, "e": 2087, "s": 2051, "text": "Create an array of let’s say, arr[]" }, { "code": null, "e": 2123, "s": 2087, "text": "Create an array of let’s say, arr[]" }, { "code": null, "e": 2251, "s": 2123, "text": "Calculate the length of an array using the length() function that will return an\ninteger value as per the elements in an array." }, { "code": null, "e": 2379, "s": 2251, "text": "Calculate the length of an array using the length() function that will return an\ninteger value as per the elements in an array." }, { "code": null, "e": 2462, "s": 2379, "text": "Call the sort function and pass the array and the size of an array as a parameter." }, { "code": null, "e": 2545, "s": 2462, "text": "Call the sort function and pass the array and the size of an array as a parameter." }, { "code": null, "e": 2619, "s": 2545, "text": "Take a temporary variable that will store the count of distinct elements." }, { "code": null, "e": 2693, "s": 2619, "text": "Take a temporary variable that will store the count of distinct elements." }, { "code": null, "e": 2763, "s": 2693, "text": "Start a loop for with i to 0 till i is less than the size of an array" }, { "code": null, "e": 2833, "s": 2763, "text": "Start a loop for with i to 0 till i is less than the size of an array" }, { "code": null, "e": 2893, "s": 2833, "text": "Inside the loop, run while i < size-1 and arr[i] = arr[i+1]" }, { "code": null, "e": 2953, "s": 2893, "text": "Inside the loop, run while i < size-1 and arr[i] = arr[i+1]" }, { "code": null, "e": 2996, "s": 2953, "text": "Inside the while, increment the value of i" }, { "code": null, "e": 3039, "s": 2996, "text": "Inside the while, increment the value of i" }, { "code": null, "e": 3084, "s": 3039, "text": "And inside for, increment the value of count" }, { "code": null, "e": 3129, "s": 3084, "text": "And inside for, increment the value of count" }, { "code": null, "e": 3142, "s": 3129, "text": "Return count" }, { "code": null, "e": 3155, "s": 3142, "text": "Return count" }, { "code": null, "e": 3173, "s": 3155, "text": "Print the result." }, { "code": null, "e": 3191, "s": 3173, "text": "Print the result." }, { "code": null, "e": 3227, "s": 3191, "text": "Create an array of let’s say, arr[]" }, { "code": null, "e": 3263, "s": 3227, "text": "Create an array of let’s say, arr[]" }, { "code": null, "e": 3391, "s": 3263, "text": "Calculate the length of an array using the length() function that will return\nan integer value as per the elements in an array." }, { "code": null, "e": 3519, "s": 3391, "text": "Calculate the length of an array using the length() function that will return\nan integer value as per the elements in an array." }, { "code": null, "e": 3593, "s": 3519, "text": "Take a temporary variable that will store the count of distinct elements." }, { "code": null, "e": 3667, "s": 3593, "text": "Take a temporary variable that will store the count of distinct elements." }, { "code": null, "e": 3737, "s": 3667, "text": "Start a loop for with i to 1 till i is less than the size of an array" }, { "code": null, "e": 3807, "s": 3737, "text": "Start a loop for with i to 1 till i is less than the size of an array" }, { "code": null, "e": 3914, "s": 3807, "text": "Inside the loop, set j to 0 and start another loop for with j to 0 and j less\nthan i and increment j wth 1" }, { "code": null, "e": 4021, "s": 3914, "text": "Inside the loop, set j to 0 and start another loop for with j to 0 and j less\nthan i and increment j wth 1" }, { "code": null, "e": 4075, "s": 4021, "text": "Inside this loop, check if arr[i] = arr[j] then break" }, { "code": null, "e": 4129, "s": 4075, "text": "Inside this loop, check if arr[i] = arr[j] then break" }, { "code": null, "e": 4192, "s": 4129, "text": "Inside this loop, check if i = j then increment the count by 1" }, { "code": null, "e": 4255, "s": 4192, "text": "Inside this loop, check if i = j then increment the count by 1" }, { "code": null, "e": 4268, "s": 4255, "text": "Return count" }, { "code": null, "e": 4281, "s": 4268, "text": "Return count" }, { "code": null, "e": 4300, "s": 4281, "text": "Print the result.r" }, { "code": null, "e": 4319, "s": 4300, "text": "Print the result.r" }, { "code": null, "e": 4330, "s": 4319, "text": " Live Demo" }, { "code": null, "e": 4897, "s": 4330, "text": "#include <algorithm>\n#include <iostream>\nusing namespace std;\nint distinct_elements(int arr[], int n){\n // Sorting the array\n sort(arr, arr + n);\n // Traverse the sorted array\n int count = 0;\n for (int i = 0; i < n; i++){\n // Moving the index when duplicate is found\n while (i < n - 1 && arr[i] == arr[i + 1]){\n i++;\n }\n count++;\n }\n return count;\n}\n// Main Function\nint main(){\n int arr[] = { 3, 6, 5, 8, 2, 3, 4 };\n int n = sizeof(arr) / sizeof(arr[0]);\n cout <<\"count is \"<<distinct_elements(arr, n);\n return 0;\n}" }, { "code": null, "e": 4957, "s": 4897, "text": "If we run the above code we will get the following output −" }, { "code": null, "e": 4968, "s": 4957, "text": "count is 6" }, { "code": null, "e": 4979, "s": 4968, "text": " Live Demo" }, { "code": null, "e": 5449, "s": 4979, "text": "#include <iostream>\nusing namespace std;\nint countDistinct(int a[], int size){\n int i, j, count = 1;\n for (i = 1; i < size; i++){\n for (j = 0; j < i; j++){\n if (a[i] == a[j]){\n break;\n }\n }\n if (i == j){\n count++;\n }\n }\n return count;\n}\n// Main function\nint main(){\n int a[] = { 3, 6, 5, 8, 2, 3, 4 };\n int size = sizeof(a) / sizeof(a[0]);\n cout << \"count is \"<<countDistinct(a, size);\n return 0;\n}" }, { "code": null, "e": 5509, "s": 5449, "text": "If we run the above code we will get the following output −" }, { "code": null, "e": 5520, "s": 5509, "text": "count is 6" } ]
How do I plot only a table in Matplotlib?
To plot only a table, we can take the following steps− Create fig and axs, using subplots. Create a figure and a set of subplots. Create random data for 10 rows and 3 columns. Create a tuple for columns name. axis('tight') − Set the limits, just large enough to show all the data, then disable further autoscaling. axis('off') − Turn off axis lines and labels. Same as ''False''. To add a table on the axis, use table() instance, with column text, column labels, columns, and location=center. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig, axs = plt.subplots(1, 1) data = np.random.random((10, 3)) columns = ("Column I", "Column II", "Column III") axs.axis('tight') axs.axis('off') the_table = axs.table(cellText=data, colLabels=columns, loc='center') plt.show()
[ { "code": null, "e": 1117, "s": 1062, "text": "To plot only a table, we can take the following steps−" }, { "code": null, "e": 1192, "s": 1117, "text": "Create fig and axs, using subplots. Create a figure and a set of subplots." }, { "code": null, "e": 1238, "s": 1192, "text": "Create random data for 10 rows and 3 columns." }, { "code": null, "e": 1271, "s": 1238, "text": "Create a tuple for columns name." }, { "code": null, "e": 1377, "s": 1271, "text": "axis('tight') − Set the limits, just large enough to show all the data, then disable further autoscaling." }, { "code": null, "e": 1442, "s": 1377, "text": "axis('off') − Turn off axis lines and labels. Same as ''False''." }, { "code": null, "e": 1555, "s": 1442, "text": "To add a table on the axis, use table() instance, with column text, column labels, columns, and location=center." }, { "code": null, "e": 1597, "s": 1555, "text": "To display the figure, use show() method." }, { "code": null, "e": 1968, "s": 1597, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig, axs = plt.subplots(1, 1)\ndata = np.random.random((10, 3))\ncolumns = (\"Column I\", \"Column II\", \"Column III\")\naxs.axis('tight')\naxs.axis('off')\nthe_table = axs.table(cellText=data, colLabels=columns, loc='center')\nplt.show()" } ]
Count Odd and Even numbers in a range from L to R in C++
We are given a range starting from L to R of integer values and the task is to calculate the count of odd numbers and the even numbers in the range. Input − L = 7, R = 17 Output − Count of Even numbers in a range from L to R are − 5 Count of Odd numbers in a range from L to R are − 6 Input − L = 1, R = 10 Output − Count of Even numbers in a range from L to R are − 5 Count of Odd numbers in a range from L to R are − 5 Input the range starting from L to R Input the range starting from L to R Pass the L and R values to the function to find out the even values and then we will calculate the odd values depending upon the return value. Pass the L and R values to the function to find out the even values and then we will calculate the odd values depending upon the return value. Start loop FOR from i to L till R Start loop FOR from i to L till R Inside the loop, check IF i%2==0 then increment the even count by 1 Inside the loop, check IF i%2==0 then increment the even count by 1 Return the even count Return the even count Now to calculate the odd count set odd as (R - L + 1) - even Now to calculate the odd count set odd as (R - L + 1) - even Live Demo #include <iostream> using namespace std; int Odd_Even(int L, int R){ int even = 0; for(int i = L ;i < R ;i++){ if(i%2==0){ even++; } } return even; } int main(){ int L = 7, R = 17; int even = Odd_Even(L, R); int odd = (R - L + 1) - even; cout<<"Count of Even numbers in a range from L to R are: "<<even<<endl; cout<<"Count of Odd numbers in a range from L to R are: "<<odd; return 0; } If we run the above code it will generate the following output − Count of Even numbers in a range from L to R are: 5 Count of Odd numbers in a range from L to R are: 6
[ { "code": null, "e": 1211, "s": 1062, "text": "We are given a range starting from L to R of integer values and the task is to calculate the count of odd numbers and the even numbers in the range." }, { "code": null, "e": 1233, "s": 1211, "text": "Input − L = 7, R = 17" }, { "code": null, "e": 1295, "s": 1233, "text": "Output − Count of Even numbers in a range from L to R are − 5" }, { "code": null, "e": 1347, "s": 1295, "text": "Count of Odd numbers in a range from L to R are − 6" }, { "code": null, "e": 1369, "s": 1347, "text": "Input − L = 1, R = 10" }, { "code": null, "e": 1431, "s": 1369, "text": "Output − Count of Even numbers in a range from L to R are − 5" }, { "code": null, "e": 1483, "s": 1431, "text": "Count of Odd numbers in a range from L to R are − 5" }, { "code": null, "e": 1520, "s": 1483, "text": "Input the range starting from L to R" }, { "code": null, "e": 1557, "s": 1520, "text": "Input the range starting from L to R" }, { "code": null, "e": 1700, "s": 1557, "text": "Pass the L and R values to the function to find out the even values and then we will calculate the odd values depending upon the return value." }, { "code": null, "e": 1843, "s": 1700, "text": "Pass the L and R values to the function to find out the even values and then we will calculate the odd values depending upon the return value." }, { "code": null, "e": 1877, "s": 1843, "text": "Start loop FOR from i to L till R" }, { "code": null, "e": 1911, "s": 1877, "text": "Start loop FOR from i to L till R" }, { "code": null, "e": 1979, "s": 1911, "text": "Inside the loop, check IF i%2==0 then increment the even count by 1" }, { "code": null, "e": 2047, "s": 1979, "text": "Inside the loop, check IF i%2==0 then increment the even count by 1" }, { "code": null, "e": 2069, "s": 2047, "text": "Return the even count" }, { "code": null, "e": 2091, "s": 2069, "text": "Return the even count" }, { "code": null, "e": 2152, "s": 2091, "text": "Now to calculate the odd count set odd as (R - L + 1) - even" }, { "code": null, "e": 2213, "s": 2152, "text": "Now to calculate the odd count set odd as (R - L + 1) - even" }, { "code": null, "e": 2224, "s": 2213, "text": " Live Demo" }, { "code": null, "e": 2661, "s": 2224, "text": "#include <iostream>\nusing namespace std;\nint Odd_Even(int L, int R){\n int even = 0;\n for(int i = L ;i < R ;i++){\n if(i%2==0){\n even++;\n }\n }\n return even;\n}\nint main(){\n int L = 7, R = 17;\n int even = Odd_Even(L, R);\n int odd = (R - L + 1) - even;\n cout<<\"Count of Even numbers in a range from L to R are: \"<<even<<endl;\n cout<<\"Count of Odd numbers in a range from L to R are: \"<<odd;\n return 0;\n}" }, { "code": null, "e": 2726, "s": 2661, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2829, "s": 2726, "text": "Count of Even numbers in a range from L to R are: 5\nCount of Odd numbers in a range from L to R are: 6" } ]
How to exclude a field from JSON using @Expose annotation in Java?
The Gson @Expose annotation can be used to mark a field to be exposed or not (included or not) for serialized or deserialized. The @Expose annotation can take two parameters and each parameter is a boolean which can take either the value true or false. In order to get GSON to react to the @Expose annotations we must create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, it configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation. public GsonBuilder excludeFieldsWithoutExposeAnnotation() import com.google.gson.*; import com.google.gson.annotations.*; public class JsonExcludeAnnotationTest { public static void main(String args[]) { Employee emp = new Employee("Raja", 28, 40000.00); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonStr = gson.toJson(emp); System.out.println(jsonStr); gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); jsonStr = gson.toJson(emp); System.out.println(jsonStr); } } // Employee class class Employee { @Expose(serialize = true, deserialize = true) public String name; @Expose(serialize = true, deserialize = true) public int age; @Expose(serialize = false, deserialize = false) public double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } } { "name": "Raja", "age": 28, "salary": 40000.0 } { "name": "Raja", "age": 28 }
[ { "code": null, "e": 1636, "s": 1062, "text": "The Gson @Expose annotation can be used to mark a field to be exposed or not (included or not) for serialized or deserialized. The @Expose annotation can take two parameters and each parameter is a boolean which can take either the value true or false. In order to get GSON to react to the @Expose annotations we must create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, it configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation." }, { "code": null, "e": 1694, "s": 1636, "text": "public GsonBuilder excludeFieldsWithoutExposeAnnotation()" }, { "code": null, "e": 2608, "s": 1694, "text": "import com.google.gson.*;\nimport com.google.gson.annotations.*;\npublic class JsonExcludeAnnotationTest {\n public static void main(String args[]) {\n Employee emp = new Employee(\"Raja\", 28, 40000.00);\n Gson gson = new GsonBuilder().setPrettyPrinting().create();\n String jsonStr = gson.toJson(emp);\n System.out.println(jsonStr);\n gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();\n jsonStr = gson.toJson(emp);\n System.out.println(jsonStr);\n }\n}\n// Employee class\nclass Employee {\n @Expose(serialize = true, deserialize = true)\n public String name;\n @Expose(serialize = true, deserialize = true)\n public int age;\n @Expose(serialize = false, deserialize = false)\n public double salary;\n public Employee(String name, int age, double salary) {\n this.name = name;\n this.age = age;\n this.salary = salary;\n }\n}" }, { "code": null, "e": 2692, "s": 2608, "text": "{\n \"name\": \"Raja\",\n \"age\": 28,\n \"salary\": 40000.0\n}\n{\n \"name\": \"Raja\",\n \"age\": 28\n}" } ]
How I Implemented HFSM In Python. Learning step-by-step implementation of... | by Debby Nirwan | Towards Data Science
I wanted to use the HFSM (Hierarchical Finite State Machine) in my Pacman AI Agent Implementation to fully understand the concepts and to compare it with the Behavior Tree. In my experience, after reading books and papers of some technical topics, my comprehension of the topics would greatly improve if I implemented them in code. Pacman AI is written in Python and so I tried searching HFSM implementation on Github, but couldn’t find a good one for my implementation and decided to write one and release it on Github. In this article, I want to share what I have learned when implementing it. We will see the step-by-step transformation from concepts to code. Hopefully, this is useful for you and encourages you to code and share your works. If you are not familiar with HFSM yet, you may want to read my previous post below: towardsdatascience.com Let’s get started. An HFSM consists of multiple FSMs, so we will start with implementing an FSM. An FSM consists of the following building blocks: State Event Transition We start with the first building block, state. Here is one example of a state: A state can be as simple as having just a name, but it can also have some actions associated with it such as entry, do, and exit. We can create a class of a state as follows. Our state class simply has a name, which is important to distinguish one state from another which we use for equality check in the code snippet above. We also have two lists of callbacks, for entry and exit which can be set by on_entry() and on_exit() functions. do action is not implemented because it is easier to implement it as an action in Transition which we will turn to in a moment. start() and stop() functions are used by the transition later to enter and exit a state when a transition occurs. The next building block is an Event, it only has a name, so it is quite simple. The last building block in an FSM is a Transition. Transition is depicted by an arrow in the picture below. It has four components: EventConditionActionState(s) Event Condition Action State(s) When an Event is raised, a Transition will occur if all of the following are satisfied: The current state matches “state 1” There is no condition set or the condition holds (returns True) If the action exists, it will be executed. There are three types of transitions: Normal Transition: a transition from a state to another state, the one that we use most Self Transition: a transition from and to itself Null Transition: a transition that only executes the action, no entry or exit. This type of transition is useful for do action in a state We can start by creating a base class of Transition: We have everything we need for a Transition here, but the __call__() function is not implemented because it will be different for the three types. Normal Transition will look like this, where a source state is exited and the destination state is entered. Self Transition is as follows. There is no change in state, but all callbacks are called if any. And a Null Transition is as follows: We can see that a Null Transition is not really a transition because there are no exiting and entering states occurring. It only executes an action. If the action doesn’t exist, it basically does nothing. Now that we have all the building blocks for an FSM, we are ready to implement the main class the StateMachine class. An FSM (or, we simply call the class StateMachine) has a collection of: States Events and, Transitions It also has a name, because we may have multiple FSMs in HFSM and also has to track its current state. The other things that we want to add are: Exit State Initial State They are the two black circles in the picture. And finally, we also want to add an exit callback, for us to check the result of an FSM when it has finished. That is the full implementation of an FSM. We have a couple of functions to add states, events, and transitions into the FSM. In the add_xxx_transition() functions we return the transition object so that the caller can simply add condition and action like in the example below: The most important function is trigger_event() which checks the conditions whether a transition can occur or not and if it is an exit state, whether an exit callback should be called or not. That’s all we need for an FSM Implementation. Next, we turn our focus on the implementation of HFSM. An example of HFSM is shown in the picture below, it is an HFSM version of the FSM we saw earlier. To transform our FSM implementation into HFSM implementation we have to: be able to add a child state machine to a statestart a child state machine when parent state is enteredstop a child state machine when parent state is exitedpropagate an event to the lower-level state machine(s) be able to add a child state machine to a state start a child state machine when parent state is entered stop a child state machine when parent state is exited propagate an event to the lower-level state machine(s) First, we need to modify our State Class to support (1), (2), and (3): And finally, we need to update the trigger_event() function in StateMachine implementation to be able to propagate an event. Hopefully, this walkthrough is useful for you to see how I implemented HFSM from concepts to code and you can learn something from it. Just like I learned when I implemented it. The full implementation can be seen in the repository hosted in Github below: github.com Or, if you want to use it, you can simply install it with pip install hfsm Thank you for reading!
[ { "code": null, "e": 504, "s": 172, "text": "I wanted to use the HFSM (Hierarchical Finite State Machine) in my Pacman AI Agent Implementation to fully understand the concepts and to compare it with the Behavior Tree. In my experience, after reading books and papers of some technical topics, my comprehension of the topics would greatly improve if I implemented them in code." }, { "code": null, "e": 693, "s": 504, "text": "Pacman AI is written in Python and so I tried searching HFSM implementation on Github, but couldn’t find a good one for my implementation and decided to write one and release it on Github." }, { "code": null, "e": 918, "s": 693, "text": "In this article, I want to share what I have learned when implementing it. We will see the step-by-step transformation from concepts to code. Hopefully, this is useful for you and encourages you to code and share your works." }, { "code": null, "e": 1002, "s": 918, "text": "If you are not familiar with HFSM yet, you may want to read my previous post below:" }, { "code": null, "e": 1025, "s": 1002, "text": "towardsdatascience.com" }, { "code": null, "e": 1044, "s": 1025, "text": "Let’s get started." }, { "code": null, "e": 1122, "s": 1044, "text": "An HFSM consists of multiple FSMs, so we will start with implementing an FSM." }, { "code": null, "e": 1172, "s": 1122, "text": "An FSM consists of the following building blocks:" }, { "code": null, "e": 1178, "s": 1172, "text": "State" }, { "code": null, "e": 1184, "s": 1178, "text": "Event" }, { "code": null, "e": 1195, "s": 1184, "text": "Transition" }, { "code": null, "e": 1274, "s": 1195, "text": "We start with the first building block, state. Here is one example of a state:" }, { "code": null, "e": 1449, "s": 1274, "text": "A state can be as simple as having just a name, but it can also have some actions associated with it such as entry, do, and exit. We can create a class of a state as follows." }, { "code": null, "e": 1600, "s": 1449, "text": "Our state class simply has a name, which is important to distinguish one state from another which we use for equality check in the code snippet above." }, { "code": null, "e": 1840, "s": 1600, "text": "We also have two lists of callbacks, for entry and exit which can be set by on_entry() and on_exit() functions. do action is not implemented because it is easier to implement it as an action in Transition which we will turn to in a moment." }, { "code": null, "e": 1954, "s": 1840, "text": "start() and stop() functions are used by the transition later to enter and exit a state when a transition occurs." }, { "code": null, "e": 2034, "s": 1954, "text": "The next building block is an Event, it only has a name, so it is quite simple." }, { "code": null, "e": 2142, "s": 2034, "text": "The last building block in an FSM is a Transition. Transition is depicted by an arrow in the picture below." }, { "code": null, "e": 2166, "s": 2142, "text": "It has four components:" }, { "code": null, "e": 2195, "s": 2166, "text": "EventConditionActionState(s)" }, { "code": null, "e": 2201, "s": 2195, "text": "Event" }, { "code": null, "e": 2211, "s": 2201, "text": "Condition" }, { "code": null, "e": 2218, "s": 2211, "text": "Action" }, { "code": null, "e": 2227, "s": 2218, "text": "State(s)" }, { "code": null, "e": 2315, "s": 2227, "text": "When an Event is raised, a Transition will occur if all of the following are satisfied:" }, { "code": null, "e": 2351, "s": 2315, "text": "The current state matches “state 1”" }, { "code": null, "e": 2415, "s": 2351, "text": "There is no condition set or the condition holds (returns True)" }, { "code": null, "e": 2458, "s": 2415, "text": "If the action exists, it will be executed." }, { "code": null, "e": 2496, "s": 2458, "text": "There are three types of transitions:" }, { "code": null, "e": 2584, "s": 2496, "text": "Normal Transition: a transition from a state to another state, the one that we use most" }, { "code": null, "e": 2633, "s": 2584, "text": "Self Transition: a transition from and to itself" }, { "code": null, "e": 2771, "s": 2633, "text": "Null Transition: a transition that only executes the action, no entry or exit. This type of transition is useful for do action in a state" }, { "code": null, "e": 2824, "s": 2771, "text": "We can start by creating a base class of Transition:" }, { "code": null, "e": 2971, "s": 2824, "text": "We have everything we need for a Transition here, but the __call__() function is not implemented because it will be different for the three types." }, { "code": null, "e": 3079, "s": 2971, "text": "Normal Transition will look like this, where a source state is exited and the destination state is entered." }, { "code": null, "e": 3176, "s": 3079, "text": "Self Transition is as follows. There is no change in state, but all callbacks are called if any." }, { "code": null, "e": 3213, "s": 3176, "text": "And a Null Transition is as follows:" }, { "code": null, "e": 3418, "s": 3213, "text": "We can see that a Null Transition is not really a transition because there are no exiting and entering states occurring. It only executes an action. If the action doesn’t exist, it basically does nothing." }, { "code": null, "e": 3536, "s": 3418, "text": "Now that we have all the building blocks for an FSM, we are ready to implement the main class the StateMachine class." }, { "code": null, "e": 3608, "s": 3536, "text": "An FSM (or, we simply call the class StateMachine) has a collection of:" }, { "code": null, "e": 3615, "s": 3608, "text": "States" }, { "code": null, "e": 3622, "s": 3615, "text": "Events" }, { "code": null, "e": 3639, "s": 3622, "text": "and, Transitions" }, { "code": null, "e": 3742, "s": 3639, "text": "It also has a name, because we may have multiple FSMs in HFSM and also has to track its current state." }, { "code": null, "e": 3784, "s": 3742, "text": "The other things that we want to add are:" }, { "code": null, "e": 3795, "s": 3784, "text": "Exit State" }, { "code": null, "e": 3809, "s": 3795, "text": "Initial State" }, { "code": null, "e": 3966, "s": 3809, "text": "They are the two black circles in the picture. And finally, we also want to add an exit callback, for us to check the result of an FSM when it has finished." }, { "code": null, "e": 4092, "s": 3966, "text": "That is the full implementation of an FSM. We have a couple of functions to add states, events, and transitions into the FSM." }, { "code": null, "e": 4244, "s": 4092, "text": "In the add_xxx_transition() functions we return the transition object so that the caller can simply add condition and action like in the example below:" }, { "code": null, "e": 4435, "s": 4244, "text": "The most important function is trigger_event() which checks the conditions whether a transition can occur or not and if it is an exit state, whether an exit callback should be called or not." }, { "code": null, "e": 4536, "s": 4435, "text": "That’s all we need for an FSM Implementation. Next, we turn our focus on the implementation of HFSM." }, { "code": null, "e": 4635, "s": 4536, "text": "An example of HFSM is shown in the picture below, it is an HFSM version of the FSM we saw earlier." }, { "code": null, "e": 4708, "s": 4635, "text": "To transform our FSM implementation into HFSM implementation we have to:" }, { "code": null, "e": 4920, "s": 4708, "text": "be able to add a child state machine to a statestart a child state machine when parent state is enteredstop a child state machine when parent state is exitedpropagate an event to the lower-level state machine(s)" }, { "code": null, "e": 4968, "s": 4920, "text": "be able to add a child state machine to a state" }, { "code": null, "e": 5025, "s": 4968, "text": "start a child state machine when parent state is entered" }, { "code": null, "e": 5080, "s": 5025, "text": "stop a child state machine when parent state is exited" }, { "code": null, "e": 5135, "s": 5080, "text": "propagate an event to the lower-level state machine(s)" }, { "code": null, "e": 5206, "s": 5135, "text": "First, we need to modify our State Class to support (1), (2), and (3):" }, { "code": null, "e": 5331, "s": 5206, "text": "And finally, we need to update the trigger_event() function in StateMachine implementation to be able to propagate an event." }, { "code": null, "e": 5509, "s": 5331, "text": "Hopefully, this walkthrough is useful for you to see how I implemented HFSM from concepts to code and you can learn something from it. Just like I learned when I implemented it." }, { "code": null, "e": 5587, "s": 5509, "text": "The full implementation can be seen in the repository hosted in Github below:" }, { "code": null, "e": 5598, "s": 5587, "text": "github.com" }, { "code": null, "e": 5656, "s": 5598, "text": "Or, if you want to use it, you can simply install it with" }, { "code": null, "e": 5673, "s": 5656, "text": "pip install hfsm" } ]
Introduction to Domain Name - GeeksforGeeks
22 Dec, 2020 Every computer on the Internet has an address which is unique in nature. It is a string of numbers and is referred to as IP address. To communicate with each other, computers identify another computer via its IP address. It is represented in either dotted decimal notation or in binary decimal notation. Example: The address 172.16.122.204 when represented like these in dotted-decimal notation and it can be converted into binary notation. After conversion, it becomes 10101100 00010000 01111010 11001100.But it is difficult for humans to remember this IP address. Thus to find the location on the Internet easily, DNS was invented. DNS stands for Domain Name Server. It implements a distributed database which translates IP address into a unique alphanumeric address which is referred to as Domain Names. Basically, a domain name is the sequence of letters and or numbers separated by one or more period (“.”). It is just like a pointer to a unique IP address on the computer network. As an analogy one can consider Domain name as address and DNS as address book of the Internet. Example-1:Lets us consider an example for domain name; www.google.com, www.yahoo.com In this “yahoo.com” is called domain name.“www.” tells the browser to look for World Wide Web Interface for that domain. As from the above example, it is clear that domain names are easy to remember than an IP address. Example-2:Assume that the IP address of www.yahoo.com is 69.147.76.15. It is easy to remember www.yahoo.com as compared to IP address 69.147.76.15. Thus, we can say like these; domain name refers to the string of letters associated with an IP address and DNS is a mechanism used to convert an IP address to the domain name.Types of Domain Names :DNS has organized all the domain names in a hierarchical structure. At the top of this hierarchy come various Top-level domains followed by second and third-level domains and sub-domains. All these types of domain names are listed as follows – Top Level Domains (TLD) :The Top Level Domains are at the highest level in DNS structure of the Internet. It is sometimes also referred to as an extension. It is further categorized into- country code TLDs and generic TLDs which Country is described as follows – Country code Top Level Domain (ccDLDs) :It consists of two-letter domains that include one entry for every country. Example – .in for India, .au for Australia, .us for United Nations, .jp for Japan etc. To target the local audience it is used by companies and organizations . Only the residents of the country are allowed to is their specified ccTLD but now some countries allowed the users outside their country to register their corresponding ccTLDs. Generic Top Level Domains (gTLDs) :These are open for registration to all the users regardless of their citizenship, residence or age. Some of the gTLD s are .com for commercial sites, .net for network companies, .biz for business, .org for organizations, .edu for education. There are various other levels which are below TLDs –Second Level :It is just below the TLD in the DNS hierarchy. It is also named as the label. Example: in .co.in, .co is the second-level domain under the .in in ccTLD. Third Level :It is directly below the second level. Example: in yahoo.co.in, .yahoo is the third level domain under the second level domain .co which is under the .in ccTLD. Sub-domain :It is the part of a higher domain name in DNS hierarchy. Example: yahoo.com comprises a subdomain of the .com domain, and login.yahoo.com comprises a subdomain of the domain .yahoo.com. Advantages of Domain Name : User not need to remember the IP address. More reliable and secure. Disadvantages of Domain Name : IP address changes due to several reasons, due to this IP address of the computer get changed but DNS may have cached previous IP which will lead to give us wrong information. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Data encryption standard (DES) | Set 1 Types of Network Topology Socket Programming in Python UDP Server-Client implementation in C TCP 3-Way Handshake Process Differences between IPv4 and IPv6 Socket Programming in Java Hamming Code in Computer Network Types of area networks - LAN, MAN and WAN Error Detection in Computer Networks
[ { "code": null, "e": 24011, "s": 23983, "text": "\n22 Dec, 2020" }, { "code": null, "e": 25093, "s": 24011, "text": "Every computer on the Internet has an address which is unique in nature. It is a string of numbers and is referred to as IP address. To communicate with each other, computers identify another computer via its IP address. It is represented in either dotted decimal notation or in binary decimal notation. Example: The address 172.16.122.204 when represented like these in dotted-decimal notation and it can be converted into binary notation. After conversion, it becomes 10101100 00010000 01111010 11001100.But it is difficult for humans to remember this IP address. Thus to find the location on the Internet easily, DNS was invented. DNS stands for Domain Name Server. It implements a distributed database which translates IP address into a unique alphanumeric address which is referred to as Domain Names. Basically, a domain name is the sequence of letters and or numbers separated by one or more period (“.”). It is just like a pointer to a unique IP address on the computer network. As an analogy one can consider Domain name as address and DNS as address book of the Internet." }, { "code": null, "e": 25148, "s": 25093, "text": "Example-1:Lets us consider an example for domain name;" }, { "code": null, "e": 25179, "s": 25148, "text": "www.google.com, www.yahoo.com " }, { "code": null, "e": 25300, "s": 25179, "text": "In this “yahoo.com” is called domain name.“www.” tells the browser to look for World Wide Web Interface for that domain." }, { "code": null, "e": 25398, "s": 25300, "text": "As from the above example, it is clear that domain names are easy to remember than an IP address." }, { "code": null, "e": 25546, "s": 25398, "text": "Example-2:Assume that the IP address of www.yahoo.com is 69.147.76.15. It is easy to remember www.yahoo.com as compared to IP address 69.147.76.15." }, { "code": null, "e": 25988, "s": 25546, "text": "Thus, we can say like these; domain name refers to the string of letters associated with an IP address and DNS is a mechanism used to convert an IP address to the domain name.Types of Domain Names :DNS has organized all the domain names in a hierarchical structure. At the top of this hierarchy come various Top-level domains followed by second and third-level domains and sub-domains. All these types of domain names are listed as follows –" }, { "code": null, "e": 26251, "s": 25988, "text": "Top Level Domains (TLD) :The Top Level Domains are at the highest level in DNS structure of the Internet. It is sometimes also referred to as an extension. It is further categorized into- country code TLDs and generic TLDs which Country is described as follows –" }, { "code": null, "e": 26704, "s": 26251, "text": "Country code Top Level Domain (ccDLDs) :It consists of two-letter domains that include one entry for every country. Example – .in for India, .au for Australia, .us for United Nations, .jp for Japan etc. To target the local audience it is used by companies and organizations . Only the residents of the country are allowed to is their specified ccTLD but now some countries allowed the users outside their country to register their corresponding ccTLDs." }, { "code": null, "e": 26980, "s": 26704, "text": "Generic Top Level Domains (gTLDs) :These are open for registration to all the users regardless of their citizenship, residence or age. Some of the gTLD s are .com for commercial sites, .net for network companies, .biz for business, .org for organizations, .edu for education." }, { "code": null, "e": 27200, "s": 26980, "text": "There are various other levels which are below TLDs –Second Level :It is just below the TLD in the DNS hierarchy. It is also named as the label. Example: in .co.in, .co is the second-level domain under the .in in ccTLD." }, { "code": null, "e": 27374, "s": 27200, "text": "Third Level :It is directly below the second level. Example: in yahoo.co.in, .yahoo is the third level domain under the second level domain .co which is under the .in ccTLD." }, { "code": null, "e": 27572, "s": 27374, "text": "Sub-domain :It is the part of a higher domain name in DNS hierarchy. Example: yahoo.com comprises a subdomain of the .com domain, and login.yahoo.com comprises a subdomain of the domain .yahoo.com." }, { "code": null, "e": 27600, "s": 27572, "text": "Advantages of Domain Name :" }, { "code": null, "e": 27642, "s": 27600, "text": "User not need to remember the IP address." }, { "code": null, "e": 27668, "s": 27642, "text": "More reliable and secure." }, { "code": null, "e": 27699, "s": 27668, "text": "Disadvantages of Domain Name :" }, { "code": null, "e": 27875, "s": 27699, "text": "IP address changes due to several reasons, due to this IP address of the computer get changed but DNS may have cached previous IP which will lead to give us wrong information." }, { "code": null, "e": 27893, "s": 27875, "text": "Computer Networks" }, { "code": null, "e": 27911, "s": 27893, "text": "Computer Networks" }, { "code": null, "e": 28009, "s": 27911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28018, "s": 28009, "text": "Comments" }, { "code": null, "e": 28031, "s": 28018, "text": "Old Comments" }, { "code": null, "e": 28070, "s": 28031, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 28096, "s": 28070, "text": "Types of Network Topology" }, { "code": null, "e": 28125, "s": 28096, "text": "Socket Programming in Python" }, { "code": null, "e": 28163, "s": 28125, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28191, "s": 28163, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 28225, "s": 28191, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 28252, "s": 28225, "text": "Socket Programming in Java" }, { "code": null, "e": 28285, "s": 28252, "text": "Hamming Code in Computer Network" }, { "code": null, "e": 28327, "s": 28285, "text": "Types of area networks - LAN, MAN and WAN" } ]
How to Reduce the Size of a Pandas Dataframe in Python | by Nicklas Ankarstad | Towards Data Science
Whether you are building a model for a hobby project or for work purposes, chances are that your first attempt will include opening up a jupyter notebook and reading in some data. Eventually you will undoubtly run into the memory issues with your notebook. Before you start dropping rows or try complex sampling techniques to reduce the size of your data, you should check the structure of the data. To explore how we can reduce the size of a dataset, we need some sample data. For this tutorial, I am using an old dataset I created for the Future Sales Prediction contest on Kaggle (here is my write-up on pre-processing the data). Once fully joined and feature engineered, the dataset has 58 columns and 11,128,050 records. That’s a lot of data to fit into a small laptop. We need a solution to reduce the size of the data. Before we begin, we should check learn a bit more about the data. One function that is very helpful to use is df.info() from the pandas library. df.info(memory_usage = "deep") This code snippit returns the below output: <class 'pandas.core.frame.DataFrame'>Int64Index: 11128050 entries, 0 to 11128049Data columns (total 58 columns): # Column Dtype --- ------ ----- 0 date_block_num int64 1 item_id int64 2 shop_id int64 3 target float64 4 item_name object 5 item_category_id int64 6 Category_type object 7 City object 8 Month_End_Date datetime64[ns] 9 Number_of_Mondays int64 10 Number_of_Tuesdays int64 11 Number_of_Wednesdays int64 12 Number_of_Thursdays int64 13 Number_of_Fridays int64 14 Number_of_Saturdays int64 15 Number_of_Sundays int64 16 Year int64 17 Month int64 18 Days_in_Month int64 19 min_item_sale_date_block_num int64 20 Months_Since_Item_First_Sold int64 21 avg_first_months_sales_by_item_category_id float64 22 avg_first_months_sales_by_item_category_and_shop float64 23 target_lag_1 float64 24 target_lag_2 float64 25 target_lag_3 float64 26 target_lag_4 float64 27 target_lag_5 float64 28 target_lag_6 float64 29 target_lag_12 float64 30 avg_monthly_by_item_lag_1 float64 31 avg_monthly_by_item_lag_2 float64 32 avg_monthly_by_item_lag_3 float64 33 avg_monthly_by_item_lag_6 float64 34 avg_monthly_by_item_lag_12 float64 35 avg_monthly_by_shop_lag_1 float64 36 avg_monthly_by_shop_lag_2 float64 37 avg_monthly_by_shop_lag_3 float64 38 avg_monthly_by_shop_lag_6 float64 39 avg_monthly_by_shop_lag_12 float64 40 avg_monthly_by_category_lag_1 float64 41 avg_monthly_by_category_lag_2 float64 42 avg_monthly_by_category_lag_3 float64 43 avg_monthly_by_category_lag_6 float64 44 avg_monthly_by_category_lag_12 float64 45 avg_monthly_by_city_lag_1 float64 46 avg_monthly_by_city_lag_2 float64 47 avg_monthly_by_city_lag_3 float64 48 avg_monthly_by_city_lag_6 float64 49 avg_monthly_by_city_lag_12 float64 50 item_price_lag_1 float64 51 item_price_lag_2 float64 52 item_price_lag_3 float64 53 item_price_lag_4 float64 54 item_price_lag_5 float64 55 item_price_lag_6 float64 56 target_3_month_avg float64 57 target_6_month_avg float64 dtypes: datetime64[ns](1), float64(38), int64(16), object(3)memory usage: 7.6 GB With the df.info we get the following information: The number of rows or entries The number of columns The index and name of each column The data type of each column Total memory usage of the data frame How many columns belong to each data type Looking closely at this table, we see numbers behind each data type illustrating the bits they use. Since a lot of these are listed as either int64 or float64, we can probably reduce them down to smaller space datatypes like int16 or float8. Downcasting means we reduce the datatypes of each feature to its lowest possible type. ## downcasting loopfor column in df: if df[column].dtype == ‘float64’: df[column]=pd.to_numeric(df[column], downcast=’float’) if df[column].dtype == ‘int64’: df[column]=pd.to_numeric(all_data[column], downcast=’integer’)## dropping an unused columndf = df.drop('item_name',axis =1) We can check the size of the dataframe again. <class 'pandas.core.frame.DataFrame'>Int64Index: 11128050 entries, 0 to 11128049Data columns (total 57 columns): # Column Dtype --- ------ ----- 0 date_block_num int8 1 item_id int16 2 shop_id int8 3 target float32 4 item_category_id int8 5 Category_type object 6 City object 7 Month_End_Date datetime64[ns] 8 Number_of_Mondays int8 9 Number_of_Tuesdays int8 10 Number_of_Wednesdays int8 11 Number_of_Thursdays int8 12 Number_of_Fridays int8 13 Number_of_Saturdays int8 14 Number_of_Sundays int8 15 Year int16 16 Month int8 17 Days_in_Month int8 18 min_item_sale_date_block_num int8 19 Months_Since_Item_First_Sold int8 20 avg_first_months_sales_by_item_category_id float32 21 avg_first_months_sales_by_item_category_and_shop float32 22 target_lag_1 float32 23 target_lag_2 float32 24 target_lag_3 float32 25 target_lag_4 float32 26 target_lag_5 float32 27 target_lag_6 float32 28 target_lag_12 float32 29 avg_monthly_by_item_lag_1 float32 30 avg_monthly_by_item_lag_2 float32 31 avg_monthly_by_item_lag_3 float32 32 avg_monthly_by_item_lag_6 float32 33 avg_monthly_by_item_lag_12 float32 34 avg_monthly_by_shop_lag_1 float32 35 avg_monthly_by_shop_lag_2 float32 36 avg_monthly_by_shop_lag_3 float32 37 avg_monthly_by_shop_lag_6 float32 38 avg_monthly_by_shop_lag_12 float32 39 avg_monthly_by_category_lag_1 float32 40 avg_monthly_by_category_lag_2 float32 41 avg_monthly_by_category_lag_3 float32 42 avg_monthly_by_category_lag_6 float32 43 avg_monthly_by_category_lag_12 float32 44 avg_monthly_by_city_lag_1 float32 45 avg_monthly_by_city_lag_2 float32 46 avg_monthly_by_city_lag_3 float32 47 avg_monthly_by_city_lag_6 float32 48 avg_monthly_by_city_lag_12 float32 49 item_price_lag_1 float32 50 item_price_lag_2 float32 51 item_price_lag_3 float32 52 item_price_lag_4 float32 53 item_price_lag_5 float32 54 item_price_lag_6 float32 55 target_3_month_avg float32 56 target_6_month_avg float32 dtypes: datetime64[ns](1), float32(38), int16(2), int8(14), object(2)memory usage: 3.2 GB We see that we now have several 8, 16 and 32 bit columns and we have effectively cut the size of our dataframe in half by simply changing the data types. What’s even more interesting is that the memory usage of the dataframe is down to 3.2gb. This is roughly half of the 7.6gb we had when we first started. With this type of memory reduction, we can load more data into smaller machines, which ultimately reduces costs. In this tutorial, we loaded 11 million record dataset into a pandas dataframe. We learned how to check the size and structure of the data by using the .info() function within pandas. This gave us useful information like the number of rows and columns, the size memory usage of the dataframe and the data type of each column. We learned about downcasting, which we used to cut the size of our dataframe in half allowing us to use less memory and do more with our data.
[ { "code": null, "e": 572, "s": 172, "text": "Whether you are building a model for a hobby project or for work purposes, chances are that your first attempt will include opening up a jupyter notebook and reading in some data. Eventually you will undoubtly run into the memory issues with your notebook. Before you start dropping rows or try complex sampling techniques to reduce the size of your data, you should check the structure of the data." }, { "code": null, "e": 998, "s": 572, "text": "To explore how we can reduce the size of a dataset, we need some sample data. For this tutorial, I am using an old dataset I created for the Future Sales Prediction contest on Kaggle (here is my write-up on pre-processing the data). Once fully joined and feature engineered, the dataset has 58 columns and 11,128,050 records. That’s a lot of data to fit into a small laptop. We need a solution to reduce the size of the data." }, { "code": null, "e": 1143, "s": 998, "text": "Before we begin, we should check learn a bit more about the data. One function that is very helpful to use is df.info() from the pandas library." }, { "code": null, "e": 1174, "s": 1143, "text": "df.info(memory_usage = \"deep\")" }, { "code": null, "e": 1218, "s": 1174, "text": "This code snippit returns the below output:" }, { "code": null, "e": 5551, "s": 1218, "text": "<class 'pandas.core.frame.DataFrame'>Int64Index: 11128050 entries, 0 to 11128049Data columns (total 58 columns): # Column Dtype --- ------ ----- 0 date_block_num int64 1 item_id int64 2 shop_id int64 3 target float64 4 item_name object 5 item_category_id int64 6 Category_type object 7 City object 8 Month_End_Date datetime64[ns] 9 Number_of_Mondays int64 10 Number_of_Tuesdays int64 11 Number_of_Wednesdays int64 12 Number_of_Thursdays int64 13 Number_of_Fridays int64 14 Number_of_Saturdays int64 15 Number_of_Sundays int64 16 Year int64 17 Month int64 18 Days_in_Month int64 19 min_item_sale_date_block_num int64 20 Months_Since_Item_First_Sold int64 21 avg_first_months_sales_by_item_category_id float64 22 avg_first_months_sales_by_item_category_and_shop float64 23 target_lag_1 float64 24 target_lag_2 float64 25 target_lag_3 float64 26 target_lag_4 float64 27 target_lag_5 float64 28 target_lag_6 float64 29 target_lag_12 float64 30 avg_monthly_by_item_lag_1 float64 31 avg_monthly_by_item_lag_2 float64 32 avg_monthly_by_item_lag_3 float64 33 avg_monthly_by_item_lag_6 float64 34 avg_monthly_by_item_lag_12 float64 35 avg_monthly_by_shop_lag_1 float64 36 avg_monthly_by_shop_lag_2 float64 37 avg_monthly_by_shop_lag_3 float64 38 avg_monthly_by_shop_lag_6 float64 39 avg_monthly_by_shop_lag_12 float64 40 avg_monthly_by_category_lag_1 float64 41 avg_monthly_by_category_lag_2 float64 42 avg_monthly_by_category_lag_3 float64 43 avg_monthly_by_category_lag_6 float64 44 avg_monthly_by_category_lag_12 float64 45 avg_monthly_by_city_lag_1 float64 46 avg_monthly_by_city_lag_2 float64 47 avg_monthly_by_city_lag_3 float64 48 avg_monthly_by_city_lag_6 float64 49 avg_monthly_by_city_lag_12 float64 50 item_price_lag_1 float64 51 item_price_lag_2 float64 52 item_price_lag_3 float64 53 item_price_lag_4 float64 54 item_price_lag_5 float64 55 item_price_lag_6 float64 56 target_3_month_avg float64 57 target_6_month_avg float64 dtypes: datetime64[ns](1), float64(38), int64(16), object(3)memory usage: 7.6 GB" }, { "code": null, "e": 5602, "s": 5551, "text": "With the df.info we get the following information:" }, { "code": null, "e": 5632, "s": 5602, "text": "The number of rows or entries" }, { "code": null, "e": 5654, "s": 5632, "text": "The number of columns" }, { "code": null, "e": 5688, "s": 5654, "text": "The index and name of each column" }, { "code": null, "e": 5717, "s": 5688, "text": "The data type of each column" }, { "code": null, "e": 5754, "s": 5717, "text": "Total memory usage of the data frame" }, { "code": null, "e": 5796, "s": 5754, "text": "How many columns belong to each data type" }, { "code": null, "e": 5896, "s": 5796, "text": "Looking closely at this table, we see numbers behind each data type illustrating the bits they use." }, { "code": null, "e": 6125, "s": 5896, "text": "Since a lot of these are listed as either int64 or float64, we can probably reduce them down to smaller space datatypes like int16 or float8. Downcasting means we reduce the datatypes of each feature to its lowest possible type." }, { "code": null, "e": 6407, "s": 6125, "text": "## downcasting loopfor column in df: if df[column].dtype == ‘float64’: df[column]=pd.to_numeric(df[column], downcast=’float’) if df[column].dtype == ‘int64’: df[column]=pd.to_numeric(all_data[column], downcast=’integer’)## dropping an unused columndf = df.drop('item_name',axis =1)" }, { "code": null, "e": 6453, "s": 6407, "text": "We can check the size of the dataframe again." }, { "code": null, "e": 10726, "s": 6453, "text": "<class 'pandas.core.frame.DataFrame'>Int64Index: 11128050 entries, 0 to 11128049Data columns (total 57 columns): # Column Dtype --- ------ ----- 0 date_block_num int8 1 item_id int16 2 shop_id int8 3 target float32 4 item_category_id int8 5 Category_type object 6 City object 7 Month_End_Date datetime64[ns] 8 Number_of_Mondays int8 9 Number_of_Tuesdays int8 10 Number_of_Wednesdays int8 11 Number_of_Thursdays int8 12 Number_of_Fridays int8 13 Number_of_Saturdays int8 14 Number_of_Sundays int8 15 Year int16 16 Month int8 17 Days_in_Month int8 18 min_item_sale_date_block_num int8 19 Months_Since_Item_First_Sold int8 20 avg_first_months_sales_by_item_category_id float32 21 avg_first_months_sales_by_item_category_and_shop float32 22 target_lag_1 float32 23 target_lag_2 float32 24 target_lag_3 float32 25 target_lag_4 float32 26 target_lag_5 float32 27 target_lag_6 float32 28 target_lag_12 float32 29 avg_monthly_by_item_lag_1 float32 30 avg_monthly_by_item_lag_2 float32 31 avg_monthly_by_item_lag_3 float32 32 avg_monthly_by_item_lag_6 float32 33 avg_monthly_by_item_lag_12 float32 34 avg_monthly_by_shop_lag_1 float32 35 avg_monthly_by_shop_lag_2 float32 36 avg_monthly_by_shop_lag_3 float32 37 avg_monthly_by_shop_lag_6 float32 38 avg_monthly_by_shop_lag_12 float32 39 avg_monthly_by_category_lag_1 float32 40 avg_monthly_by_category_lag_2 float32 41 avg_monthly_by_category_lag_3 float32 42 avg_monthly_by_category_lag_6 float32 43 avg_monthly_by_category_lag_12 float32 44 avg_monthly_by_city_lag_1 float32 45 avg_monthly_by_city_lag_2 float32 46 avg_monthly_by_city_lag_3 float32 47 avg_monthly_by_city_lag_6 float32 48 avg_monthly_by_city_lag_12 float32 49 item_price_lag_1 float32 50 item_price_lag_2 float32 51 item_price_lag_3 float32 52 item_price_lag_4 float32 53 item_price_lag_5 float32 54 item_price_lag_6 float32 55 target_3_month_avg float32 56 target_6_month_avg float32 dtypes: datetime64[ns](1), float32(38), int16(2), int8(14), object(2)memory usage: 3.2 GB" }, { "code": null, "e": 10880, "s": 10726, "text": "We see that we now have several 8, 16 and 32 bit columns and we have effectively cut the size of our dataframe in half by simply changing the data types." }, { "code": null, "e": 11146, "s": 10880, "text": "What’s even more interesting is that the memory usage of the dataframe is down to 3.2gb. This is roughly half of the 7.6gb we had when we first started. With this type of memory reduction, we can load more data into smaller machines, which ultimately reduces costs." }, { "code": null, "e": 11471, "s": 11146, "text": "In this tutorial, we loaded 11 million record dataset into a pandas dataframe. We learned how to check the size and structure of the data by using the .info() function within pandas. This gave us useful information like the number of rows and columns, the size memory usage of the dataframe and the data type of each column." } ]
Beta Geometric Negative Binomial Distribution — CLTV Prediction Model | by Sarit Maitra | Towards Data Science
ERROR: type should be string, got "https://sarit-maitra.medium.com/membership\nCustomer life time value (CLTV) is one of the most important metric to modern customer centric business scenario. It is the metric indicating the total revenue a business can reasonably expect from a single customer during the entire relationship. With CLTV business not only quantify the relationship but prioritize the CRM activity and take necessary steps to keep the existing customers happy. It also helps companies to focus on those potential customers who can bring in the more revenue in the future.\n80% of the effect comes from 20% of the causes, this is known as 80/20 rule or Pareto principle...Vilfredo Pareto.\nIf we put Pareto’s principle in business context, we can safely assume that 20% key customers are contributing 80% is business revenue. A number of studies have developed scoring mechanisms (e.g. regression models to predict a customer’s future behavior). The measures of a customer’s past behavior are key predictors of their future behavior in all the empirical analysis. It is common practice to summarize a customer’s past behavior by investigating the Recency, Frequency & Monetary (RFM) characteristics.\nLet us use some simple equations as below:\nCustomer Value = Average Order Value (AOV)* Purchase Frequency\nChurn Rate: Churn Rate is the % of customers who have not ordered again.\nCustomer Lifetime = 1/ churn rate\nChurn Rate= 1-Repeat Rate\nThe above formulas may look quite simple; however, complexity in terms of predictive analytics involved in measuring CLTV where future sales and $ values to be predicted given historical data. This can be done either using regression techniques or probabilistic modeling approach.\nWe shall target a probabilistic model for predicting CLTV in non-contractual setting on an individual level of business. Using the results of this exercise, managers should be able to:\nDistinguish active customers from inactive customers,\nGenerate transaction forecasts for individual customers,\nPredict the purchase volume of the entire customer base.\nThe stochastic model presented here, featuring Beta Geometric Negative Binomial Distribution (BG/NBD) framework to capture the flow of transactions over time. BG/NBD portrays the story being about how/when customers become inactive.\nThe BG/NBD require only two pieces of information about each customer’s past purchasing history: “recency” (when the last transaction occurred) and “frequency” (how many transactions was made in a specified time period). The notation used to represent this information is [X = x, t(x), T], where x is the number of transactions observed in the time period (0, T) and t(x) (0 < t(x) ≤T) is the time of the last transaction. Using these two key summary statistics, SMC(2) derive expressions for a number of managerially relevant quantities, such as:\nE[X(t)], the expected number of transactions in a time period of length t, which is central to computing the expected transaction volume for the whole customer base over time.\nP[X(t) = x], the probability of observing x transactions in a time period of length t.\nE[Y (t)| X = x, t(x), T], the expected number of transactions in the period (T,T + t] for an individual with observed behavior (X = x, tx, T).\nTherefore, customers will purchase at a randomly distributed interval within a time range. After each purchase they have a certain probability of dying or becoming inactive. Each customer is different and have varying purchase intervals and probability of going inactive.\nLet’s explore the data.\nFrequency (F) is the number of repeat purchases the customer has made.\nT represents the age of the customer which is equal to the duration between a customer’s first purchase and the end of the period under study.\nRecency (R) is the age of the customer when they made their most recent purchases. This is equal to the duration between a customer’s first purchase and their latest purchase.\nMonetary Value\nAfter doing the necessary cleaning and creating a new data frame containing CustomerID, InvoiceDate (remove the time) and adding a new column (‘sales’) :\ndata[‘InvoiceDate’] = pd.to_datetime(data[‘InvoiceDate’]).dt.datedata = data[pd.notnull(data[‘CustomerID’])]data = data[(data[‘Quantity’]>0)]data[‘Sales’] = data[‘Quantity’] * data[‘UnitPrice’]cols_of_interest = [‘CustomerID’, ‘InvoiceDate’, ‘Sales’]data = data[cols_of_interest]print(data.head())print(data[‘CustomerID’].nunique())\nWe can make some observations here. There are 4339 customers and 12346 made single purchase, so the F and R are 0, and the T is 325 days.\ndf[‘frequency’].plot(kind=’hist’, bins=50)print(df[‘frequency’].describe())print(sum(df[‘frequency’] == 0)/float(len(data)))\nAs shown, both frequency and recency are distributed quite near 0. Among all customers, >38% of them only made zero repeat purchase while the rest of the sample (62%) is divided into two equal parts: 31% of the customer base makes one repeat purchase while the other 31% of the customer base makes more than one repeat purchase. Similarly, for Recency, most customers have made their last purchase early in their lifetime and then became inactive. Indeed, the last repeat purchase that half our customers will make is within less than a year (252 days to be precise), since their first purchase for 75th quantile.\nWe first need to fit the customer probability model to the data so that it picks up on their behaviors and pattern. This is done by looking at each individual’s Frequency, Recency and Age and adjusting its parameters so that it better reflects the intervals in which our customer-base purchases.\nThe parameters also vary across different customers so it is calculated over two distributions for a more accurate and flexible fit of the data. Mathematically, this is done by taking the expectation of the equation over both distributions.\nbgf = BetaGeoFitter(penalizer_coef=0.0)bgf.fit(df[‘frequency’], df[‘recency’], df[‘T’], )print (bgf)# Plotgbd = beta.rvs(bgf.params_[‘a’], bgf.params_[‘b’], size = 50000)ggd = gamma.rvs(bgf.params_[‘r’], scale=1./bgf.params_[‘alpha’], size = 50000)plt.figure(figsize=(14,4))plt.subplot(121)plt.title(‘Heterogenity of $p$’)temp = plt.hist(gbd, 20, alpha=0.75)plt.subplot(122) plt.title(‘Heterogenity of $\\lambda$’)temp = plt.hist(ggd, 20, alpha=0.75)\nFrequency/Recency matrix computes the expected number of transactions a customer is to make in the next time period, given the R(age at last purchase) and F (the number of repeat transactions made).\nThe matrix has the customer’s recency on the Y axis and the frequency on the X axis and the heatmap component is showing the predicted number of future purchases customers at intersecting points will make in one unit of time. The customers most likely to order are those who’ve placed lots of previous orders and have been seen relatively recently.\nplot_frequency_recency_matrix(bgf)\nThe RF plots maps a customer’s expected purchases by the next year and probability that they’re alive given the frequency / recency. Intuitively, we can see that customers with high frequency and recency are expected to purchase more in the future and have a higher chance of being alive. Customers in the white zone are of interest as well since they are 50/50 on leaving the company but we can still expect them to purchase about 2 to 2.5 times during the next year. These are the customers that may need a little customer servicing to come back and buy more. It is interesting to note that for a fixed recency, customer’s with more frequency are more likely to be considered dead. This is a property of the model that illustrates a clear behavioral story:\nA customer making more frequent purchases is more likely to die off if we observe a longer period of inactivity than the customers previous intervals.\nWe can see that if a customer has bought 120 times and their latest purchase (R) was when they were 120 days back, then they are you best customer (bottom-right). The coldest customers are those that in the top-right corner: they bought a lot quickly, and haven’t seen them in weeks. The tail around (20,50) represents the customers who buy infrequently, but are not seen recently, so they might buy again — we’re unsure if they are dead or just between purchases.\nWe can visualize is the probability that each customer is alive based on their frequency and recency.\nplot_probability_alive_matrix(bgf)\nCustomers who have purchased recently are almost surely “alive”. Customers who have purchased a lot but not recently, are likely to have dropped out. And the more they bought in the past, the more likely they have dropped out. They are represented in the upper-right.\nLet’s rank the customers from “highest expected purchases in the next period” to lowest. Models expose a method that will predict a customer’s expected purchases in the next period using their history.\nt = 31*3df[‘predicted_purchases’] = bgf.conditional_expected_number_of_purchases_up_to_time(t, df[‘frequency’], df[‘recency’], df[‘T’])df.sort_values(by=’predicted_purchases’).tail(10)\nListed here is our top 10 customers that the model expects them to purchase in the next 3 months. We can see that the customer who has made 131 purchases, and bought very recently, is probably going to buy again in the next period. The predicted_purchases column displays their expected number of purchases while the other three columns represent their current RFM metrics. The BG/NBD model believes these individuals will be making more purchases within the near future as they are the current best customers.\nAfter fitting the model, we’re interested in seeing how well it is able to relate to our data. The first is to compare our data versus artificial data simulated with our fitted model’s parameters.\nplot_period_transactions(bgf)\nThe two are almost identical indicating that, the model is a very good fit and predicts the number of periods in the calibration period rather well. The expected number of customers that are going to repeat purchase 0, 1, 2, 3 ... 6 times in the future. For each number of repeat purchases (x-axis), we plot both what the model predicted and what the actual numbers were. As we can see, little to no errors in the fit for up to 6 repeat purchases. Let’s do the next fact check.\nHowever, it is always a good idea to compute the overall % error which is(predicted transactions/actual transactions -1) and the % error per transactions done in the calibration period. This will help us to quantify how close to reality the model is.\nsummary_cal_holdout = calibration_and_holdout_data(data, ‘CustomerID’, ‘InvoiceDate’, calibration_period_end=’2011–06–08', observation_period_end=’2011–12–9' )print(summary_cal_holdout.head())\nbgf.fit(summary_cal_holdout[‘frequency_cal’], summary_cal_holdout[‘recency_cal’], summary_cal_holdout[‘T_cal’])plot_calibration_purchases_vs_holdout_purchases(bgf, summary_cal_holdout)\nIn this plot, we separate the data into both a in-sample (calibration) and validation (holdout) period. The sample period consists from the beginning to 2011–06–08; the validation period spans the rest of the duration ( 2011–06–09 to 2011–12–09). The plot groups all customers in the calibration period by their number of repeat purchases (x-axis) and then averages over their repeat purchases in the holdout period (y-axis). The plot groups all customers in the calibration period by their number of repeat purchases (x-axis) and then averages over their repeat purchases in the holdout period (y-axis). The orange and blue line presents the model prediction and actual result of the y-axis respectively. The lines are quite close to each other indicating that, the model is not far off at predicting the number of orders each customer will make.\nThe model is able to accurately predict the customer base’s behavior out of the sample, the model under-estimates at 4 purchases and after 5 purchases.\nBased on customer history, we can now predict what an individual’s future purchases might look like:\nt = 10individual = df.loc[12347]bgf.predict(t, individual[‘frequency’], individual[‘recency’], individual[‘T’])\n0.15727742663038222\nThe model predicts that customer’s (id:12347) future transaction is 0.157 in 10 days.\nCustomers are the most important assets of a business and CLTV allows assessing their current and future value in a customer base. The CRM strategy and marketing resource allocation are based on this metric. Business not only need to predict the retention but also analyze the purchase behavior of customers if we consider customer centric business. BG/NBD is a slight variation in the behavioral story associated with the Pareto/NBD but vastly easier to implement. The transition from an exponential distribution to a geometric process (to capture customer dropout) does not require any different psychological theories nor does it have any noteworthy managerial implications.\nI can be reached at here ."
[ { "code": null, "e": 215, "s": 172, "text": "https://sarit-maitra.medium.com/membership" }, { "code": null, "e": 723, "s": 215, "text": "Customer life time value (CLTV) is one of the most important metric to modern customer centric business scenario. It is the metric indicating the total revenue a business can reasonably expect from a single customer during the entire relationship. With CLTV business not only quantify the relationship but prioritize the CRM activity and take necessary steps to keep the existing customers happy. It also helps companies to focus on those potential customers who can bring in the more revenue in the future." }, { "code": null, "e": 838, "s": 723, "text": "80% of the effect comes from 20% of the causes, this is known as 80/20 rule or Pareto principle...Vilfredo Pareto." }, { "code": null, "e": 1348, "s": 838, "text": "If we put Pareto’s principle in business context, we can safely assume that 20% key customers are contributing 80% is business revenue. A number of studies have developed scoring mechanisms (e.g. regression models to predict a customer’s future behavior). The measures of a customer’s past behavior are key predictors of their future behavior in all the empirical analysis. It is common practice to summarize a customer’s past behavior by investigating the Recency, Frequency & Monetary (RFM) characteristics." }, { "code": null, "e": 1391, "s": 1348, "text": "Let us use some simple equations as below:" }, { "code": null, "e": 1454, "s": 1391, "text": "Customer Value = Average Order Value (AOV)* Purchase Frequency" }, { "code": null, "e": 1527, "s": 1454, "text": "Churn Rate: Churn Rate is the % of customers who have not ordered again." }, { "code": null, "e": 1561, "s": 1527, "text": "Customer Lifetime = 1/ churn rate" }, { "code": null, "e": 1587, "s": 1561, "text": "Churn Rate= 1-Repeat Rate" }, { "code": null, "e": 1868, "s": 1587, "text": "The above formulas may look quite simple; however, complexity in terms of predictive analytics involved in measuring CLTV where future sales and $ values to be predicted given historical data. This can be done either using regression techniques or probabilistic modeling approach." }, { "code": null, "e": 2053, "s": 1868, "text": "We shall target a probabilistic model for predicting CLTV in non-contractual setting on an individual level of business. Using the results of this exercise, managers should be able to:" }, { "code": null, "e": 2107, "s": 2053, "text": "Distinguish active customers from inactive customers," }, { "code": null, "e": 2164, "s": 2107, "text": "Generate transaction forecasts for individual customers," }, { "code": null, "e": 2221, "s": 2164, "text": "Predict the purchase volume of the entire customer base." }, { "code": null, "e": 2454, "s": 2221, "text": "The stochastic model presented here, featuring Beta Geometric Negative Binomial Distribution (BG/NBD) framework to capture the flow of transactions over time. BG/NBD portrays the story being about how/when customers become inactive." }, { "code": null, "e": 3002, "s": 2454, "text": "The BG/NBD require only two pieces of information about each customer’s past purchasing history: “recency” (when the last transaction occurred) and “frequency” (how many transactions was made in a specified time period). The notation used to represent this information is [X = x, t(x), T], where x is the number of transactions observed in the time period (0, T) and t(x) (0 < t(x) ≤T) is the time of the last transaction. Using these two key summary statistics, SMC(2) derive expressions for a number of managerially relevant quantities, such as:" }, { "code": null, "e": 3178, "s": 3002, "text": "E[X(t)], the expected number of transactions in a time period of length t, which is central to computing the expected transaction volume for the whole customer base over time." }, { "code": null, "e": 3265, "s": 3178, "text": "P[X(t) = x], the probability of observing x transactions in a time period of length t." }, { "code": null, "e": 3408, "s": 3265, "text": "E[Y (t)| X = x, t(x), T], the expected number of transactions in the period (T,T + t] for an individual with observed behavior (X = x, tx, T)." }, { "code": null, "e": 3680, "s": 3408, "text": "Therefore, customers will purchase at a randomly distributed interval within a time range. After each purchase they have a certain probability of dying or becoming inactive. Each customer is different and have varying purchase intervals and probability of going inactive." }, { "code": null, "e": 3704, "s": 3680, "text": "Let’s explore the data." }, { "code": null, "e": 3775, "s": 3704, "text": "Frequency (F) is the number of repeat purchases the customer has made." }, { "code": null, "e": 3918, "s": 3775, "text": "T represents the age of the customer which is equal to the duration between a customer’s first purchase and the end of the period under study." }, { "code": null, "e": 4094, "s": 3918, "text": "Recency (R) is the age of the customer when they made their most recent purchases. This is equal to the duration between a customer’s first purchase and their latest purchase." }, { "code": null, "e": 4109, "s": 4094, "text": "Monetary Value" }, { "code": null, "e": 4263, "s": 4109, "text": "After doing the necessary cleaning and creating a new data frame containing CustomerID, InvoiceDate (remove the time) and adding a new column (‘sales’) :" }, { "code": null, "e": 4596, "s": 4263, "text": "data[‘InvoiceDate’] = pd.to_datetime(data[‘InvoiceDate’]).dt.datedata = data[pd.notnull(data[‘CustomerID’])]data = data[(data[‘Quantity’]>0)]data[‘Sales’] = data[‘Quantity’] * data[‘UnitPrice’]cols_of_interest = [‘CustomerID’, ‘InvoiceDate’, ‘Sales’]data = data[cols_of_interest]print(data.head())print(data[‘CustomerID’].nunique())" }, { "code": null, "e": 4734, "s": 4596, "text": "We can make some observations here. There are 4339 customers and 12346 made single purchase, so the F and R are 0, and the T is 325 days." }, { "code": null, "e": 4859, "s": 4734, "text": "df[‘frequency’].plot(kind=’hist’, bins=50)print(df[‘frequency’].describe())print(sum(df[‘frequency’] == 0)/float(len(data)))" }, { "code": null, "e": 5473, "s": 4859, "text": "As shown, both frequency and recency are distributed quite near 0. Among all customers, >38% of them only made zero repeat purchase while the rest of the sample (62%) is divided into two equal parts: 31% of the customer base makes one repeat purchase while the other 31% of the customer base makes more than one repeat purchase. Similarly, for Recency, most customers have made their last purchase early in their lifetime and then became inactive. Indeed, the last repeat purchase that half our customers will make is within less than a year (252 days to be precise), since their first purchase for 75th quantile." }, { "code": null, "e": 5769, "s": 5473, "text": "We first need to fit the customer probability model to the data so that it picks up on their behaviors and pattern. This is done by looking at each individual’s Frequency, Recency and Age and adjusting its parameters so that it better reflects the intervals in which our customer-base purchases." }, { "code": null, "e": 6010, "s": 5769, "text": "The parameters also vary across different customers so it is calculated over two distributions for a more accurate and flexible fit of the data. Mathematically, this is done by taking the expectation of the equation over both distributions." }, { "code": null, "e": 6460, "s": 6010, "text": "bgf = BetaGeoFitter(penalizer_coef=0.0)bgf.fit(df[‘frequency’], df[‘recency’], df[‘T’], )print (bgf)# Plotgbd = beta.rvs(bgf.params_[‘a’], bgf.params_[‘b’], size = 50000)ggd = gamma.rvs(bgf.params_[‘r’], scale=1./bgf.params_[‘alpha’], size = 50000)plt.figure(figsize=(14,4))plt.subplot(121)plt.title(‘Heterogenity of $p$’)temp = plt.hist(gbd, 20, alpha=0.75)plt.subplot(122) plt.title(‘Heterogenity of $\\lambda$’)temp = plt.hist(ggd, 20, alpha=0.75)" }, { "code": null, "e": 6659, "s": 6460, "text": "Frequency/Recency matrix computes the expected number of transactions a customer is to make in the next time period, given the R(age at last purchase) and F (the number of repeat transactions made)." }, { "code": null, "e": 7008, "s": 6659, "text": "The matrix has the customer’s recency on the Y axis and the frequency on the X axis and the heatmap component is showing the predicted number of future purchases customers at intersecting points will make in one unit of time. The customers most likely to order are those who’ve placed lots of previous orders and have been seen relatively recently." }, { "code": null, "e": 7043, "s": 7008, "text": "plot_frequency_recency_matrix(bgf)" }, { "code": null, "e": 7802, "s": 7043, "text": "The RF plots maps a customer’s expected purchases by the next year and probability that they’re alive given the frequency / recency. Intuitively, we can see that customers with high frequency and recency are expected to purchase more in the future and have a higher chance of being alive. Customers in the white zone are of interest as well since they are 50/50 on leaving the company but we can still expect them to purchase about 2 to 2.5 times during the next year. These are the customers that may need a little customer servicing to come back and buy more. It is interesting to note that for a fixed recency, customer’s with more frequency are more likely to be considered dead. This is a property of the model that illustrates a clear behavioral story:" }, { "code": null, "e": 7953, "s": 7802, "text": "A customer making more frequent purchases is more likely to die off if we observe a longer period of inactivity than the customers previous intervals." }, { "code": null, "e": 8418, "s": 7953, "text": "We can see that if a customer has bought 120 times and their latest purchase (R) was when they were 120 days back, then they are you best customer (bottom-right). The coldest customers are those that in the top-right corner: they bought a lot quickly, and haven’t seen them in weeks. The tail around (20,50) represents the customers who buy infrequently, but are not seen recently, so they might buy again — we’re unsure if they are dead or just between purchases." }, { "code": null, "e": 8520, "s": 8418, "text": "We can visualize is the probability that each customer is alive based on their frequency and recency." }, { "code": null, "e": 8555, "s": 8520, "text": "plot_probability_alive_matrix(bgf)" }, { "code": null, "e": 8823, "s": 8555, "text": "Customers who have purchased recently are almost surely “alive”. Customers who have purchased a lot but not recently, are likely to have dropped out. And the more they bought in the past, the more likely they have dropped out. They are represented in the upper-right." }, { "code": null, "e": 9025, "s": 8823, "text": "Let’s rank the customers from “highest expected purchases in the next period” to lowest. Models expose a method that will predict a customer’s expected purchases in the next period using their history." }, { "code": null, "e": 9210, "s": 9025, "text": "t = 31*3df[‘predicted_purchases’] = bgf.conditional_expected_number_of_purchases_up_to_time(t, df[‘frequency’], df[‘recency’], df[‘T’])df.sort_values(by=’predicted_purchases’).tail(10)" }, { "code": null, "e": 9721, "s": 9210, "text": "Listed here is our top 10 customers that the model expects them to purchase in the next 3 months. We can see that the customer who has made 131 purchases, and bought very recently, is probably going to buy again in the next period. The predicted_purchases column displays their expected number of purchases while the other three columns represent their current RFM metrics. The BG/NBD model believes these individuals will be making more purchases within the near future as they are the current best customers." }, { "code": null, "e": 9918, "s": 9721, "text": "After fitting the model, we’re interested in seeing how well it is able to relate to our data. The first is to compare our data versus artificial data simulated with our fitted model’s parameters." }, { "code": null, "e": 9948, "s": 9918, "text": "plot_period_transactions(bgf)" }, { "code": null, "e": 10426, "s": 9948, "text": "The two are almost identical indicating that, the model is a very good fit and predicts the number of periods in the calibration period rather well. The expected number of customers that are going to repeat purchase 0, 1, 2, 3 ... 6 times in the future. For each number of repeat purchases (x-axis), we plot both what the model predicted and what the actual numbers were. As we can see, little to no errors in the fit for up to 6 repeat purchases. Let’s do the next fact check." }, { "code": null, "e": 10677, "s": 10426, "text": "However, it is always a good idea to compute the overall % error which is(predicted transactions/actual transactions -1) and the % error per transactions done in the calibration period. This will help us to quantify how close to reality the model is." }, { "code": null, "e": 10870, "s": 10677, "text": "summary_cal_holdout = calibration_and_holdout_data(data, ‘CustomerID’, ‘InvoiceDate’, calibration_period_end=’2011–06–08', observation_period_end=’2011–12–9' )print(summary_cal_holdout.head())" }, { "code": null, "e": 11055, "s": 10870, "text": "bgf.fit(summary_cal_holdout[‘frequency_cal’], summary_cal_holdout[‘recency_cal’], summary_cal_holdout[‘T_cal’])plot_calibration_purchases_vs_holdout_purchases(bgf, summary_cal_holdout)" }, { "code": null, "e": 11903, "s": 11055, "text": "In this plot, we separate the data into both a in-sample (calibration) and validation (holdout) period. The sample period consists from the beginning to 2011–06–08; the validation period spans the rest of the duration ( 2011–06–09 to 2011–12–09). The plot groups all customers in the calibration period by their number of repeat purchases (x-axis) and then averages over their repeat purchases in the holdout period (y-axis). The plot groups all customers in the calibration period by their number of repeat purchases (x-axis) and then averages over their repeat purchases in the holdout period (y-axis). The orange and blue line presents the model prediction and actual result of the y-axis respectively. The lines are quite close to each other indicating that, the model is not far off at predicting the number of orders each customer will make." }, { "code": null, "e": 12055, "s": 11903, "text": "The model is able to accurately predict the customer base’s behavior out of the sample, the model under-estimates at 4 purchases and after 5 purchases." }, { "code": null, "e": 12156, "s": 12055, "text": "Based on customer history, we can now predict what an individual’s future purchases might look like:" }, { "code": null, "e": 12268, "s": 12156, "text": "t = 10individual = df.loc[12347]bgf.predict(t, individual[‘frequency’], individual[‘recency’], individual[‘T’])" }, { "code": null, "e": 12288, "s": 12268, "text": "0.15727742663038222" }, { "code": null, "e": 12374, "s": 12288, "text": "The model predicts that customer’s (id:12347) future transaction is 0.157 in 10 days." }, { "code": null, "e": 13052, "s": 12374, "text": "Customers are the most important assets of a business and CLTV allows assessing their current and future value in a customer base. The CRM strategy and marketing resource allocation are based on this metric. Business not only need to predict the retention but also analyze the purchase behavior of customers if we consider customer centric business. BG/NBD is a slight variation in the behavioral story associated with the Pareto/NBD but vastly easier to implement. The transition from an exponential distribution to a geometric process (to capture customer dropout) does not require any different psychological theories nor does it have any noteworthy managerial implications." } ]
CSS Background Properties
CSS background properties help us style the background of elements. The CSS background property is a shorthand for specifying the background of an element. background-color, background-image, background-repeat, background-position, background-clip, background-size, background-origin and background-attachment together comprise the CSS background properties. The syntax of CSS background property is as follows− Selector { background: /*value*/ } The following examples illustrate CSS background property − Live Demo <!DOCTYPE html> <html> <head> <style> #main { margin: auto; width: 300px; background-image: url("https://www.tutorialspoint.com/hadoop/images/hadoop-mini-logo.jpg"); background-repeat: no-repeat; background-size: cover; } #im { height: 200px; width: 200px; background-image: url("https://www.tutorialspoint.com/images/css.png"); background-repeat: no-repeat; background-position: center; } </style> </head> <body> <div id="main"> <div id="im"></div> </div> </body> </html> This gives the following output − Live Demo <!DOCTYPE html> <html> <head> <style> body { background-image: url("https://www.tutorialspoint.com/hcatalog/images/hcatalog-mini- logo.jpg"),url("https://www.tutorialspoint.com/hbase/images/hbase-mini-logo.jpg"),url("https://www.tutorialspoint.com/hadoop/images/hadoop-mini-logo.jpg"); background-repeat: no-repeat; background-attachment: fixed; background-position: 10% 10%, 40% 40%, 90% 10%; } </style> </head> <body> </body> </html> This gives the following output
[ { "code": null, "e": 1421, "s": 1062, "text": "CSS background properties help us style the background of elements. The CSS background property is a shorthand for specifying the background of an element. background-color, background-image, background-repeat, background-position, background-clip, background-size, background-origin and background-attachment together comprise the CSS background properties." }, { "code": null, "e": 1474, "s": 1421, "text": "The syntax of CSS background property is as follows−" }, { "code": null, "e": 1512, "s": 1474, "text": "Selector {\n background: /*value*/\n}" }, { "code": null, "e": 1572, "s": 1512, "text": "The following examples illustrate CSS background property −" }, { "code": null, "e": 1583, "s": 1572, "text": " Live Demo" }, { "code": null, "e": 2086, "s": 1583, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n#main {\n margin: auto;\n width: 300px;\n background-image: url(\"https://www.tutorialspoint.com/hadoop/images/hadoop-mini-logo.jpg\");\n background-repeat: no-repeat;\n background-size: cover;\n}\n#im {\n height: 200px;\n width: 200px;\n background-image: url(\"https://www.tutorialspoint.com/images/css.png\");\n background-repeat: no-repeat;\n background-position: center;\n}\n</style>\n</head>\n<body>\n<div id=\"main\">\n<div id=\"im\"></div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2120, "s": 2086, "text": "This gives the following output −" }, { "code": null, "e": 2131, "s": 2120, "text": " Live Demo" }, { "code": null, "e": 2581, "s": 2131, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n background-image: url(\"https://www.tutorialspoint.com/hcatalog/images/hcatalog-mini- logo.jpg\"),url(\"https://www.tutorialspoint.com/hbase/images/hbase-mini-logo.jpg\"),url(\"https://www.tutorialspoint.com/hadoop/images/hadoop-mini-logo.jpg\");\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-position: 10% 10%, 40% 40%, 90% 10%;\n}\n</style>\n</head>\n<body>\n</body>\n</html>" }, { "code": null, "e": 2613, "s": 2581, "text": "This gives the following output" } ]
Difference Between scikit-learn and sklearn | Towards Data Science
scikit-learn is definitely one of the most commonly used packages when it comes to Machine Learning and Python. However, a lot of newcomers get confused about the naming of the package itself due to the fact that it looks to appear with two distinct names; scikit-learn and sklearn. In today’s short article, we will discuss whether there’s any difference between the two packages in the first place. Additionally, we’ll discuss whether it matters which one you install and import in your source code. The project was originally started back in 2007 as part of the Google Summer of Code while the first public release was made in early 2010. scikit-learn is an open source Machine Learning Python package that offers functionality supporting supervised and unsupervised learning. Additionally, it provides tools for model development, selection and evaluation as well as many other utilities including data pre-processing functionality. More specifically, scikit-learn’s main functionality includes classification, regression, clustering, dimensionality reduction, model selection and pre-processing. sThe library is very simple to use and most importantly efficient as it is built on NumPy, SciPy and matplotlib. The short answer is no. scikit-learn and sklearn both refer to the same package however, there are a couple of things you need to be aware of. Firstly, you can install the package by using either of scikit-learn or sklearn identifiers however, it is recommended to install scikit-learn through pip using the skikit-learn identifier. If you install the package using the sklearn identifier and then run pip list you will notice the annoying sklearn 0.0 entry: $ pip install sklearn$ pip listPackage Version------------- -------joblib 1.0.1numpy 1.21.2pip 19.2.3scikit-learn 0.24.2scipy 1.7.1setuptools 41.2.0sklearn 0.0threadpoolctl 2.2.0 Additionally, if you now attempt to uninstall sklearn, the package won’t be uninstalled: $ pip uninstall sklearn$ pip listPackage Version------------- -------joblib 1.0.1numpy 1.21.2pip 19.2.3scikit-learn 0.24.2scipy 1.7.1setuptools 41.2.0threadpoolctl 2.2.0 Essentially, sklearn is a dummy project on PyPi that will in turn install scikit-learn. Therefore, if you uninstall sklearn you are just uninstalling the dummy package, and not the actual package itself. Now despite how you installed scikit-learn, you must import it in your code using the sklearn identifier: import sklearn If you attempt to import the package using the scikit-learn identifier, you will end up with a SyntaxError: >>> import sklearn>>> import scikit-learnFile "<stdin>", line 1import scikit-learn ^SyntaxError: invalid syntax Even if you try to import it with __import__() in order to deal with the hyphen in the package’s name, you will still get a ModuleNotFoundError: >>> __import__('scikit-learn')Traceback (most recent call last):File "<stdin>", line 1, in <module>ModuleNotFoundError: No module named 'scikit-learn' In today’s short article, we attempted to shed some light around scikit-learn and sklearn since a lot of beginners seem to be confused about which term to use when developing ML functionality in Python. In general, you are advised to install the library using the scikit-learn identifier (i.e. pip install scikit-learn) but in your source code, you must import it using the sklearn identifier (i.e. import sklearn). Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You may also like
[ { "code": null, "e": 455, "s": 172, "text": "scikit-learn is definitely one of the most commonly used packages when it comes to Machine Learning and Python. However, a lot of newcomers get confused about the naming of the package itself due to the fact that it looks to appear with two distinct names; scikit-learn and sklearn." }, { "code": null, "e": 674, "s": 455, "text": "In today’s short article, we will discuss whether there’s any difference between the two packages in the first place. Additionally, we’ll discuss whether it matters which one you install and import in your source code." }, { "code": null, "e": 814, "s": 674, "text": "The project was originally started back in 2007 as part of the Google Summer of Code while the first public release was made in early 2010." }, { "code": null, "e": 1109, "s": 814, "text": "scikit-learn is an open source Machine Learning Python package that offers functionality supporting supervised and unsupervised learning. Additionally, it provides tools for model development, selection and evaluation as well as many other utilities including data pre-processing functionality." }, { "code": null, "e": 1386, "s": 1109, "text": "More specifically, scikit-learn’s main functionality includes classification, regression, clustering, dimensionality reduction, model selection and pre-processing. sThe library is very simple to use and most importantly efficient as it is built on NumPy, SciPy and matplotlib." }, { "code": null, "e": 1529, "s": 1386, "text": "The short answer is no. scikit-learn and sklearn both refer to the same package however, there are a couple of things you need to be aware of." }, { "code": null, "e": 1719, "s": 1529, "text": "Firstly, you can install the package by using either of scikit-learn or sklearn identifiers however, it is recommended to install scikit-learn through pip using the skikit-learn identifier." }, { "code": null, "e": 1845, "s": 1719, "text": "If you install the package using the sklearn identifier and then run pip list you will notice the annoying sklearn 0.0 entry:" }, { "code": null, "e": 2073, "s": 1845, "text": "$ pip install sklearn$ pip listPackage Version------------- -------joblib 1.0.1numpy 1.21.2pip 19.2.3scikit-learn 0.24.2scipy 1.7.1setuptools 41.2.0sklearn 0.0threadpoolctl 2.2.0" }, { "code": null, "e": 2162, "s": 2073, "text": "Additionally, if you now attempt to uninstall sklearn, the package won’t be uninstalled:" }, { "code": null, "e": 2375, "s": 2162, "text": "$ pip uninstall sklearn$ pip listPackage Version------------- -------joblib 1.0.1numpy 1.21.2pip 19.2.3scikit-learn 0.24.2scipy 1.7.1setuptools 41.2.0threadpoolctl 2.2.0" }, { "code": null, "e": 2579, "s": 2375, "text": "Essentially, sklearn is a dummy project on PyPi that will in turn install scikit-learn. Therefore, if you uninstall sklearn you are just uninstalling the dummy package, and not the actual package itself." }, { "code": null, "e": 2685, "s": 2579, "text": "Now despite how you installed scikit-learn, you must import it in your code using the sklearn identifier:" }, { "code": null, "e": 2700, "s": 2685, "text": "import sklearn" }, { "code": null, "e": 2808, "s": 2700, "text": "If you attempt to import the package using the scikit-learn identifier, you will end up with a SyntaxError:" }, { "code": null, "e": 2932, "s": 2808, "text": ">>> import sklearn>>> import scikit-learnFile \"<stdin>\", line 1import scikit-learn ^SyntaxError: invalid syntax" }, { "code": null, "e": 3077, "s": 2932, "text": "Even if you try to import it with __import__() in order to deal with the hyphen in the package’s name, you will still get a ModuleNotFoundError:" }, { "code": null, "e": 3228, "s": 3077, "text": ">>> __import__('scikit-learn')Traceback (most recent call last):File \"<stdin>\", line 1, in <module>ModuleNotFoundError: No module named 'scikit-learn'" }, { "code": null, "e": 3431, "s": 3228, "text": "In today’s short article, we attempted to shed some light around scikit-learn and sklearn since a lot of beginners seem to be confused about which term to use when developing ML functionality in Python." }, { "code": null, "e": 3644, "s": 3431, "text": "In general, you are advised to install the library using the scikit-learn identifier (i.e. pip install scikit-learn) but in your source code, you must import it using the sklearn identifier (i.e. import sklearn)." }, { "code": null, "e": 3761, "s": 3644, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read." } ]
How to create digital clock with textview in android?
This example demonstrates How to create digital clock with textview in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <TextView android:id = "@+id/textview" android:layout_width = "match_parent" android:layout_height = "match_parent" android:gravity = "center" android:textStyle = "bold" android:textSize = "50sp" app:fontFamily = "@font/orbitron" /> </LinearLayout> In the above code, we have taken textview. It will show clock with blink animation as we see in normal digital clock. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; public class MainActivity extends AppCompatActivity { TextView textview; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); textview = findViewById(R.id.textview); Date today = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("HH:MM"); textview.setText(formatter.format(today)); blink(); } private void blink() { final Handler hander = new Handler(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(550); } catch (InterruptedException e) { e.printStackTrace(); } hander.post(new Runnable() { @Override public void run() { if(textview.getVisibility() = = View.VISIBLE) { textview.setVisibility(View.INVISIBLE); } else { textview.setVisibility(View.VISIBLE); } blink(); } }); } }).start(); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above time textview will blink for forever Click here to download the project code
[ { "code": null, "e": 1142, "s": 1062, "text": "This example demonstrates How to create digital clock with textview in android." }, { "code": null, "e": 1271, "s": 1142, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1336, "s": 1271, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2012, "s": 1336, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/textview\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:gravity = \"center\"\n android:textStyle = \"bold\"\n android:textSize = \"50sp\"\n app:fontFamily = \"@font/orbitron\" />\n</LinearLayout>" }, { "code": null, "e": 2130, "s": 2012, "text": "In the above code, we have taken textview. It will show clock with blink animation as we see in normal digital clock." }, { "code": null, "e": 2187, "s": 2130, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3708, "s": 2187, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.HashMap;\npublic class MainActivity extends AppCompatActivity {\n TextView textview;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n textview = findViewById(R.id.textview);\n Date today = new Date();\n SimpleDateFormat formatter = new SimpleDateFormat(\"HH:MM\");\n textview.setText(formatter.format(today));\n blink();\n }\n private void blink() {\n final Handler hander = new Handler();\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(550);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n hander.post(new Runnable() {\n @Override\n public void run() {\n if(textview.getVisibility() = = View.VISIBLE) {\n textview.setVisibility(View.INVISIBLE);\n } else {\n textview.setVisibility(View.VISIBLE);\n }\n blink();\n }\n });\n }\n }).start();\n }\n}" }, { "code": null, "e": 4055, "s": 3708, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4105, "s": 4055, "text": "In the above time textview will blink for forever" }, { "code": null, "e": 4145, "s": 4105, "text": "Click here to download the project code" } ]
Linear Regression with one or more variables | by Luca Zammataro | Towards Data Science
Linear Regression is a statistical model used in Machine Learning that falls in the “Supervised Learning” class of algorithms, and it applies to the analysis of biomedical data. We use it for predicting continuous-valued outputs, differently from the Logistic Regression, that instead is used for predicting discrete-valued outputs (i.e., classification). Before starting, I suggest readers following the interesting course in Machine Learning at Coursera by Andrew NG [1]. The course provides an excellent explanation of all the arguments treated in this post. Let’s start with our example: we have a dataset of patients checked for Systolic Blood Pressure (SBP) and monitored for age and weight, and we want to predict the SBP for a new patient. Implicitly we hypothesize that factors such as weight and age influence the SBP. For our dataset, we will take values of a Table from [2] The Variable to be explained (SBP) is called the Dependent Variable, or Response Variable, and it matches with our output variable or target vector. Instead, the variables that explain the input (age and weight) are called Independent Variables or Predictor Variables, or Features. If the dependent and independent variables are continuous, as is the case for SBP, age, and weight, then a Correlation coefficient can be calculated as a measure of the strength of the relationship between them. [3] We say that Linear Regression represents an evolution of the Correlation. The difference between them is: Correlation refers to the strength of the relationship between two or more variables. The Regression, instead, refers to an ensemble of statistical techniques and algorithms for describing the relationship between two or more variables [2]. Linear Regression assumes that the relationship between one or multiple input features and the relative target vector (outputs) is approximatively linear. [4], and it enables the identification and characterization of this relationship. The consequence of this assumption is that, in the Linear Regression model, the input features have an “effect” on the target vector (output), and this effect is constant. The “effect” is often identified as “coefficient”, “weight” or “parameter”, and more simply, we say that Linear Regression computes a weighted sum of the input features, plus a constant called “bias term” or intercept [5]. To simplify, let’s start with the application of the Linear Regression with one variable. Starting One Variable is a fundamental step if we want to understand thoroughly how the Linear Regression works. We will use the dataset in Table 1, only extrapolating the feature “Age” and using the “SBP” column as output. All the code presented in this post is written in Python 2.7, and it’s self-explicative also for the porting to many other languages. For the implementation environment, I suggest the use of Jupyter Notebook. Linear Algebra calculation will be primarily used, because of one the intrinsic advantages in avoiding, where possible, ‘while’ and ‘for’ loops. To accomplish this goal, we will use NumPy, a robust library of math functions for scientific computing with Python. Before starting with the description of the Linear Regression model, it’s necessary to take a glance at our data and try to understand whether Linear Regression could apply to the data. The aim is predicting, for example, systolic pressure value, based on the patient age. First of all, we import all the packages required for the Python code that will be discussed in this post: NumPy, Pandas and matplot. These packages belong to SciPy.org, which is a Python-based ecosystem of open-source software for mathematics, science, and engineering. Numpy is necessary for the Linear Algebra calculations. Pandas is an open-source library providing high-performance, data structures, and data analysis tools for Python. A pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure. It consists of three principal components, the data, rows, and columns, with labeled axes (rows and columns). Follow this link to the GeeksForGeeks portal, for having access to detailed information about the use of the pandas DataFrame. Matplotlib is fundamental for creating all the plots. In this step, we will create a dataset with our values. An example of the comma-separated-values format, with a header, is the following: Age,Weight,SBP60,58,11761,90,12074,96,14557,72,12963,62,13268,79,13066,69,11077,96,16363,96,13654,54,11563,67,11876,99,13260,74,11161,73,11265,85,14779,80,138 Copy and paste the values in a file, and save it as “SBP.csv” Once we have created the SBP.csv dataset, upload it and create a DataFrame using the Pandas pd object. The Python code for the dataset uploading is the following: Typing “df” in a Jupyter cell, will display the DataFrame content as following: The SBP dataset is formed by 3 columns (Age, Weight, and SBP), but we will upload the first and the last columns (Age and SBP); our model will determine the strength of the relationship between Age and SBP. Pandas makes easy accessing to DataFrame variables, that will be copied in an X vector, containing the input, and a y vector, for the output. Before going ahead, the SBP dataset reported here has to be rescaled and normalized. In Machine Learning, scaling and normalization are required, especially when discrepancies in order of magnitude among the features and the output occurs. As mentioned in the Introduction, we will use Linear Algebra on matrixes to avoid, where possible, while and for loops on variables. Moreover, programming Linear Algebra will result in good readability of the code. For this purpose, In Python, we can take advantage of NumPy. As mentioned before, NumPy is a library of math functions for scientific calculation and for Linear Algebra. All the operations can be simplified, creating a NumPy object, and using some of the associated methods. The reason why we want to use NumPy is that, even though many operations on matrixes can be done using the regular operators (+, -, *, /), NumPy guarantees a better control over the operations, especially if the matrixes are big. For example, with NumPy, we can multiply arguments element-wise, like the features matrix X and the output vector y: An in-depth discussion on the use of NumPy goes beyond this post. To implement Scaling and Normalization of features, this code is what we need: Code 5 implements a Python function called FeatureScalingNormalization(). This function takes X that is the features vector as an argument, and return 3 arguments: 1) the same X vector but scaled and normalized (X_norm), 2) mu, that is the average values of X in training set) and 3) sigma that is the Standard Deviation. Also, we will store mu and sigma because these parameters will be fundamental later. Copy the following code and paste it in a new Jupyter Notebook cell: Typing ‘X’ in a Notebook cell will display the new values of X: array([-0.73189052, -0.59728997, 1.15251726, -1.13569219, -0.32808885, 0.34491392, 0.07571281, 1.55631892, -0.32808885, -1.53949386, -0.32808885, 1.42171837, -0.73189052, -0.59728997, -0.05888774, 1.82552004]) The X vector containing the Age values is now normalized. Now we will add a column of ones to the X vector. This is the new structure of X: array([[ 1. , -0.73189052], [ 1. , -0.59728997], [ 1. , 1.15251726], [ 1. , -1.13569219], [ 1. , -0.32808885], [ 1. , 0.34491392], [ 1. , 0.07571281], [ 1. , 1.55631892], [ 1. , -0.32808885], [ 1. , -1.53949386], [ 1. , -0.32808885], [ 1. , 1.42171837], [ 1. , -0.73189052], [ 1. , -0.59728997], [ 1. , -0.05888774], [ 1. , 1.82552004]]) Plotting our data is a useful practice when we want to have an idea of how they are distributed. Plot the data using the matplotlib scatter method: Visualizing the data at a glance, we can notice a pattern of increasing relationship, between Age and SBP. This is what we expect since systolic pressure is physiologically connected to age increasing. The idea underlying the Linear Regression is represented by a function that predicts the output y based on the input feature X. The predicted output is the h = θ * X term that is equal to a constant called “bias term” or “intercept term” or θ_0 plus a weighted sum of the input features X, where θ_1 represents the weight for X. We will call this function “Hypothesis” , and we will use it to “map” from X (Age) to y (SBP). Since we are using Linear Algebra, for all the calculation, we can write the Hypothesis model in the vectorized form: where θ_0 and θ_1 are expressed as vector θ=[θ_0, θ_1], and the Hypothesis is equal to θX. The best performance in predicting y consists of finding θ values for which the distance between the predicted y value and the actual y value is closer to the minimum. Let’s try two parameters randomly chosen, for the vector θ, for instance: θ = [140.0, 5.0], and see what happens: The Hypothesis model in Figure 2, represented by the red line, should predict y (the SBP). It represents our h=θX vector in predicting y for the values of θ = [140.0, 5.0]. But this model, obviously, does not fit our data. As highlighted by the blue lines connecting dots with the red line, the Hypothesis “touches” some of the y values, but the rest of the h vector is far from the minimum. So we are tempted to guess which θ could predict y when setting with different values. We could choose θ “by trial and error” to minimize all the distances between the Hypothesis and y. To accomplish this goal, we can calculate the Cost Function for our model. The Cost Function can register how much far we are from the minimum of the Hypothesis model and can help us in finding the best θ. The equation describing the Cost Function is the following: Where m is the length of the X vector (in our case = 16), and i is the index assigned to each item in the dataset. The Equation is composed of three components: the Hypothesis (h=θX)the SquaredError that is = (h-y) ^2The Cost Function J that is then calculated as J = 1/2m * Sum(SquaredError) the Hypothesis (h=θX) the SquaredError that is = (h-y) ^2 The Cost Function J that is then calculated as J = 1/2m * Sum(SquaredError) Since we use Linear Algebra, the vectorized implementation of Equation 3 is the following: Intuition I. In order to simplify the explanation, let’s try to manually calculate the Cost Function for a smaller dataset composed only of the first 3 values of the SBP dataset, and with θ = [120.0, 10.0]. These parameters are chosen randomly, at the moment, because we don’t have to set the best θ for now. We will split the X and y, producing arrays X_1 and y_1: Also, we have to set m=3, because we have three samples now. Let’s plot the data and the Hypothesis as following: The vector y corresponding to the first three values (the blue dots) of the SBP is: y = [117.0, 120.0, 145.0] Since our θ is = [120, 10.0], the product of h = θ*X_1 will be represented by the following vector, (highlighted by the dots on the red line): h = θ*X_1 = [112.7, 114.0, 131.5] The dashed blue lines highlight the distances between actual y_1 values and predicted values. Now, we have all we need, to calculate the Cost Function J. We will apply the Cost Function as described in Solution 1: ...the Cost Function (J) is = 39.3 The Cost Function in Python. The following Python code implements the Cost Function: The code implements step by step the Cost Function described in Equation 4 (vectorized). Let’s repeat again: the Hypothesis (h=θX)the SquaredError that is = (h-y) ^2)the Cost Function J that is = 1/2m * Sum(SquaredError) the Hypothesis (h=θX) the SquaredError that is = (h-y) ^2) the Cost Function J that is = 1/2m * Sum(SquaredError) Now that we have understood the mechanism underlying the Cost Function calculation, let’s go back to the complete SBP dataset (16 patients). If we want to calculate the Cost Function for the whole SBP dataset, using θ = [140.0; 5.0], we will type : The function will return J = 138.04, which is the Cost Function calculated for θ = [140.0; 5.0]. This J is not the minimum J that we could find, since that we have manually set θ, without any idea about how to minimize it. The following Intuition II could help us in understanding better the limit of our manual approach. Intuition II. The following code generates randomly 10 θ vectors and passes them to the calcCostFunction, producing a table of the relative Cost Functions (J): The resulting output is: [Th0 Th1] J[38. 55.] 5100.4688623710845[71. 47.] 2352.6631642080174[28. 76.] 7148.466632549135[73. 75.] 3579.826857778751[79. 47.] 1925.1631642080174[12. 42.] 7320.026790356101[68. 25.] 1992.2131192595837[25. 92.] 8565.015528875269[51. 46.] 3667.1483894376343[13. 62.] 7992.509785763768 The “take-home message” is that trying to handly minimize J, is not the correct way to proceed. After 10 runs on randomly selected θ’s, the behavior of J is unpredictable. Moreover, there is no way to guess J basing on θ. So the question is: How we can choose θ, to find the minimum J? We need an algorithm that can minimize J for us, and this algorithm is the argument of the next Step. We are interested in finding the minimum of the Cost Function using Gradient Descent, which is an algorithm that can automatize this search. The Gradient Descent calculates the derivative of the Cost Function, updating the vector θ by mean of the parameter α, that is the learning rate. From this moment on, we will refer to the SBP dataset, as the training set. This clarification is essential since Gradient Descent will use the difference between the actual vector y of the dataset and the h vector prediction, to “learn” how to find the minimum J. The algorithm will repeat until it will converge. θ updating has to be simultaneous. Since we use Linear Algebra, the vectorized implementation is the following: Note that here we have to transpose X since X is a [16, 2] matrix and Error is a [16, 1] vector. Gradient Descent implementation. The following Python code implements the Gradient Descent. We will use the vectorized form of Equation 5: To run the Gradient Descent, we have to initialize θ, iterations, and α, that together with X and y are the arguments of the gradientDescent function: The results are collected in the “results” list. This list is composed of the found θ, plus two lists containing the θ and J histories. After 2000 iterations the Gradient Descent has found θ = [128.4, 9.9], and J = 59.7, which is the minimum J. We will use the two lists for plotting the Gradient Descent activity. The following code will plot the training set and h. The Hypothesis h now fits with our data! Let’s plot the θ history: A plot of the θ history is shown in Figure 6. The red curve represents θ_0, the green curve θ_1. After 2000 iterations, θ is = [128.4; 9.9] Now let’s plot the J history: After circa 200 iterations the Cost Function falls down, stabilizing around 59.7 after 1500 iterations. The J curve depends on α, that we have set to 0.01. Now that we have found the best θ, we can predict the Systolic Blood Pressure for a 75 years-old person. The query is a vector, composed of two numbers [1, 75]. The first number corresponds to the feature x_0. To run the prediction, we have to scale and normalize the query vector, using the mu and sigma parameters that we have calculated in Step 5: Feature Scaling and Normalization. The query vector will be [1, 1.29]. Then, we have to multiply the query for the θ vector (θ = [128.4, 9.95]). The following code implements the prediction. The SBP for a 75 years-old man is: 141.2 Let’s do some experiments with the learning rate α. Changing α will affect the dynamics of J. If α is too little, the Gradient Descent will converge slowly, and we need to train it with more iterations for finding the minimum of J. Contrarily, if α is too big, the Gradient Descent risks to never converge. Interestingly, for values of α around 1.9, the Gradient Descent converges, but for the first 40 iterations, the behavior of θ is turbulent, for successively reaching stability. (Figure 8) We can create a contour plot, which is a graph containing many concentric tracks. For each track there are various pairs of θ associated with a constant value of J. The θ corresponding to the minimum J, lies at the center (the red dot). The other concentric lines correspond to all the different values of J. The most the distance from the center, the higher the value of the Cost Function J. Code 20 produces the following plot: Note that θ = [128.4; 9.9] corresponding to the minimum J (59.7), is the red dot in the center of the graph. The blue dots track the path of the Gradient Descent in converging to the minimum. We have explained the statistical mechanisms underlying Linear Regression with one variable: the feature Age in the SBP dataset. The major part of the code here proposed works also with multiple variables. The SBP dataset is composed of 2 features (Age and Weight) and one output: SBP. In this step, we will update the code in a way that it can fit with multiple variables. The only adjustments required concern: The Dataset uploadingThe Feature Scaling and Normalization functionThe code for adding a column of “ones” to the vector XThe Prediction Query. The Dataset uploading The Feature Scaling and Normalization function The code for adding a column of “ones” to the vector X The Prediction Query. Dataset uploading The code for uploading the dataset has to be modified in order to produce a new X vector containing Age and Weight of each patient: The numpy method used for producing the new X vector is .vstack() because we now want an X vector with two sets of distinct features. Feature Scaling and Normalization function The code concerning Feature Scaling and Normalization is modified in vectors mu and sigma. Now the two vectors will accept two parameters each. Adding a column of “ones” to the vector X The line for adding “ones” to the X vector is modified as follows: The Prediction Query The query for the predictions and the code for the normalization are modified as follows: The prediction result, in this case, is an SBP =143.47 With these changes, the Python code is ready for Linear Regression with multiple variables. You have to update the code every time you will add new features from your training set! I hope you find this post useful! Andrew NG, Machine Learning | Coursera.John Pezzullo, Biostatistics For Dummies, Wiley, ISBN-13: 9781118553985Schneider, A; Hommel, G; Blettner, M. Linear Regression Analysis Part 14 of a Series on Evaluation of Scientific Publications, Dtsch Arztebl Int 2010; 107(44): 776–82; DOI: 10.3238/arztebl.2010.0776Chris Albon, Machine Learning with Python Cookbook, O’Really, ISBN-13: 978–1491989388.Aurélien Géron, Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems, O’Reilly, ISBN-13: 978–1491962299. Andrew NG, Machine Learning | Coursera. John Pezzullo, Biostatistics For Dummies, Wiley, ISBN-13: 9781118553985 Schneider, A; Hommel, G; Blettner, M. Linear Regression Analysis Part 14 of a Series on Evaluation of Scientific Publications, Dtsch Arztebl Int 2010; 107(44): 776–82; DOI: 10.3238/arztebl.2010.0776 Chris Albon, Machine Learning with Python Cookbook, O’Really, ISBN-13: 978–1491989388. Aurélien Géron, Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems, O’Reilly, ISBN-13: 978–1491962299.
[ { "code": null, "e": 527, "s": 171, "text": "Linear Regression is a statistical model used in Machine Learning that falls in the “Supervised Learning” class of algorithms, and it applies to the analysis of biomedical data. We use it for predicting continuous-valued outputs, differently from the Logistic Regression, that instead is used for predicting discrete-valued outputs (i.e., classification)." }, { "code": null, "e": 733, "s": 527, "text": "Before starting, I suggest readers following the interesting course in Machine Learning at Coursera by Andrew NG [1]. The course provides an excellent explanation of all the arguments treated in this post." }, { "code": null, "e": 1057, "s": 733, "text": "Let’s start with our example: we have a dataset of patients checked for Systolic Blood Pressure (SBP) and monitored for age and weight, and we want to predict the SBP for a new patient. Implicitly we hypothesize that factors such as weight and age influence the SBP. For our dataset, we will take values of a Table from [2]" }, { "code": null, "e": 1555, "s": 1057, "text": "The Variable to be explained (SBP) is called the Dependent Variable, or Response Variable, and it matches with our output variable or target vector. Instead, the variables that explain the input (age and weight) are called Independent Variables or Predictor Variables, or Features. If the dependent and independent variables are continuous, as is the case for SBP, age, and weight, then a Correlation coefficient can be calculated as a measure of the strength of the relationship between them. [3]" }, { "code": null, "e": 1902, "s": 1555, "text": "We say that Linear Regression represents an evolution of the Correlation. The difference between them is: Correlation refers to the strength of the relationship between two or more variables. The Regression, instead, refers to an ensemble of statistical techniques and algorithms for describing the relationship between two or more variables [2]." }, { "code": null, "e": 2311, "s": 1902, "text": "Linear Regression assumes that the relationship between one or multiple input features and the relative target vector (outputs) is approximatively linear. [4], and it enables the identification and characterization of this relationship. The consequence of this assumption is that, in the Linear Regression model, the input features have an “effect” on the target vector (output), and this effect is constant." }, { "code": null, "e": 2534, "s": 2311, "text": "The “effect” is often identified as “coefficient”, “weight” or “parameter”, and more simply, we say that Linear Regression computes a weighted sum of the input features, plus a constant called “bias term” or intercept [5]." }, { "code": null, "e": 2624, "s": 2534, "text": "To simplify, let’s start with the application of the Linear Regression with one variable." }, { "code": null, "e": 2848, "s": 2624, "text": "Starting One Variable is a fundamental step if we want to understand thoroughly how the Linear Regression works. We will use the dataset in Table 1, only extrapolating the feature “Age” and using the “SBP” column as output." }, { "code": null, "e": 3057, "s": 2848, "text": "All the code presented in this post is written in Python 2.7, and it’s self-explicative also for the porting to many other languages. For the implementation environment, I suggest the use of Jupyter Notebook." }, { "code": null, "e": 3319, "s": 3057, "text": "Linear Algebra calculation will be primarily used, because of one the intrinsic advantages in avoiding, where possible, ‘while’ and ‘for’ loops. To accomplish this goal, we will use NumPy, a robust library of math functions for scientific computing with Python." }, { "code": null, "e": 3592, "s": 3319, "text": "Before starting with the description of the Linear Regression model, it’s necessary to take a glance at our data and try to understand whether Linear Regression could apply to the data. The aim is predicting, for example, systolic pressure value, based on the patient age." }, { "code": null, "e": 3863, "s": 3592, "text": "First of all, we import all the packages required for the Python code that will be discussed in this post: NumPy, Pandas and matplot. These packages belong to SciPy.org, which is a Python-based ecosystem of open-source software for mathematics, science, and engineering." }, { "code": null, "e": 3919, "s": 3863, "text": "Numpy is necessary for the Linear Algebra calculations." }, { "code": null, "e": 4374, "s": 3919, "text": "Pandas is an open-source library providing high-performance, data structures, and data analysis tools for Python. A pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure. It consists of three principal components, the data, rows, and columns, with labeled axes (rows and columns). Follow this link to the GeeksForGeeks portal, for having access to detailed information about the use of the pandas DataFrame." }, { "code": null, "e": 4428, "s": 4374, "text": "Matplotlib is fundamental for creating all the plots." }, { "code": null, "e": 4566, "s": 4428, "text": "In this step, we will create a dataset with our values. An example of the comma-separated-values format, with a header, is the following:" }, { "code": null, "e": 4725, "s": 4566, "text": "Age,Weight,SBP60,58,11761,90,12074,96,14557,72,12963,62,13268,79,13066,69,11077,96,16363,96,13654,54,11563,67,11876,99,13260,74,11161,73,11265,85,14779,80,138" }, { "code": null, "e": 4787, "s": 4725, "text": "Copy and paste the values in a file, and save it as “SBP.csv”" }, { "code": null, "e": 4950, "s": 4787, "text": "Once we have created the SBP.csv dataset, upload it and create a DataFrame using the Pandas pd object. The Python code for the dataset uploading is the following:" }, { "code": null, "e": 5030, "s": 4950, "text": "Typing “df” in a Jupyter cell, will display the DataFrame content as following:" }, { "code": null, "e": 5379, "s": 5030, "text": "The SBP dataset is formed by 3 columns (Age, Weight, and SBP), but we will upload the first and the last columns (Age and SBP); our model will determine the strength of the relationship between Age and SBP. Pandas makes easy accessing to DataFrame variables, that will be copied in an X vector, containing the input, and a y vector, for the output." }, { "code": null, "e": 5834, "s": 5379, "text": "Before going ahead, the SBP dataset reported here has to be rescaled and normalized. In Machine Learning, scaling and normalization are required, especially when discrepancies in order of magnitude among the features and the output occurs. As mentioned in the Introduction, we will use Linear Algebra on matrixes to avoid, where possible, while and for loops on variables. Moreover, programming Linear Algebra will result in good readability of the code." }, { "code": null, "e": 6456, "s": 5834, "text": "For this purpose, In Python, we can take advantage of NumPy. As mentioned before, NumPy is a library of math functions for scientific calculation and for Linear Algebra. All the operations can be simplified, creating a NumPy object, and using some of the associated methods. The reason why we want to use NumPy is that, even though many operations on matrixes can be done using the regular operators (+, -, *, /), NumPy guarantees a better control over the operations, especially if the matrixes are big. For example, with NumPy, we can multiply arguments element-wise, like the features matrix X and the output vector y:" }, { "code": null, "e": 6601, "s": 6456, "text": "An in-depth discussion on the use of NumPy goes beyond this post. To implement Scaling and Normalization of features, this code is what we need:" }, { "code": null, "e": 7077, "s": 6601, "text": "Code 5 implements a Python function called FeatureScalingNormalization(). This function takes X that is the features vector as an argument, and return 3 arguments: 1) the same X vector but scaled and normalized (X_norm), 2) mu, that is the average values of X in training set) and 3) sigma that is the Standard Deviation. Also, we will store mu and sigma because these parameters will be fundamental later. Copy the following code and paste it in a new Jupyter Notebook cell:" }, { "code": null, "e": 7141, "s": 7077, "text": "Typing ‘X’ in a Notebook cell will display the new values of X:" }, { "code": null, "e": 7355, "s": 7141, "text": "array([-0.73189052, -0.59728997, 1.15251726, -1.13569219, -0.32808885, 0.34491392, 0.07571281, 1.55631892, -0.32808885, -1.53949386, -0.32808885, 1.42171837, -0.73189052, -0.59728997, -0.05888774, 1.82552004])" }, { "code": null, "e": 7413, "s": 7355, "text": "The X vector containing the Age values is now normalized." }, { "code": null, "e": 7463, "s": 7413, "text": "Now we will add a column of ones to the X vector." }, { "code": null, "e": 7495, "s": 7463, "text": "This is the new structure of X:" }, { "code": null, "e": 8041, "s": 7495, "text": "array([[ 1. , -0.73189052], [ 1. , -0.59728997], [ 1. , 1.15251726], [ 1. , -1.13569219], [ 1. , -0.32808885], [ 1. , 0.34491392], [ 1. , 0.07571281], [ 1. , 1.55631892], [ 1. , -0.32808885], [ 1. , -1.53949386], [ 1. , -0.32808885], [ 1. , 1.42171837], [ 1. , -0.73189052], [ 1. , -0.59728997], [ 1. , -0.05888774], [ 1. , 1.82552004]])" }, { "code": null, "e": 8189, "s": 8041, "text": "Plotting our data is a useful practice when we want to have an idea of how they are distributed. Plot the data using the matplotlib scatter method:" }, { "code": null, "e": 8391, "s": 8189, "text": "Visualizing the data at a glance, we can notice a pattern of increasing relationship, between Age and SBP. This is what we expect since systolic pressure is physiologically connected to age increasing." }, { "code": null, "e": 8519, "s": 8391, "text": "The idea underlying the Linear Regression is represented by a function that predicts the output y based on the input feature X." }, { "code": null, "e": 8815, "s": 8519, "text": "The predicted output is the h = θ * X term that is equal to a constant called “bias term” or “intercept term” or θ_0 plus a weighted sum of the input features X, where θ_1 represents the weight for X. We will call this function “Hypothesis” , and we will use it to “map” from X (Age) to y (SBP)." }, { "code": null, "e": 8933, "s": 8815, "text": "Since we are using Linear Algebra, for all the calculation, we can write the Hypothesis model in the vectorized form:" }, { "code": null, "e": 9024, "s": 8933, "text": "where θ_0 and θ_1 are expressed as vector θ=[θ_0, θ_1], and the Hypothesis is equal to θX." }, { "code": null, "e": 9192, "s": 9024, "text": "The best performance in predicting y consists of finding θ values for which the distance between the predicted y value and the actual y value is closer to the minimum." }, { "code": null, "e": 9306, "s": 9192, "text": "Let’s try two parameters randomly chosen, for the vector θ, for instance: θ = [140.0, 5.0], and see what happens:" }, { "code": null, "e": 9959, "s": 9306, "text": "The Hypothesis model in Figure 2, represented by the red line, should predict y (the SBP). It represents our h=θX vector in predicting y for the values of θ = [140.0, 5.0]. But this model, obviously, does not fit our data. As highlighted by the blue lines connecting dots with the red line, the Hypothesis “touches” some of the y values, but the rest of the h vector is far from the minimum. So we are tempted to guess which θ could predict y when setting with different values. We could choose θ “by trial and error” to minimize all the distances between the Hypothesis and y. To accomplish this goal, we can calculate the Cost Function for our model." }, { "code": null, "e": 10150, "s": 9959, "text": "The Cost Function can register how much far we are from the minimum of the Hypothesis model and can help us in finding the best θ. The equation describing the Cost Function is the following:" }, { "code": null, "e": 10311, "s": 10150, "text": "Where m is the length of the X vector (in our case = 16), and i is the index assigned to each item in the dataset. The Equation is composed of three components:" }, { "code": null, "e": 10443, "s": 10311, "text": "the Hypothesis (h=θX)the SquaredError that is = (h-y) ^2The Cost Function J that is then calculated as J = 1/2m * Sum(SquaredError)" }, { "code": null, "e": 10465, "s": 10443, "text": "the Hypothesis (h=θX)" }, { "code": null, "e": 10501, "s": 10465, "text": "the SquaredError that is = (h-y) ^2" }, { "code": null, "e": 10577, "s": 10501, "text": "The Cost Function J that is then calculated as J = 1/2m * Sum(SquaredError)" }, { "code": null, "e": 10668, "s": 10577, "text": "Since we use Linear Algebra, the vectorized implementation of Equation 3 is the following:" }, { "code": null, "e": 10681, "s": 10668, "text": "Intuition I." }, { "code": null, "e": 11034, "s": 10681, "text": "In order to simplify the explanation, let’s try to manually calculate the Cost Function for a smaller dataset composed only of the first 3 values of the SBP dataset, and with θ = [120.0, 10.0]. These parameters are chosen randomly, at the moment, because we don’t have to set the best θ for now. We will split the X and y, producing arrays X_1 and y_1:" }, { "code": null, "e": 11148, "s": 11034, "text": "Also, we have to set m=3, because we have three samples now. Let’s plot the data and the Hypothesis as following:" }, { "code": null, "e": 11232, "s": 11148, "text": "The vector y corresponding to the first three values (the blue dots) of the SBP is:" }, { "code": null, "e": 11258, "s": 11232, "text": "y = [117.0, 120.0, 145.0]" }, { "code": null, "e": 11401, "s": 11258, "text": "Since our θ is = [120, 10.0], the product of h = θ*X_1 will be represented by the following vector, (highlighted by the dots on the red line):" }, { "code": null, "e": 11435, "s": 11401, "text": "h = θ*X_1 = [112.7, 114.0, 131.5]" }, { "code": null, "e": 11649, "s": 11435, "text": "The dashed blue lines highlight the distances between actual y_1 values and predicted values. Now, we have all we need, to calculate the Cost Function J. We will apply the Cost Function as described in Solution 1:" }, { "code": null, "e": 11684, "s": 11649, "text": "...the Cost Function (J) is = 39.3" }, { "code": null, "e": 11713, "s": 11684, "text": "The Cost Function in Python." }, { "code": null, "e": 11769, "s": 11713, "text": "The following Python code implements the Cost Function:" }, { "code": null, "e": 11878, "s": 11769, "text": "The code implements step by step the Cost Function described in Equation 4 (vectorized). Let’s repeat again:" }, { "code": null, "e": 11990, "s": 11878, "text": "the Hypothesis (h=θX)the SquaredError that is = (h-y) ^2)the Cost Function J that is = 1/2m * Sum(SquaredError)" }, { "code": null, "e": 12012, "s": 11990, "text": "the Hypothesis (h=θX)" }, { "code": null, "e": 12049, "s": 12012, "text": "the SquaredError that is = (h-y) ^2)" }, { "code": null, "e": 12104, "s": 12049, "text": "the Cost Function J that is = 1/2m * Sum(SquaredError)" }, { "code": null, "e": 12353, "s": 12104, "text": "Now that we have understood the mechanism underlying the Cost Function calculation, let’s go back to the complete SBP dataset (16 patients). If we want to calculate the Cost Function for the whole SBP dataset, using θ = [140.0; 5.0], we will type :" }, { "code": null, "e": 12675, "s": 12353, "text": "The function will return J = 138.04, which is the Cost Function calculated for θ = [140.0; 5.0]. This J is not the minimum J that we could find, since that we have manually set θ, without any idea about how to minimize it. The following Intuition II could help us in understanding better the limit of our manual approach." }, { "code": null, "e": 12689, "s": 12675, "text": "Intuition II." }, { "code": null, "e": 12835, "s": 12689, "text": "The following code generates randomly 10 θ vectors and passes them to the calcCostFunction, producing a table of the relative Cost Functions (J):" }, { "code": null, "e": 12860, "s": 12835, "text": "The resulting output is:" }, { "code": null, "e": 13147, "s": 12860, "text": "[Th0 Th1] J[38. 55.] 5100.4688623710845[71. 47.] 2352.6631642080174[28. 76.] 7148.466632549135[73. 75.] 3579.826857778751[79. 47.] 1925.1631642080174[12. 42.] 7320.026790356101[68. 25.] 1992.2131192595837[25. 92.] 8565.015528875269[51. 46.] 3667.1483894376343[13. 62.] 7992.509785763768" }, { "code": null, "e": 13535, "s": 13147, "text": "The “take-home message” is that trying to handly minimize J, is not the correct way to proceed. After 10 runs on randomly selected θ’s, the behavior of J is unpredictable. Moreover, there is no way to guess J basing on θ. So the question is: How we can choose θ, to find the minimum J? We need an algorithm that can minimize J for us, and this algorithm is the argument of the next Step." }, { "code": null, "e": 14172, "s": 13535, "text": "We are interested in finding the minimum of the Cost Function using Gradient Descent, which is an algorithm that can automatize this search. The Gradient Descent calculates the derivative of the Cost Function, updating the vector θ by mean of the parameter α, that is the learning rate. From this moment on, we will refer to the SBP dataset, as the training set. This clarification is essential since Gradient Descent will use the difference between the actual vector y of the dataset and the h vector prediction, to “learn” how to find the minimum J. The algorithm will repeat until it will converge. θ updating has to be simultaneous." }, { "code": null, "e": 14249, "s": 14172, "text": "Since we use Linear Algebra, the vectorized implementation is the following:" }, { "code": null, "e": 14346, "s": 14249, "text": "Note that here we have to transpose X since X is a [16, 2] matrix and Error is a [16, 1] vector." }, { "code": null, "e": 14379, "s": 14346, "text": "Gradient Descent implementation." }, { "code": null, "e": 14485, "s": 14379, "text": "The following Python code implements the Gradient Descent. We will use the vectorized form of Equation 5:" }, { "code": null, "e": 14636, "s": 14485, "text": "To run the Gradient Descent, we have to initialize θ, iterations, and α, that together with X and y are the arguments of the gradientDescent function:" }, { "code": null, "e": 15004, "s": 14636, "text": "The results are collected in the “results” list. This list is composed of the found θ, plus two lists containing the θ and J histories. After 2000 iterations the Gradient Descent has found θ = [128.4, 9.9], and J = 59.7, which is the minimum J. We will use the two lists for plotting the Gradient Descent activity. The following code will plot the training set and h." }, { "code": null, "e": 15045, "s": 15004, "text": "The Hypothesis h now fits with our data!" }, { "code": null, "e": 15071, "s": 15045, "text": "Let’s plot the θ history:" }, { "code": null, "e": 15211, "s": 15071, "text": "A plot of the θ history is shown in Figure 6. The red curve represents θ_0, the green curve θ_1. After 2000 iterations, θ is = [128.4; 9.9]" }, { "code": null, "e": 15241, "s": 15211, "text": "Now let’s plot the J history:" }, { "code": null, "e": 15397, "s": 15241, "text": "After circa 200 iterations the Cost Function falls down, stabilizing around 59.7 after 1500 iterations. The J curve depends on α, that we have set to 0.01." }, { "code": null, "e": 15939, "s": 15397, "text": "Now that we have found the best θ, we can predict the Systolic Blood Pressure for a 75 years-old person. The query is a vector, composed of two numbers [1, 75]. The first number corresponds to the feature x_0. To run the prediction, we have to scale and normalize the query vector, using the mu and sigma parameters that we have calculated in Step 5: Feature Scaling and Normalization. The query vector will be [1, 1.29]. Then, we have to multiply the query for the θ vector (θ = [128.4, 9.95]). The following code implements the prediction." }, { "code": null, "e": 15980, "s": 15939, "text": "The SBP for a 75 years-old man is: 141.2" }, { "code": null, "e": 16475, "s": 15980, "text": "Let’s do some experiments with the learning rate α. Changing α will affect the dynamics of J. If α is too little, the Gradient Descent will converge slowly, and we need to train it with more iterations for finding the minimum of J. Contrarily, if α is too big, the Gradient Descent risks to never converge. Interestingly, for values of α around 1.9, the Gradient Descent converges, but for the first 40 iterations, the behavior of θ is turbulent, for successively reaching stability. (Figure 8)" }, { "code": null, "e": 16868, "s": 16475, "text": "We can create a contour plot, which is a graph containing many concentric tracks. For each track there are various pairs of θ associated with a constant value of J. The θ corresponding to the minimum J, lies at the center (the red dot). The other concentric lines correspond to all the different values of J. The most the distance from the center, the higher the value of the Cost Function J." }, { "code": null, "e": 16905, "s": 16868, "text": "Code 20 produces the following plot:" }, { "code": null, "e": 17097, "s": 16905, "text": "Note that θ = [128.4; 9.9] corresponding to the minimum J (59.7), is the red dot in the center of the graph. The blue dots track the path of the Gradient Descent in converging to the minimum." }, { "code": null, "e": 17510, "s": 17097, "text": "We have explained the statistical mechanisms underlying Linear Regression with one variable: the feature Age in the SBP dataset. The major part of the code here proposed works also with multiple variables. The SBP dataset is composed of 2 features (Age and Weight) and one output: SBP. In this step, we will update the code in a way that it can fit with multiple variables. The only adjustments required concern:" }, { "code": null, "e": 17653, "s": 17510, "text": "The Dataset uploadingThe Feature Scaling and Normalization functionThe code for adding a column of “ones” to the vector XThe Prediction Query." }, { "code": null, "e": 17675, "s": 17653, "text": "The Dataset uploading" }, { "code": null, "e": 17722, "s": 17675, "text": "The Feature Scaling and Normalization function" }, { "code": null, "e": 17777, "s": 17722, "text": "The code for adding a column of “ones” to the vector X" }, { "code": null, "e": 17799, "s": 17777, "text": "The Prediction Query." }, { "code": null, "e": 17817, "s": 17799, "text": "Dataset uploading" }, { "code": null, "e": 17949, "s": 17817, "text": "The code for uploading the dataset has to be modified in order to produce a new X vector containing Age and Weight of each patient:" }, { "code": null, "e": 18083, "s": 17949, "text": "The numpy method used for producing the new X vector is .vstack() because we now want an X vector with two sets of distinct features." }, { "code": null, "e": 18126, "s": 18083, "text": "Feature Scaling and Normalization function" }, { "code": null, "e": 18270, "s": 18126, "text": "The code concerning Feature Scaling and Normalization is modified in vectors mu and sigma. Now the two vectors will accept two parameters each." }, { "code": null, "e": 18312, "s": 18270, "text": "Adding a column of “ones” to the vector X" }, { "code": null, "e": 18379, "s": 18312, "text": "The line for adding “ones” to the X vector is modified as follows:" }, { "code": null, "e": 18400, "s": 18379, "text": "The Prediction Query" }, { "code": null, "e": 18490, "s": 18400, "text": "The query for the predictions and the code for the normalization are modified as follows:" }, { "code": null, "e": 18545, "s": 18490, "text": "The prediction result, in this case, is an SBP =143.47" }, { "code": null, "e": 18726, "s": 18545, "text": "With these changes, the Python code is ready for Linear Regression with multiple variables. You have to update the code every time you will add new features from your training set!" }, { "code": null, "e": 18760, "s": 18726, "text": "I hope you find this post useful!" }, { "code": null, "e": 19329, "s": 18760, "text": "Andrew NG, Machine Learning | Coursera.John Pezzullo, Biostatistics For Dummies, Wiley, ISBN-13: 9781118553985Schneider, A; Hommel, G; Blettner, M. Linear Regression Analysis Part 14 of a Series on Evaluation of Scientific Publications, Dtsch Arztebl Int 2010; 107(44): 776–82; DOI: 10.3238/arztebl.2010.0776Chris Albon, Machine Learning with Python Cookbook, O’Really, ISBN-13: 978–1491989388.Aurélien Géron, Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems, O’Reilly, ISBN-13: 978–1491962299." }, { "code": null, "e": 19369, "s": 19329, "text": "Andrew NG, Machine Learning | Coursera." }, { "code": null, "e": 19441, "s": 19369, "text": "John Pezzullo, Biostatistics For Dummies, Wiley, ISBN-13: 9781118553985" }, { "code": null, "e": 19640, "s": 19441, "text": "Schneider, A; Hommel, G; Blettner, M. Linear Regression Analysis Part 14 of a Series on Evaluation of Scientific Publications, Dtsch Arztebl Int 2010; 107(44): 776–82; DOI: 10.3238/arztebl.2010.0776" }, { "code": null, "e": 19727, "s": 19640, "text": "Chris Albon, Machine Learning with Python Cookbook, O’Really, ISBN-13: 978–1491989388." } ]
Extract annotations from CVAT XML file into mask files in Python | by Oleksii Sheremet | Towards Data Science
The Computer Vision Annotation Tool (CVAT) is a well-known image annotation tool. The results of the data labelers work can be imported in XML file. This XML file contains all the necessary information about the markup. However, for image segmentation task it is necessary to have masks in the form of image files (JPEG, GIF, PNG, etc.). In other words, having the markup coordinates in the CVAT XML file, you need to draw the corresponding masks. If the data labelers worked with images in a higher resolution than it is supposed to be used for training, then the task will become more complicated. It is necessary to take into account the influence of the image compression factor on the numerical values of the cue points presented in the XML file. All code for extracting annotations is implemented as a script in Python. The lxml library is used for parsing XML. It is a fast and flexible solution for handling XML and HTML markup The lxml package has XPath and XSLT support, including an API for SAX and an API for compatibility with C modules. The tqdm package is used as a progress bar to illustrate the processing of a large number of files. Let’s take a closer look. Import libraries: import osimport cv2import argparseimport shutilimport numpy as npfrom lxml import etreefrom tqdm import tqdm A useful function for creating a new directory and recursively deleting the contents of an existing one: def dir_create(path): if (os.path.exists(path)) and (os.listdir(path) != []): shutil.rmtree(path) os.makedirs(path) if not os.path.exists(path): os.makedirs(path) The arguments for the script in question are the following data: directory with input images, input file with CVAT annotation in XML format, directory for output masks and scale factor for images. A function for parsing arguments from the command line: def parse_args(): parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations to contours' )parser.add_argument( '--image-dir', metavar='DIRECTORY', required=True, help='directory with input images' )parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file with CVAT annotation in xml format' )parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for output masks' )parser.add_argument( '--scale-factor', type=float, default=1.0, help='choose scale factor for images' )return parser.parse_args() For understanding how the extracting function works, let’s take a closer look at the section of the CVAT XML file: <image id="7" name="7.jpg" width="4800" height="2831"> <polygon label="roofs" occluded="0" points="2388.11,2069.80;2313.80,2089.10;2297.46,2080.21;2285.57,2043.80;2339.07,2031.17;2336.10,2018.54;2428.23,2060.89"> </polygon> <polygon label="roofs" occluded="0" points="1431.35,1161.11;1353.11,1179.63;1366.25,1229.79;1398.80,1219.94;1396.11,1210.08;1437.91,1194.26"> </polygon> <polygon label="roofs" occluded="0" points="1344.81,1673.28;1270.10,1619.40;1213.00,1697.00"> </polygon> <polygon label="roofs" occluded="0" points="1498.35,939.31;1573.30,923.19;1586.74,985.00;1509.10,1002.32"> </polygon>... At first, it is necessary to find in the XML file the area corresponding to the currently processed image. The easiest way to do this is by the file name (‘7.jpg’ in the example). Next, you need to find the tags ‘polygon’ or ‘box’ and extract the necessary data from them (in this example, roofs are marked on the basis of polygons). You can use the following function to obtain markup results from CVAT XML: def parse_anno_file(cvat_xml, image_name): root = etree.parse(cvat_xml).getroot() anno = []image_name_attr = ".//image[@name='{}']".format(image_name)for image_tag in root.iterfind(image_name_attr): image = {} for key, value in image_tag.items(): image[key] = value image['shapes'] = [] for poly_tag in image_tag.iter('polygon'): polygon = {'type': 'polygon'} for key, value in poly_tag.items(): polygon[key] = value image['shapes'].append(polygon) for box_tag in image_tag.iter('box'): box = {'type': 'box'} for key, value in box_tag.items(): box[key] = value box['points'] = "{0},{1};{2},{1};{2},{3};{0},{3}".format( box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image) return anno Next, we need to create mask files. Draw the sides of the mask polygons in white, and the inner content in red (as shown in the picture above). The following function allows you to do this: def create_mask_file(width, height, bitness, background, shapes, scale_factor): mask = np.full((height, width, bitness // 8), background, dtype=np.uint8) for shape in shapes: points = [tuple(map(float, p.split(','))) for p in shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1])) for p in points]) points = points*scale_factor points = points.astype(int) mask = cv2.drawContours(mask, [points], -1, color=(255, 255, 255), thickness=5) mask = cv2.fillPoly(mask, [points], color=(0, 0, 255)) return mask And in the end, the main function: def main(): args = parse_args() dir_create(args.output_dir) img_list = [f for f in os.listdir(args.image_dir) if os.path.isfile(os.path.join(args.image_dir, f))] mask_bitness = 24 for img in tqdm(img_list, desc='Writing contours:'): img_path = os.path.join(args.image_dir, img) anno = parse_anno_file(args.cvat_xml, img) background = [] is_first_image = True for image in anno: if is_first_image: current_image = cv2.imread(img_path) height, width, _ = current_image.shape background = np.zeros((height, width, 3), np.uint8) is_first_image = False output_path = os.path.join(args.output_dir, img.split('.')[0] + '.png') background = create_mask_file(width, height, mask_bitness, background, image['shapes'], args.scale_factor) cv2.imwrite(output_path, background) When we execute file as command to the python interpreter, we must add the following construct: if __name__ == "__main__": main() That’s all. To run the script, you should run the following command (scale factor is 1 by default when after markup you don’t resize images): python script_name.py --image-dir original_images_dir --cvat-xml cvat.xml --output-dir masks_dir --scale-factor 0.4 An original image example: The mask obtained as a result of the script: Conclusion The considered approach allows obtaining more complex mask files from the data contained in the CVAT XML. You can extract individual polygons or highlight polygons with different colors depending on the number of vertices. In addition, after a little revision, the considered script will allow cutting polygonal sections from the original images in accordance with the marking contour. References Computer Vision Annotation Tool (CVAT) lxml — XML and HTML with Python OpenCV How to Run Your Python Scripts
[ { "code": null, "e": 619, "s": 171, "text": "The Computer Vision Annotation Tool (CVAT) is a well-known image annotation tool. The results of the data labelers work can be imported in XML file. This XML file contains all the necessary information about the markup. However, for image segmentation task it is necessary to have masks in the form of image files (JPEG, GIF, PNG, etc.). In other words, having the markup coordinates in the CVAT XML file, you need to draw the corresponding masks." }, { "code": null, "e": 923, "s": 619, "text": "If the data labelers worked with images in a higher resolution than it is supposed to be used for training, then the task will become more complicated. It is necessary to take into account the influence of the image compression factor on the numerical values of the cue points presented in the XML file." }, { "code": null, "e": 1222, "s": 923, "text": "All code for extracting annotations is implemented as a script in Python. The lxml library is used for parsing XML. It is a fast and flexible solution for handling XML and HTML markup The lxml package has XPath and XSLT support, including an API for SAX and an API for compatibility with C modules." }, { "code": null, "e": 1322, "s": 1222, "text": "The tqdm package is used as a progress bar to illustrate the processing of a large number of files." }, { "code": null, "e": 1366, "s": 1322, "text": "Let’s take a closer look. Import libraries:" }, { "code": null, "e": 1475, "s": 1366, "text": "import osimport cv2import argparseimport shutilimport numpy as npfrom lxml import etreefrom tqdm import tqdm" }, { "code": null, "e": 1580, "s": 1475, "text": "A useful function for creating a new directory and recursively deleting the contents of an existing one:" }, { "code": null, "e": 1770, "s": 1580, "text": "def dir_create(path): if (os.path.exists(path)) and (os.listdir(path) != []): shutil.rmtree(path) os.makedirs(path) if not os.path.exists(path): os.makedirs(path)" }, { "code": null, "e": 2023, "s": 1770, "text": "The arguments for the script in question are the following data: directory with input images, input file with CVAT annotation in XML format, directory for output masks and scale factor for images. A function for parsing arguments from the command line:" }, { "code": null, "e": 2712, "s": 2023, "text": "def parse_args(): parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description='Convert CVAT XML annotations to contours' )parser.add_argument( '--image-dir', metavar='DIRECTORY', required=True, help='directory with input images' )parser.add_argument( '--cvat-xml', metavar='FILE', required=True, help='input file with CVAT annotation in xml format' )parser.add_argument( '--output-dir', metavar='DIRECTORY', required=True, help='directory for output masks' )parser.add_argument( '--scale-factor', type=float, default=1.0, help='choose scale factor for images' )return parser.parse_args()" }, { "code": null, "e": 2827, "s": 2712, "text": "For understanding how the extracting function works, let’s take a closer look at the section of the CVAT XML file:" }, { "code": null, "e": 3454, "s": 2827, "text": "<image id=\"7\" name=\"7.jpg\" width=\"4800\" height=\"2831\"> <polygon label=\"roofs\" occluded=\"0\" points=\"2388.11,2069.80;2313.80,2089.10;2297.46,2080.21;2285.57,2043.80;2339.07,2031.17;2336.10,2018.54;2428.23,2060.89\"> </polygon> <polygon label=\"roofs\" occluded=\"0\" points=\"1431.35,1161.11;1353.11,1179.63;1366.25,1229.79;1398.80,1219.94;1396.11,1210.08;1437.91,1194.26\"> </polygon> <polygon label=\"roofs\" occluded=\"0\" points=\"1344.81,1673.28;1270.10,1619.40;1213.00,1697.00\"> </polygon> <polygon label=\"roofs\" occluded=\"0\" points=\"1498.35,939.31;1573.30,923.19;1586.74,985.00;1509.10,1002.32\"> </polygon>..." }, { "code": null, "e": 3863, "s": 3454, "text": "At first, it is necessary to find in the XML file the area corresponding to the currently processed image. The easiest way to do this is by the file name (‘7.jpg’ in the example). Next, you need to find the tags ‘polygon’ or ‘box’ and extract the necessary data from them (in this example, roofs are marked on the basis of polygons). You can use the following function to obtain markup results from CVAT XML:" }, { "code": null, "e": 4841, "s": 3863, "text": "def parse_anno_file(cvat_xml, image_name): root = etree.parse(cvat_xml).getroot() anno = []image_name_attr = \".//image[@name='{}']\".format(image_name)for image_tag in root.iterfind(image_name_attr): image = {} for key, value in image_tag.items(): image[key] = value image['shapes'] = [] for poly_tag in image_tag.iter('polygon'): polygon = {'type': 'polygon'} for key, value in poly_tag.items(): polygon[key] = value image['shapes'].append(polygon) for box_tag in image_tag.iter('box'): box = {'type': 'box'} for key, value in box_tag.items(): box[key] = value box['points'] = \"{0},{1};{2},{1};{2},{3};{0},{3}\".format( box['xtl'], box['ytl'], box['xbr'], box['ybr']) image['shapes'].append(box) image['shapes'].sort(key=lambda x: int(x.get('z_order', 0))) anno.append(image) return anno" }, { "code": null, "e": 5031, "s": 4841, "text": "Next, we need to create mask files. Draw the sides of the mask polygons in white, and the inner content in red (as shown in the picture above). The following function allows you to do this:" }, { "code": null, "e": 5600, "s": 5031, "text": "def create_mask_file(width, height, bitness, background, shapes, scale_factor): mask = np.full((height, width, bitness // 8), background, dtype=np.uint8) for shape in shapes: points = [tuple(map(float, p.split(','))) for p in shape['points'].split(';')] points = np.array([(int(p[0]), int(p[1])) for p in points]) points = points*scale_factor points = points.astype(int) mask = cv2.drawContours(mask, [points], -1, color=(255, 255, 255), thickness=5) mask = cv2.fillPoly(mask, [points], color=(0, 0, 255)) return mask" }, { "code": null, "e": 5635, "s": 5600, "text": "And in the end, the main function:" }, { "code": null, "e": 6754, "s": 5635, "text": "def main(): args = parse_args() dir_create(args.output_dir) img_list = [f for f in os.listdir(args.image_dir) if os.path.isfile(os.path.join(args.image_dir, f))] mask_bitness = 24 for img in tqdm(img_list, desc='Writing contours:'): img_path = os.path.join(args.image_dir, img) anno = parse_anno_file(args.cvat_xml, img) background = [] is_first_image = True for image in anno: if is_first_image: current_image = cv2.imread(img_path) height, width, _ = current_image.shape background = np.zeros((height, width, 3), np.uint8) is_first_image = False output_path = os.path.join(args.output_dir, img.split('.')[0] + '.png') background = create_mask_file(width, height, mask_bitness, background, image['shapes'], args.scale_factor) cv2.imwrite(output_path, background)" }, { "code": null, "e": 6850, "s": 6754, "text": "When we execute file as command to the python interpreter, we must add the following construct:" }, { "code": null, "e": 6887, "s": 6850, "text": "if __name__ == \"__main__\": main()" }, { "code": null, "e": 7029, "s": 6887, "text": "That’s all. To run the script, you should run the following command (scale factor is 1 by default when after markup you don’t resize images):" }, { "code": null, "e": 7145, "s": 7029, "text": "python script_name.py --image-dir original_images_dir --cvat-xml cvat.xml --output-dir masks_dir --scale-factor 0.4" }, { "code": null, "e": 7172, "s": 7145, "text": "An original image example:" }, { "code": null, "e": 7217, "s": 7172, "text": "The mask obtained as a result of the script:" }, { "code": null, "e": 7228, "s": 7217, "text": "Conclusion" }, { "code": null, "e": 7614, "s": 7228, "text": "The considered approach allows obtaining more complex mask files from the data contained in the CVAT XML. You can extract individual polygons or highlight polygons with different colors depending on the number of vertices. In addition, after a little revision, the considered script will allow cutting polygonal sections from the original images in accordance with the marking contour." }, { "code": null, "e": 7625, "s": 7614, "text": "References" }, { "code": null, "e": 7664, "s": 7625, "text": "Computer Vision Annotation Tool (CVAT)" }, { "code": null, "e": 7696, "s": 7664, "text": "lxml — XML and HTML with Python" }, { "code": null, "e": 7703, "s": 7696, "text": "OpenCV" } ]
How to find the median for factor levels in R?
The second most used measure of central tendency median is calculated when we have ordinal data or the continuous data has outliers, also if there are factors data then we might need to find the median for levels to compare them with each other. The easiest way to do this is finding summary with aggregate function. Consider the below data frame that contains one factor column − Live Demo set.seed(191) x1<-as.factor(sample(LETTERS[1:3],20,replace=TRUE)) x2<-sample(1:10,20,replace=TRUE) df1<-data.frame(x1,x2) df1 x1 x2 1 B 6 2 C 5 3 B 4 4 C 8 5 B 5 6 B 5 7 A 4 8 C 8 9 C 3 10 C 4 11 B 9 12 A 10 13 C 6 14 C 1 15 A 10 16 A 3 17 A 5 18 C 7 19 B 3 20 C 1 > str(df1) 'data.frame': 20 obs. of 2 variables: $ x1: Factor w/ 3 levels "A","B","C": 2 3 2 3 2 2 1 3 3 3 ... $ x2: int 6 5 4 8 5 5 4 8 3 4 ... Finding the median of x2 for the categories in x1 − aggregate(x2~x1,data=df1,summary) x1 x2.Min. x2.1st Qu.x2.Median x2.Mean x2.3rd Qu. x2.Max. 1 A 3.000000 4.000000 5.000000 6.400000 10.000000 10.000000 2 B 3.000000 4.250000 5.000000 5.333333 5.750000 9.000000 3 C 1.000000 3.000000 5.000000 4.777778 7.000000 8.000000 Let’s have a look at another example − Live Demo Temperature<-as.factor(sample(c("Cold","Hot"),20,replace=TRUE)) Sales<-sample(50000:80000,20) df2<-data.frame(Temperature,Sales) df2 Temperature Sales 1 Cold 72210 2 Cold 56758 3 Hot 53809 4 Hot 79977 5 Hot 77135 6 Cold 56932 7 Hot 51104 8 Cold 67742 9 Hot 75402 10 Hot 62546 11 Cold 68520 12 Hot 54575 13 Cold 51591 14 Hot 55232 15 Hot 77742 16 Hot 62507 17 Hot 62156 18 Cold 73853 19 Cold 69807 20 Hot 53930 Finding the median of Sales for the categories in Temperature − aggregate(Sales~Temperature,data=df2,summary) Temperature Sales.Min. Sales.1st Qu. Sales.Median Sales.Mean Sales.3rd Qu. 1 Cold 51591.00 56888.50 68131.00 64676.62 70407.75 2 Hot 51104.00 54413.75 62331.50 63842.92 75835.25 Sales.Max. 1 73853.00 2 79977.00
[ { "code": null, "e": 1379, "s": 1062, "text": "The second most used measure of central tendency median is calculated when we have ordinal data or the continuous data has outliers, also if there are factors data then we might need to find the median for levels to compare them with each other. The easiest way to do this is finding summary with aggregate function." }, { "code": null, "e": 1443, "s": 1379, "text": "Consider the below data frame that contains one factor column −" }, { "code": null, "e": 1454, "s": 1443, "text": " Live Demo" }, { "code": null, "e": 1580, "s": 1454, "text": "set.seed(191)\nx1<-as.factor(sample(LETTERS[1:3],20,replace=TRUE))\nx2<-sample(1:10,20,replace=TRUE)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 1730, "s": 1580, "text": " x1 x2\n1 B 6\n2 C 5\n3 B 4\n4 C 8\n5 B 5\n6 B 5\n7 A 4\n8 C 8\n9 C 3\n10 C 4\n11 B 9\n12 A 10\n13 C 6\n14 C 1\n15 A 10\n16 A 3\n17 A 5\n18 C 7\n19 B 3\n20 C 1" }, { "code": null, "e": 1741, "s": 1730, "text": "> str(df1)" }, { "code": null, "e": 1875, "s": 1741, "text": "'data.frame': 20 obs. of 2 variables:\n$ x1: Factor w/ 3 levels \"A\",\"B\",\"C\": 2 3 2 3 2 2 1 3 3 3 ...\n$ x2: int 6 5 4 8 5 5 4 8 3 4 ..." }, { "code": null, "e": 1927, "s": 1875, "text": "Finding the median of x2 for the categories in x1 −" }, { "code": null, "e": 1961, "s": 1927, "text": "aggregate(x2~x1,data=df1,summary)" }, { "code": null, "e": 2207, "s": 1961, "text": " x1 x2.Min. x2.1st Qu.x2.Median x2.Mean x2.3rd Qu. x2.Max.\n1 A 3.000000 4.000000 5.000000 6.400000 10.000000 10.000000\n2 B 3.000000 4.250000 5.000000 5.333333 5.750000 9.000000\n3 C 1.000000 3.000000 5.000000 4.777778 7.000000 8.000000" }, { "code": null, "e": 2246, "s": 2207, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2257, "s": 2246, "text": " Live Demo" }, { "code": null, "e": 2390, "s": 2257, "text": "Temperature<-as.factor(sample(c(\"Cold\",\"Hot\"),20,replace=TRUE))\nSales<-sample(50000:80000,20)\ndf2<-data.frame(Temperature,Sales)\ndf2" }, { "code": null, "e": 2784, "s": 2390, "text": " Temperature Sales\n1 Cold 72210\n2 Cold 56758\n3 Hot 53809\n4 Hot 79977\n5 Hot 77135\n6 Cold 56932\n7 Hot 51104\n8 Cold 67742\n9 Hot 75402\n10 Hot 62546\n11 Cold 68520\n12 Hot 54575\n13 Cold 51591\n14 Hot 55232\n15 Hot 77742\n16 Hot 62507\n17 Hot 62156\n18 Cold 73853\n19 Cold 69807\n20 Hot 53930" }, { "code": null, "e": 2848, "s": 2784, "text": "Finding the median of Sales for the categories in Temperature −" }, { "code": null, "e": 2894, "s": 2848, "text": "aggregate(Sales~Temperature,data=df2,summary)" }, { "code": null, "e": 3150, "s": 2894, "text": " Temperature Sales.Min. Sales.1st Qu. Sales.Median Sales.Mean Sales.3rd Qu.\n1 Cold 51591.00 56888.50 68131.00 64676.62 70407.75\n2 Hot 51104.00 54413.75 62331.50 63842.92 75835.25\n Sales.Max.\n1 73853.00\n2 79977.00" } ]
Scala | Final - GeeksforGeeks
02 Sep, 2021 In Scala, Final is a keyword and used to impose restriction on super class or parent class through various ways. We can use final keyword along with variables, methods and classes.Following are the ways of using final keyword in Scala Scala Final Variable:Scale final variable initialized only once while declared and used as constant throughout the program. In below example, variable area is final which is declared as final and also initialized while declare in superclass shapes. if we want to access or modify the variable area from derived class Rectangle then it is not possible because the restriction on variable area is added by keyword final.Scala final variable initialized by following ways:While declaringIn static blockIn ConstructorScalaScala// Scala program of using final variableclass Shapes{ // define final variable final val area:Int = 60} class Rectangle extends Shapes{ override val area:Int = 100 def display() { println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.display() } }Following error occurs while running above codeOutput : prog.scala:5: error: overriding value area in class Shapes of type Int; value area cannot override final member override val area:Int = 100 ^ one error found Scala Final Methods:Final method CalArea in the parent class (Shapes) indicate that, method cannot override in a child class (Rectangle).ScalaScala// Scala program of using final methodclass Shapes{ val height:Int = 0 val width :Int =0 // Define final method final def CalArea(){ }} class Rectangle extends Shapes{ override def CalArea() { val area:Int = height * width println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput :prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit; method CalArea cannot override final member override def CalArea(){ ^ one error found Scala Final ClassesIf the class in Scala is final then it cannot inherit to derived class. Inheritance restriction will be added by final keyword. Here if class Shapes are final then its all members also final and cannot used in derived class.ScalaScala// Scala program of using final classfinal class Shapes{ // Final variables and functions val height:Int = 0 val width :Int =0 final def CalArea() { }} class Rectangle extends Shapes{ // Cannot inherit Shapes class override def CalArea() { val area:Int = height * width println(area) } } // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput : prog.scala:4: error: illegal inheritance from final class Shapes class Rectangle extends Shapes{ ^ one error found Scala Final Variable:Scale final variable initialized only once while declared and used as constant throughout the program. In below example, variable area is final which is declared as final and also initialized while declare in superclass shapes. if we want to access or modify the variable area from derived class Rectangle then it is not possible because the restriction on variable area is added by keyword final.Scala final variable initialized by following ways:While declaringIn static blockIn ConstructorScalaScala// Scala program of using final variableclass Shapes{ // define final variable final val area:Int = 60} class Rectangle extends Shapes{ override val area:Int = 100 def display() { println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.display() } }Following error occurs while running above codeOutput : prog.scala:5: error: overriding value area in class Shapes of type Int; value area cannot override final member override val area:Int = 100 ^ one error found Scala final variable initialized by following ways: While declaring In static block In Constructor Scala // Scala program of using final variableclass Shapes{ // define final variable final val area:Int = 60} class Rectangle extends Shapes{ override val area:Int = 100 def display() { println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.display() } } Output : prog.scala:5: error: overriding value area in class Shapes of type Int; value area cannot override final member override val area:Int = 100 ^ one error found Scala Final Methods:Final method CalArea in the parent class (Shapes) indicate that, method cannot override in a child class (Rectangle).ScalaScala// Scala program of using final methodclass Shapes{ val height:Int = 0 val width :Int =0 // Define final method final def CalArea(){ }} class Rectangle extends Shapes{ override def CalArea() { val area:Int = height * width println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput :prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit; method CalArea cannot override final member override def CalArea(){ ^ one error found Scala // Scala program of using final methodclass Shapes{ val height:Int = 0 val width :Int =0 // Define final method final def CalArea(){ }} class Rectangle extends Shapes{ override def CalArea() { val area:Int = height * width println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } } Output : prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit; method CalArea cannot override final member override def CalArea(){ ^ one error found Scala Final ClassesIf the class in Scala is final then it cannot inherit to derived class. Inheritance restriction will be added by final keyword. Here if class Shapes are final then its all members also final and cannot used in derived class.ScalaScala// Scala program of using final classfinal class Shapes{ // Final variables and functions val height:Int = 0 val width :Int =0 final def CalArea() { }} class Rectangle extends Shapes{ // Cannot inherit Shapes class override def CalArea() { val area:Int = height * width println(area) } } // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput : prog.scala:4: error: illegal inheritance from final class Shapes class Rectangle extends Shapes{ ^ one error found Scala // Scala program of using final classfinal class Shapes{ // Final variables and functions val height:Int = 0 val width :Int =0 final def CalArea() { }} class Rectangle extends Shapes{ // Cannot inherit Shapes class override def CalArea() { val area:Int = height * width println(area) } } // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } } Output : prog.scala:4: error: illegal inheritance from final class Shapes class Rectangle extends Shapes{ ^ one error found 9607whel Picked Scala Scala-Inheritance Scala-Keyword Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hello World in Scala Scala Map get() method with example Scala ListBuffer Scala List map() method with example How to install Scala on Windows? Inheritance in Scala Scala | Case Class and Case Object Scala | Traits Scala List length() method with example
[ { "code": null, "e": 23695, "s": 23667, "text": "\n02 Sep, 2021" }, { "code": null, "e": 23930, "s": 23695, "text": "In Scala, Final is a keyword and used to impose restriction on super class or parent class through various ways. We can use final keyword along with variables, methods and classes.Following are the ways of using final keyword in Scala" }, { "code": null, "e": 26835, "s": 23930, "text": "Scala Final Variable:Scale final variable initialized only once while declared and used as constant throughout the program. In below example, variable area is final which is declared as final and also initialized while declare in superclass shapes. if we want to access or modify the variable area from derived class Rectangle then it is not possible because the restriction on variable area is added by keyword final.Scala final variable initialized by following ways:While declaringIn static blockIn ConstructorScalaScala// Scala program of using final variableclass Shapes{ // define final variable final val area:Int = 60} class Rectangle extends Shapes{ override val area:Int = 100 def display() { println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.display() } }Following error occurs while running above codeOutput : \nprog.scala:5: error: overriding value area in class Shapes of type Int;\n value area cannot override final member\noverride val area:Int = 100\n ^\none error found\nScala Final Methods:Final method CalArea in the parent class (Shapes) indicate that, method cannot override in a child class (Rectangle).ScalaScala// Scala program of using final methodclass Shapes{ val height:Int = 0 val width :Int =0 // Define final method final def CalArea(){ }} class Rectangle extends Shapes{ override def CalArea() { val area:Int = height * width println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput :prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit;\n method CalArea cannot override final member\n override def CalArea(){\n ^\none error found\nScala Final ClassesIf the class in Scala is final then it cannot inherit to derived class. Inheritance restriction will be added by final keyword. Here if class Shapes are final then its all members also final and cannot used in derived class.ScalaScala// Scala program of using final classfinal class Shapes{ // Final variables and functions val height:Int = 0 val width :Int =0 final def CalArea() { }} class Rectangle extends Shapes{ // Cannot inherit Shapes class override def CalArea() { val area:Int = height * width println(area) } } // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput : \nprog.scala:4: error: illegal inheritance from final class Shapes\nclass Rectangle extends Shapes{\n ^\none error found\n" }, { "code": null, "e": 27962, "s": 26835, "text": "Scala Final Variable:Scale final variable initialized only once while declared and used as constant throughout the program. In below example, variable area is final which is declared as final and also initialized while declare in superclass shapes. if we want to access or modify the variable area from derived class Rectangle then it is not possible because the restriction on variable area is added by keyword final.Scala final variable initialized by following ways:While declaringIn static blockIn ConstructorScalaScala// Scala program of using final variableclass Shapes{ // define final variable final val area:Int = 60} class Rectangle extends Shapes{ override val area:Int = 100 def display() { println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.display() } }Following error occurs while running above codeOutput : \nprog.scala:5: error: overriding value area in class Shapes of type Int;\n value area cannot override final member\noverride val area:Int = 100\n ^\none error found\n" }, { "code": null, "e": 28014, "s": 27962, "text": "Scala final variable initialized by following ways:" }, { "code": null, "e": 28030, "s": 28014, "text": "While declaring" }, { "code": null, "e": 28046, "s": 28030, "text": "In static block" }, { "code": null, "e": 28061, "s": 28046, "text": "In Constructor" }, { "code": null, "e": 28067, "s": 28061, "text": "Scala" }, { "code": "// Scala program of using final variableclass Shapes{ // define final variable final val area:Int = 60} class Rectangle extends Shapes{ override val area:Int = 100 def display() { println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.display() } }", "e": 28442, "s": 28067, "text": null }, { "code": null, "e": 28451, "s": 28442, "text": "Output :" }, { "code": null, "e": 28626, "s": 28451, "text": " \nprog.scala:5: error: overriding value area in class Shapes of type Int;\n value area cannot override final member\noverride val area:Int = 100\n ^\none error found\n" }, { "code": null, "e": 29458, "s": 28626, "text": "Scala Final Methods:Final method CalArea in the parent class (Shapes) indicate that, method cannot override in a child class (Rectangle).ScalaScala// Scala program of using final methodclass Shapes{ val height:Int = 0 val width :Int =0 // Define final method final def CalArea(){ }} class Rectangle extends Shapes{ override def CalArea() { val area:Int = height * width println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput :prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit;\n method CalArea cannot override final member\n override def CalArea(){\n ^\none error found\n" }, { "code": null, "e": 29464, "s": 29458, "text": "Scala" }, { "code": "// Scala program of using final methodclass Shapes{ val height:Int = 0 val width :Int =0 // Define final method final def CalArea(){ }} class Rectangle extends Shapes{ override def CalArea() { val area:Int = height * width println(area) } } // Creating objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }", "e": 29903, "s": 29464, "text": null }, { "code": null, "e": 29912, "s": 29903, "text": "Output :" }, { "code": null, "e": 30104, "s": 29912, "text": "prog.scala:8: error: overriding method CalArea in class Shapes of type ()Unit;\n method CalArea cannot override final member\n override def CalArea(){\n ^\none error found\n" }, { "code": null, "e": 31052, "s": 30104, "text": "Scala Final ClassesIf the class in Scala is final then it cannot inherit to derived class. Inheritance restriction will be added by final keyword. Here if class Shapes are final then its all members also final and cannot used in derived class.ScalaScala// Scala program of using final classfinal class Shapes{ // Final variables and functions val height:Int = 0 val width :Int =0 final def CalArea() { }} class Rectangle extends Shapes{ // Cannot inherit Shapes class override def CalArea() { val area:Int = height * width println(area) } } // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }Following error occurs while running above codeOutput : \nprog.scala:4: error: illegal inheritance from final class Shapes\nclass Rectangle extends Shapes{\n ^\none error found\n" }, { "code": null, "e": 31058, "s": 31052, "text": "Scala" }, { "code": "// Scala program of using final classfinal class Shapes{ // Final variables and functions val height:Int = 0 val width :Int =0 final def CalArea() { }} class Rectangle extends Shapes{ // Cannot inherit Shapes class override def CalArea() { val area:Int = height * width println(area) } } // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { var b = new Rectangle() b.CalArea() } }", "e": 31557, "s": 31058, "text": null }, { "code": null, "e": 31566, "s": 31557, "text": "Output :" }, { "code": null, "e": 31708, "s": 31566, "text": " \nprog.scala:4: error: illegal inheritance from final class Shapes\nclass Rectangle extends Shapes{\n ^\none error found\n" }, { "code": null, "e": 31717, "s": 31708, "text": "9607whel" }, { "code": null, "e": 31724, "s": 31717, "text": "Picked" }, { "code": null, "e": 31730, "s": 31724, "text": "Scala" }, { "code": null, "e": 31748, "s": 31730, "text": "Scala-Inheritance" }, { "code": null, "e": 31762, "s": 31748, "text": "Scala-Keyword" }, { "code": null, "e": 31773, "s": 31762, "text": "Scala-OOPS" }, { "code": null, "e": 31779, "s": 31773, "text": "Scala" }, { "code": null, "e": 31877, "s": 31779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31886, "s": 31877, "text": "Comments" }, { "code": null, "e": 31899, "s": 31886, "text": "Old Comments" }, { "code": null, "e": 31920, "s": 31899, "text": "Hello World in Scala" }, { "code": null, "e": 31956, "s": 31920, "text": "Scala Map get() method with example" }, { "code": null, "e": 31973, "s": 31956, "text": "Scala ListBuffer" }, { "code": null, "e": 32010, "s": 31973, "text": "Scala List map() method with example" }, { "code": null, "e": 32043, "s": 32010, "text": "How to install Scala on Windows?" }, { "code": null, "e": 32064, "s": 32043, "text": "Inheritance in Scala" }, { "code": null, "e": 32099, "s": 32064, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 32114, "s": 32099, "text": "Scala | Traits" } ]
Introduction to Clinical Natural Language Processing: Predicting Hospital Readmission with Discharge Summaries | by Andrew Long | Towards Data Science
Doctors have always written clinical notes about their patients — originally, the notes were on paper and were locked away in a cabinet. Fortunately for data scientists, doctors now enter their notes in an electronic medical record. These notes represent a vast wealth of knowledge and insight that can be utilized for predictive models using Natural Language Processing (NLP) to improve patient care and hospital workflow. As an example, I will show you how to predict hospital readmission with discharge summaries. This article is intended for people interested in healthcare data science. After completing this tutorial, you will learn How to prepare data for a machine learning project How to preprocess the unstructured notes using a bag-of-words approach How to build a simple predictive model How to assess the quality of your model How to decide the next step for improving the model I recently read this great paper “Scalable and accurate deep learning for electronic health records” by Rajkomar et al. (paper at https://arxiv.org/abs/1801.07860). The authors built many state-of-the-art deep learning models with hospital data to predict in-hospital mortality (AUC = 0.93–0.94), 30-day unplanned readmission (AUC = 0.75–76), prolonged length of stay (AUC = 0.85–0.86) and discharge diagnoses (AUC = 0.90). AUC is a data science performance metric (more about this below) where closer to 1 is better. It is clear that predicting readmission is the hardest task since it has a lower AUC. I was curious how good of a model we can get if use the discharge free-text summaries with a simple predictive model. If you would like to follow along with the Python code in a Jupyter Notebook, feel free to download the code from my github. This blog post will outline how to build a classification model to predict which patients are at risk for 30-day unplanned readmission utilizing free-text hospital discharge summaries. We will utilize the MIMIC-III (Medical Information Mart for Intensive Care III) database. This amazing free hospital database contains de-identified data from over 50,000 patients who were admitted to Beth Israel Deaconess Medical Center in Boston, Massachusetts from 2001 to 2012. In order to get access to the data for this project, you will need to request access at this link (https://mimic.physionet.org/gettingstarted/access/). In this project, we will make use of the following MIMIC III tables ADMISSIONS — a table containing admission and discharge dates (has a unique identifier HADM_ID for each admission) NOTEEVENTS — contains all notes for each hospitalization (links with HADM_ID) To maintain anonymity, all dates have been shifted far into the future for each patient, but the time between two consecutive events for a patient is maintained in the database. This is important as it maintains the time between two hospitalizations for a specific patient. Since this is a restricted dataset, I am not able to publicly share raw patient data. As a result, I will only show you artificial single patient data or aggregated descriptions. We will follow the steps below to prepare the data from the ADMISSIONS and NOTEEVENTS MIMIC tables for our machine learning project. First, we load the admissions table using pandas dataframes: # set up notebookimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt# read the admissions tabledf_adm = pd.read_csv('ADMISSIONS.csv') The main columns of interest in this table are : SUBJECT_ID: unique identifier for each subject HADM_ID: unique identifier for each hospitalization ADMITTIME: admission date with format YYYY-MM-DD hh:mm:ss DISCHTIME: discharge date with same format DEATHTIME: death time (if it exists) with same format ADMISSION_TYPE: includes ELECTIVE, EMERGENCY, NEWBORN, URGENT The next step is to convert the dates from their string format into a datetime. We use the errors = ‘coerce’ flag to allow for missing dates. # convert to datesdf_adm.ADMITTIME = pd.to_datetime(df_adm.ADMITTIME, format = '%Y-%m-%d %H:%M:%S', errors = 'coerce')df_adm.DISCHTIME = pd.to_datetime(df_adm.DISCHTIME, format = '%Y-%m-%d %H:%M:%S', errors = 'coerce')df_adm.DEATHTIME = pd.to_datetime(df_adm.DEATHTIME, format = '%Y-%m-%d %H:%M:%S', errors = 'coerce') The next step is to get the next unplanned admission date if it exists. This will follow a few steps, and I’ll show you what happens for an artificial patient. First we will sort the dataframe by the admission date # sort by subject_ID and admission datedf_adm = df_adm.sort_values(['SUBJECT_ID','ADMITTIME'])df_adm = df_adm.reset_index(drop = True) The dataframe could look like this now for a single patient: We can use the groupby shift operator to get the next admission (if it exists) for each SUBJECT_ID # add the next admission date and type for each subject using groupby# you have to use groupby otherwise the dates will be from different subjectsdf_adm['NEXT_ADMITTIME'] = df_adm.groupby('SUBJECT_ID').ADMITTIME.shift(-1)# get the next admission typedf_adm['NEXT_ADMISSION_TYPE'] = df_adm.groupby('SUBJECT_ID').ADMISSION_TYPE.shift(-1) Note that the last admission doesn’t have a next admission. But, we want to predict UNPLANNED re-admissions, so we should filter out the ELECTIVE next admissions. # get rows where next admission is elective and replace with naT or nanrows = df_adm.NEXT_ADMISSION_TYPE == 'ELECTIVE'df_adm.loc[rows,'NEXT_ADMITTIME'] = pd.NaTdf_adm.loc[rows,'NEXT_ADMISSION_TYPE'] = np.NaN And then backfill the values that we removed # sort by subject_ID and admission date# it is safer to sort right before the fill in case something changed the order abovedf_adm = df_adm.sort_values(['SUBJECT_ID','ADMITTIME'])# back fill (this will take a little while)df_adm[['NEXT_ADMITTIME','NEXT_ADMISSION_TYPE']] = df_adm.groupby(['SUBJECT_ID'])[['NEXT_ADMITTIME','NEXT_ADMISSION_TYPE']].fillna(method = 'bfill') We can then calculate the days until the next admission df_adm['DAYS_NEXT_ADMIT']= (df_adm.NEXT_ADMITTIME - df_adm.DISCHTIME).dt.total_seconds()/(24*60*60) In our dataset with 58976 hospitalizations, there are 11399 re-admissions. For those with a re-admission, we can plot the histogram of days between admissions. Now we are ready to work with the NOTEEVENTS.csv df_notes = pd.read_csv("NOTEEVENTS.csv") The main columns of interest are: SUBJECT_ID HADM_ID CATEGORY: includes ‘Discharge summary’, ‘Echo’, ‘ECG’, ‘Nursing’, ‘Physician ‘, ‘Rehab Services’, ‘Case Management ‘, ‘Respiratory ‘, ‘Nutrition’, ‘General’, ‘Social Work’, ‘Pharmacy’, ‘Consult’, ‘Radiology’, ‘Nursing/other’ TEXT: our clinical notes column Since I can’t show individual notes, I will just describe them here. The dataset has 2,083,180 rows, indicating that there are multiple notes per hospitalization. In the notes, the dates and PHI (name, doctor, location) have been converted for confidentiality. There are also special characters such as \n (new line), numbers and punctuation. Since there are multiple notes per hospitalization, we need to make a choice on what notes to use. For simplicity, let’s use the discharge summary, but we could use all the notes by concatenating them if we wanted. # filter to discharge summarydf_notes_dis_sum = df_notes.loc[df_notes.CATEGORY == 'Discharge summary'] Since the next step is to merge the notes on the admissions table, we might have the assumption that there is one discharge summary per admission, but we should probably check this. We can check this with an assert statement, which ends up failing. At this point, you might want to investigate why there are multiple summaries, but for simplicity let’s just use the last one df_notes_dis_sum_last = (df_notes_dis_sum.groupby(['SUBJECT_ID','HADM_ID']).nth(-1)).reset_index()assert df_notes_dis_sum_last.duplicated(['HADM_ID']).sum() == 0, 'Multiple discharge summaries per admission' Now we are ready to merge the admissions and notes tables. I use a left merge to account for when notes are missing. There are a lot of cases where you get multiple rows after a merge(although we dealt with it above), so I like to add assert statements after a merge df_adm_notes = pd.merge(df_adm[['SUBJECT_ID','HADM_ID','ADMITTIME','DISCHTIME','DAYS_NEXT_ADMIT','NEXT_ADMITTIME','ADMISSION_TYPE','DEATHTIME']], df_notes_dis_sum_last[['SUBJECT_ID','HADM_ID','TEXT']], on = ['SUBJECT_ID','HADM_ID'], how = 'left')assert len(df_adm) == len(df_adm_notes), 'Number of rows increased' 10.6 % of the admissions are missing (df_adm_notes.TEXT.isnull().sum() / len(df_adm_notes)), so I investigated a bit further with df_adm_notes.groupby('ADMISSION_TYPE').apply(lambda g: g.TEXT.isnull().sum())/df_adm_notes.groupby('ADMISSION_TYPE').size() and discovered that 53% of the NEWBORN admissions were missing discharge summaries vs ~4% for the others. At this point I decided to remove the NEWBORN admissions. Most likely, these missing NEWBORN admissions have their discharge summary stored outside of the MIMIC dataset. For this problem, we are going to classify if a patient will be admitted in the next 30 days. Therefore, we need to create a variable with the output label (1 = readmitted, 0 = not readmitted) df_adm_notes_clean['OUTPUT_LABEL'] = (df_adm_notes_clean.DAYS_NEXT_ADMIT < 30).astype('int') A quick count of positive and negative results in 3004 positive samples, 48109 negative samples. This indicates that we have an imbalanced dataset, which is a common occurrence in healthcare data science. The last step to prepare our data is to split the data into training, validation and test sets. For reproducible results, I have made the random_state always 42. # shuffle the samplesdf_adm_notes_clean = df_adm_notes_clean.sample(n = len(df_adm_notes_clean), random_state = 42)df_adm_notes_clean = df_adm_notes_clean.reset_index(drop = True)# Save 30% of the data as validation and test data df_valid_test=df_adm_notes_clean.sample(frac=0.30,random_state=42)df_test = df_valid_test.sample(frac = 0.5, random_state = 42)df_valid = df_valid_test.drop(df_test.index)# use the rest of the data as training datadf_train_all=df_adm_notes_clean.drop(df_valid_test.index) Since the prevalence is so low, we want to prevent the model from always predicting negative (not re-admitted). To do this, we have a few options to balance the training data sub-sampling the negatives over-sampling the positives create synthetic data (e.g. SMOTE) Since I didn’t make any restrictions on size of RAM for your computer, we will sub-sample the negatives, but I encourage you to try out the other techniques if your computer or server can handle it to see if you can get an improvement. (Post as a comment below if you try this out!) # split the training data into positive and negativerows_pos = df_train_all.OUTPUT_LABEL == 1df_train_pos = df_train_all.loc[rows_pos]df_train_neg = df_train_all.loc[~rows_pos]# merge the balanced datadf_train = pd.concat([df_train_pos, df_train_neg.sample(n = len(df_train_pos), random_state = 42)],axis = 0)# shuffle the order of training samples df_train = df_train.sample(n = len(df_train), random_state = 42).reset_index(drop = True) Now that we have created data sets that have a label and the notes, we need to preprocess our text data to convert it to something useful (i.e. numbers) for the machine learning model. We are going to use the Bag-of-Words (BOW) approach. BOW basically breaks up the note into the individual words and counts how many times each word occurs. Your numerical data then becomes counts for some set of words as shown below. BOW is the simplest way to do NLP classification. In most blog posts I have read, fancier techniques have a hard time beating BOW for NLP classification tasks. In this process, there are few choices that need to be made how to preprocess the words how to count the words which words to use There is no optimal choice for all NLP projects, so I recommend trying out a few options when building your own models. You can do the preprocessing in two ways modify the original dataframe TEXT column preprocess as part of your pipeline so you don’t edit the original data I will show you how to do both of these, but I prefer the second one since it took a lot of work to get to this point. Let’s define a function that will modify the original dataframe by filling missing notes with space and removing newline and carriage returns def preprocess_text(df): # This function preprocesses the text by filling not a number and replacing new lines ('\n') and carriage returns ('\r') df.TEXT = df.TEXT.fillna(' ') df.TEXT = df.TEXT.str.replace('\n',' ') df.TEXT = df.TEXT.str.replace('\r',' ') return df# preprocess the text to deal with known issuesdf_train = preprocess_text(df_train)df_valid = preprocess_text(df_valid)df_test = preprocess_text(df_test) The other option is to preprocess as part of the pipeline. This process consists of using a tokenizer and a vectorizer. The tokenizer breaks a single note into a list of words and a vectorizer takes a list of words and counts the words. We will use word_tokenize from the nltk package for our default tokenizer, which basically breaks the note based on spaces and some punctuation. An example is shown below: import nltkfrom nltk import word_tokenizeword_tokenize('This should be tokenized. 02/02/2018 sentence has stars**') With output: [‘This’, ‘should’, ‘be’, ‘tokenized’, ‘.’, ‘02/02/2018’, ‘sentence’, ‘has’, ‘stars**’] The default shows that some punctuation is separated and that numbers stay in the sentence. We will write our own tokenizer function to replace punctuation with spaces replace numbers with spaces lower case all words import stringdef tokenizer_better(text): # tokenize the text by replacing punctuation and numbers with spaces and lowercase all words punc_list = string.punctuation+'0123456789' t = str.maketrans(dict.fromkeys(punc_list, " ")) text = text.lower().translate(t) tokens = word_tokenize(text) return tokens With this tokenizer we get from our original sentence ['this', 'should', 'be', 'tokenized', 'sentence', 'has', 'stars'] Additional things you can do would be to lemmatize or stem the words, but that is more advanced so I’ll skip that. Now that we have a way to convert free-text into tokens, we need a way to count the tokens for each discharge summary. We will use the built in CountVectorizer from scikit-learn package. This vectorizer simply counts how many times each word occurs in the note. There is also a TfidfVectorizer which takes into how often words are used across all notes, but for this project let’s use the simpler one (I got similar results with the second one too). As an example, let’s say we have 3 notes sample_text = ['Data science is about the data', 'The science is amazing', 'Predictive modeling is part of data science'] Essentially, you fit the CountVectorizer to learn the words in your data and the transform your data to create counts for each word. from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(tokenizer = tokenizer_better)vect.fit(sample_text)# matrix is stored as a sparse matrix (since you have a lot of zeros)X = vect.transform(sample_text) The matrix X will be a sparse matrix, but if you convert it to an array (X.toarray()), you will see this array([[1, 0, 2, 1, 0, 0, 0, 0, 1, 1], [0, 1, 0, 1, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0]], dtype=int64) Where there are 3 rows (since we have 3 notes) and counts of each word. You can see the column names with vect.get_feature_names() ['about', 'amazing', 'data', 'is', 'modeling', 'of', 'part', 'predictive', 'science', 'the'] We can now fit our CountVectorizer on the clinical notes. It is important to use only the training data because you don’t want to include any new words that show up in the validation and test sets. There is a hyperparameter called max_features which you can set to constrain how many words are included in the Vectorizer. This will use the top N most frequently used words. In step 5, we will adjust this to see its effect. # fit our vectorizer. This will take a while depending on your computer. from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(max_features = 3000, tokenizer = tokenizer_better)# this could take a whilevect.fit(df_train.TEXT.values) We can look at the most frequently used words and we will see that many of these words might not add any value for our model. These words are called stop words, and we can remove them easily (if we want) with the CountVectorizer. There are lists of common stop words for different NLP corpus, but we will just make up our own based on the image below. my_stop_words = ['the','and','to','of','was','with','a','on','in','for','name', 'is','patient','s','he','at','as','or','one','she','his','her','am', 'were','you','pt','pm','by','be','had','your','this','date', 'from','there','an','that','p','are','have','has','h','but','o', 'namepattern','which','every','also'] Feel free to add your own stop words if you want. from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(max_features = 3000, tokenizer = tokenizer_better, stop_words = my_stop_words)# this could take a whilevect.fit(df_train.TEXT.values) Now we can transform our notes into numerical matrices. At this point, I will only use the training and validation data so I’m not tempted to see how it works on the test data yet. X_train_tf = vect.transform(df_train.TEXT.values)X_valid_tf = vect.transform(df_valid.TEXT.values) We also need our output labels as separate variables y_train = df_train.OUTPUT_LABELy_valid = df_valid.OUTPUT_LABEL As seen by the location of the scroll bar... as always, it takes 80% of the time to get the data ready for the predictive model. We can now build a simple predictive model that takes our bag-of-words inputs and predicts if a patient will be readmitted in 30 days (YES = 1, NO = 0). Here we will use the Logistic Regression model. Logistic regression is a good baseline model for NLP tasks since it works well with sparse matrices and is interpretable. We have a few additional choices (called hyperparameters) including C which is a coefficient on regularization and penalty which tells how to measure the regularization. Regularization is essentially a technique to try to minimize overfitting. # logistic regressionfrom sklearn.linear_model import LogisticRegressionclf=LogisticRegression(C = 0.0001, penalty = 'l2', random_state = 42)clf.fit(X_train_tf, y_train) We can calculate the probability of readmission for each sample with the fitted model model = clfy_train_preds = model.predict_proba(X_train_tf)[:,1]y_valid_preds = model.predict_proba(X_valid_tf)[:,1] At this point, we need to measure how well our model performed. There are a few different data science performance metrics. I wrote another blog post explaining these in detail if you are interested. Since this post is quite long now, I will start just showing results and figures. You can see the github account for the code to produce the figures. For a threshold of 0.5 for predicting positive, we get the following performance With the current selection of hyperparameters, we do have some overfitting. One thing to point out is that the major difference between the precision in the two sets of data is due to the fact that we balanced the training set, where as the validation set is the original distribution. Currently, if we make a list of patients predicted to be readmitted we catch twice as many of them as if we randomly selected patients (PRECISION vs PREVALENCE). Another performance metric not shown above is AUC or area under the ROC curve. The ROC curve for our current model is shown below. Essentially the ROC curve allows you to see the trade-off between true positive rate and false positive rate as you vary the threshold on what you define as predicted positive vs predicted negative. At this point, you might be tempted to calculate the performance on your test set and see how you did. But wait! We made many choices (a few below) which we could change and see if there is an improvement: should we spend time getting more data? how to tokenize — should we use stemming? how to vectorize — should we change the number of words? how to regularized the logistic regression — should we change C or penalty? which model to use? When I am trying to improve my models, I read a lot of other blog posts and articles to see how people tackled similar issues. When you do this, you start to see interesting ways to visualize data and I highly recommend holding on to these techniques for your own projects. For NLP projects that use BOW+logistic regression, we can plot the most important words to see if we can gain any insight. For this step, I borrowed code from a nice NLP article by Insight Data Science. When you look at the most important words, I see two immediate things: Oops! I forgot to exclude the patients who died since ‘expired’ showed up in the negative list. For now, I will ignore this and fix it below. There are also some other stop words we should probably remove (‘should’,’if’,’it’,’been’,’who’,’during’, ‘x’) When we want to improve the model, we want to do it in a data-driven manner. You can spend a lot of time on ‘hunches’, that don’t end up panning out. To do this, it is recommend to pick a single performance metric that you use to make your decisions. For this project, I am going to pick AUC. For the first question above, we can plot something called a Learning Curve to understand the effect of adding more data. Andrew Ng has a set of great Coursera classes on the discussion of high-bias vs high-variance models. We can see that we have some overfitting but adding more data is likely not going to drastically change the AUC on a validation set. This is good to know because it means we shouldn’t spend months getting more data. Some simple things that we can do is try to see the effect of some of our hyperparameters (max_features and C). We could run a grid search, but since we only have 2 parameters here we could look at them separately and see the effect. We can see that increasing C and max_features, cause the model to overfit pretty quickly. I selected C = 0.0001 and max_features = 3000 where the validation set started to plateau. At this point, you could try a few other things change sub-sample to over-sample add stemming or lemmatization to the tokenizer test a few different sci-kit learn models concatenate all the notes instead of the last discharge summary try a deep learning method such as LSTMs review the discharge summaries that you are getting wrong We will now fit our final model with hyperparameter selection. We will also exclude the patients who died with a re-balancing. rows_not_death = df_adm_notes_clean.DEATHTIME.isnull()df_adm_notes_not_death = df_adm_notes_clean.loc[rows_not_death].copy()df_adm_notes_not_death = df_adm_notes_not_death.sample(n = len(df_adm_notes_not_death), random_state = 42)df_adm_notes_not_death = df_adm_notes_not_death.reset_index(drop = True)# Save 30% of the data as validation and test data df_valid_test=df_adm_notes_not_death.sample(frac=0.30,random_state=42)df_test = df_valid_test.sample(frac = 0.5, random_state = 42)df_valid = df_valid_test.drop(df_test.index)# use the rest of the data as training datadf_train_all=df_adm_notes_not_death.drop(df_valid_test.index)assert len(df_adm_notes_not_death) == (len(df_test)+len(df_valid)+len(df_train_all)),'math didnt work'# split the training data into positive and negativerows_pos = df_train_all.OUTPUT_LABEL == 1df_train_pos = df_train_all.loc[rows_pos]df_train_neg = df_train_all.loc[~rows_pos]# merge the balanced datadf_train = pd.concat([df_train_pos, df_train_neg.sample(n = len(df_train_pos), random_state = 42)],axis = 0)# shuffle the order of training samples df_train = df_train.sample(n = len(df_train), random_state = 42).reset_index(drop = True)# preprocess the text to deal with known issuesdf_train = preprocess_text(df_train)df_valid = preprocess_text(df_valid)df_test = preprocess_text(df_test)my_new_stop_words = ['the','and','to','of','was','with','a','on','in','for','name', 'is','patient','s','he','at','as','or','one','she','his','her','am', 'were','you','pt','pm','by','be','had','your','this','date', 'from','there','an','that','p','are','have','has','h','but','o', 'namepattern','which','every','also','should','if','it','been','who','during', 'x']from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(lowercase = True, max_features = 3000, tokenizer = tokenizer_better, stop_words = my_new_stop_words)# fit the vectorizervect.fit(df_train.TEXT.values)X_train_tf = vect.transform(df_train.TEXT.values)X_valid_tf = vect.transform(df_valid.TEXT.values)X_test_tf = vect.transform(df_test.TEXT.values)y_train = df_train.OUTPUT_LABELy_valid = df_valid.OUTPUT_LABELy_test = df_test.OUTPUT_LABELfrom sklearn.linear_model import LogisticRegressionclf=LogisticRegression(C = 0.0001, penalty = 'l2', random_state = 42)clf.fit(X_train_tf, y_train)model = clfy_train_preds = model.predict_proba(X_train_tf)[:,1]y_valid_preds = model.predict_proba(X_valid_tf)[:,1]y_test_preds = model.predict_proba(X_test_tf)[:,1] This produces the following results and ROC curve. Congratulations! You built a simple NLP model (AUC = 0.70) to predict re-admission based on hospital discharge summaries that is only slightly worse than the state-of-the-art deep learning method that uses all hospital data (AUC = 0.75). If you have any feedback, feel free to leave it below. If you are interested in deep learning NLP in healthcare, I recommend reading the article by Erin Craig at https://arxiv.org/abs/1711.10663 Scalable and accurate deep learning with electronic health records. Rajkomar A, Oren E, Chen K, et al. NPJ Digital Medicine (2018). DOI: 10.1038/s41746–018–0029–1. Available at: https://www.nature.com/articles/s41746-018-0029-1 MIMIC-III, a freely accessible critical care database. Johnson AEW, Pollard TJ, Shen L, Lehman L, Feng M, Ghassemi M, Moody B, Szolovits P, Celi LA, and Mark RG. Scientific Data (2016). DOI: 10.1038/sdata.2016.35. Available at: http://www.nature.com/articles/sdata201635
[ { "code": null, "e": 688, "s": 171, "text": "Doctors have always written clinical notes about their patients — originally, the notes were on paper and were locked away in a cabinet. Fortunately for data scientists, doctors now enter their notes in an electronic medical record. These notes represent a vast wealth of knowledge and insight that can be utilized for predictive models using Natural Language Processing (NLP) to improve patient care and hospital workflow. As an example, I will show you how to predict hospital readmission with discharge summaries." }, { "code": null, "e": 810, "s": 688, "text": "This article is intended for people interested in healthcare data science. After completing this tutorial, you will learn" }, { "code": null, "e": 861, "s": 810, "text": "How to prepare data for a machine learning project" }, { "code": null, "e": 932, "s": 861, "text": "How to preprocess the unstructured notes using a bag-of-words approach" }, { "code": null, "e": 971, "s": 932, "text": "How to build a simple predictive model" }, { "code": null, "e": 1011, "s": 971, "text": "How to assess the quality of your model" }, { "code": null, "e": 1063, "s": 1011, "text": "How to decide the next step for improving the model" }, { "code": null, "e": 1785, "s": 1063, "text": "I recently read this great paper “Scalable and accurate deep learning for electronic health records” by Rajkomar et al. (paper at https://arxiv.org/abs/1801.07860). The authors built many state-of-the-art deep learning models with hospital data to predict in-hospital mortality (AUC = 0.93–0.94), 30-day unplanned readmission (AUC = 0.75–76), prolonged length of stay (AUC = 0.85–0.86) and discharge diagnoses (AUC = 0.90). AUC is a data science performance metric (more about this below) where closer to 1 is better. It is clear that predicting readmission is the hardest task since it has a lower AUC. I was curious how good of a model we can get if use the discharge free-text summaries with a simple predictive model." }, { "code": null, "e": 1910, "s": 1785, "text": "If you would like to follow along with the Python code in a Jupyter Notebook, feel free to download the code from my github." }, { "code": null, "e": 2095, "s": 1910, "text": "This blog post will outline how to build a classification model to predict which patients are at risk for 30-day unplanned readmission utilizing free-text hospital discharge summaries." }, { "code": null, "e": 2529, "s": 2095, "text": "We will utilize the MIMIC-III (Medical Information Mart for Intensive Care III) database. This amazing free hospital database contains de-identified data from over 50,000 patients who were admitted to Beth Israel Deaconess Medical Center in Boston, Massachusetts from 2001 to 2012. In order to get access to the data for this project, you will need to request access at this link (https://mimic.physionet.org/gettingstarted/access/)." }, { "code": null, "e": 2597, "s": 2529, "text": "In this project, we will make use of the following MIMIC III tables" }, { "code": null, "e": 2712, "s": 2597, "text": "ADMISSIONS — a table containing admission and discharge dates (has a unique identifier HADM_ID for each admission)" }, { "code": null, "e": 2790, "s": 2712, "text": "NOTEEVENTS — contains all notes for each hospitalization (links with HADM_ID)" }, { "code": null, "e": 3064, "s": 2790, "text": "To maintain anonymity, all dates have been shifted far into the future for each patient, but the time between two consecutive events for a patient is maintained in the database. This is important as it maintains the time between two hospitalizations for a specific patient." }, { "code": null, "e": 3243, "s": 3064, "text": "Since this is a restricted dataset, I am not able to publicly share raw patient data. As a result, I will only show you artificial single patient data or aggregated descriptions." }, { "code": null, "e": 3376, "s": 3243, "text": "We will follow the steps below to prepare the data from the ADMISSIONS and NOTEEVENTS MIMIC tables for our machine learning project." }, { "code": null, "e": 3437, "s": 3376, "text": "First, we load the admissions table using pandas dataframes:" }, { "code": null, "e": 3588, "s": 3437, "text": "# set up notebookimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt# read the admissions tabledf_adm = pd.read_csv('ADMISSIONS.csv')" }, { "code": null, "e": 3637, "s": 3588, "text": "The main columns of interest in this table are :" }, { "code": null, "e": 3684, "s": 3637, "text": "SUBJECT_ID: unique identifier for each subject" }, { "code": null, "e": 3736, "s": 3684, "text": "HADM_ID: unique identifier for each hospitalization" }, { "code": null, "e": 3794, "s": 3736, "text": "ADMITTIME: admission date with format YYYY-MM-DD hh:mm:ss" }, { "code": null, "e": 3837, "s": 3794, "text": "DISCHTIME: discharge date with same format" }, { "code": null, "e": 3891, "s": 3837, "text": "DEATHTIME: death time (if it exists) with same format" }, { "code": null, "e": 3953, "s": 3891, "text": "ADMISSION_TYPE: includes ELECTIVE, EMERGENCY, NEWBORN, URGENT" }, { "code": null, "e": 4095, "s": 3953, "text": "The next step is to convert the dates from their string format into a datetime. We use the errors = ‘coerce’ flag to allow for missing dates." }, { "code": null, "e": 4414, "s": 4095, "text": "# convert to datesdf_adm.ADMITTIME = pd.to_datetime(df_adm.ADMITTIME, format = '%Y-%m-%d %H:%M:%S', errors = 'coerce')df_adm.DISCHTIME = pd.to_datetime(df_adm.DISCHTIME, format = '%Y-%m-%d %H:%M:%S', errors = 'coerce')df_adm.DEATHTIME = pd.to_datetime(df_adm.DEATHTIME, format = '%Y-%m-%d %H:%M:%S', errors = 'coerce')" }, { "code": null, "e": 4629, "s": 4414, "text": "The next step is to get the next unplanned admission date if it exists. This will follow a few steps, and I’ll show you what happens for an artificial patient. First we will sort the dataframe by the admission date" }, { "code": null, "e": 4764, "s": 4629, "text": "# sort by subject_ID and admission datedf_adm = df_adm.sort_values(['SUBJECT_ID','ADMITTIME'])df_adm = df_adm.reset_index(drop = True)" }, { "code": null, "e": 4825, "s": 4764, "text": "The dataframe could look like this now for a single patient:" }, { "code": null, "e": 4924, "s": 4825, "text": "We can use the groupby shift operator to get the next admission (if it exists) for each SUBJECT_ID" }, { "code": null, "e": 5260, "s": 4924, "text": "# add the next admission date and type for each subject using groupby# you have to use groupby otherwise the dates will be from different subjectsdf_adm['NEXT_ADMITTIME'] = df_adm.groupby('SUBJECT_ID').ADMITTIME.shift(-1)# get the next admission typedf_adm['NEXT_ADMISSION_TYPE'] = df_adm.groupby('SUBJECT_ID').ADMISSION_TYPE.shift(-1)" }, { "code": null, "e": 5320, "s": 5260, "text": "Note that the last admission doesn’t have a next admission." }, { "code": null, "e": 5423, "s": 5320, "text": "But, we want to predict UNPLANNED re-admissions, so we should filter out the ELECTIVE next admissions." }, { "code": null, "e": 5631, "s": 5423, "text": "# get rows where next admission is elective and replace with naT or nanrows = df_adm.NEXT_ADMISSION_TYPE == 'ELECTIVE'df_adm.loc[rows,'NEXT_ADMITTIME'] = pd.NaTdf_adm.loc[rows,'NEXT_ADMISSION_TYPE'] = np.NaN" }, { "code": null, "e": 5676, "s": 5631, "text": "And then backfill the values that we removed" }, { "code": null, "e": 6047, "s": 5676, "text": "# sort by subject_ID and admission date# it is safer to sort right before the fill in case something changed the order abovedf_adm = df_adm.sort_values(['SUBJECT_ID','ADMITTIME'])# back fill (this will take a little while)df_adm[['NEXT_ADMITTIME','NEXT_ADMISSION_TYPE']] = df_adm.groupby(['SUBJECT_ID'])[['NEXT_ADMITTIME','NEXT_ADMISSION_TYPE']].fillna(method = 'bfill')" }, { "code": null, "e": 6103, "s": 6047, "text": "We can then calculate the days until the next admission" }, { "code": null, "e": 6204, "s": 6103, "text": "df_adm['DAYS_NEXT_ADMIT']= (df_adm.NEXT_ADMITTIME - df_adm.DISCHTIME).dt.total_seconds()/(24*60*60)" }, { "code": null, "e": 6364, "s": 6204, "text": "In our dataset with 58976 hospitalizations, there are 11399 re-admissions. For those with a re-admission, we can plot the histogram of days between admissions." }, { "code": null, "e": 6413, "s": 6364, "text": "Now we are ready to work with the NOTEEVENTS.csv" }, { "code": null, "e": 6454, "s": 6413, "text": "df_notes = pd.read_csv(\"NOTEEVENTS.csv\")" }, { "code": null, "e": 6488, "s": 6454, "text": "The main columns of interest are:" }, { "code": null, "e": 6499, "s": 6488, "text": "SUBJECT_ID" }, { "code": null, "e": 6507, "s": 6499, "text": "HADM_ID" }, { "code": null, "e": 6732, "s": 6507, "text": "CATEGORY: includes ‘Discharge summary’, ‘Echo’, ‘ECG’, ‘Nursing’, ‘Physician ‘, ‘Rehab Services’, ‘Case Management ‘, ‘Respiratory ‘, ‘Nutrition’, ‘General’, ‘Social Work’, ‘Pharmacy’, ‘Consult’, ‘Radiology’, ‘Nursing/other’" }, { "code": null, "e": 6764, "s": 6732, "text": "TEXT: our clinical notes column" }, { "code": null, "e": 7107, "s": 6764, "text": "Since I can’t show individual notes, I will just describe them here. The dataset has 2,083,180 rows, indicating that there are multiple notes per hospitalization. In the notes, the dates and PHI (name, doctor, location) have been converted for confidentiality. There are also special characters such as \\n (new line), numbers and punctuation." }, { "code": null, "e": 7322, "s": 7107, "text": "Since there are multiple notes per hospitalization, we need to make a choice on what notes to use. For simplicity, let’s use the discharge summary, but we could use all the notes by concatenating them if we wanted." }, { "code": null, "e": 7425, "s": 7322, "text": "# filter to discharge summarydf_notes_dis_sum = df_notes.loc[df_notes.CATEGORY == 'Discharge summary']" }, { "code": null, "e": 7674, "s": 7425, "text": "Since the next step is to merge the notes on the admissions table, we might have the assumption that there is one discharge summary per admission, but we should probably check this. We can check this with an assert statement, which ends up failing." }, { "code": null, "e": 7800, "s": 7674, "text": "At this point, you might want to investigate why there are multiple summaries, but for simplicity let’s just use the last one" }, { "code": null, "e": 8008, "s": 7800, "text": "df_notes_dis_sum_last = (df_notes_dis_sum.groupby(['SUBJECT_ID','HADM_ID']).nth(-1)).reset_index()assert df_notes_dis_sum_last.duplicated(['HADM_ID']).sum() == 0, 'Multiple discharge summaries per admission'" }, { "code": null, "e": 8275, "s": 8008, "text": "Now we are ready to merge the admissions and notes tables. I use a left merge to account for when notes are missing. There are a lot of cases where you get multiple rows after a merge(although we dealt with it above), so I like to add assert statements after a merge" }, { "code": null, "e": 8659, "s": 8275, "text": "df_adm_notes = pd.merge(df_adm[['SUBJECT_ID','HADM_ID','ADMITTIME','DISCHTIME','DAYS_NEXT_ADMIT','NEXT_ADMITTIME','ADMISSION_TYPE','DEATHTIME']], df_notes_dis_sum_last[['SUBJECT_ID','HADM_ID','TEXT']], on = ['SUBJECT_ID','HADM_ID'], how = 'left')assert len(df_adm) == len(df_adm_notes), 'Number of rows increased'" }, { "code": null, "e": 8789, "s": 8659, "text": "10.6 % of the admissions are missing (df_adm_notes.TEXT.isnull().sum() / len(df_adm_notes)), so I investigated a bit further with" }, { "code": null, "e": 8913, "s": 8789, "text": "df_adm_notes.groupby('ADMISSION_TYPE').apply(lambda g: g.TEXT.isnull().sum())/df_adm_notes.groupby('ADMISSION_TYPE').size()" }, { "code": null, "e": 9189, "s": 8913, "text": "and discovered that 53% of the NEWBORN admissions were missing discharge summaries vs ~4% for the others. At this point I decided to remove the NEWBORN admissions. Most likely, these missing NEWBORN admissions have their discharge summary stored outside of the MIMIC dataset." }, { "code": null, "e": 9382, "s": 9189, "text": "For this problem, we are going to classify if a patient will be admitted in the next 30 days. Therefore, we need to create a variable with the output label (1 = readmitted, 0 = not readmitted)" }, { "code": null, "e": 9475, "s": 9382, "text": "df_adm_notes_clean['OUTPUT_LABEL'] = (df_adm_notes_clean.DAYS_NEXT_ADMIT < 30).astype('int')" }, { "code": null, "e": 9680, "s": 9475, "text": "A quick count of positive and negative results in 3004 positive samples, 48109 negative samples. This indicates that we have an imbalanced dataset, which is a common occurrence in healthcare data science." }, { "code": null, "e": 9842, "s": 9680, "text": "The last step to prepare our data is to split the data into training, validation and test sets. For reproducible results, I have made the random_state always 42." }, { "code": null, "e": 10344, "s": 9842, "text": "# shuffle the samplesdf_adm_notes_clean = df_adm_notes_clean.sample(n = len(df_adm_notes_clean), random_state = 42)df_adm_notes_clean = df_adm_notes_clean.reset_index(drop = True)# Save 30% of the data as validation and test data df_valid_test=df_adm_notes_clean.sample(frac=0.30,random_state=42)df_test = df_valid_test.sample(frac = 0.5, random_state = 42)df_valid = df_valid_test.drop(df_test.index)# use the rest of the data as training datadf_train_all=df_adm_notes_clean.drop(df_valid_test.index)" }, { "code": null, "e": 10519, "s": 10344, "text": "Since the prevalence is so low, we want to prevent the model from always predicting negative (not re-admitted). To do this, we have a few options to balance the training data" }, { "code": null, "e": 10546, "s": 10519, "text": "sub-sampling the negatives" }, { "code": null, "e": 10574, "s": 10546, "text": "over-sampling the positives" }, { "code": null, "e": 10609, "s": 10574, "text": "create synthetic data (e.g. SMOTE)" }, { "code": null, "e": 10892, "s": 10609, "text": "Since I didn’t make any restrictions on size of RAM for your computer, we will sub-sample the negatives, but I encourage you to try out the other techniques if your computer or server can handle it to see if you can get an improvement. (Post as a comment below if you try this out!)" }, { "code": null, "e": 11331, "s": 10892, "text": "# split the training data into positive and negativerows_pos = df_train_all.OUTPUT_LABEL == 1df_train_pos = df_train_all.loc[rows_pos]df_train_neg = df_train_all.loc[~rows_pos]# merge the balanced datadf_train = pd.concat([df_train_pos, df_train_neg.sample(n = len(df_train_pos), random_state = 42)],axis = 0)# shuffle the order of training samples df_train = df_train.sample(n = len(df_train), random_state = 42).reset_index(drop = True)" }, { "code": null, "e": 11569, "s": 11331, "text": "Now that we have created data sets that have a label and the notes, we need to preprocess our text data to convert it to something useful (i.e. numbers) for the machine learning model. We are going to use the Bag-of-Words (BOW) approach." }, { "code": null, "e": 11910, "s": 11569, "text": "BOW basically breaks up the note into the individual words and counts how many times each word occurs. Your numerical data then becomes counts for some set of words as shown below. BOW is the simplest way to do NLP classification. In most blog posts I have read, fancier techniques have a hard time beating BOW for NLP classification tasks." }, { "code": null, "e": 11970, "s": 11910, "text": "In this process, there are few choices that need to be made" }, { "code": null, "e": 11998, "s": 11970, "text": "how to preprocess the words" }, { "code": null, "e": 12021, "s": 11998, "text": "how to count the words" }, { "code": null, "e": 12040, "s": 12021, "text": "which words to use" }, { "code": null, "e": 12160, "s": 12040, "text": "There is no optimal choice for all NLP projects, so I recommend trying out a few options when building your own models." }, { "code": null, "e": 12201, "s": 12160, "text": "You can do the preprocessing in two ways" }, { "code": null, "e": 12243, "s": 12201, "text": "modify the original dataframe TEXT column" }, { "code": null, "e": 12315, "s": 12243, "text": "preprocess as part of your pipeline so you don’t edit the original data" }, { "code": null, "e": 12434, "s": 12315, "text": "I will show you how to do both of these, but I prefer the second one since it took a lot of work to get to this point." }, { "code": null, "e": 12576, "s": 12434, "text": "Let’s define a function that will modify the original dataframe by filling missing notes with space and removing newline and carriage returns" }, { "code": null, "e": 13010, "s": 12576, "text": "def preprocess_text(df): # This function preprocesses the text by filling not a number and replacing new lines ('\\n') and carriage returns ('\\r') df.TEXT = df.TEXT.fillna(' ') df.TEXT = df.TEXT.str.replace('\\n',' ') df.TEXT = df.TEXT.str.replace('\\r',' ') return df# preprocess the text to deal with known issuesdf_train = preprocess_text(df_train)df_valid = preprocess_text(df_valid)df_test = preprocess_text(df_test)" }, { "code": null, "e": 13247, "s": 13010, "text": "The other option is to preprocess as part of the pipeline. This process consists of using a tokenizer and a vectorizer. The tokenizer breaks a single note into a list of words and a vectorizer takes a list of words and counts the words." }, { "code": null, "e": 13419, "s": 13247, "text": "We will use word_tokenize from the nltk package for our default tokenizer, which basically breaks the note based on spaces and some punctuation. An example is shown below:" }, { "code": null, "e": 13535, "s": 13419, "text": "import nltkfrom nltk import word_tokenizeword_tokenize('This should be tokenized. 02/02/2018 sentence has stars**')" }, { "code": null, "e": 13548, "s": 13535, "text": "With output:" }, { "code": null, "e": 13635, "s": 13548, "text": "[‘This’, ‘should’, ‘be’, ‘tokenized’, ‘.’, ‘02/02/2018’, ‘sentence’, ‘has’, ‘stars**’]" }, { "code": null, "e": 13771, "s": 13635, "text": "The default shows that some punctuation is separated and that numbers stay in the sentence. We will write our own tokenizer function to" }, { "code": null, "e": 13803, "s": 13771, "text": "replace punctuation with spaces" }, { "code": null, "e": 13831, "s": 13803, "text": "replace numbers with spaces" }, { "code": null, "e": 13852, "s": 13831, "text": "lower case all words" }, { "code": null, "e": 14177, "s": 13852, "text": "import stringdef tokenizer_better(text): # tokenize the text by replacing punctuation and numbers with spaces and lowercase all words punc_list = string.punctuation+'0123456789' t = str.maketrans(dict.fromkeys(punc_list, \" \")) text = text.lower().translate(t) tokens = word_tokenize(text) return tokens" }, { "code": null, "e": 14231, "s": 14177, "text": "With this tokenizer we get from our original sentence" }, { "code": null, "e": 14297, "s": 14231, "text": "['this', 'should', 'be', 'tokenized', 'sentence', 'has', 'stars']" }, { "code": null, "e": 14412, "s": 14297, "text": "Additional things you can do would be to lemmatize or stem the words, but that is more advanced so I’ll skip that." }, { "code": null, "e": 14862, "s": 14412, "text": "Now that we have a way to convert free-text into tokens, we need a way to count the tokens for each discharge summary. We will use the built in CountVectorizer from scikit-learn package. This vectorizer simply counts how many times each word occurs in the note. There is also a TfidfVectorizer which takes into how often words are used across all notes, but for this project let’s use the simpler one (I got similar results with the second one too)." }, { "code": null, "e": 14903, "s": 14862, "text": "As an example, let’s say we have 3 notes" }, { "code": null, "e": 15025, "s": 14903, "text": "sample_text = ['Data science is about the data', 'The science is amazing', 'Predictive modeling is part of data science']" }, { "code": null, "e": 15158, "s": 15025, "text": "Essentially, you fit the CountVectorizer to learn the words in your data and the transform your data to create counts for each word." }, { "code": null, "e": 15391, "s": 15158, "text": "from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(tokenizer = tokenizer_better)vect.fit(sample_text)# matrix is stored as a sparse matrix (since you have a lot of zeros)X = vect.transform(sample_text)" }, { "code": null, "e": 15496, "s": 15391, "text": "The matrix X will be a sparse matrix, but if you convert it to an array (X.toarray()), you will see this" }, { "code": null, "e": 15625, "s": 15496, "text": "array([[1, 0, 2, 1, 0, 0, 0, 0, 1, 1], [0, 1, 0, 1, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0]], dtype=int64)" }, { "code": null, "e": 15756, "s": 15625, "text": "Where there are 3 rows (since we have 3 notes) and counts of each word. You can see the column names with vect.get_feature_names()" }, { "code": null, "e": 15849, "s": 15756, "text": "['about', 'amazing', 'data', 'is', 'modeling', 'of', 'part', 'predictive', 'science', 'the']" }, { "code": null, "e": 16273, "s": 15849, "text": "We can now fit our CountVectorizer on the clinical notes. It is important to use only the training data because you don’t want to include any new words that show up in the validation and test sets. There is a hyperparameter called max_features which you can set to constrain how many words are included in the Vectorizer. This will use the top N most frequently used words. In step 5, we will adjust this to see its effect." }, { "code": null, "e": 16534, "s": 16273, "text": "# fit our vectorizer. This will take a while depending on your computer. from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(max_features = 3000, tokenizer = tokenizer_better)# this could take a whilevect.fit(df_train.TEXT.values)" }, { "code": null, "e": 16886, "s": 16534, "text": "We can look at the most frequently used words and we will see that many of these words might not add any value for our model. These words are called stop words, and we can remove them easily (if we want) with the CountVectorizer. There are lists of common stop words for different NLP corpus, but we will just make up our own based on the image below." }, { "code": null, "e": 17261, "s": 16886, "text": "my_stop_words = ['the','and','to','of','was','with','a','on','in','for','name', 'is','patient','s','he','at','as','or','one','she','his','her','am', 'were','you','pt','pm','by','be','had','your','this','date', 'from','there','an','that','p','are','have','has','h','but','o', 'namepattern','which','every','also']" }, { "code": null, "e": 17311, "s": 17261, "text": "Feel free to add your own stop words if you want." }, { "code": null, "e": 17573, "s": 17311, "text": "from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(max_features = 3000, tokenizer = tokenizer_better, stop_words = my_stop_words)# this could take a whilevect.fit(df_train.TEXT.values)" }, { "code": null, "e": 17754, "s": 17573, "text": "Now we can transform our notes into numerical matrices. At this point, I will only use the training and validation data so I’m not tempted to see how it works on the test data yet." }, { "code": null, "e": 17853, "s": 17754, "text": "X_train_tf = vect.transform(df_train.TEXT.values)X_valid_tf = vect.transform(df_valid.TEXT.values)" }, { "code": null, "e": 17906, "s": 17853, "text": "We also need our output labels as separate variables" }, { "code": null, "e": 17969, "s": 17906, "text": "y_train = df_train.OUTPUT_LABELy_valid = df_valid.OUTPUT_LABEL" }, { "code": null, "e": 18098, "s": 17969, "text": "As seen by the location of the scroll bar... as always, it takes 80% of the time to get the data ready for the predictive model." }, { "code": null, "e": 18251, "s": 18098, "text": "We can now build a simple predictive model that takes our bag-of-words inputs and predicts if a patient will be readmitted in 30 days (YES = 1, NO = 0)." }, { "code": null, "e": 18665, "s": 18251, "text": "Here we will use the Logistic Regression model. Logistic regression is a good baseline model for NLP tasks since it works well with sparse matrices and is interpretable. We have a few additional choices (called hyperparameters) including C which is a coefficient on regularization and penalty which tells how to measure the regularization. Regularization is essentially a technique to try to minimize overfitting." }, { "code": null, "e": 18835, "s": 18665, "text": "# logistic regressionfrom sklearn.linear_model import LogisticRegressionclf=LogisticRegression(C = 0.0001, penalty = 'l2', random_state = 42)clf.fit(X_train_tf, y_train)" }, { "code": null, "e": 18921, "s": 18835, "text": "We can calculate the probability of readmission for each sample with the fitted model" }, { "code": null, "e": 19037, "s": 18921, "text": "model = clfy_train_preds = model.predict_proba(X_train_tf)[:,1]y_valid_preds = model.predict_proba(X_valid_tf)[:,1]" }, { "code": null, "e": 19387, "s": 19037, "text": "At this point, we need to measure how well our model performed. There are a few different data science performance metrics. I wrote another blog post explaining these in detail if you are interested. Since this post is quite long now, I will start just showing results and figures. You can see the github account for the code to produce the figures." }, { "code": null, "e": 19468, "s": 19387, "text": "For a threshold of 0.5 for predicting positive, we get the following performance" }, { "code": null, "e": 19916, "s": 19468, "text": "With the current selection of hyperparameters, we do have some overfitting. One thing to point out is that the major difference between the precision in the two sets of data is due to the fact that we balanced the training set, where as the validation set is the original distribution. Currently, if we make a list of patients predicted to be readmitted we catch twice as many of them as if we randomly selected patients (PRECISION vs PREVALENCE)." }, { "code": null, "e": 20246, "s": 19916, "text": "Another performance metric not shown above is AUC or area under the ROC curve. The ROC curve for our current model is shown below. Essentially the ROC curve allows you to see the trade-off between true positive rate and false positive rate as you vary the threshold on what you define as predicted positive vs predicted negative." }, { "code": null, "e": 20452, "s": 20246, "text": "At this point, you might be tempted to calculate the performance on your test set and see how you did. But wait! We made many choices (a few below) which we could change and see if there is an improvement:" }, { "code": null, "e": 20492, "s": 20452, "text": "should we spend time getting more data?" }, { "code": null, "e": 20534, "s": 20492, "text": "how to tokenize — should we use stemming?" }, { "code": null, "e": 20591, "s": 20534, "text": "how to vectorize — should we change the number of words?" }, { "code": null, "e": 20667, "s": 20591, "text": "how to regularized the logistic regression — should we change C or penalty?" }, { "code": null, "e": 20687, "s": 20667, "text": "which model to use?" }, { "code": null, "e": 20961, "s": 20687, "text": "When I am trying to improve my models, I read a lot of other blog posts and articles to see how people tackled similar issues. When you do this, you start to see interesting ways to visualize data and I highly recommend holding on to these techniques for your own projects." }, { "code": null, "e": 21235, "s": 20961, "text": "For NLP projects that use BOW+logistic regression, we can plot the most important words to see if we can gain any insight. For this step, I borrowed code from a nice NLP article by Insight Data Science. When you look at the most important words, I see two immediate things:" }, { "code": null, "e": 21377, "s": 21235, "text": "Oops! I forgot to exclude the patients who died since ‘expired’ showed up in the negative list. For now, I will ignore this and fix it below." }, { "code": null, "e": 21488, "s": 21377, "text": "There are also some other stop words we should probably remove (‘should’,’if’,’it’,’been’,’who’,’during’, ‘x’)" }, { "code": null, "e": 21781, "s": 21488, "text": "When we want to improve the model, we want to do it in a data-driven manner. You can spend a lot of time on ‘hunches’, that don’t end up panning out. To do this, it is recommend to pick a single performance metric that you use to make your decisions. For this project, I am going to pick AUC." }, { "code": null, "e": 22005, "s": 21781, "text": "For the first question above, we can plot something called a Learning Curve to understand the effect of adding more data. Andrew Ng has a set of great Coursera classes on the discussion of high-bias vs high-variance models." }, { "code": null, "e": 22221, "s": 22005, "text": "We can see that we have some overfitting but adding more data is likely not going to drastically change the AUC on a validation set. This is good to know because it means we shouldn’t spend months getting more data." }, { "code": null, "e": 22455, "s": 22221, "text": "Some simple things that we can do is try to see the effect of some of our hyperparameters (max_features and C). We could run a grid search, but since we only have 2 parameters here we could look at them separately and see the effect." }, { "code": null, "e": 22636, "s": 22455, "text": "We can see that increasing C and max_features, cause the model to overfit pretty quickly. I selected C = 0.0001 and max_features = 3000 where the validation set started to plateau." }, { "code": null, "e": 22684, "s": 22636, "text": "At this point, you could try a few other things" }, { "code": null, "e": 22717, "s": 22684, "text": "change sub-sample to over-sample" }, { "code": null, "e": 22764, "s": 22717, "text": "add stemming or lemmatization to the tokenizer" }, { "code": null, "e": 22806, "s": 22764, "text": "test a few different sci-kit learn models" }, { "code": null, "e": 22870, "s": 22806, "text": "concatenate all the notes instead of the last discharge summary" }, { "code": null, "e": 22911, "s": 22870, "text": "try a deep learning method such as LSTMs" }, { "code": null, "e": 22969, "s": 22911, "text": "review the discharge summaries that you are getting wrong" }, { "code": null, "e": 23096, "s": 22969, "text": "We will now fit our final model with hyperparameter selection. We will also exclude the patients who died with a re-balancing." }, { "code": null, "e": 25668, "s": 23096, "text": "rows_not_death = df_adm_notes_clean.DEATHTIME.isnull()df_adm_notes_not_death = df_adm_notes_clean.loc[rows_not_death].copy()df_adm_notes_not_death = df_adm_notes_not_death.sample(n = len(df_adm_notes_not_death), random_state = 42)df_adm_notes_not_death = df_adm_notes_not_death.reset_index(drop = True)# Save 30% of the data as validation and test data df_valid_test=df_adm_notes_not_death.sample(frac=0.30,random_state=42)df_test = df_valid_test.sample(frac = 0.5, random_state = 42)df_valid = df_valid_test.drop(df_test.index)# use the rest of the data as training datadf_train_all=df_adm_notes_not_death.drop(df_valid_test.index)assert len(df_adm_notes_not_death) == (len(df_test)+len(df_valid)+len(df_train_all)),'math didnt work'# split the training data into positive and negativerows_pos = df_train_all.OUTPUT_LABEL == 1df_train_pos = df_train_all.loc[rows_pos]df_train_neg = df_train_all.loc[~rows_pos]# merge the balanced datadf_train = pd.concat([df_train_pos, df_train_neg.sample(n = len(df_train_pos), random_state = 42)],axis = 0)# shuffle the order of training samples df_train = df_train.sample(n = len(df_train), random_state = 42).reset_index(drop = True)# preprocess the text to deal with known issuesdf_train = preprocess_text(df_train)df_valid = preprocess_text(df_valid)df_test = preprocess_text(df_test)my_new_stop_words = ['the','and','to','of','was','with','a','on','in','for','name', 'is','patient','s','he','at','as','or','one','she','his','her','am', 'were','you','pt','pm','by','be','had','your','this','date', 'from','there','an','that','p','are','have','has','h','but','o', 'namepattern','which','every','also','should','if','it','been','who','during', 'x']from sklearn.feature_extraction.text import CountVectorizervect = CountVectorizer(lowercase = True, max_features = 3000, tokenizer = tokenizer_better, stop_words = my_new_stop_words)# fit the vectorizervect.fit(df_train.TEXT.values)X_train_tf = vect.transform(df_train.TEXT.values)X_valid_tf = vect.transform(df_valid.TEXT.values)X_test_tf = vect.transform(df_test.TEXT.values)y_train = df_train.OUTPUT_LABELy_valid = df_valid.OUTPUT_LABELy_test = df_test.OUTPUT_LABELfrom sklearn.linear_model import LogisticRegressionclf=LogisticRegression(C = 0.0001, penalty = 'l2', random_state = 42)clf.fit(X_train_tf, y_train)model = clfy_train_preds = model.predict_proba(X_train_tf)[:,1]y_valid_preds = model.predict_proba(X_valid_tf)[:,1]y_test_preds = model.predict_proba(X_test_tf)[:,1]" }, { "code": null, "e": 25719, "s": 25668, "text": "This produces the following results and ROC curve." }, { "code": null, "e": 26012, "s": 25719, "text": "Congratulations! You built a simple NLP model (AUC = 0.70) to predict re-admission based on hospital discharge summaries that is only slightly worse than the state-of-the-art deep learning method that uses all hospital data (AUC = 0.75). If you have any feedback, feel free to leave it below." }, { "code": null, "e": 26152, "s": 26012, "text": "If you are interested in deep learning NLP in healthcare, I recommend reading the article by Erin Craig at https://arxiv.org/abs/1711.10663" }, { "code": null, "e": 26380, "s": 26152, "text": "Scalable and accurate deep learning with electronic health records. Rajkomar A, Oren E, Chen K, et al. NPJ Digital Medicine (2018). DOI: 10.1038/s41746–018–0029–1. Available at: https://www.nature.com/articles/s41746-018-0029-1" } ]
PHP mysqli_stmt_bind_result() Function
The mysqli_stmt_bind_result() function is used to bind the columns of a result set to variables. After binding variables, you need to invoke the mysqli_stmt_fetch() function to get the values of the columns in the specified variables. mysqli_stmt_bind_result($stmt, $var1, $var2...); stmt(Mandatory) This is an object representing a prepared statement. var1(Mandatory) This represent the variable(s) to be bound to the columns. The PHP mysqli_stmt_bind_result() function returns a boolean value which is true on success and false on failure. This function was first introduced in PHP Version 5 and works works in all the later versions. Following example demonstrates the usage of the mysqli_stmt_bind_result() function (in procedural style) − <?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("Table Created.....\n"); mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')"); print("Record Inserted.....\n"); //Retrieving the contents of the table $stmt = mysqli_prepare($con, "SELECT * FROM myplayers"); //Executing the statement mysqli_stmt_execute($stmt); //Binding values in result to variables mysqli_stmt_bind_result($stmt, $id, $fname, $lname, $pob, $country); while (mysqli_stmt_fetch($stmt)) { print("Id: ".$id."\n"); print("fname: ".$fname."\n"); print("lname: ".$lname."\n"); print("pob: ".$pob."\n"); print("country: ".$country."\n"); print("\n"); } //Closing the statement mysqli_stmt_close($stmt); //Closing the connection mysqli_close($con); ?> This will produce following result − Table Created..... Record Inserted..... Id: 1 fname: Sikhar lname: Dhawan pob: Delhi country: India Id: 2 fname: Jonathan lname: Trott pob: CapeTown country: SouthAfrica Id: 3 fname: Kumara lname: Sangakkara pob: Matale country: Srilanka In object oriented style the syntax of this function is $stmt->bind_result(); Following is the example of this function in object oriented style $minus; <?php //Creating a connection $con = new mysqli("localhost", "root", "password", "mydb"); $con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("Table Created.....\n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; print("Records Deleted.....\n"); //Executing the statement $stmt->execute(); //Binding variables to resultset $stmt->bind_result($name, $age); while ($stmt->fetch()) { print("Name: ".$name."\n"); print("Age: ".$age."\n"); } //Closing the statement $stmt->close(); //Closing the connection $con->close(); ?> This will produce following result − Table Created..... Records Deleted..... Name: Raju Age: 25 Name: Rahman Age: 30 Following example fetches the results of the DESCRIBE query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions − <?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("Table Created.....\n"); //Description of the table $stmt = mysqli_prepare($con, "DESC myplayers"); //Executing the statement mysqli_stmt_execute($stmt); //Binding values in result to variables mysqli_stmt_bind_result($stmt, $field, $type, $null, $key, $default, $extra); while (mysqli_stmt_fetch($stmt)) { print("Field: ".$field."\n"); print("Type: ".$type."\n"); print("Null: ".$null."\n"); print("Key: ".$key."\n"); print("Default: ".$default."\n"); print("Extra: ".$extra."\n"); print("\n"); } //Closing the statement mysqli_stmt_close($stmt); //Closing the connection mysqli_close($con); ?> This will produce following result − Table Created..... Field: ID Type: int(11) Null: YES Key: Default: Extra: Field: First_Name Type: varchar(255) Null: YES Key: Default: Extra: Field: Last_Name Type: varchar(255) Null: YES Key: Default: Extra: Field: Place_Of_Birth Type: varchar(255) Null: YES Key: Default: Extra: Field: Country Type: varchar(255) Null: YES Key: Default: Extra: Following example fetches the results of the SHOW TABLES query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions − <?php $con = mysqli_connect("localhost", "root", "password"); //Selecting the database mysqli_query($con, "CREATE DATABASE NewDatabase"); mysqli_select_db($con, "NewDatabase"); //Creating tables mysqli_query($con, "CREATE TABLE test1(Name VARCHAR(255), Age INT)"); mysqli_query($con, "CREATE TABLE test2(Name VARCHAR(255), Age INT)"); mysqli_query($con, "CREATE TABLE test3(Name VARCHAR(255), Age INT)"); print("Tables Created.....\n"); //Description of the table $stmt = mysqli_prepare($con, "SHOW TABLES"); //Executing the statement mysqli_stmt_execute($stmt); //Binding values in result to variables mysqli_stmt_bind_result($stmt, $table_name); print("List of tables in the current database: \n"); while (mysqli_stmt_fetch($stmt)) { print($table_name."\n"); } //Closing the statement mysqli_stmt_close($stmt); //Closing the connection mysqli_close($con); ?> This will produce following result − Tables Created..... List of tables in the current database: test1 test2 test3 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2992, "s": 2757, "text": "The mysqli_stmt_bind_result() function is used to bind the columns of a result set to variables. After binding variables, you need to invoke the mysqli_stmt_fetch() function to get the values of the columns in the specified variables." }, { "code": null, "e": 3042, "s": 2992, "text": "mysqli_stmt_bind_result($stmt, $var1, $var2...);\n" }, { "code": null, "e": 3058, "s": 3042, "text": "stmt(Mandatory)" }, { "code": null, "e": 3111, "s": 3058, "text": "This is an object representing a prepared statement." }, { "code": null, "e": 3127, "s": 3111, "text": "var1(Mandatory)" }, { "code": null, "e": 3186, "s": 3127, "text": "This represent the variable(s) to be bound to the columns." }, { "code": null, "e": 3300, "s": 3186, "text": "The PHP mysqli_stmt_bind_result() function returns a boolean value which is true on success and false on failure." }, { "code": null, "e": 3395, "s": 3300, "text": "This function was first introduced in PHP Version 5 and works works in all the later versions." }, { "code": null, "e": 3502, "s": 3395, "text": "Following example demonstrates the usage of the mysqli_stmt_bind_result() function (in procedural style) −" }, { "code": null, "e": 4738, "s": 3502, "text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created.....\\n\");\n mysqli_query($con, \"INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')\");\n mysqli_query($con, \"INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')\");\n mysqli_query($con, \"INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')\");\n print(\"Record Inserted.....\\n\");\n\n //Retrieving the contents of the table\n $stmt = mysqli_prepare($con, \"SELECT * FROM myplayers\");\n\n //Executing the statement\n mysqli_stmt_execute($stmt);\n\n //Binding values in result to variables\n mysqli_stmt_bind_result($stmt, $id, $fname, $lname, $pob, $country);\n\n while (mysqli_stmt_fetch($stmt)) {\n print(\"Id: \".$id.\"\\n\");\n print(\"fname: \".$fname.\"\\n\");\n print(\"lname: \".$lname.\"\\n\");\n print(\"pob: \".$pob.\"\\n\");\n print(\"country: \".$country.\"\\n\");\n print(\"\\n\");\n\n }\n //Closing the statement\n mysqli_stmt_close($stmt);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 4775, "s": 4738, "text": "This will produce following result −" }, { "code": null, "e": 5016, "s": 4775, "text": "Table Created.....\nRecord Inserted.....\nId: 1\nfname: Sikhar\nlname: Dhawan\npob: Delhi\ncountry: India\n\nId: 2\nfname: Jonathan\nlname: Trott\npob: CapeTown\ncountry: SouthAfrica\n\nId: 3\nfname: Kumara\nlname: Sangakkara\npob: Matale\ncountry: Srilanka\n" }, { "code": null, "e": 5169, "s": 5016, "text": "In object oriented style the syntax of this function is $stmt->bind_result(); Following is the example of this function in object oriented style $minus;" }, { "code": null, "e": 5972, "s": 5169, "text": "<?php\n //Creating a connection\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"mydb\");\n\n $con -> query(\"CREATE TABLE Test(Name VARCHAR(255), AGE INT)\");\n $con -> query(\"insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)\");\n print(\"Table Created.....\\n\");\n\n $stmt = $con -> prepare( \"SELECT * FROM Test WHERE Name in(?, ?)\");\n $stmt -> bind_param(\"ss\", $name1, $name2);\n $name1 = 'Raju';\n $name2 = 'Rahman';\n print(\"Records Deleted.....\\n\");\n\n //Executing the statement\n $stmt->execute();\n\n //Binding variables to resultset\n $stmt->bind_result($name, $age);\n while ($stmt->fetch()) {\n print(\"Name: \".$name.\"\\n\");\n print(\"Age: \".$age.\"\\n\");\n }\n\n //Closing the statement\n $stmt->close();\n\n //Closing the connection\n $con->close();\n?>" }, { "code": null, "e": 6009, "s": 5972, "text": "This will produce following result −" }, { "code": null, "e": 6090, "s": 6009, "text": "Table Created.....\nRecords Deleted.....\nName: Raju\nAge: 25\nName: Rahman\nAge: 30\n" }, { "code": null, "e": 6219, "s": 6090, "text": "Following example fetches the results of the DESCRIBE query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions −" }, { "code": null, "e": 7139, "s": 6219, "text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"mydb\");\n\n mysqli_query($con, \"CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))\");\n print(\"Table Created.....\\n\");\n\n //Description of the table\n $stmt = mysqli_prepare($con, \"DESC myplayers\");\n\n //Executing the statement\n mysqli_stmt_execute($stmt);\n\n //Binding values in result to variables\n mysqli_stmt_bind_result($stmt, $field, $type, $null, $key, $default, $extra);\n\n while (mysqli_stmt_fetch($stmt)) {\n print(\"Field: \".$field.\"\\n\");\n print(\"Type: \".$type.\"\\n\");\n print(\"Null: \".$null.\"\\n\");\n print(\"Key: \".$key.\"\\n\");\n print(\"Default: \".$default.\"\\n\");\n print(\"Extra: \".$extra.\"\\n\");\n print(\"\\n\");\n }\n\n //Closing the statement\n mysqli_stmt_close($stmt);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 7176, "s": 7139, "text": "This will produce following result −" }, { "code": null, "e": 7527, "s": 7176, "text": "Table Created.....\nField: ID\nType: int(11)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: First_Name\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: Last_Name\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: Place_Of_Birth\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n\nField: Country\nType: varchar(255)\nNull: YES\nKey:\nDefault:\nExtra:\n" }, { "code": null, "e": 7658, "s": 7527, "text": "Following example fetches the results of the SHOW TABLES query using mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions −" }, { "code": null, "e": 8599, "s": 7658, "text": "<?php\n $con = mysqli_connect(\"localhost\", \"root\", \"password\");\n\n //Selecting the database\n mysqli_query($con, \"CREATE DATABASE NewDatabase\");\n mysqli_select_db($con, \"NewDatabase\");\n\n //Creating tables\n mysqli_query($con, \"CREATE TABLE test1(Name VARCHAR(255), Age INT)\");\n mysqli_query($con, \"CREATE TABLE test2(Name VARCHAR(255), Age INT)\");\n mysqli_query($con, \"CREATE TABLE test3(Name VARCHAR(255), Age INT)\");\n print(\"Tables Created.....\\n\");\n\n //Description of the table\n $stmt = mysqli_prepare($con, \"SHOW TABLES\");\n\n //Executing the statement\n mysqli_stmt_execute($stmt);\n\n //Binding values in result to variables\n mysqli_stmt_bind_result($stmt, $table_name);\n\n print(\"List of tables in the current database: \\n\");\n while (mysqli_stmt_fetch($stmt)) {\n print($table_name.\"\\n\");\n }\n\n //Closing the statement\n mysqli_stmt_close($stmt);\n\n //Closing the connection\n mysqli_close($con);\n?>" }, { "code": null, "e": 8636, "s": 8599, "text": "This will produce following result −" }, { "code": null, "e": 8715, "s": 8636, "text": "Tables Created.....\nList of tables in the current database:\ntest1\ntest2\ntest3\n" }, { "code": null, "e": 8748, "s": 8715, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 8764, "s": 8748, "text": " Malhar Lathkar" }, { "code": null, "e": 8797, "s": 8764, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 8808, "s": 8797, "text": " Syed Raza" }, { "code": null, "e": 8843, "s": 8808, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8860, "s": 8843, "text": " Frahaan Hussain" }, { "code": null, "e": 8893, "s": 8860, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 8908, "s": 8893, "text": " Nivedita Jain" }, { "code": null, "e": 8943, "s": 8908, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 8955, "s": 8943, "text": " Azaz Patel" }, { "code": null, "e": 8990, "s": 8955, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9018, "s": 8990, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 9025, "s": 9018, "text": " Print" }, { "code": null, "e": 9036, "s": 9025, "text": " Add Notes" } ]
Make the cutest charts in Python. Visualize your data with hand-drawn... | by Di(Candice) Han | Towards Data Science
In this tutorial, I would like to introduce a very cool Python hand-painted style visualization package: cutecharts. Different from the common charts such as Matplotlib and seaborn, this package can be used to generate the following kinds of charts that look like hand drawn, and the effect may be better in some scenarios. Cute charts are also interactive and dynamic. Whenever the mouse is hovering on the chart, the numbers show up. To create this chart, you just need a few lines of Python codes. For now, this library supports five kinds of charts — Bar, Line, Pie, Radar and Scatter. It also supports combination of charts. Let us explore them one by one. Before we start to draw cute charts, we need to install the cutechart library. $ pip install cutecharts Let us use dataset of Toronto temperature to draw bar and line charts. #import library and dataimport cutecharts.charts as ctcdf=pd.DataFrame({ ‘x’:[‘Sun.’,’Mon.’,’Tue.’,’Wed.’,’Thu.’,’Fri.’,’Sat.’], ‘y’:[14,15,17,20,22.3,23.7,24.8], ‘z’:[16,16.4,23.6,24.5,19.9,13.6,13.4]}) Bar Chart Bar Chart chart = ctc.Bar(‘Toronto Temperature’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), x_label='Days', y_label='Temperature (Celsius)' , colors=[‘#1EAFAE’ for i in range(len(df))] )chart.add_series('This week',list(df[‘y’]))chart.render_notebook() In this bar chart, all bars have the same color. If you would like to customize the colors for each bar, you just need to change one line in the codes. chart = ctc.Bar(‘title’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” , colors=[‘#FFF1C9’,’#F7B7A3',’#EA5F89',’#9B3192',’#57167E’,’#47B39C’,’#00529B’] )chart.add_series(“This week”,list(df[‘y’]))chart.render_notebook() 2. Line Chart It makes more sense to draw the line chart for our dataset so that we can see the differences between temperatures of last week and this week. chart = ctc.Line(“Toronto Temperature”,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” )chart.add_series(“This Week”, list(df[‘y’])) chart.add_series(“Last Week”, list(df[‘z’]))chart.render_notebook() When you hover the mouse on the chart, the chart will automatically show labels with numbers and it also draws a dashed line so that the differences of temperatures between this week and last week become more visualized. 3. Radar Chart To change the line chart to a radar chart, you just need to change the chart type to ctc.Radar. chart = ctc.Radar(‘Toronto Temperature’,width=’700px’,height=’600px’)chart.set_options( labels=list(df[‘x’]), is_show_legend=True, #by default, it is true. You can turn it off. legend_pos=’upRight’ #location of the legend )chart.add_series(‘This week’,list(df[‘y’]))chart.add_series(“Last week”,list(df[‘z’]))chart.render_notebook() 4. Pie Chart We need another dataset to make pie and donut charts. df=pd.DataFrame({‘x’:[‘Asia’, ‘Africa’, ‘Europe’, ‘North America’, ‘South America’, ‘Australia’], ‘y’:[59.69, 16, 9.94, 7.79, 5.68, 0.54]}) The datasets contains names of continents and their percentages of population. chart = ctc.Pie(‘% of population by continent’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), inner_radius=0 )chart.add_series(list(df[‘y’])) chart.render_notebook() You can change the colors of each part in the pie chart. And it is also very easy to turn a pie chart in to a donut chart. You just need to change the parameter of inner_radius. df=pd.DataFrame({‘x’:[‘Asia’, ‘Africa’, ‘Europe’, ‘North America’, ‘South America’, ‘Australia’], ‘y’:[59.69, 16, 9.94, 7.79, 5.68, 0.54]})chart = ctc.Pie(‘% of population by continent’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), inner_radius=0.6 )chart.add_series(list(df[‘y’])) chart.render_notebook() 5. Scatter Plot To plot the scatter plot, I will create a new dataset to map out the relationship between temperature and ice cream sales. Temperature = [14.2,16.4,11.9,15.2,18.5,22.1,19.4,25.1,23.4,18.1,22.6,17.2]Sales = [215,325,185,332,406,522,412,614,544,421,445,408] Then, we can create the scatter plot. chart = ctc.Scatter(‘Ice Cream Sales vs Temperature’,width=’500px’,height=’600px’)chart.set_options( x_label=”Temperature (Celcius)”, y_label=”Icecream Sales” , colors=[‘#1EAFAE’], is_show_line = False, dot_size=1)chart.add_series(“Temperature”, [(z[0], z[1]) for z in zip(Temperature, Sales)])chart.render_notebook() We can easily see that that warmer weather leads to more sales. 6. Combined Charts You are also able to combine multiple charts together. chart1 = ctc.Line(“Toronto Temperature”,width=’500px’,height=’400px’)chart1.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” )chart1.add_series(“This Week”, list(df[‘y’])) chart1.add_series(“Last Week”, list(df[‘z’]))chart2 = ctc.Bar(‘Toronto Temperature’,width=’500px’,height=’400px’)chart2.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” , colors=[‘#1EAFAE’ for i in range(len(df))] )chart2.add_series(“This week”,list(df[‘y’]))chart2.add_series(“Last week”,list(df[‘z’]))page = Page()page.add(chart1, chart2)page.render_notebook() As you can see, the cutechart package can really provide impressively cute charts. The limit of this package is that it can only generate five different kinds charts. If you are interested in making other types of beautiful charts, you may want to check out my other posts. Make beautiful Nightinggale rose chart in python-visualize covid19 death rateMake a beautiful water polo chart in a few lines in PythonMake a beautiful bar chart in just few lines in PythonMake a beautiful scatterplot in a few lines in Python to make your report outstandingMake an impressive animated bubble chart with Plotly in Python — inspired by professor Hans RoslingDraw a unique barplot using Matplotlib in Python Make beautiful Nightinggale rose chart in python-visualize covid19 death rate Make a beautiful water polo chart in a few lines in Python Make a beautiful bar chart in just few lines in Python Make a beautiful scatterplot in a few lines in Python to make your report outstanding Make an impressive animated bubble chart with Plotly in Python — inspired by professor Hans Rosling Draw a unique barplot using Matplotlib in Python
[ { "code": null, "e": 289, "s": 172, "text": "In this tutorial, I would like to introduce a very cool Python hand-painted style visualization package: cutecharts." }, { "code": null, "e": 608, "s": 289, "text": "Different from the common charts such as Matplotlib and seaborn, this package can be used to generate the following kinds of charts that look like hand drawn, and the effect may be better in some scenarios. Cute charts are also interactive and dynamic. Whenever the mouse is hovering on the chart, the numbers show up." }, { "code": null, "e": 673, "s": 608, "text": "To create this chart, you just need a few lines of Python codes." }, { "code": null, "e": 834, "s": 673, "text": "For now, this library supports five kinds of charts — Bar, Line, Pie, Radar and Scatter. It also supports combination of charts. Let us explore them one by one." }, { "code": null, "e": 913, "s": 834, "text": "Before we start to draw cute charts, we need to install the cutechart library." }, { "code": null, "e": 938, "s": 913, "text": "$ pip install cutecharts" }, { "code": null, "e": 1009, "s": 938, "text": "Let us use dataset of Toronto temperature to draw bar and line charts." }, { "code": null, "e": 1213, "s": 1009, "text": "#import library and dataimport cutecharts.charts as ctcdf=pd.DataFrame({ ‘x’:[‘Sun.’,’Mon.’,’Tue.’,’Wed.’,’Thu.’,’Fri.’,’Sat.’], ‘y’:[14,15,17,20,22.3,23.7,24.8], ‘z’:[16,16.4,23.6,24.5,19.9,13.6,13.4]})" }, { "code": null, "e": 1223, "s": 1213, "text": "Bar Chart" }, { "code": null, "e": 1233, "s": 1223, "text": "Bar Chart" }, { "code": null, "e": 1502, "s": 1233, "text": "chart = ctc.Bar(‘Toronto Temperature’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), x_label='Days', y_label='Temperature (Celsius)' , colors=[‘#1EAFAE’ for i in range(len(df))] )chart.add_series('This week',list(df[‘y’]))chart.render_notebook()" }, { "code": null, "e": 1654, "s": 1502, "text": "In this bar chart, all bars have the same color. If you would like to customize the colors for each bar, you just need to change one line in the codes." }, { "code": null, "e": 1945, "s": 1654, "text": "chart = ctc.Bar(‘title’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” , colors=[‘#FFF1C9’,’#F7B7A3',’#EA5F89',’#9B3192',’#57167E’,’#47B39C’,’#00529B’] )chart.add_series(“This week”,list(df[‘y’]))chart.render_notebook()" }, { "code": null, "e": 1959, "s": 1945, "text": "2. Line Chart" }, { "code": null, "e": 2102, "s": 1959, "text": "It makes more sense to draw the line chart for our dataset so that we can see the differences between temperatures of last week and this week." }, { "code": null, "e": 2374, "s": 2102, "text": "chart = ctc.Line(“Toronto Temperature”,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” )chart.add_series(“This Week”, list(df[‘y’])) chart.add_series(“Last Week”, list(df[‘z’]))chart.render_notebook()" }, { "code": null, "e": 2595, "s": 2374, "text": "When you hover the mouse on the chart, the chart will automatically show labels with numbers and it also draws a dashed line so that the differences of temperatures between this week and last week become more visualized." }, { "code": null, "e": 2610, "s": 2595, "text": "3. Radar Chart" }, { "code": null, "e": 2706, "s": 2610, "text": "To change the line chart to a radar chart, you just need to change the chart type to ctc.Radar." }, { "code": null, "e": 3040, "s": 2706, "text": "chart = ctc.Radar(‘Toronto Temperature’,width=’700px’,height=’600px’)chart.set_options( labels=list(df[‘x’]), is_show_legend=True, #by default, it is true. You can turn it off. legend_pos=’upRight’ #location of the legend )chart.add_series(‘This week’,list(df[‘y’]))chart.add_series(“Last week”,list(df[‘z’]))chart.render_notebook()" }, { "code": null, "e": 3053, "s": 3040, "text": "4. Pie Chart" }, { "code": null, "e": 3107, "s": 3053, "text": "We need another dataset to make pie and donut charts." }, { "code": null, "e": 3247, "s": 3107, "text": "df=pd.DataFrame({‘x’:[‘Asia’, ‘Africa’, ‘Europe’, ‘North America’, ‘South America’, ‘Australia’], ‘y’:[59.69, 16, 9.94, 7.79, 5.68, 0.54]})" }, { "code": null, "e": 3326, "s": 3247, "text": "The datasets contains names of continents and their percentages of population." }, { "code": null, "e": 3515, "s": 3326, "text": "chart = ctc.Pie(‘% of population by continent’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), inner_radius=0 )chart.add_series(list(df[‘y’])) chart.render_notebook()" }, { "code": null, "e": 3572, "s": 3515, "text": "You can change the colors of each part in the pie chart." }, { "code": null, "e": 3693, "s": 3572, "text": "And it is also very easy to turn a pie chart in to a donut chart. You just need to change the parameter of inner_radius." }, { "code": null, "e": 4023, "s": 3693, "text": "df=pd.DataFrame({‘x’:[‘Asia’, ‘Africa’, ‘Europe’, ‘North America’, ‘South America’, ‘Australia’], ‘y’:[59.69, 16, 9.94, 7.79, 5.68, 0.54]})chart = ctc.Pie(‘% of population by continent’,width=’500px’,height=’400px’)chart.set_options( labels=list(df[‘x’]), inner_radius=0.6 )chart.add_series(list(df[‘y’])) chart.render_notebook()" }, { "code": null, "e": 4039, "s": 4023, "text": "5. Scatter Plot" }, { "code": null, "e": 4162, "s": 4039, "text": "To plot the scatter plot, I will create a new dataset to map out the relationship between temperature and ice cream sales." }, { "code": null, "e": 4295, "s": 4162, "text": "Temperature = [14.2,16.4,11.9,15.2,18.5,22.1,19.4,25.1,23.4,18.1,22.6,17.2]Sales = [215,325,185,332,406,522,412,614,544,421,445,408]" }, { "code": null, "e": 4333, "s": 4295, "text": "Then, we can create the scatter plot." }, { "code": null, "e": 4651, "s": 4333, "text": "chart = ctc.Scatter(‘Ice Cream Sales vs Temperature’,width=’500px’,height=’600px’)chart.set_options( x_label=”Temperature (Celcius)”, y_label=”Icecream Sales” , colors=[‘#1EAFAE’], is_show_line = False, dot_size=1)chart.add_series(“Temperature”, [(z[0], z[1]) for z in zip(Temperature, Sales)])chart.render_notebook()" }, { "code": null, "e": 4715, "s": 4651, "text": "We can easily see that that warmer weather leads to more sales." }, { "code": null, "e": 4734, "s": 4715, "text": "6. Combined Charts" }, { "code": null, "e": 4789, "s": 4734, "text": "You are also able to combine multiple charts together." }, { "code": null, "e": 5393, "s": 4789, "text": "chart1 = ctc.Line(“Toronto Temperature”,width=’500px’,height=’400px’)chart1.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” )chart1.add_series(“This Week”, list(df[‘y’])) chart1.add_series(“Last Week”, list(df[‘z’]))chart2 = ctc.Bar(‘Toronto Temperature’,width=’500px’,height=’400px’)chart2.set_options( labels=list(df[‘x’]), x_label=”Days”, y_label=”Temperature (Celsius)” , colors=[‘#1EAFAE’ for i in range(len(df))] )chart2.add_series(“This week”,list(df[‘y’]))chart2.add_series(“Last week”,list(df[‘z’]))page = Page()page.add(chart1, chart2)page.render_notebook()" }, { "code": null, "e": 5560, "s": 5393, "text": "As you can see, the cutechart package can really provide impressively cute charts. The limit of this package is that it can only generate five different kinds charts." }, { "code": null, "e": 5667, "s": 5560, "text": "If you are interested in making other types of beautiful charts, you may want to check out my other posts." }, { "code": null, "e": 6089, "s": 5667, "text": "Make beautiful Nightinggale rose chart in python-visualize covid19 death rateMake a beautiful water polo chart in a few lines in PythonMake a beautiful bar chart in just few lines in PythonMake a beautiful scatterplot in a few lines in Python to make your report outstandingMake an impressive animated bubble chart with Plotly in Python — inspired by professor Hans RoslingDraw a unique barplot using Matplotlib in Python" }, { "code": null, "e": 6167, "s": 6089, "text": "Make beautiful Nightinggale rose chart in python-visualize covid19 death rate" }, { "code": null, "e": 6226, "s": 6167, "text": "Make a beautiful water polo chart in a few lines in Python" }, { "code": null, "e": 6281, "s": 6226, "text": "Make a beautiful bar chart in just few lines in Python" }, { "code": null, "e": 6367, "s": 6281, "text": "Make a beautiful scatterplot in a few lines in Python to make your report outstanding" }, { "code": null, "e": 6467, "s": 6367, "text": "Make an impressive animated bubble chart with Plotly in Python — inspired by professor Hans Rosling" } ]
Python program to find the factorial of a number using recursion - GeeksforGeeks
12 Nov, 2020 A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than or equal to n. For example: In this article, we are going to calculate the factorial of a number using recursion. Examples: Input: 5 Output: 120 Input: 6 Output: 720 Implementation: If fact(5) is called, it will call fact(4), fact(3), fact(2) and fact(1). So it means keeps calling itself by reducing value by one till it reaches 1. Python3 # Python 3 program to find # factorial of given number def factorial(n): # Checking the number # is 1 or 0 then # return 1 # other wise return # factorial if (n==1 or n==0): return 1 else: return (n * factorial(n - 1)) # Driver Code num = 5; print("number : ",num)print("Factorial : ",factorial(num)) Output: Number : 5 Factorial : 120 factorial Python Python Programs factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25561, "s": 25533, "text": "\n12 Nov, 2020" }, { "code": null, "e": 25682, "s": 25561, "text": "A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than or equal to n." }, { "code": null, "e": 25695, "s": 25682, "text": "For example:" }, { "code": null, "e": 25781, "s": 25695, "text": "In this article, we are going to calculate the factorial of a number using recursion." }, { "code": null, "e": 25791, "s": 25781, "text": "Examples:" }, { "code": null, "e": 25835, "s": 25791, "text": "Input: 5\nOutput: 120\n\nInput: 6\nOutput: 720\n" }, { "code": null, "e": 25851, "s": 25835, "text": "Implementation:" }, { "code": null, "e": 26002, "s": 25851, "text": "If fact(5) is called, it will call fact(4), fact(3), fact(2) and fact(1). So it means keeps calling itself by reducing value by one till it reaches 1." }, { "code": null, "e": 26010, "s": 26002, "text": "Python3" }, { "code": "# Python 3 program to find # factorial of given number def factorial(n): # Checking the number # is 1 or 0 then # return 1 # other wise return # factorial if (n==1 or n==0): return 1 else: return (n * factorial(n - 1)) # Driver Code num = 5; print(\"number : \",num)print(\"Factorial : \",factorial(num))", "e": 26382, "s": 26010, "text": null }, { "code": null, "e": 26390, "s": 26382, "text": "Output:" }, { "code": null, "e": 26420, "s": 26390, "text": "Number : 5\nFactorial : 120\n" }, { "code": null, "e": 26430, "s": 26420, "text": "factorial" }, { "code": null, "e": 26437, "s": 26430, "text": "Python" }, { "code": null, "e": 26453, "s": 26437, "text": "Python Programs" }, { "code": null, "e": 26463, "s": 26453, "text": "factorial" }, { "code": null, "e": 26561, "s": 26463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26593, "s": 26561, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26635, "s": 26593, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26677, "s": 26635, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26704, "s": 26677, "text": "Python Classes and Objects" }, { "code": null, "e": 26760, "s": 26704, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26782, "s": 26760, "text": "Defaultdict in Python" }, { "code": null, "e": 26821, "s": 26782, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26867, "s": 26821, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26905, "s": 26867, "text": "Python | Convert a list to dictionary" } ]
Python | Filter list of strings based on the substring list - GeeksforGeeks
29 May, 2019 Given two lists of strings string and substr, write a Python program to filter out all the strings in string that contains string in substr. Examples: Input : string = ['city1', 'class5', 'room2', 'city2'] substr = ['class', 'city'] Output : ['city1', 'class5', 'city2'] Input : string = ['coordinates', 'xyCoord', '123abc'] substr = ['abc', 'xy'] Output : ['xyCoord', '123abc'] Method #1 : Using List comprehension We can Use list comprehension along with in operator to check if the string in ‘substr’ is contained in ‘string’ or not. # Python3 program to Filter list of # strings based on another listimport re def Filter(string, substr): return [str for str in string if any(sub in str for sub in substr)] # Driver codestring = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']print(Filter(string, substr)) ['city1', 'class5', 'city2'] Method #2 : Python Regex # Python3 program to Filter list of # strings based on another listimport re def Filter(string, substr): return [str for str in string if re.match(r'[^\d]+|^', str).group(0) in substr] # Driver codestring = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']print(Filter(string, substr)) ['city1', 'class5', 'city2'] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 26181, "s": 26153, "text": "\n29 May, 2019" }, { "code": null, "e": 26322, "s": 26181, "text": "Given two lists of strings string and substr, write a Python program to filter out all the strings in string that contains string in substr." }, { "code": null, "e": 26332, "s": 26322, "text": "Examples:" }, { "code": null, "e": 26578, "s": 26332, "text": "Input : string = ['city1', 'class5', 'room2', 'city2']\n substr = ['class', 'city']\nOutput : ['city1', 'class5', 'city2']\n\nInput : string = ['coordinates', 'xyCoord', '123abc']\n substr = ['abc', 'xy']\nOutput : ['xyCoord', '123abc']\n" }, { "code": null, "e": 26616, "s": 26578, "text": " Method #1 : Using List comprehension" }, { "code": null, "e": 26737, "s": 26616, "text": "We can Use list comprehension along with in operator to check if the string in ‘substr’ is contained in ‘string’ or not." }, { "code": "# Python3 program to Filter list of # strings based on another listimport re def Filter(string, substr): return [str for str in string if any(sub in str for sub in substr)] # Driver codestring = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']print(Filter(string, substr))", "e": 27046, "s": 26737, "text": null }, { "code": null, "e": 27076, "s": 27046, "text": "['city1', 'class5', 'city2']\n" }, { "code": null, "e": 27102, "s": 27076, "text": " Method #2 : Python Regex" }, { "code": "# Python3 program to Filter list of # strings based on another listimport re def Filter(string, substr): return [str for str in string if re.match(r'[^\\d]+|^', str).group(0) in substr] # Driver codestring = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']print(Filter(string, substr))", "e": 27415, "s": 27102, "text": null }, { "code": null, "e": 27445, "s": 27415, "text": "['city1', 'class5', 'city2']\n" }, { "code": null, "e": 27468, "s": 27445, "text": "Python string-programs" }, { "code": null, "e": 27475, "s": 27468, "text": "Python" }, { "code": null, "e": 27491, "s": 27475, "text": "Python Programs" }, { "code": null, "e": 27589, "s": 27491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27607, "s": 27589, "text": "Python Dictionary" }, { "code": null, "e": 27639, "s": 27607, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27661, "s": 27639, "text": "Enumerate() in Python" }, { "code": null, "e": 27703, "s": 27661, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27732, "s": 27703, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27754, "s": 27732, "text": "Defaultdict in Python" }, { "code": null, "e": 27793, "s": 27754, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27839, "s": 27793, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27877, "s": 27839, "text": "Python | Convert a list to dictionary" } ]
Turn on or off Bulb using HTML & CSS - GeeksforGeeks
09 Apr, 2021 HTML frames are used to divide the browser window into multiple sections where each section loads a separate HTML document. In this project we are going to make a webpage that will ON and OFF a bulb on user’s click. We will be using HTML frame and frameset feature and some CSS to design our ON and OFF button. Approach: To use frames, we have used <frameset> tag instead of <body> tag. The <frameset> tag defines, how to divide the window into frames. The rows attribute of <frameset> tag defines horizontal frames and cols attribute defines vertical frames. Inside the frame, we have used src attribute which is used to give the file name that should be loaded in the frame. Separately we have created two files namely – ON.html and OFF.html which has images of bulbs in on and off position respectively. Whenever user presses on, ON file is loaded into the frame and whenever off is pressed, the OFF file is loaded. Example: index.html <!DOCTYPE html><html lang="en"> <!--Setting the frames and opening on and off html-pages--><frameset cols="25%,75%"> <frame src="main.html" name="left-frame"></frame> <frame src="off.html" name="right-frame"></frame></frameset> </html> main.html <!DOCTYPE html><html lang="en"> <head> <style type="text/css"> /* Styling the anchor tag */ a { font-weight: bold; text-decoration: none; font-size: 2rem; display: inline-block; } /* Styling the on button */ #on { background-color: chartreuse; color: black; width: 75px; text-align: center; margin-bottom: 25px; margin-top: 70%; margin-left: 40%; } /* Styling the off button */ #off { background-color: orangered; color: black; width: 75px; text-align: center; margin-left: 40%; } </style></head> <body> <p> <a href="on.html" target="right-frame" id="on">ON</a> </p> <p> <a href="off.html" target="right-frame" id="off">OFF</a> </p></body> </html> on.html <!DOCTYPE html><html lang="en"> <head> <style> /* Styling the image */ img { margin-left: 30%; margin-top: 15%; } </style></head> <body> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20210324132942/on.png" height="350px" width="350px"></body> </html> off.html <!DOCTYPE html><html lang="en"> <head> <style> /* Styling the image */ img { margin-left: 30%; margin-top: 15%; } </style></head> <body> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20210324132941/off.png" height="350px" width="350px"></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-Properties CSS-Questions HTML-Attributes HTML-Questions HTML-Tags CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n09 Apr, 2021" }, { "code": null, "e": 26932, "s": 26621, "text": "HTML frames are used to divide the browser window into multiple sections where each section loads a separate HTML document. In this project we are going to make a webpage that will ON and OFF a bulb on user’s click. We will be using HTML frame and frameset feature and some CSS to design our ON and OFF button." }, { "code": null, "e": 26943, "s": 26932, "text": "Approach: " }, { "code": null, "e": 27299, "s": 26943, "text": "To use frames, we have used <frameset> tag instead of <body> tag. The <frameset> tag defines, how to divide the window into frames. The rows attribute of <frameset> tag defines horizontal frames and cols attribute defines vertical frames. Inside the frame, we have used src attribute which is used to give the file name that should be loaded in the frame." }, { "code": null, "e": 27541, "s": 27299, "text": "Separately we have created two files namely – ON.html and OFF.html which has images of bulbs in on and off position respectively. Whenever user presses on, ON file is loaded into the frame and whenever off is pressed, the OFF file is loaded." }, { "code": null, "e": 27550, "s": 27541, "text": "Example:" }, { "code": null, "e": 27561, "s": 27550, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <!--Setting the frames and opening on and off html-pages--><frameset cols=\"25%,75%\"> <frame src=\"main.html\" name=\"left-frame\"></frame> <frame src=\"off.html\" name=\"right-frame\"></frame></frameset> </html>", "e": 27807, "s": 27561, "text": null }, { "code": null, "e": 27819, "s": 27809, "text": "main.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style type=\"text/css\"> /* Styling the anchor tag */ a { font-weight: bold; text-decoration: none; font-size: 2rem; display: inline-block; } /* Styling the on button */ #on { background-color: chartreuse; color: black; width: 75px; text-align: center; margin-bottom: 25px; margin-top: 70%; margin-left: 40%; } /* Styling the off button */ #off { background-color: orangered; color: black; width: 75px; text-align: center; margin-left: 40%; } </style></head> <body> <p> <a href=\"on.html\" target=\"right-frame\" id=\"on\">ON</a> </p> <p> <a href=\"off.html\" target=\"right-frame\" id=\"off\">OFF</a> </p></body> </html>", "e": 28768, "s": 27819, "text": null }, { "code": null, "e": 28776, "s": 28768, "text": "on.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Styling the image */ img { margin-left: 30%; margin-top: 15%; } </style></head> <body> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/20210324132942/on.png\" height=\"350px\" width=\"350px\"></body> </html>", "e": 29109, "s": 28776, "text": null }, { "code": null, "e": 29118, "s": 29109, "text": "off.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Styling the image */ img { margin-left: 30%; margin-top: 15%; } </style></head> <body> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/20210324132941/off.png\" height=\"350px\" width=\"350px\"></body> </html>", "e": 29452, "s": 29118, "text": null }, { "code": null, "e": 29460, "s": 29452, "text": "Output:" }, { "code": null, "e": 29597, "s": 29460, "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": 29612, "s": 29597, "text": "CSS-Properties" }, { "code": null, "e": 29626, "s": 29612, "text": "CSS-Questions" }, { "code": null, "e": 29642, "s": 29626, "text": "HTML-Attributes" }, { "code": null, "e": 29657, "s": 29642, "text": "HTML-Questions" }, { "code": null, "e": 29667, "s": 29657, "text": "HTML-Tags" }, { "code": null, "e": 29671, "s": 29667, "text": "CSS" }, { "code": null, "e": 29676, "s": 29671, "text": "HTML" }, { "code": null, "e": 29693, "s": 29676, "text": "Web Technologies" }, { "code": null, "e": 29698, "s": 29693, "text": "HTML" }, { "code": null, "e": 29796, "s": 29698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29835, "s": 29796, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29872, "s": 29835, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29901, "s": 29872, "text": "Form validation using jQuery" }, { "code": null, "e": 29943, "s": 29901, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29978, "s": 29943, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 30038, "s": 29978, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30091, "s": 30038, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30152, "s": 30091, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30176, "s": 30152, "text": "REST API (Introduction)" } ]
Java.util.concurrent.CyclicBarrier in Java - GeeksforGeeks
09 Feb, 2018 CyclicBarrier is used to make threads wait for each other. It is used when different threads process a part of computation and when all threads have completed the execution, the result needs to be combined in the parent thread. In other words, a CyclicBarrier is used when multiple thread carry out different sub tasks and the output of these sub tasks need to be combined to form the final output. After completing its execution, threads call await() method and wait for other threads to reach the barrier. Once all the threads have reached, the barriers then give the way for threads to proceed. Working of CyclicBarrier CyclicBarriers are defined in java.util.concurrent package. First a new instance of a CyclicBarriers is created specifying the number of threads that the barriers should wait upon. CyclicBarrier newBarrier = new CyclicBarrier(numberOfThreads); Each and every thread does some computation and after completing it’s execution, calls await() methods as shown: public void run() { // thread does the computation newBarrier.await(); } Working of CyclicBarrier: Once the number of threads that called await() equals numberOfThreads, the barrier then gives a way for the waiting threads. The CyclicBarrier can also be initialized with some action that is performed once all the threads have reached the barrier. This action can combine/utilize the result of computation of individual thread waiting in the barrier. Runnable action = ... //action to be performed when all threads reach the barrier; CyclicBarrier newBarrier = new CyclicBarrier(numberOfThreads, action); Important Methods of CyclicBarrier: getParties: Returns the number of parties required to trip this barrier.Syntax:public int getParties()Returns:the number of parties required to trip this barrierreset: Resets the barrier to its initial state.Syntax:public void reset()Returns:void but resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException.isBroken: Queries if this barrier is in a broken state.Syntax:public boolean isBroken()Returns:true if one or more parties broke out of this barrier due to interruption or timeout since construction or the last reset, or a barrier action failed due to an exception; false otherwise.getNumberWaiting: Returns the number of parties currently waiting at the barrier.Syntax:public int getNumberWaiting()Returns:the number of parties currently blocked in await()await: Waits until all parties have invoked await on this barrier.Syntax:public int await() throws InterruptedException, BrokenBarrierExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive.await: Waits until all parties have invoked await on this barrier, or the specified waiting time elapses.Syntax:public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive getParties: Returns the number of parties required to trip this barrier.Syntax:public int getParties()Returns:the number of parties required to trip this barrier public int getParties() Returns:the number of parties required to trip this barrier reset: Resets the barrier to its initial state.Syntax:public void reset()Returns:void but resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException. public void reset() Returns:void but resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException. isBroken: Queries if this barrier is in a broken state.Syntax:public boolean isBroken()Returns:true if one or more parties broke out of this barrier due to interruption or timeout since construction or the last reset, or a barrier action failed due to an exception; false otherwise. public boolean isBroken() Returns:true if one or more parties broke out of this barrier due to interruption or timeout since construction or the last reset, or a barrier action failed due to an exception; false otherwise. getNumberWaiting: Returns the number of parties currently waiting at the barrier.Syntax:public int getNumberWaiting()Returns:the number of parties currently blocked in await() public int getNumberWaiting() Returns:the number of parties currently blocked in await() await: Waits until all parties have invoked await on this barrier.Syntax:public int await() throws InterruptedException, BrokenBarrierExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive. public int await() throws InterruptedException, BrokenBarrierException Returns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive. await: Waits until all parties have invoked await on this barrier, or the specified waiting time elapses.Syntax:public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException Returns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive //JAVA program to demonstrate execution on Cyclic Barrier import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier; class Computation1 implements Runnable{ public static int product = 0; public void run() { product = 2 * 3; try { Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }} class Computation2 implements Runnable{ public static int sum = 0; public void run() { // check if newBarrier is broken or not System.out.println("Is the barrier broken? - " + Tester.newBarrier.isBroken()); sum = 10 + 20; try { Tester.newBarrier.await(3000, TimeUnit.MILLISECONDS); // number of parties waiting at the barrier System.out.println("Number of parties waiting at the barrier "+ "at this point = " + Tester.newBarrier.getNumberWaiting()); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } }} public class Tester implements Runnable{ public static CyclicBarrier newBarrier = new CyclicBarrier(3); public static void main(String[] args) { // parent thread Tester test = new Tester(); Thread t1 = new Thread(test); t1.start(); } public void run() { System.out.println("Number of parties required to trip the barrier = "+ newBarrier.getParties()); System.out.println("Sum of product and sum = " + (Computation1.product + Computation2.sum)); // objects on which the child thread has to run Computation1 comp1 = new Computation1(); Computation2 comp2 = new Computation2(); // creation of child thread Thread t1 = new Thread(comp1); Thread t2 = new Thread(comp2); // moving child thread to runnable state t1.start(); t2.start(); try { Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } // barrier breaks as the number of thread waiting for the barrier // at this point = 3 System.out.println("Sum of product and sum = " + (Computation1.product + Computation2.sum)); // Resetting the newBarrier newBarrier.reset(); System.out.println("Barrier reset successful"); }} Output: <Number of parties required to trip the barrier = 3 Sum of product and sum = 0 Is the barrier broken? - false Number of parties waiting at the barrier at this point = 0 Sum of product and sum = 36 Barrier reset successful Explanation: The value of (sum + product) = 0 is printed on the console because the child thread has’t yet ran to set the values of sum and product variable. Following this, (sum + product) = 36 is printed on the console because the child threads ran setting the values of sum and product. Furthermore, the number of waiting thread on the barrier reached 3, due to which the barrier then allowed all thread to pass and finally 36 was printed. The value of “Number of parties waiting at the barrier at this point” = 0 because all the three threads had already called await() method and hence, the barrier is no longer active. In the end, newBarrier is reset and can be used again. BrokenBarrierException A barrier breaks when any of the waiting thread leaves the barrier. This happens when one or more waiting thread is interrupted or when the waiting time is completed because the thread called the await() methods with a timeout as follows: newBarrier.await(1000, TimeUnit.MILLISECONDS); // thread calling this await() // methods waits for only 1000 milliseconds. When the barrier breaks due to one of more participating threads, the await() methods of all the other threads throws a BrokenThreadException. Whereas, the threads that are already waiting in the barriers have their await() call terminated. Difference between a CyclicBarrier and a CountDownLatch A CountDownLatch can be used only once in a program(until it’s count reaches 0). A CyclicBarrier can be used again and again once all the threads in a barriers is released. Reference: Oracle This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java - util package Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Reverse a string in Java Arrays.sort() in Java with examples Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 25195, "s": 25167, "text": "\n09 Feb, 2018" }, { "code": null, "e": 25793, "s": 25195, "text": "CyclicBarrier is used to make threads wait for each other. It is used when different threads process a part of computation and when all threads have completed the execution, the result needs to be combined in the parent thread. In other words, a CyclicBarrier is used when multiple thread carry out different sub tasks and the output of these sub tasks need to be combined to form the final output. After completing its execution, threads call await() method and wait for other threads to reach the barrier. Once all the threads have reached, the barriers then give the way for threads to proceed." }, { "code": null, "e": 25818, "s": 25793, "text": "Working of CyclicBarrier" }, { "code": null, "e": 25999, "s": 25818, "text": "CyclicBarriers are defined in java.util.concurrent package. First a new instance of a CyclicBarriers is created specifying the number of threads that the barriers should wait upon." }, { "code": null, "e": 26062, "s": 25999, "text": "CyclicBarrier newBarrier = new CyclicBarrier(numberOfThreads);" }, { "code": null, "e": 26175, "s": 26062, "text": "Each and every thread does some computation and after completing it’s execution, calls await() methods as shown:" }, { "code": null, "e": 26257, "s": 26175, "text": "public void run()\n{\n // thread does the computation\n newBarrier.await();\n}\n" }, { "code": null, "e": 26283, "s": 26257, "text": "Working of CyclicBarrier:" }, { "code": null, "e": 26635, "s": 26283, "text": "Once the number of threads that called await() equals numberOfThreads, the barrier then gives a way for the waiting threads. The CyclicBarrier can also be initialized with some action that is performed once all the threads have reached the barrier. This action can combine/utilize the result of computation of individual thread waiting in the barrier." }, { "code": null, "e": 26790, "s": 26635, "text": "Runnable action = ... \n//action to be performed when all threads reach the barrier;\nCyclicBarrier newBarrier = new CyclicBarrier(numberOfThreads, action);" }, { "code": null, "e": 26826, "s": 26790, "text": "Important Methods of CyclicBarrier:" }, { "code": null, "e": 28338, "s": 26826, "text": "getParties: Returns the number of parties required to trip this barrier.Syntax:public int getParties()Returns:the number of parties required to trip this barrierreset: Resets the barrier to its initial state.Syntax:public void reset()Returns:void but resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException.isBroken: Queries if this barrier is in a broken state.Syntax:public boolean isBroken()Returns:true if one or more parties broke out of this barrier due to interruption or timeout since construction or the last reset, or a barrier action failed due to an exception; false otherwise.getNumberWaiting: Returns the number of parties currently waiting at the barrier.Syntax:public int getNumberWaiting()Returns:the number of parties currently blocked in await()await: Waits until all parties have invoked await on this barrier.Syntax:public int await() throws InterruptedException, BrokenBarrierExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive.await: Waits until all parties have invoked await on this barrier, or the specified waiting time elapses.Syntax:public int await(long timeout, TimeUnit unit) \nthrows InterruptedException,\nBrokenBarrierException, TimeoutExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive" }, { "code": null, "e": 28500, "s": 28338, "text": "getParties: Returns the number of parties required to trip this barrier.Syntax:public int getParties()Returns:the number of parties required to trip this barrier" }, { "code": null, "e": 28524, "s": 28500, "text": "public int getParties()" }, { "code": null, "e": 28584, "s": 28524, "text": "Returns:the number of parties required to trip this barrier" }, { "code": null, "e": 28816, "s": 28584, "text": "reset: Resets the barrier to its initial state.Syntax:public void reset()Returns:void but resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException." }, { "code": null, "e": 28836, "s": 28816, "text": "public void reset()" }, { "code": null, "e": 28995, "s": 28836, "text": "Returns:void but resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException." }, { "code": null, "e": 29278, "s": 28995, "text": "isBroken: Queries if this barrier is in a broken state.Syntax:public boolean isBroken()Returns:true if one or more parties broke out of this barrier due to interruption or timeout since construction or the last reset, or a barrier action failed due to an exception; false otherwise." }, { "code": null, "e": 29304, "s": 29278, "text": "public boolean isBroken()" }, { "code": null, "e": 29500, "s": 29304, "text": "Returns:true if one or more parties broke out of this barrier due to interruption or timeout since construction or the last reset, or a barrier action failed due to an exception; false otherwise." }, { "code": null, "e": 29676, "s": 29500, "text": "getNumberWaiting: Returns the number of parties currently waiting at the barrier.Syntax:public int getNumberWaiting()Returns:the number of parties currently blocked in await()" }, { "code": null, "e": 29706, "s": 29676, "text": "public int getNumberWaiting()" }, { "code": null, "e": 29765, "s": 29706, "text": "Returns:the number of parties currently blocked in await()" }, { "code": null, "e": 30055, "s": 29765, "text": "await: Waits until all parties have invoked await on this barrier.Syntax:public int await() throws InterruptedException, BrokenBarrierExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive." }, { "code": null, "e": 30126, "s": 30055, "text": "public int await() throws InterruptedException, BrokenBarrierException" }, { "code": null, "e": 30273, "s": 30126, "text": "Returns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive." }, { "code": null, "e": 30647, "s": 30273, "text": "await: Waits until all parties have invoked await on this barrier, or the specified waiting time elapses.Syntax:public int await(long timeout, TimeUnit unit) \nthrows InterruptedException,\nBrokenBarrierException, TimeoutExceptionReturns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive" }, { "code": null, "e": 30764, "s": 30647, "text": "public int await(long timeout, TimeUnit unit) \nthrows InterruptedException,\nBrokenBarrierException, TimeoutException" }, { "code": null, "e": 30910, "s": 30764, "text": "Returns:the arrival index of the current thread, where index getParties() – 1 indicates the first to arrive and zero indicates the last to arrive" }, { "code": "//JAVA program to demonstrate execution on Cyclic Barrier import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier; class Computation1 implements Runnable{ public static int product = 0; public void run() { product = 2 * 3; try { Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }} class Computation2 implements Runnable{ public static int sum = 0; public void run() { // check if newBarrier is broken or not System.out.println(\"Is the barrier broken? - \" + Tester.newBarrier.isBroken()); sum = 10 + 20; try { Tester.newBarrier.await(3000, TimeUnit.MILLISECONDS); // number of parties waiting at the barrier System.out.println(\"Number of parties waiting at the barrier \"+ \"at this point = \" + Tester.newBarrier.getNumberWaiting()); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } }} public class Tester implements Runnable{ public static CyclicBarrier newBarrier = new CyclicBarrier(3); public static void main(String[] args) { // parent thread Tester test = new Tester(); Thread t1 = new Thread(test); t1.start(); } public void run() { System.out.println(\"Number of parties required to trip the barrier = \"+ newBarrier.getParties()); System.out.println(\"Sum of product and sum = \" + (Computation1.product + Computation2.sum)); // objects on which the child thread has to run Computation1 comp1 = new Computation1(); Computation2 comp2 = new Computation2(); // creation of child thread Thread t1 = new Thread(comp1); Thread t2 = new Thread(comp2); // moving child thread to runnable state t1.start(); t2.start(); try { Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } // barrier breaks as the number of thread waiting for the barrier // at this point = 3 System.out.println(\"Sum of product and sum = \" + (Computation1.product + Computation2.sum)); // Resetting the newBarrier newBarrier.reset(); System.out.println(\"Barrier reset successful\"); }}", "e": 33684, "s": 30910, "text": null }, { "code": null, "e": 33692, "s": 33684, "text": "Output:" }, { "code": null, "e": 33914, "s": 33692, "text": "<Number of parties required to trip the barrier = 3\nSum of product and sum = 0\nIs the barrier broken? - false\nNumber of parties waiting at the barrier at this point = 0\nSum of product and sum = 36\nBarrier reset successful" }, { "code": null, "e": 34594, "s": 33914, "text": "Explanation: The value of (sum + product) = 0 is printed on the console because the child thread has’t yet ran to set the values of sum and product variable. Following this, (sum + product) = 36 is printed on the console because the child threads ran setting the values of sum and product. Furthermore, the number of waiting thread on the barrier reached 3, due to which the barrier then allowed all thread to pass and finally 36 was printed. The value of “Number of parties waiting at the barrier at this point” = 0 because all the three threads had already called await() method and hence, the barrier is no longer active. In the end, newBarrier is reset and can be used again." }, { "code": null, "e": 34617, "s": 34594, "text": "BrokenBarrierException" }, { "code": null, "e": 34856, "s": 34617, "text": "A barrier breaks when any of the waiting thread leaves the barrier. This happens when one or more waiting thread is interrupted or when the waiting time is completed because the thread called the await() methods with a timeout as follows:" }, { "code": null, "e": 34980, "s": 34856, "text": "newBarrier.await(1000, TimeUnit.MILLISECONDS);\n// thread calling this await() \n// methods waits for only 1000 milliseconds." }, { "code": null, "e": 35221, "s": 34980, "text": "When the barrier breaks due to one of more participating threads, the await() methods of all the other threads throws a BrokenThreadException. Whereas, the threads that are already waiting in the barriers have their await() call terminated." }, { "code": null, "e": 35277, "s": 35221, "text": "Difference between a CyclicBarrier and a CountDownLatch" }, { "code": null, "e": 35358, "s": 35277, "text": "A CountDownLatch can be used only once in a program(until it’s count reaches 0)." }, { "code": null, "e": 35450, "s": 35358, "text": "A CyclicBarrier can be used again and again once all the threads in a barriers is released." }, { "code": null, "e": 35468, "s": 35450, "text": "Reference: Oracle" }, { "code": null, "e": 35768, "s": 35468, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 35893, "s": 35768, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 35913, "s": 35893, "text": "Java - util package" }, { "code": null, "e": 35933, "s": 35913, "text": "Java-Multithreading" }, { "code": null, "e": 35938, "s": 35933, "text": "Java" }, { "code": null, "e": 35943, "s": 35938, "text": "Java" }, { "code": null, "e": 36041, "s": 35943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36056, "s": 36041, "text": "Arrays in Java" }, { "code": null, "e": 36100, "s": 36056, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36122, "s": 36100, "text": "For-each loop in Java" }, { "code": null, "e": 36173, "s": 36122, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 36203, "s": 36173, "text": "HashMap in Java with Examples" }, { "code": null, "e": 36228, "s": 36203, "text": "Reverse a string in Java" }, { "code": null, "e": 36264, "s": 36228, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 36279, "s": 36264, "text": "Stream In Java" }, { "code": null, "e": 36298, "s": 36279, "text": "Interfaces in Java" } ]
Apache Presto - HIVE Connector
The Hive connector allows querying data stored in a Hive data warehouse. Hadoop Hive Hopefully you have installed Hadoop and Hive on your machine. Start all the services one by one in the new terminal. Then, start hive metastore using the following command, hive --service metastore Presto uses Hive metastore service to get the hive table’s details. Create a file “hive.properties” under “etc/catalog” directory. Use the following command. $ cd etc $ cd catalog $ vi hive.properties connector.name = hive-cdh4 hive.metastore.uri = thrift://localhost:9083 After making all the changes, save the file and quit the terminal. Create a database in Hive using the following query − hive> CREATE SCHEMA tutorials; After the database is created, you can verify it using the “show databases” command. Create Table is a statement used to create a table in Hive. For example, use the following query. hive> create table author(auth_id int, auth_name varchar(50), topic varchar(100) STORED AS SEQUENCEFILE; Following query is used to insert records in hive’s table. hive> insert into table author values (1,’ Doug Cutting’,Hadoop), (2,’ James Gosling’,java),(3,’ Dennis Ritchie’,C); You can start Presto CLI to connect Hive storage plugin using the following command. $ ./presto --server localhost:8080 --catalog hive —schema tutorials; You will receive the following response. presto:tutorials > To list out all the schemas in Hive connector, type the following command. presto:tutorials > show schemas from hive; default tutorials To list out all the tables in “tutorials” schema, use the following query. presto:tutorials > show tables from hive.tutorials; author Following query is used to fetch all the records from hive’s table. presto:tutorials > select * from hive.tutorials.author; auth_id | auth_name | topic ---------+----------------+-------- 1 | Doug Cutting | Hadoop 2 | James Gosling | java 3 | Dennis Ritchie | C 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2079, "s": 2006, "text": "The Hive connector allows querying data stored in a Hive data warehouse." }, { "code": null, "e": 2086, "s": 2079, "text": "Hadoop" }, { "code": null, "e": 2091, "s": 2086, "text": "Hive" }, { "code": null, "e": 2264, "s": 2091, "text": "Hopefully you have installed Hadoop and Hive on your machine. Start all the services one by one in the new terminal. Then, start hive metastore using the following command," }, { "code": null, "e": 2290, "s": 2264, "text": "hive --service metastore\n" }, { "code": null, "e": 2358, "s": 2290, "text": "Presto uses Hive metastore service to get the hive table’s details." }, { "code": null, "e": 2448, "s": 2358, "text": "Create a file “hive.properties” under “etc/catalog” directory. Use the following command." }, { "code": null, "e": 2570, "s": 2448, "text": "$ cd etc \n$ cd catalog \n$ vi hive.properties \n\nconnector.name = hive-cdh4 \nhive.metastore.uri = thrift://localhost:9083\n" }, { "code": null, "e": 2637, "s": 2570, "text": "After making all the changes, save the file and quit the terminal." }, { "code": null, "e": 2691, "s": 2637, "text": "Create a database in Hive using the following query −" }, { "code": null, "e": 2723, "s": 2691, "text": "hive> CREATE SCHEMA tutorials; " }, { "code": null, "e": 2808, "s": 2723, "text": "After the database is created, you can verify it using the “show databases” command." }, { "code": null, "e": 2906, "s": 2808, "text": "Create Table is a statement used to create a table in Hive. For example, use the following query." }, { "code": null, "e": 3012, "s": 2906, "text": "hive> create table author(auth_id int, auth_name varchar(50), \ntopic varchar(100) STORED AS SEQUENCEFILE;" }, { "code": null, "e": 3071, "s": 3012, "text": "Following query is used to insert records in hive’s table." }, { "code": null, "e": 3188, "s": 3071, "text": "hive> insert into table author values (1,’ Doug Cutting’,Hadoop),\n(2,’ James Gosling’,java),(3,’ Dennis Ritchie’,C);" }, { "code": null, "e": 3273, "s": 3188, "text": "You can start Presto CLI to connect Hive storage plugin using the following command." }, { "code": null, "e": 3344, "s": 3273, "text": "$ ./presto --server localhost:8080 --catalog hive —schema tutorials; \n" }, { "code": null, "e": 3385, "s": 3344, "text": "You will receive the following response." }, { "code": null, "e": 3405, "s": 3385, "text": "presto:tutorials >\n" }, { "code": null, "e": 3480, "s": 3405, "text": "To list out all the schemas in Hive connector, type the following command." }, { "code": null, "e": 3523, "s": 3480, "text": "presto:tutorials > show schemas from hive;" }, { "code": null, "e": 3546, "s": 3523, "text": "default \n\ntutorials \n" }, { "code": null, "e": 3621, "s": 3546, "text": "To list out all the tables in “tutorials” schema, use the following query." }, { "code": null, "e": 3674, "s": 3621, "text": "presto:tutorials > show tables from hive.tutorials; " }, { "code": null, "e": 3682, "s": 3674, "text": "author\n" }, { "code": null, "e": 3750, "s": 3682, "text": "Following query is used to fetch all the records from hive’s table." }, { "code": null, "e": 3807, "s": 3750, "text": "presto:tutorials > select * from hive.tutorials.author; " }, { "code": null, "e": 3980, "s": 3807, "text": "auth_id | auth_name | topic \n---------+----------------+-------- \n 1 | Doug Cutting | Hadoop \n 2 | James Gosling | java \n 3 | Dennis Ritchie | C\n" }, { "code": null, "e": 4015, "s": 3980, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4034, "s": 4015, "text": " Arnab Chakraborty" }, { "code": null, "e": 4069, "s": 4034, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4090, "s": 4069, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 4123, "s": 4090, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4136, "s": 4123, "text": " Nilay Mehta" }, { "code": null, "e": 4171, "s": 4136, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4189, "s": 4171, "text": " Bigdata Engineer" }, { "code": null, "e": 4222, "s": 4189, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 4240, "s": 4222, "text": " Bigdata Engineer" }, { "code": null, "e": 4273, "s": 4240, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 4291, "s": 4273, "text": " Bigdata Engineer" }, { "code": null, "e": 4298, "s": 4291, "text": " Print" }, { "code": null, "e": 4309, "s": 4298, "text": " Add Notes" } ]
Heap overflow and Stack overflow - GeeksforGeeks
25 Feb, 2018 Heap Overflow: Heap is a region of process’s memory which is used to store dynamic variables. These variables are allocated using malloc() and calloc() functions and resize using realloc() function, which are inbuilt functions of C. These variables can be accessed globally and once we allocate memory on heap it is our responsibility to free that memory space after use. There are two situations which can result in heap overflow: If we continuously allocate memory and we do not free that memory space after use it may result in memory leakage – memory is still being used but not available for other processes.// C program to demonstrate heap overflow// by continuously allocating memory#include<stdio.h> int main(){ for (int i=0; i<10000000; i++) { // Allocating memory without freeing it int *ptr = (int *)malloc(sizeof(int)); }}If we dynamically allocate large number of variables.// C program to demonstrate heap overflow// by allocating large memory#include<stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)*10000000));} If we continuously allocate memory and we do not free that memory space after use it may result in memory leakage – memory is still being used but not available for other processes.// C program to demonstrate heap overflow// by continuously allocating memory#include<stdio.h> int main(){ for (int i=0; i<10000000; i++) { // Allocating memory without freeing it int *ptr = (int *)malloc(sizeof(int)); }} // C program to demonstrate heap overflow// by continuously allocating memory#include<stdio.h> int main(){ for (int i=0; i<10000000; i++) { // Allocating memory without freeing it int *ptr = (int *)malloc(sizeof(int)); }} If we dynamically allocate large number of variables.// C program to demonstrate heap overflow// by allocating large memory#include<stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)*10000000));} // C program to demonstrate heap overflow// by allocating large memory#include<stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)*10000000));} Stack Overflow: Stack is a special region of our process’s memory which is used to store local variables used inside the function, parameters passed through a function and their return addresses. Whenever a new local variable is declared it is pushed onto the stack. All the variables associated with a function are deleted and memory they use is freed up, after the function finishes running. The user does not have any need to free up stack space manually. Stack is Last-In-First-Out data structure. In our computer’s memory, stack size is limited. If a program uses more memory space than the stack size then stack overflow will occur and can result in a program crash. There are two cases in which stack overflow can occur: If we declare large number of local variables or declare an array or matrix or any higher dimensional array of large size can result in overflow of stack.// C program to demonstrate stack overflow// by allocating a large local memory#include<stdio.h> int main() { // Creating a matrix of size 10^5 x 10^5 // which may result in stack overflow. int mat[100000][100000];}If function recursively call itself infinite times then the stack is unable to store large number of local variables used by every function call and will result in overflow of stack.// C program to demonstrate stack overflow// by creating a non-terminating recursive// function.#include<stdio.h> void fun(int x){ if (x == 1) return; x = 6; fun(x);} int main(){ int x = 5; fun(x);} If we declare large number of local variables or declare an array or matrix or any higher dimensional array of large size can result in overflow of stack.// C program to demonstrate stack overflow// by allocating a large local memory#include<stdio.h> int main() { // Creating a matrix of size 10^5 x 10^5 // which may result in stack overflow. int mat[100000][100000];} // C program to demonstrate stack overflow// by allocating a large local memory#include<stdio.h> int main() { // Creating a matrix of size 10^5 x 10^5 // which may result in stack overflow. int mat[100000][100000];} If function recursively call itself infinite times then the stack is unable to store large number of local variables used by every function call and will result in overflow of stack.// C program to demonstrate stack overflow// by creating a non-terminating recursive// function.#include<stdio.h> void fun(int x){ if (x == 1) return; x = 6; fun(x);} int main(){ int x = 5; fun(x);} // C program to demonstrate stack overflow// by creating a non-terminating recursive// function.#include<stdio.h> void fun(int x){ if (x == 1) return; x = 6; fun(x);} int main(){ int x = 5; fun(x);} Please refer Memory Layout of C Programs for details. system-programming C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ rand() and srand() in C/C++ fork() in C std::string class in C++ Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++
[ { "code": null, "e": 25692, "s": 25664, "text": "\n25 Feb, 2018" }, { "code": null, "e": 25707, "s": 25692, "text": "Heap Overflow:" }, { "code": null, "e": 26124, "s": 25707, "text": "Heap is a region of process’s memory which is used to store dynamic variables. These variables are allocated using malloc() and calloc() functions and resize using realloc() function, which are inbuilt functions of C. These variables can be accessed globally and once we allocate memory on heap it is our responsibility to free that memory space after use. There are two situations which can result in heap overflow:" }, { "code": null, "e": 26755, "s": 26124, "text": "If we continuously allocate memory and we do not free that memory space after use it may result in memory leakage – memory is still being used but not available for other processes.// C program to demonstrate heap overflow// by continuously allocating memory#include<stdio.h> int main(){ for (int i=0; i<10000000; i++) { // Allocating memory without freeing it int *ptr = (int *)malloc(sizeof(int)); }}If we dynamically allocate large number of variables.// C program to demonstrate heap overflow// by allocating large memory#include<stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)*10000000));}" }, { "code": null, "e": 27180, "s": 26755, "text": "If we continuously allocate memory and we do not free that memory space after use it may result in memory leakage – memory is still being used but not available for other processes.// C program to demonstrate heap overflow// by continuously allocating memory#include<stdio.h> int main(){ for (int i=0; i<10000000; i++) { // Allocating memory without freeing it int *ptr = (int *)malloc(sizeof(int)); }}" }, { "code": "// C program to demonstrate heap overflow// by continuously allocating memory#include<stdio.h> int main(){ for (int i=0; i<10000000; i++) { // Allocating memory without freeing it int *ptr = (int *)malloc(sizeof(int)); }}", "e": 27424, "s": 27180, "text": null }, { "code": null, "e": 27631, "s": 27424, "text": "If we dynamically allocate large number of variables.// C program to demonstrate heap overflow// by allocating large memory#include<stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)*10000000));}" }, { "code": "// C program to demonstrate heap overflow// by allocating large memory#include<stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)*10000000));}", "e": 27785, "s": 27631, "text": null }, { "code": null, "e": 27801, "s": 27785, "text": "Stack Overflow:" }, { "code": null, "e": 28287, "s": 27801, "text": "Stack is a special region of our process’s memory which is used to store local variables used inside the function, parameters passed through a function and their return addresses. Whenever a new local variable is declared it is pushed onto the stack. All the variables associated with a function are deleted and memory they use is freed up, after the function finishes running. The user does not have any need to free up stack space manually. Stack is Last-In-First-Out data structure." }, { "code": null, "e": 28513, "s": 28287, "text": "In our computer’s memory, stack size is limited. If a program uses more memory space than the stack size then stack overflow will occur and can result in a program crash. There are two cases in which stack overflow can occur:" }, { "code": null, "e": 29293, "s": 28513, "text": "If we declare large number of local variables or declare an array or matrix or any higher dimensional array of large size can result in overflow of stack.// C program to demonstrate stack overflow// by allocating a large local memory#include<stdio.h> int main() { // Creating a matrix of size 10^5 x 10^5 // which may result in stack overflow. int mat[100000][100000];}If function recursively call itself infinite times then the stack is unable to store large number of local variables used by every function call and will result in overflow of stack.// C program to demonstrate stack overflow// by creating a non-terminating recursive// function.#include<stdio.h> void fun(int x){ if (x == 1) return; x = 6; fun(x);} int main(){ int x = 5; fun(x);}" }, { "code": null, "e": 29672, "s": 29293, "text": "If we declare large number of local variables or declare an array or matrix or any higher dimensional array of large size can result in overflow of stack.// C program to demonstrate stack overflow// by allocating a large local memory#include<stdio.h> int main() { // Creating a matrix of size 10^5 x 10^5 // which may result in stack overflow. int mat[100000][100000];}" }, { "code": "// C program to demonstrate stack overflow// by allocating a large local memory#include<stdio.h> int main() { // Creating a matrix of size 10^5 x 10^5 // which may result in stack overflow. int mat[100000][100000];}", "e": 29897, "s": 29672, "text": null }, { "code": null, "e": 30299, "s": 29897, "text": "If function recursively call itself infinite times then the stack is unable to store large number of local variables used by every function call and will result in overflow of stack.// C program to demonstrate stack overflow// by creating a non-terminating recursive// function.#include<stdio.h> void fun(int x){ if (x == 1) return; x = 6; fun(x);} int main(){ int x = 5; fun(x);}" }, { "code": "// C program to demonstrate stack overflow// by creating a non-terminating recursive// function.#include<stdio.h> void fun(int x){ if (x == 1) return; x = 6; fun(x);} int main(){ int x = 5; fun(x);}", "e": 30519, "s": 30299, "text": null }, { "code": null, "e": 30573, "s": 30519, "text": "Please refer Memory Layout of C Programs for details." }, { "code": null, "e": 30592, "s": 30573, "text": "system-programming" }, { "code": null, "e": 30603, "s": 30592, "text": "C Language" }, { "code": null, "e": 30607, "s": 30603, "text": "C++" }, { "code": null, "e": 30611, "s": 30607, "text": "CPP" }, { "code": null, "e": 30709, "s": 30611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30731, "s": 30709, "text": "Function Pointer in C" }, { "code": null, "e": 30748, "s": 30731, "text": "Substring in C++" }, { "code": null, "e": 30776, "s": 30748, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 30788, "s": 30776, "text": "fork() in C" }, { "code": null, "e": 30813, "s": 30788, "text": "std::string class in C++" }, { "code": null, "e": 30832, "s": 30813, "text": "Inheritance in C++" }, { "code": null, "e": 30878, "s": 30832, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30921, "s": 30878, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 30945, "s": 30921, "text": "C++ Classes and Objects" } ]
Output of Java Programs | Set 21 (Type Conversions) - GeeksforGeeks
03 Jun, 2017 Prerequisite – Type Conversions in Java with Examples 1) What is the output of the following program? public class Test{ public static void main(String[] args) { int value = 554; String var = (String)value; //line 1 String temp = "123"; int data = (int)temp; //line 2 System.out.println(data + var); }} a) 677b) Compilation error due to line 1c) Compilation error due to line 2d) Compilation error due to line 1 and line 2 Ans. (d)Explanation: Converting from int to String as well as converting from String to int is not allowed in java. 2) What is the output of the following program? public class Test{ public static void main(String[] args) { double data = 444.324; int value = data; System.out.println(data); }} a) 444.324b) 444c) Runtime errord) Compilation error Ans. (d)Explanation: Converting from a bigger data type to a smaller data type is not allowed in java as it is a lossy conversion. 3) What is the output of the following program? public class Test{ public static void main(String[] args) { double data = 444.324; int sum = 9; float value = 5.1f; System.out.println(data + sum + value); }} a) 444.32495.1b) 456c) 458.42399d) 458.4 Ans. (c)Explanation: If one of the operands is long, double or float, the entire expression is converted to long, double or float respectively. 4) What is the output of the following program? public class Test{ public static void main(String[] args) { byte var = 1; var = (byte) var * 0; //line 1 byte data = (byte) (var * 0); //line 2 System.out.println(var); }} a) 0b) Compilation error due to line 1c) Compilation error due to line 2d) Compilation error due to line 1 and line 2 Ans. (b)Explanation: When the expressions are evaluated, the data type of the result is implicitly changed to a larger data type and therefore, explicit recasting has to be done as shown in line 2. On the other hand, line 1 shows compilation error because the expression on the right side has data type as int whereas left side it is byte. 5) What is the output of the following program? public class Test{ public static void main(String[] args) { System.out.println((100/25.0)*Integer.parseInt("5") + 50); }} a) Compilation errorb) 70c) 70.0d) Runtime error Ans. (c)Explanation: If a double value is used in an expression then the output is returned in double format rather than an int. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of C++ programs | Set 34 (File Handling) Different ways to copy a string in C/C++ Output of Java program | Set 28 Runtime Errors Output of C++ Program | Set 1 Output of Java Programs | Set 48 (Static keyword) How to show full column content in a PySpark Dataframe ? Output of Java program | Set 26 Output of python program | Set 2 Output of C Programs | Set 3
[ { "code": null, "e": 25633, "s": 25605, "text": "\n03 Jun, 2017" }, { "code": null, "e": 25687, "s": 25633, "text": "Prerequisite – Type Conversions in Java with Examples" }, { "code": null, "e": 25735, "s": 25687, "text": "1) What is the output of the following program?" }, { "code": "public class Test{ public static void main(String[] args) { int value = 554; String var = (String)value; //line 1 String temp = \"123\"; int data = (int)temp; //line 2 System.out.println(data + var); }}", "e": 25981, "s": 25735, "text": null }, { "code": null, "e": 26101, "s": 25981, "text": "a) 677b) Compilation error due to line 1c) Compilation error due to line 2d) Compilation error due to line 1 and line 2" }, { "code": null, "e": 26265, "s": 26101, "text": "Ans. (d)Explanation: Converting from int to String as well as converting from String to int is not allowed in java. 2) What is the output of the following program?" }, { "code": "public class Test{ public static void main(String[] args) { double data = 444.324; int value = data; System.out.println(data); }}", "e": 26425, "s": 26265, "text": null }, { "code": null, "e": 26478, "s": 26425, "text": "a) 444.324b) 444c) Runtime errord) Compilation error" }, { "code": null, "e": 26610, "s": 26478, "text": "Ans. (d)Explanation: Converting from a bigger data type to a smaller data type is not allowed in java as it is a lossy conversion. " }, { "code": null, "e": 26658, "s": 26610, "text": "3) What is the output of the following program?" }, { "code": "public class Test{ public static void main(String[] args) { double data = 444.324; int sum = 9; float value = 5.1f; System.out.println(data + sum + value); }}", "e": 26864, "s": 26658, "text": null }, { "code": null, "e": 26905, "s": 26864, "text": "a) 444.32495.1b) 456c) 458.42399d) 458.4" }, { "code": null, "e": 27050, "s": 26905, "text": "Ans. (c)Explanation: If one of the operands is long, double or float, the entire expression is converted to long, double or float respectively. " }, { "code": null, "e": 27098, "s": 27050, "text": "4) What is the output of the following program?" }, { "code": "public class Test{ public static void main(String[] args) { byte var = 1; var = (byte) var * 0; //line 1 byte data = (byte) (var * 0); //line 2 System.out.println(var); }}", "e": 27315, "s": 27098, "text": null }, { "code": null, "e": 27433, "s": 27315, "text": "a) 0b) Compilation error due to line 1c) Compilation error due to line 2d) Compilation error due to line 1 and line 2" }, { "code": null, "e": 27774, "s": 27433, "text": "Ans. (b)Explanation: When the expressions are evaluated, the data type of the result is implicitly changed to a larger data type and therefore, explicit recasting has to be done as shown in line 2. On the other hand, line 1 shows compilation error because the expression on the right side has data type as int whereas left side it is byte. " }, { "code": null, "e": 27822, "s": 27774, "text": "5) What is the output of the following program?" }, { "code": "public class Test{ public static void main(String[] args) { System.out.println((100/25.0)*Integer.parseInt(\"5\") + 50); }}", "e": 27960, "s": 27822, "text": null }, { "code": null, "e": 28009, "s": 27960, "text": "a) Compilation errorb) 70c) 70.0d) Runtime error" }, { "code": null, "e": 28138, "s": 28009, "text": "Ans. (c)Explanation: If a double value is used in an expression then the output is returned in double format rather than an int." }, { "code": null, "e": 28438, "s": 28138, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28563, "s": 28438, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28575, "s": 28563, "text": "Java-Output" }, { "code": null, "e": 28590, "s": 28575, "text": "Program Output" }, { "code": null, "e": 28688, "s": 28590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28736, "s": 28688, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 28777, "s": 28736, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 28809, "s": 28777, "text": "Output of Java program | Set 28" }, { "code": null, "e": 28824, "s": 28809, "text": "Runtime Errors" }, { "code": null, "e": 28854, "s": 28824, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 28904, "s": 28854, "text": "Output of Java Programs | Set 48 (Static keyword)" }, { "code": null, "e": 28961, "s": 28904, "text": "How to show full column content in a PySpark Dataframe ?" }, { "code": null, "e": 28993, "s": 28961, "text": "Output of Java program | Set 26" }, { "code": null, "e": 29026, "s": 28993, "text": "Output of python program | Set 2" } ]
Python | Convert image to text and then to speech - GeeksforGeeks
09 Sep, 2019 Our goal is to convert a given text image into a string of text, saving it to a file and to hear what is written in the image through audio. For this, we need to import some Libraries Pytesseract(Python-tesseract) : It is an optical character recognition (OCR) tool for python sponsored by google.pyttsx3 : It is an offline cross-platform Text-to-Speech libraryPython Imaging Library (PIL) : It adds image processing capabilities to your Python interpreterGoogletrans : It is a free python library that implements the Google Translate API. Pytesseract(Python-tesseract) : It is an optical character recognition (OCR) tool for python sponsored by google. pyttsx3 : It is an offline cross-platform Text-to-Speech library Python Imaging Library (PIL) : It adds image processing capabilities to your Python interpreter Googletrans : It is a free python library that implements the Google Translate API. Examples: Input : We Have an image with some text Output: THE TEXT FROM THE IMAGE IS EXTRACTED AND A VOICE WILL SPEAK THE TEXT This is the first line of this text example. This is the second line of the same text. Translated(src=en, dest=de, text=Dies ist die erste Zeile von Dieses Textbeispiel. Dies ist die zweite Zeile desselben Textes., pronunciation=None, extra_data="{'translat..." Code : Python code to convert text to speech # import the following libraries# will convert the image to text stringimport pytesseract # adds image processing capabilitiesfrom PIL import Image # converts the text to speech import pyttsx3 #translates into the mentioned languagefrom googletrans import Translator # opening an image from the source pathimg = Image.open('text1.png') # describes image format in the outputprint(img) # path where the tesseract module is installedpytesseract.pytesseract.tesseract_cmd ='C:/Program Files (x86)/Tesseract-OCR/tesseract.exe' # converts the image to result and saves it into result variableresult = pytesseract.image_to_string(img) # write text in a text file and save it to source path with open('abc.txt',mode ='w') as file: file.write(result) print(result) p = Translator() # translates the text into german languagek = p.translate(result,dest='german') print(k)engine = pyttsx3.init() # an audio will be played which speaks the test if pyttsx3 recognizes itengine.say(k) engine.runAndWait() NOTE : We can convert the text into any desired language. For Example Japanese, Russian, Hindi. But the only condition is that the googletrans should recognize the destination language. Also, pyttsx3 will speak only the languages which are recognized by it. Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25615, "s": 25587, "text": "\n09 Sep, 2019" }, { "code": null, "e": 25756, "s": 25615, "text": "Our goal is to convert a given text image into a string of text, saving it to a file and to hear what is written in the image through audio." }, { "code": null, "e": 25799, "s": 25756, "text": "For this, we need to import some Libraries" }, { "code": null, "e": 26155, "s": 25799, "text": "Pytesseract(Python-tesseract) : It is an optical character recognition (OCR) tool for python sponsored by google.pyttsx3 : It is an offline cross-platform Text-to-Speech libraryPython Imaging Library (PIL) : It adds image processing capabilities to your Python interpreterGoogletrans : It is a free python library that implements the Google Translate API." }, { "code": null, "e": 26269, "s": 26155, "text": "Pytesseract(Python-tesseract) : It is an optical character recognition (OCR) tool for python sponsored by google." }, { "code": null, "e": 26334, "s": 26269, "text": "pyttsx3 : It is an offline cross-platform Text-to-Speech library" }, { "code": null, "e": 26430, "s": 26334, "text": "Python Imaging Library (PIL) : It adds image processing capabilities to your Python interpreter" }, { "code": null, "e": 26514, "s": 26430, "text": "Googletrans : It is a free python library that implements the Google Translate API." }, { "code": null, "e": 26524, "s": 26514, "text": "Examples:" }, { "code": null, "e": 27003, "s": 26524, "text": "\nInput : We Have an image with some text \n\nOutput: THE TEXT FROM THE IMAGE IS EXTRACTED AND A VOICE WILL SPEAK THE TEXT\n \n\n This is the first line of\n this text example.\n\n This is the second line\n of the same text.\n\n Translated(src=en, dest=de, text=Dies ist die erste Zeile von\n\n Dieses Textbeispiel.\n\n Dies ist die zweite Zeile\n desselben Textes., pronunciation=None, extra_data=\"{'translat...\"\n" }, { "code": null, "e": 27048, "s": 27003, "text": "Code : Python code to convert text to speech" }, { "code": "# import the following libraries# will convert the image to text stringimport pytesseract # adds image processing capabilitiesfrom PIL import Image # converts the text to speech import pyttsx3 #translates into the mentioned languagefrom googletrans import Translator # opening an image from the source pathimg = Image.open('text1.png') # describes image format in the outputprint(img) # path where the tesseract module is installedpytesseract.pytesseract.tesseract_cmd ='C:/Program Files (x86)/Tesseract-OCR/tesseract.exe' # converts the image to result and saves it into result variableresult = pytesseract.image_to_string(img) # write text in a text file and save it to source path with open('abc.txt',mode ='w') as file: file.write(result) print(result) p = Translator() # translates the text into german languagek = p.translate(result,dest='german') print(k)engine = pyttsx3.init() # an audio will be played which speaks the test if pyttsx3 recognizes itengine.say(k) engine.runAndWait()", "e": 28227, "s": 27048, "text": null }, { "code": null, "e": 28485, "s": 28227, "text": "NOTE : We can convert the text into any desired language. For Example Japanese, Russian, Hindi. But the only condition is that the googletrans should recognize the destination language. Also, pyttsx3 will speak only the languages which are recognized by it." }, { "code": null, "e": 28502, "s": 28485, "text": "Machine Learning" }, { "code": null, "e": 28509, "s": 28502, "text": "Python" }, { "code": null, "e": 28526, "s": 28509, "text": "Machine Learning" }, { "code": null, "e": 28624, "s": 28526, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28665, "s": 28624, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28698, "s": 28665, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28726, "s": 28698, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 28762, "s": 28726, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 28817, "s": 28762, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 28845, "s": 28817, "text": "Read JSON file using Python" }, { "code": null, "e": 28895, "s": 28845, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28917, "s": 28895, "text": "Python map() function" } ]
How to Implement Offline Caching using NetworkBoundResource in Android? - GeeksforGeeks
30 Aug, 2021 Almost, every android application that requires fetching data over a network, needs caching. First, let understand What does caching means? Most of us have used applications that require the data to be fetched from the web. Such an application with an offline-first architecture will always try to fetch the data from the local storage. On the other hand, if there is some failure, it requests the data to be fetched from a network, thereafter storing it locally, for future retrieval. The data will be stored in an SQLite database. The advantage of such an architecture is that we will be able to use the application even if it is offline. Moreover, since the data is cached, the application will respond faster. To handle caching, we will be using NetworkBound Resource. It is a helper class that decides when to use the cache data and when to fetch data from the web and update the View. It coordinates between the two. The above decision tree shows the algorithm for the NetworkBound Resource algorithm. Let us see the flow of this algorithm: Whenever the user accesses the application in offline mode, the data is dispatched into the view, it can either be a fragment or an activity. If there is no data or the data is insufficient in the disk as a cache, then it should fetch the data over the network. It checks if there is a need to log in (if the user logouts, then re-login would be required). It re-authenticates, if successful then it fetches the data, but it failed, then it prompts the user to re-authenticate. Once the credentials are matched, then it fetches the data over the network. If the fetch phase is failed, then it prompts the user. Otherwise, if successful, then the data is stored automatically into the local storage. It then refreshes the view. The requirement here is, there should be minimal changes in the User Experience when the user comes to online mode. So process like Re-authentication, fetching data over the network, and refreshing the views should be done in the background. One thing to be noted here is, the user only needs to re-login, if there are some changes in the user credentials like password, or username. To understand more about this, let us build an application. This is a simple news application, which uses a fake API for fetching data from the web. Let us look at the high-level design of our application: It will be using MVVM architecture.SQLite database for caching data.Use Kotlin FLow.(Kotlin Coroutine)Dagger Hilt for dependency injection. It will be using MVVM architecture. SQLite database for caching data. Use Kotlin FLow.(Kotlin Coroutine) Dagger Hilt for dependency injection. The above diagram is the overview of the architecture that will be implemented in our application. This architecture is recommended by Android to develop a modern well-architecture android application. Let us start building the project. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Setting up the layout It is always recommended to first set up the layout, followed by implementing the logic. So we will first create the layout. As mentioned, we will be fetching data from a web service. Since this is a sample project, we would just fetch data from a random data generator. Now the data is a list of cars, which would include the following properties: Make and model of carTransmission of the carColour of the carDrive type of the car.Fuel type of the car.Car type of the car. Make and model of car Transmission of the car Colour of the car Drive type of the car. Fuel type of the car. Car type of the car. We will be using RecyclerView to show the list. Hence first it is required to design how each element of the list would look like. Followed by making the list. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp"> <!-- This will display the make and model of the car--> <TextView android:id="@+id/car_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:textColor="@color/black" android:textSize="15sp" tools:text="Car Name" /> <!-- This will display the transmission type of the car--> <TextView android:id="@+id/car_transmission" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:layout_toEndOf="@id/car_name" tools:text="Transmission type" /> <!-- This will display the colour of the car--> <TextView android:id="@+id/car_color" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/car_name" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" tools:text="Car colour" /> <!-- This will display the drive type of the car--> <TextView android:id="@+id/car_drive_type" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/car_name" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:layout_toEndOf="@id/car_color" tools:text="Car Drive Type" /> <!-- This will display the fuel type of the car--> <TextView android:id="@+id/car_fuel_type" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/car_transmission" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:layout_toEndOf="@id/car_drive_type" tools:text="Car fuel_type" /> <!-- This will display the car type of the car--> <TextView android:id="@+id/car_car_type" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/car_transmission" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:layout_toEndOf="@id/car_fuel_type" tools:text="Car Type" /> </RelativeLayout> Now, let’s code the list layout: XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".CarActivity"> <!-- The recycler view--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_viewer" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:padding="4dp" tools:listitem="@layout/carlist_item" /> <!--Initially the app will fetch data from the web, hence a progress bar for that--> <ProgressBar android:id="@+id/progress_bar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="invisible" tools:visibility="visible" /> <!--If the application is not able to fetch/ expose the data to the view--> <TextView android:id="@+id/text_view_error" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="8dp" android:gravity="center_horizontal" android:visibility="invisible" tools:text="Error Message" tools:visibility="visible" /> </RelativeLayout> Step 3: Now let’s create the API package CarListAPI.kt Kotlin package com.gfg.carlist.api import com.gfg.carlist.data.CarListimport retrofit2.http.GET interface CarListAPI { // Companion object to hold the base URL companion object{ const val BASE_URL = "https://random-data-api.com/api/" } // The number of cars can be varied using the size. // By default it is kept at 20, but can be tweaked. // @GET annotation to make a GET request. @GET("vehicle/random_vehicle?size=20") // Store the data in a list. suspend fun getCarList() : List<CarList>} Step 4: Implementing the app module A module is nothing but an object class, which provides a container to the app’s source code. It encapsulates data models associated with a task. The android architecture suggests making minimal use of business logic in the view model, hence the business application task is represented in the app module. It will include three methods: A method for calling the API via Retrofit A method to provide the list A method to provide the database or rather build a database. AppModule.kt Kotlin package com.gfg.carlist.di import android.app.Applicationimport androidx.room.Roomimport com.gfg.carlist.api.CarListAPIimport com.gfg.carlist.data.CarListDatabaseimport dagger.Moduleimport dagger.Providesimport dagger.hilt.InstallInimport dagger.hilt.components.SingletonComponentimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryimport javax.inject.Singleton @Module@InstallIn(SingletonComponent::class)object AppModule { @Provides @Singleton fun provideRetrofit(): Retrofit = Retrofit.Builder() .baseUrl(CarListAPI.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() @Provides @Singleton fun provideCarListAPI(retrofit: Retrofit): CarListAPI = retrofit.create(CarListAPI::class.java) @Provides @Singleton fun provideDatabase(app: Application): CarListDatabase = Room.databaseBuilder(app, CarListDatabase::class.java, "carlist_database") .build()} Step 5: Creating Data Class We are done with handling the API, fetching the data from the web service, but where to store the data? Let’s create a class to store the data. We have to create a data class. If the app were to just fetch and expose data, then it would have just a single data class file. But here, we have to fetch, expose as well as cache the data. Hence ROOM comes into play here. So in the data class, we’ve to create an entity. CarList.kt Kotlin package com.gfg.carlist.data import androidx.room.Entityimport androidx.room.PrimaryKey // Data Class to store the data// Here the name of the table is "cars"@Entity(tableName = "cars")data class CarList( @PrimaryKey val make_and_model: String, val color: String, val transmission: String, val drive_type: String, val fuel_type: String, val car_type: String) Since we would be caching the data locally, hence a database is needed to be created. CarListDatabase.kt Kotlin package com.gfg.carlist.data import androidx.room.Databaseimport androidx.room.RoomDatabase @Database(entities = [CarList::class], version = 1)abstract class CarListDatabase : RoomDatabase() { abstract fun carsDao(): CarsDao} Since we have created a table, we need to have some queries to retrieve data from the table. This is achieved using DAO or Data Access Object. CarsDao.kt Kotlin package com.gfg.carlist.data import androidx.room.Daoimport androidx.room.Insertimport androidx.room.OnConflictStrategyimport androidx.room.Queryimport kotlinx.coroutines.flow.Flow @Daointerface CarsDao { // Query to fetch all the data from the // SQLite database // No need of suspend method here @Query("SELECT * FROM cars") // Kotlin flow is an asynchronous stream of values fun getAllCars(): Flow<List<CarList>> // If a new data is inserted with same primary key // It will get replaced by the previous one // This ensures that there is always a latest // data in the database @Insert(onConflict = OnConflictStrategy.REPLACE) // The fetching of data should NOT be done on the // Main thread. Hence coroutine is used // If it is executing on one one thread, it may suspend // its execution there, and resume in another one suspend fun insertCars(cars: List<CarList>) // Once the device comes online, the cached data // need to be replaced, i.e. delete it // Again it will use coroutine to achieve this task @Query("DELETE FROM cars") suspend fun deleteAllCars()} A repository class to handle data from web service and the data locally. CarListRepository.kt Kotlin package com.gfg.carlist.data import androidx.room.withTransactionimport com.gfg.carlist.api.CarListAPIimport com.gfg.carlist.util.networkBoundResourceimport kotlinx.coroutines.delayimport javax.inject.Inject class CarListRepository @Inject constructor( private val api: CarListAPI, private val db: CarListDatabase) { private val carsDao = db.carsDao() fun getCars() = networkBoundResource( // Query to return the list of all cars query = { carsDao.getAllCars() }, // Just for testing purpose, // a delay of 2 second is set. fetch = { delay(2000) api.getCarList() }, // Save the results in the table. // If data exists, then delete it // and then store. saveFetchResult = { CarList -> db.withTransaction { carsDao.deleteAllCars() carsDao.insertCars(CarList) } } )} Step 6: Working on the UI Remember in Step 1, we created a RecyclerView to expose the list of cars. But the work is not completed till now. We need to make an adapter as well as a ViewModel. These two classes work together to define how our data is displayed. CarAdapter.kt Kotlin package com.gfg.carlist.features.carlist import android.view.LayoutInflaterimport android.view.ViewGroupimport androidx.recyclerview.widget.DiffUtilimport androidx.recyclerview.widget.ListAdapterimport androidx.recyclerview.widget.RecyclerViewimport com.gfg.carlist.data.CarListimport com.gfg.carlist.databinding.CarlistItemBinding class CarAdapter : ListAdapter<CarList, CarAdapter.CarViewHolder>(CarListComparator()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder { val binding = CarlistItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return CarViewHolder(binding) } override fun onBindViewHolder(holder: CarViewHolder, position: Int) { val currentItem = getItem(position) if (currentItem != null) { holder.bind(currentItem) } } // View Holder class to hold the view class CarViewHolder(private val binding: CarlistItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(carlist: CarList) { binding.apply { carName.text = carlist.make_and_model carTransmission.text = carlist.transmission carColor.text = carlist.color carDriveType.text = carlist.drive_type carFuelType.text = carlist.fuel_type carCarType.text = carlist.car_type } } } // Comparator class to check for the changes made. // If there are no changes then no need to do anything. class CarListComparator : DiffUtil.ItemCallback<CarList>() { override fun areItemsTheSame(oldItem: CarList, newItem: CarList) = oldItem.make_and_model == newItem.make_and_model override fun areContentsTheSame(oldItem: CarList, newItem: CarList) = oldItem == newItem }} CarListViewModel.kt Kotlin package com.gfg.carlist.features.carlist import androidx.lifecycle.ViewModelimport androidx.lifecycle.asLiveDataimport com.gfg.carlist.data.CarListRepositoryimport dagger.hilt.android.lifecycle.HiltViewModelimport javax.inject.Inject // Using Dagger Hilt library to // inject the data into the view model@HiltViewModelclass CarListViewModel @Inject constructor( repository: CarListRepository) : ViewModel() { val cars = repository.getCars().asLiveData()} Finally, we have to create an activity to show the data from the ViewModel. Remember, all the business logic should be present in the ViewModel, and not in the activity. The activity should also not hold the data, because when the screen is tilted, the data gets destroyed, due to which the loading time increases. Hence the purpose of the activity is to only show the data. CarActivity.kt Kotlin package com.gfg.carlist.features.carlist import android.os.Bundleimport androidx.activity.viewModelsimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.isVisibleimport androidx.recyclerview.widget.LinearLayoutManagerimport com.gfg.carlist.databinding.ActivityCarBindingimport com.gfg.carlist.util.Resourceimport dagger.hilt.android.AndroidEntryPoint @AndroidEntryPointclass CarActivity : AppCompatActivity() { // Helps to preserve the view // If the app is closed, then after // reopening it the app will open // in a state in which it was closed // DaggerHilt will inject the view-model for us private val viewModel: CarListViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // The bellow segment would // instantiate the activity_car layout // and will create a property for different // views inside it! val binding = ActivityCarBinding.inflate(layoutInflater) setContentView(binding.root) val carAdapter = CarAdapter() binding.apply { recyclerViewer.apply { adapter = carAdapter layoutManager = LinearLayoutManager(this@CarActivity) } viewModel.cars.observe(this@CarActivity) { result -> carAdapter.submitList(result.data) progressBar.isVisible = result is Resource.Loading<*> && result.data.isNullOrEmpty() textViewError.isVisible = result is Resource.Error<*> && result.data.isNullOrEmpty() textViewError.text = result.error?.localizedMessage } } }} Finally, we are done with the coding part. After successfully building the project, the app would look like this: Output: The following video demonstrates the application. Output Explanation: Project Link: Click Here Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Kotlin Array Android UI Layouts Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Setters and Getters
[ { "code": null, "e": 26407, "s": 26379, "text": "\n30 Aug, 2021" }, { "code": null, "e": 27330, "s": 26407, "text": "Almost, every android application that requires fetching data over a network, needs caching. First, let understand What does caching means? Most of us have used applications that require the data to be fetched from the web. Such an application with an offline-first architecture will always try to fetch the data from the local storage. On the other hand, if there is some failure, it requests the data to be fetched from a network, thereafter storing it locally, for future retrieval. The data will be stored in an SQLite database. The advantage of such an architecture is that we will be able to use the application even if it is offline. Moreover, since the data is cached, the application will respond faster. To handle caching, we will be using NetworkBound Resource. It is a helper class that decides when to use the cache data and when to fetch data from the web and update the View. It coordinates between the two." }, { "code": null, "e": 27416, "s": 27330, "text": "The above decision tree shows the algorithm for the NetworkBound Resource algorithm. " }, { "code": null, "e": 27456, "s": 27416, "text": "Let us see the flow of this algorithm: " }, { "code": null, "e": 27598, "s": 27456, "text": "Whenever the user accesses the application in offline mode, the data is dispatched into the view, it can either be a fragment or an activity." }, { "code": null, "e": 27718, "s": 27598, "text": "If there is no data or the data is insufficient in the disk as a cache, then it should fetch the data over the network." }, { "code": null, "e": 27934, "s": 27718, "text": "It checks if there is a need to log in (if the user logouts, then re-login would be required). It re-authenticates, if successful then it fetches the data, but it failed, then it prompts the user to re-authenticate." }, { "code": null, "e": 28011, "s": 27934, "text": "Once the credentials are matched, then it fetches the data over the network." }, { "code": null, "e": 28067, "s": 28011, "text": "If the fetch phase is failed, then it prompts the user." }, { "code": null, "e": 28183, "s": 28067, "text": "Otherwise, if successful, then the data is stored automatically into the local storage. It then refreshes the view." }, { "code": null, "e": 28567, "s": 28183, "text": "The requirement here is, there should be minimal changes in the User Experience when the user comes to online mode. So process like Re-authentication, fetching data over the network, and refreshing the views should be done in the background. One thing to be noted here is, the user only needs to re-login, if there are some changes in the user credentials like password, or username." }, { "code": null, "e": 28773, "s": 28567, "text": "To understand more about this, let us build an application. This is a simple news application, which uses a fake API for fetching data from the web. Let us look at the high-level design of our application:" }, { "code": null, "e": 28913, "s": 28773, "text": "It will be using MVVM architecture.SQLite database for caching data.Use Kotlin FLow.(Kotlin Coroutine)Dagger Hilt for dependency injection." }, { "code": null, "e": 28949, "s": 28913, "text": "It will be using MVVM architecture." }, { "code": null, "e": 28983, "s": 28949, "text": "SQLite database for caching data." }, { "code": null, "e": 29018, "s": 28983, "text": "Use Kotlin FLow.(Kotlin Coroutine)" }, { "code": null, "e": 29056, "s": 29018, "text": "Dagger Hilt for dependency injection." }, { "code": null, "e": 29293, "s": 29056, "text": "The above diagram is the overview of the architecture that will be implemented in our application. This architecture is recommended by Android to develop a modern well-architecture android application. Let us start building the project." }, { "code": null, "e": 29322, "s": 29293, "text": "Step 1: Create a New Project" }, { "code": null, "e": 29486, "s": 29322, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 29516, "s": 29486, "text": "Step 2: Setting up the layout" }, { "code": null, "e": 29865, "s": 29516, "text": "It is always recommended to first set up the layout, followed by implementing the logic. So we will first create the layout. As mentioned, we will be fetching data from a web service. Since this is a sample project, we would just fetch data from a random data generator. Now the data is a list of cars, which would include the following properties:" }, { "code": null, "e": 29990, "s": 29865, "text": "Make and model of carTransmission of the carColour of the carDrive type of the car.Fuel type of the car.Car type of the car." }, { "code": null, "e": 30012, "s": 29990, "text": "Make and model of car" }, { "code": null, "e": 30036, "s": 30012, "text": "Transmission of the car" }, { "code": null, "e": 30054, "s": 30036, "text": "Colour of the car" }, { "code": null, "e": 30077, "s": 30054, "text": "Drive type of the car." }, { "code": null, "e": 30099, "s": 30077, "text": "Fuel type of the car." }, { "code": null, "e": 30120, "s": 30099, "text": "Car type of the car." }, { "code": null, "e": 30280, "s": 30120, "text": "We will be using RecyclerView to show the list. Hence first it is required to design how each element of the list would look like. Followed by making the list." }, { "code": null, "e": 30284, "s": 30280, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"4dp\"> <!-- This will display the make and model of the car--> <TextView android:id=\"@+id/car_name\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"8dp\" android:textColor=\"@color/black\" android:textSize=\"15sp\" tools:text=\"Car Name\" /> <!-- This will display the transmission type of the car--> <TextView android:id=\"@+id/car_transmission\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" android:layout_toEndOf=\"@id/car_name\" tools:text=\"Transmission type\" /> <!-- This will display the colour of the car--> <TextView android:id=\"@+id/car_color\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/car_name\" android:layout_marginStart=\"8dp\" android:layout_marginEnd=\"8dp\" tools:text=\"Car colour\" /> <!-- This will display the drive type of the car--> <TextView android:id=\"@+id/car_drive_type\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/car_name\" android:layout_marginStart=\"8dp\" android:layout_marginEnd=\"8dp\" android:layout_toEndOf=\"@id/car_color\" tools:text=\"Car Drive Type\" /> <!-- This will display the fuel type of the car--> <TextView android:id=\"@+id/car_fuel_type\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/car_transmission\" android:layout_marginStart=\"8dp\" android:layout_marginEnd=\"8dp\" android:layout_toEndOf=\"@id/car_drive_type\" tools:text=\"Car fuel_type\" /> <!-- This will display the car type of the car--> <TextView android:id=\"@+id/car_car_type\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/car_transmission\" android:layout_marginStart=\"8dp\" android:layout_marginEnd=\"8dp\" android:layout_toEndOf=\"@id/car_fuel_type\" tools:text=\"Car Type\" /> </RelativeLayout>", "e": 32922, "s": 30284, "text": null }, { "code": null, "e": 32955, "s": 32922, "text": "Now, let’s code the list layout:" }, { "code": null, "e": 32959, "s": 32955, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".CarActivity\"> <!-- The recycler view--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recycler_viewer\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:clipToPadding=\"false\" android:padding=\"4dp\" tools:listitem=\"@layout/carlist_item\" /> <!--Initially the app will fetch data from the web, hence a progress bar for that--> <ProgressBar android:id=\"@+id/progress_bar\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:visibility=\"invisible\" tools:visibility=\"visible\" /> <!--If the application is not able to fetch/ expose the data to the view--> <TextView android:id=\"@+id/text_view_error\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_margin=\"8dp\" android:gravity=\"center_horizontal\" android:visibility=\"invisible\" tools:text=\"Error Message\" tools:visibility=\"visible\" /> </RelativeLayout>", "e": 34411, "s": 32959, "text": null }, { "code": null, "e": 34452, "s": 34411, "text": "Step 3: Now let’s create the API package" }, { "code": null, "e": 34466, "s": 34452, "text": "CarListAPI.kt" }, { "code": null, "e": 34473, "s": 34466, "text": "Kotlin" }, { "code": "package com.gfg.carlist.api import com.gfg.carlist.data.CarListimport retrofit2.http.GET interface CarListAPI { // Companion object to hold the base URL companion object{ const val BASE_URL = \"https://random-data-api.com/api/\" } // The number of cars can be varied using the size. // By default it is kept at 20, but can be tweaked. // @GET annotation to make a GET request. @GET(\"vehicle/random_vehicle?size=20\") // Store the data in a list. suspend fun getCarList() : List<CarList>}", "e": 34994, "s": 34473, "text": null }, { "code": null, "e": 35030, "s": 34994, "text": "Step 4: Implementing the app module" }, { "code": null, "e": 35367, "s": 35030, "text": "A module is nothing but an object class, which provides a container to the app’s source code. It encapsulates data models associated with a task. The android architecture suggests making minimal use of business logic in the view model, hence the business application task is represented in the app module. It will include three methods:" }, { "code": null, "e": 35409, "s": 35367, "text": "A method for calling the API via Retrofit" }, { "code": null, "e": 35438, "s": 35409, "text": "A method to provide the list" }, { "code": null, "e": 35499, "s": 35438, "text": "A method to provide the database or rather build a database." }, { "code": null, "e": 35512, "s": 35499, "text": "AppModule.kt" }, { "code": null, "e": 35519, "s": 35512, "text": "Kotlin" }, { "code": "package com.gfg.carlist.di import android.app.Applicationimport androidx.room.Roomimport com.gfg.carlist.api.CarListAPIimport com.gfg.carlist.data.CarListDatabaseimport dagger.Moduleimport dagger.Providesimport dagger.hilt.InstallInimport dagger.hilt.components.SingletonComponentimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryimport javax.inject.Singleton @Module@InstallIn(SingletonComponent::class)object AppModule { @Provides @Singleton fun provideRetrofit(): Retrofit = Retrofit.Builder() .baseUrl(CarListAPI.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() @Provides @Singleton fun provideCarListAPI(retrofit: Retrofit): CarListAPI = retrofit.create(CarListAPI::class.java) @Provides @Singleton fun provideDatabase(app: Application): CarListDatabase = Room.databaseBuilder(app, CarListDatabase::class.java, \"carlist_database\") .build()}", "e": 36514, "s": 35519, "text": null }, { "code": null, "e": 36542, "s": 36514, "text": "Step 5: Creating Data Class" }, { "code": null, "e": 36960, "s": 36542, "text": "We are done with handling the API, fetching the data from the web service, but where to store the data? Let’s create a class to store the data. We have to create a data class. If the app were to just fetch and expose data, then it would have just a single data class file. But here, we have to fetch, expose as well as cache the data. Hence ROOM comes into play here. So in the data class, we’ve to create an entity." }, { "code": null, "e": 36971, "s": 36960, "text": "CarList.kt" }, { "code": null, "e": 36978, "s": 36971, "text": "Kotlin" }, { "code": "package com.gfg.carlist.data import androidx.room.Entityimport androidx.room.PrimaryKey // Data Class to store the data// Here the name of the table is \"cars\"@Entity(tableName = \"cars\")data class CarList( @PrimaryKey val make_and_model: String, val color: String, val transmission: String, val drive_type: String, val fuel_type: String, val car_type: String)", "e": 37357, "s": 36978, "text": null }, { "code": null, "e": 37443, "s": 37357, "text": "Since we would be caching the data locally, hence a database is needed to be created." }, { "code": null, "e": 37462, "s": 37443, "text": "CarListDatabase.kt" }, { "code": null, "e": 37469, "s": 37462, "text": "Kotlin" }, { "code": "package com.gfg.carlist.data import androidx.room.Databaseimport androidx.room.RoomDatabase @Database(entities = [CarList::class], version = 1)abstract class CarListDatabase : RoomDatabase() { abstract fun carsDao(): CarsDao}", "e": 37700, "s": 37469, "text": null }, { "code": null, "e": 37843, "s": 37700, "text": "Since we have created a table, we need to have some queries to retrieve data from the table. This is achieved using DAO or Data Access Object." }, { "code": null, "e": 37854, "s": 37843, "text": "CarsDao.kt" }, { "code": null, "e": 37861, "s": 37854, "text": "Kotlin" }, { "code": "package com.gfg.carlist.data import androidx.room.Daoimport androidx.room.Insertimport androidx.room.OnConflictStrategyimport androidx.room.Queryimport kotlinx.coroutines.flow.Flow @Daointerface CarsDao { // Query to fetch all the data from the // SQLite database // No need of suspend method here @Query(\"SELECT * FROM cars\") // Kotlin flow is an asynchronous stream of values fun getAllCars(): Flow<List<CarList>> // If a new data is inserted with same primary key // It will get replaced by the previous one // This ensures that there is always a latest // data in the database @Insert(onConflict = OnConflictStrategy.REPLACE) // The fetching of data should NOT be done on the // Main thread. Hence coroutine is used // If it is executing on one one thread, it may suspend // its execution there, and resume in another one suspend fun insertCars(cars: List<CarList>) // Once the device comes online, the cached data // need to be replaced, i.e. delete it // Again it will use coroutine to achieve this task @Query(\"DELETE FROM cars\") suspend fun deleteAllCars()}", "e": 39010, "s": 37861, "text": null }, { "code": null, "e": 39083, "s": 39010, "text": "A repository class to handle data from web service and the data locally." }, { "code": null, "e": 39104, "s": 39083, "text": "CarListRepository.kt" }, { "code": null, "e": 39111, "s": 39104, "text": "Kotlin" }, { "code": "package com.gfg.carlist.data import androidx.room.withTransactionimport com.gfg.carlist.api.CarListAPIimport com.gfg.carlist.util.networkBoundResourceimport kotlinx.coroutines.delayimport javax.inject.Inject class CarListRepository @Inject constructor( private val api: CarListAPI, private val db: CarListDatabase) { private val carsDao = db.carsDao() fun getCars() = networkBoundResource( // Query to return the list of all cars query = { carsDao.getAllCars() }, // Just for testing purpose, // a delay of 2 second is set. fetch = { delay(2000) api.getCarList() }, // Save the results in the table. // If data exists, then delete it // and then store. saveFetchResult = { CarList -> db.withTransaction { carsDao.deleteAllCars() carsDao.insertCars(CarList) } } )}", "e": 40091, "s": 39111, "text": null }, { "code": null, "e": 40117, "s": 40091, "text": "Step 6: Working on the UI" }, { "code": null, "e": 40351, "s": 40117, "text": "Remember in Step 1, we created a RecyclerView to expose the list of cars. But the work is not completed till now. We need to make an adapter as well as a ViewModel. These two classes work together to define how our data is displayed." }, { "code": null, "e": 40365, "s": 40351, "text": "CarAdapter.kt" }, { "code": null, "e": 40372, "s": 40365, "text": "Kotlin" }, { "code": "package com.gfg.carlist.features.carlist import android.view.LayoutInflaterimport android.view.ViewGroupimport androidx.recyclerview.widget.DiffUtilimport androidx.recyclerview.widget.ListAdapterimport androidx.recyclerview.widget.RecyclerViewimport com.gfg.carlist.data.CarListimport com.gfg.carlist.databinding.CarlistItemBinding class CarAdapter : ListAdapter<CarList, CarAdapter.CarViewHolder>(CarListComparator()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder { val binding = CarlistItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return CarViewHolder(binding) } override fun onBindViewHolder(holder: CarViewHolder, position: Int) { val currentItem = getItem(position) if (currentItem != null) { holder.bind(currentItem) } } // View Holder class to hold the view class CarViewHolder(private val binding: CarlistItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(carlist: CarList) { binding.apply { carName.text = carlist.make_and_model carTransmission.text = carlist.transmission carColor.text = carlist.color carDriveType.text = carlist.drive_type carFuelType.text = carlist.fuel_type carCarType.text = carlist.car_type } } } // Comparator class to check for the changes made. // If there are no changes then no need to do anything. class CarListComparator : DiffUtil.ItemCallback<CarList>() { override fun areItemsTheSame(oldItem: CarList, newItem: CarList) = oldItem.make_and_model == newItem.make_and_model override fun areContentsTheSame(oldItem: CarList, newItem: CarList) = oldItem == newItem }}", "e": 42223, "s": 40372, "text": null }, { "code": null, "e": 42243, "s": 42223, "text": "CarListViewModel.kt" }, { "code": null, "e": 42250, "s": 42243, "text": "Kotlin" }, { "code": "package com.gfg.carlist.features.carlist import androidx.lifecycle.ViewModelimport androidx.lifecycle.asLiveDataimport com.gfg.carlist.data.CarListRepositoryimport dagger.hilt.android.lifecycle.HiltViewModelimport javax.inject.Inject // Using Dagger Hilt library to // inject the data into the view model@HiltViewModelclass CarListViewModel @Inject constructor( repository: CarListRepository) : ViewModel() { val cars = repository.getCars().asLiveData()}", "e": 42713, "s": 42250, "text": null }, { "code": null, "e": 43088, "s": 42713, "text": "Finally, we have to create an activity to show the data from the ViewModel. Remember, all the business logic should be present in the ViewModel, and not in the activity. The activity should also not hold the data, because when the screen is tilted, the data gets destroyed, due to which the loading time increases. Hence the purpose of the activity is to only show the data." }, { "code": null, "e": 43103, "s": 43088, "text": "CarActivity.kt" }, { "code": null, "e": 43110, "s": 43103, "text": "Kotlin" }, { "code": "package com.gfg.carlist.features.carlist import android.os.Bundleimport androidx.activity.viewModelsimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.isVisibleimport androidx.recyclerview.widget.LinearLayoutManagerimport com.gfg.carlist.databinding.ActivityCarBindingimport com.gfg.carlist.util.Resourceimport dagger.hilt.android.AndroidEntryPoint @AndroidEntryPointclass CarActivity : AppCompatActivity() { // Helps to preserve the view // If the app is closed, then after // reopening it the app will open // in a state in which it was closed // DaggerHilt will inject the view-model for us private val viewModel: CarListViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // The bellow segment would // instantiate the activity_car layout // and will create a property for different // views inside it! val binding = ActivityCarBinding.inflate(layoutInflater) setContentView(binding.root) val carAdapter = CarAdapter() binding.apply { recyclerViewer.apply { adapter = carAdapter layoutManager = LinearLayoutManager(this@CarActivity) } viewModel.cars.observe(this@CarActivity) { result -> carAdapter.submitList(result.data) progressBar.isVisible = result is Resource.Loading<*> && result.data.isNullOrEmpty() textViewError.isVisible = result is Resource.Error<*> && result.data.isNullOrEmpty() textViewError.text = result.error?.localizedMessage } } }}", "e": 44804, "s": 43110, "text": null }, { "code": null, "e": 44918, "s": 44804, "text": "Finally, we are done with the coding part. After successfully building the project, the app would look like this:" }, { "code": null, "e": 44927, "s": 44918, "text": "Output: " }, { "code": null, "e": 44977, "s": 44927, "text": "The following video demonstrates the application." }, { "code": null, "e": 44997, "s": 44977, "text": "Output Explanation:" }, { "code": null, "e": 45022, "s": 44997, "text": "Project Link: Click Here" }, { "code": null, "e": 45030, "s": 45022, "text": "Android" }, { "code": null, "e": 45037, "s": 45030, "text": "Kotlin" }, { "code": null, "e": 45045, "s": 45037, "text": "Android" }, { "code": null, "e": 45143, "s": 45045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45181, "s": 45143, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 45220, "s": 45181, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 45270, "s": 45220, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 45312, "s": 45270, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 45363, "s": 45312, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 45376, "s": 45363, "text": "Kotlin Array" }, { "code": null, "e": 45395, "s": 45376, "text": "Android UI Layouts" }, { "code": null, "e": 45437, "s": 45395, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 45477, "s": 45437, "text": "How to Get Current Location in Android?" } ]
Python compile() Function - GeeksforGeeks
17 Sep, 2021 Python compile() function takes source code as input and returns a code object which is ready to be executed and which can later be executed by the exec() function. Syntax compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) Parameters: Source – It can be a normal string, a byte string, or an AST object Filename -This is the file from which the code was read. If it wasn’t read from a file, you can give a name yourself. Mode – Mode can be exec, eval or single. a. eval – If the source is a single expression. b. exec – It can take a block of a code that has Python statements, class and functions and so on. c. single – It is used if consists of a single interactive statement Flags (optional) and dont_inherit (optional) – Default value=0. It takes care that which future statements affect the compilation of the source. Optimize (optional) – It tells optimization level of compiler. Default value -1. Here filename is mulstring and exec mode allows the use of exec() method and the compile method converts the string to Python code object. Python3 # Python code to demonstrate working of compile(). # Creating sample sourcecode to multiply two variables# x and y.srcCode = 'x = 10\ny = 20\nmul = x * y\nprint("mul =", mul)' # Converting above source code to an executableexecCode = compile(srcCode, 'mulstring', 'exec') # Running the executable code.exec(execCode) Output: mul = 200 Python # Another Python code to demonstrate working of compile().x = 50 # Note eval is used for single statementa = compile('x', 'test', 'single')print(type(a))exec(a) Output: <class 'code'> 50 In this example, we will take main.py file with some string display methods, and then we read the file content and compile it to code the object and execute it. main.py: Python3 String = "Welcome to Geeksforgeeks"print(String) Code: Here we will read the file content as a string and then compile it to a code object. Python3 # reading code from a filef = open('main.py', 'r')temp = f.read()f.close() code = compile(temp, 'main.py', 'exec')exec(code) Output: Welcome to Geeksforgeeks Here eval is used when the source is a single expression. Python3 # Another Python code to demonstrate# working of compile() with eval.x = 50 # Note eval is used for statementa = compile('x == 50', '', 'eval')print(eval(a)) Output: True If the Python code is in string form or is an AST object, and you want to change it to a code object, then you can use compile() method.The code object returned by the compile() method can later be called using methods like: exec() and eval() which will execute dynamically generated Python code. If the Python code is in string form or is an AST object, and you want to change it to a code object, then you can use compile() method. The code object returned by the compile() method can later be called using methods like: exec() and eval() which will execute dynamically generated Python code. varshagumber28 kumar_satyam Python-Library 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 | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n17 Sep, 2021" }, { "code": null, "e": 25727, "s": 25562, "text": "Python compile() function takes source code as input and returns a code object which is ready to be executed and which can later be executed by the exec() function." }, { "code": null, "e": 25808, "s": 25727, "text": "Syntax compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)" }, { "code": null, "e": 25820, "s": 25808, "text": "Parameters:" }, { "code": null, "e": 25888, "s": 25820, "text": "Source – It can be a normal string, a byte string, or an AST object" }, { "code": null, "e": 26006, "s": 25888, "text": "Filename -This is the file from which the code was read. If it wasn’t read from a file, you can give a name yourself." }, { "code": null, "e": 26047, "s": 26006, "text": "Mode – Mode can be exec, eval or single." }, { "code": null, "e": 26095, "s": 26047, "text": "a. eval – If the source is a single expression." }, { "code": null, "e": 26194, "s": 26095, "text": "b. exec – It can take a block of a code that has Python statements, class and functions and so on." }, { "code": null, "e": 26263, "s": 26194, "text": "c. single – It is used if consists of a single interactive statement" }, { "code": null, "e": 26408, "s": 26263, "text": "Flags (optional) and dont_inherit (optional) – Default value=0. It takes care that which future statements affect the compilation of the source." }, { "code": null, "e": 26489, "s": 26408, "text": "Optimize (optional) – It tells optimization level of compiler. Default value -1." }, { "code": null, "e": 26628, "s": 26489, "text": "Here filename is mulstring and exec mode allows the use of exec() method and the compile method converts the string to Python code object." }, { "code": null, "e": 26636, "s": 26628, "text": "Python3" }, { "code": "# Python code to demonstrate working of compile(). # Creating sample sourcecode to multiply two variables# x and y.srcCode = 'x = 10\\ny = 20\\nmul = x * y\\nprint(\"mul =\", mul)' # Converting above source code to an executableexecCode = compile(srcCode, 'mulstring', 'exec') # Running the executable code.exec(execCode)", "e": 26953, "s": 26636, "text": null }, { "code": null, "e": 26961, "s": 26953, "text": "Output:" }, { "code": null, "e": 26971, "s": 26961, "text": "mul = 200" }, { "code": null, "e": 26978, "s": 26971, "text": "Python" }, { "code": "# Another Python code to demonstrate working of compile().x = 50 # Note eval is used for single statementa = compile('x', 'test', 'single')print(type(a))exec(a)", "e": 27139, "s": 26978, "text": null }, { "code": null, "e": 27147, "s": 27139, "text": "Output:" }, { "code": null, "e": 27165, "s": 27147, "text": "<class 'code'>\n50" }, { "code": null, "e": 27326, "s": 27165, "text": "In this example, we will take main.py file with some string display methods, and then we read the file content and compile it to code the object and execute it." }, { "code": null, "e": 27335, "s": 27326, "text": "main.py:" }, { "code": null, "e": 27343, "s": 27335, "text": "Python3" }, { "code": "String = \"Welcome to Geeksforgeeks\"print(String)", "e": 27392, "s": 27343, "text": null }, { "code": null, "e": 27483, "s": 27392, "text": "Code: Here we will read the file content as a string and then compile it to a code object." }, { "code": null, "e": 27491, "s": 27483, "text": "Python3" }, { "code": "# reading code from a filef = open('main.py', 'r')temp = f.read()f.close() code = compile(temp, 'main.py', 'exec')exec(code)", "e": 27616, "s": 27491, "text": null }, { "code": null, "e": 27624, "s": 27616, "text": "Output:" }, { "code": null, "e": 27649, "s": 27624, "text": "Welcome to Geeksforgeeks" }, { "code": null, "e": 27708, "s": 27649, "text": "Here eval is used when the source is a single expression. " }, { "code": null, "e": 27716, "s": 27708, "text": "Python3" }, { "code": "# Another Python code to demonstrate# working of compile() with eval.x = 50 # Note eval is used for statementa = compile('x == 50', '', 'eval')print(eval(a))", "e": 27874, "s": 27716, "text": null }, { "code": null, "e": 27882, "s": 27874, "text": "Output:" }, { "code": null, "e": 27887, "s": 27882, "text": "True" }, { "code": null, "e": 28184, "s": 27887, "text": "If the Python code is in string form or is an AST object, and you want to change it to a code object, then you can use compile() method.The code object returned by the compile() method can later be called using methods like: exec() and eval() which will execute dynamically generated Python code." }, { "code": null, "e": 28321, "s": 28184, "text": "If the Python code is in string form or is an AST object, and you want to change it to a code object, then you can use compile() method." }, { "code": null, "e": 28482, "s": 28321, "text": "The code object returned by the compile() method can later be called using methods like: exec() and eval() which will execute dynamically generated Python code." }, { "code": null, "e": 28497, "s": 28482, "text": "varshagumber28" }, { "code": null, "e": 28510, "s": 28497, "text": "kumar_satyam" }, { "code": null, "e": 28525, "s": 28510, "text": "Python-Library" }, { "code": null, "e": 28532, "s": 28525, "text": "Python" }, { "code": null, "e": 28630, "s": 28532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28662, "s": 28630, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28704, "s": 28662, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28746, "s": 28704, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28802, "s": 28746, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28829, "s": 28802, "text": "Python Classes and Objects" }, { "code": null, "e": 28868, "s": 28829, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28899, "s": 28868, "text": "Python | os.path.join() method" }, { "code": null, "e": 28928, "s": 28899, "text": "Create a directory in Python" }, { "code": null, "e": 28950, "s": 28928, "text": "Defaultdict in Python" } ]
First and Last Three Bits - GeeksforGeeks
25 Mar, 2021 Given an integer N. The task is to print the decimal equivalent of the first three bits and the last three bits in the binary representation of N.Examples: Input: 86 Output: 5 6 The binary representation of 86 is 1010110. The decimal equivalent of the first three bits (101) is 5. The decimal equivalent of the last three bits (110) is 6. Hence the output is 5 6.Input: 7 Output: 7 7 Simple Approach: Convert N into binary and store the bits in an array. Convert the first three values from the array into decimal equivalent and print it. Similarly, convert the last three values from the array into decimal equivalent and print it. 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 print the first// and last 3 bits equivalent decimal numbervoid binToDecimal3(int n){ // Converting n to binary int a[64] = { 0 }; int x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n /= 2; } // Length of the array has to be at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal int d = 0, p = 0; for (int i = x - 3; i < x; i++) d += a[i] * pow(2, p++); // Print the decimal cout << d << " "; // Convert last three bits to decimal d = 0; p = 0; for (int i = 0; i < 3; i++) d += a[i] * pow(2, p++); // Print the decimal cout << d;} // Driver codeint main(){ int n = 86; binToDecimal3(n); return 0;} //Java implementation of the approach import java.math.*;public class GFG { //Function to print the first //and last 3 bits equivalent decimal number static void binToDecimal3(int n) { // Converting n to binary int a[] = new int[64] ; int x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n /= 2; } // Length of the array has to be at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal int d = 0, p = 0; for (int j = x - 3; j < x; j++) d += a[j] * Math.pow(2, p++); // Print the decimal System.out.print( d + " "); // Convert last three bits to decimal d = 0; p = 0; for (int k = 0; k < 3; k++) d += a[k] * Math.pow(2, p++); // Print the decimal System.out.print(d); } //Driver code public static void main(String[] args) { int n = 86; binToDecimal3(n); } } # Python 3 implementation of the approachfrom math import pow # Function to print the first and last 3# bits equivalent decimal numberdef binToDecimal3(n): # Converting n to binary a = [0 for i in range(64)] x = 0 i = 0 while(n > 0): a[i] = n % 2 n = int(n / 2) i += 1 # Length of the array has to # be at least 3 if (i < 3): x = 3 else: x = i # Convert first three bits to decimal d = 0 p = 0 for i in range(x - 3, x, 1): d += a[i] * pow(2, p) p += 1 # Print the decimal print(int(d), end =" ") # Convert last three bits to decimal d = 0 p = 0 for i in range(0, 3, 1): d += a[i] * pow(2, p) p += 1 # Print the decimal print(int(d),end = " ") # Driver codeif __name__ == '__main__': n = 86 binToDecimal3(n) # This code is contributed by# Sanjit_Prasad // C# implementation of the approachusing System; class GFG{ // Function to print the first and last// 3 bits equivalent decimal numberstatic void binToDecimal3(int n){ // Converting n to binary int [] a= new int[64] ; int x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n /= 2; } // Length of the array has to be // at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal int d = 0, p = 0; for (int j = x - 3; j < x; j++) d += a[j] *(int)Math.Pow(2, p++); // Print the decimal int d1 = d; // Convert last three bits to decimal d = 0; p = 0; for (int k = 0; k < 3; k++) d += a[k] * (int)Math.Pow(2, p++); // Print the decimal Console.WriteLine(d1 + " " + d);} // Driver codestatic void Main(){ int n = 86; binToDecimal3(n);}} // This code is contributed by Mohit kumar 29 <script> // Javascript implementation of the approach // Function to print the first// and last 3 bits equivalent decimal numberfunction binToDecimal3(n){ // Converting n to binary var a = Array(64).fill(0); var x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n = parseInt(n/2); } // Length of the array has to be at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal var d = 0, p = 0; for (var i = x - 3; i < x; i++) d += a[i] * parseInt(Math.pow(2, p++)); // Print the decimal document.write(d + " "); // Convert last three bits to decimal d = 0; p = 0; for (var i = 0; i < 3; i++) d += a[i] * parseInt(Math.pow(2, p++)); // Print the decimal document.write(d);} // Driver codevar n = 86;binToDecimal3(n); </script> 5 6 Efficient Approach: We can use bitwise operators to find the required numbers. C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the first// and last 3 bits equivalent decimal// numbervoid binToDecimal3(int n){ // Number formed from last three // bits int last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first three // bits int first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result cout << first_3 << " " << last_3;} // Driver codeint main(){ int n = 86; binToDecimal3(n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to print the first// and last 3 bits equivalent// decimal numberstatic void binToDecimal3(int n){ // Number formed from last three // bits int last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first // three bits int first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result System.out.println(first_3 + " " + last_3);} // Driver codepublic static void main(String args[]){ int n = 86; binToDecimal3(n);}} // This code is contributed by// Surendra_Gangwar # Python3 implementation of the approach # Function to print the first and# last 3 bits equivalent decimal# numberdef binToDecimal3(n) : # Number formed from last three # bits last_3 = ((n & 4) + (n & 2) + (n & 1)); # Let us get first three bits in n n = n >> 3 while (n > 7) : n = n >> 1 # Number formed from first three # bits first_3 = ((n & 4) + (n & 2) + (n & 1)) # Printing result print(first_3,last_3) # Driver codeif __name__ == "__main__" : n = 86 binToDecimal3(n) # This code is contributed by Ryuga // C# implementation of the approachusing System; class GFG{ // Function to print the first// and last 3 bits equivalent// decimal numberstatic void binToDecimal3(int n){ // Number formed from last three // bits int last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first // three bits int first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result Console.WriteLine(first_3 + " " + last_3);} // Driver codestatic public void Main (){ int n = 86; binToDecimal3(n);}} // This code is contributed by akt_mit.. <?php// PHP implementation of the approach // Function to print the first and last// 3 bits equivalent decimal numberfunction binToDecimal3($n){ // Number formed from last three // bits $last_3 = (($n & 4) + ($n & 2) + ($n & 1)); // Let us get first three bits in n $n = $n >> 3; while ($n > 7) $n = $n >> 1; // Number formed from first three // bits $first_3 = (($n & 4) + ($n & 2) + ($n & 1)); // Printing result echo($first_3); echo(" "); echo($last_3);} // Driver code$n = 86;binToDecimal3($n); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript implementation of the approach // Function to print the first // and last 3 bits equivalent decimal // number function binToDecimal3(n) { // Number formed from last three // bits var last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first three // bits var first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result document.write(first_3 + " " + last_3); } // Driver code var n = 86; binToDecimal3(n); // This code is contributed by rrrtnx. </script> 5 6 Sanjit_Prasad ankthon ukasp Shivi_Aggarwal SURENDRA_GANGWAR jit_t mohit kumar 29 noob2000 rrrtnx Bit Magic C++ Programs Technical Scripter Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Find the size of Largest Subset with positive Bitwise AND Check whether bitwise AND of a number with any subset of an array is zero or not Write an Efficient Method to Check if a Number is Multiple of 3 Highest power of 2 less than or equal to given number Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 26279, "s": 26251, "text": "\n25 Mar, 2021" }, { "code": null, "e": 26437, "s": 26279, "text": "Given an integer N. The task is to print the decimal equivalent of the first three bits and the last three bits in the binary representation of N.Examples: " }, { "code": null, "e": 26667, "s": 26437, "text": "Input: 86 Output: 5 6 The binary representation of 86 is 1010110. The decimal equivalent of the first three bits (101) is 5. The decimal equivalent of the last three bits (110) is 6. Hence the output is 5 6.Input: 7 Output: 7 7 " }, { "code": null, "e": 26688, "s": 26669, "text": "Simple Approach: " }, { "code": null, "e": 26742, "s": 26688, "text": "Convert N into binary and store the bits in an array." }, { "code": null, "e": 26826, "s": 26742, "text": "Convert the first three values from the array into decimal equivalent and print it." }, { "code": null, "e": 26920, "s": 26826, "text": "Similarly, convert the last three values from the array into decimal equivalent and print it." }, { "code": null, "e": 26973, "s": 26920, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26977, "s": 26973, "text": "C++" }, { "code": null, "e": 26982, "s": 26977, "text": "Java" }, { "code": null, "e": 26990, "s": 26982, "text": "Python3" }, { "code": null, "e": 26993, "s": 26990, "text": "C#" }, { "code": null, "e": 27004, "s": 26993, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the first// and last 3 bits equivalent decimal numbervoid binToDecimal3(int n){ // Converting n to binary int a[64] = { 0 }; int x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n /= 2; } // Length of the array has to be at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal int d = 0, p = 0; for (int i = x - 3; i < x; i++) d += a[i] * pow(2, p++); // Print the decimal cout << d << \" \"; // Convert last three bits to decimal d = 0; p = 0; for (int i = 0; i < 3; i++) d += a[i] * pow(2, p++); // Print the decimal cout << d;} // Driver codeint main(){ int n = 86; binToDecimal3(n); return 0;}", "e": 27816, "s": 27004, "text": null }, { "code": "//Java implementation of the approach import java.math.*;public class GFG { //Function to print the first //and last 3 bits equivalent decimal number static void binToDecimal3(int n) { // Converting n to binary int a[] = new int[64] ; int x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n /= 2; } // Length of the array has to be at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal int d = 0, p = 0; for (int j = x - 3; j < x; j++) d += a[j] * Math.pow(2, p++); // Print the decimal System.out.print( d + \" \"); // Convert last three bits to decimal d = 0; p = 0; for (int k = 0; k < 3; k++) d += a[k] * Math.pow(2, p++); // Print the decimal System.out.print(d); } //Driver code public static void main(String[] args) { int n = 86; binToDecimal3(n); } }", "e": 28752, "s": 27816, "text": null }, { "code": "# Python 3 implementation of the approachfrom math import pow # Function to print the first and last 3# bits equivalent decimal numberdef binToDecimal3(n): # Converting n to binary a = [0 for i in range(64)] x = 0 i = 0 while(n > 0): a[i] = n % 2 n = int(n / 2) i += 1 # Length of the array has to # be at least 3 if (i < 3): x = 3 else: x = i # Convert first three bits to decimal d = 0 p = 0 for i in range(x - 3, x, 1): d += a[i] * pow(2, p) p += 1 # Print the decimal print(int(d), end =\" \") # Convert last three bits to decimal d = 0 p = 0 for i in range(0, 3, 1): d += a[i] * pow(2, p) p += 1 # Print the decimal print(int(d),end = \" \") # Driver codeif __name__ == '__main__': n = 86 binToDecimal3(n) # This code is contributed by# Sanjit_Prasad", "e": 29651, "s": 28752, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to print the first and last// 3 bits equivalent decimal numberstatic void binToDecimal3(int n){ // Converting n to binary int [] a= new int[64] ; int x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n /= 2; } // Length of the array has to be // at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal int d = 0, p = 0; for (int j = x - 3; j < x; j++) d += a[j] *(int)Math.Pow(2, p++); // Print the decimal int d1 = d; // Convert last three bits to decimal d = 0; p = 0; for (int k = 0; k < 3; k++) d += a[k] * (int)Math.Pow(2, p++); // Print the decimal Console.WriteLine(d1 + \" \" + d);} // Driver codestatic void Main(){ int n = 86; binToDecimal3(n);}} // This code is contributed by Mohit kumar 29", "e": 30561, "s": 29651, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print the first// and last 3 bits equivalent decimal numberfunction binToDecimal3(n){ // Converting n to binary var a = Array(64).fill(0); var x = 0, i; for (i = 0; n > 0; i++) { a[i] = n % 2; n = parseInt(n/2); } // Length of the array has to be at least 3 x = (i < 3) ? 3 : i; // Convert first three bits to decimal var d = 0, p = 0; for (var i = x - 3; i < x; i++) d += a[i] * parseInt(Math.pow(2, p++)); // Print the decimal document.write(d + \" \"); // Convert last three bits to decimal d = 0; p = 0; for (var i = 0; i < 3; i++) d += a[i] * parseInt(Math.pow(2, p++)); // Print the decimal document.write(d);} // Driver codevar n = 86;binToDecimal3(n); </script>", "e": 31389, "s": 30561, "text": null }, { "code": null, "e": 31393, "s": 31389, "text": "5 6" }, { "code": null, "e": 31476, "s": 31395, "text": "Efficient Approach: We can use bitwise operators to find the required numbers. " }, { "code": null, "e": 31480, "s": 31476, "text": "C++" }, { "code": null, "e": 31485, "s": 31480, "text": "Java" }, { "code": null, "e": 31493, "s": 31485, "text": "Python3" }, { "code": null, "e": 31496, "s": 31493, "text": "C#" }, { "code": null, "e": 31500, "s": 31496, "text": "PHP" }, { "code": null, "e": 31511, "s": 31500, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the first// and last 3 bits equivalent decimal// numbervoid binToDecimal3(int n){ // Number formed from last three // bits int last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first three // bits int first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result cout << first_3 << \" \" << last_3;} // Driver codeint main(){ int n = 86; binToDecimal3(n); return 0;}", "e": 32115, "s": 31511, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to print the first// and last 3 bits equivalent// decimal numberstatic void binToDecimal3(int n){ // Number formed from last three // bits int last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first // three bits int first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result System.out.println(first_3 + \" \" + last_3);} // Driver codepublic static void main(String args[]){ int n = 86; binToDecimal3(n);}} // This code is contributed by// Surendra_Gangwar", "e": 32824, "s": 32115, "text": null }, { "code": "# Python3 implementation of the approach # Function to print the first and# last 3 bits equivalent decimal# numberdef binToDecimal3(n) : # Number formed from last three # bits last_3 = ((n & 4) + (n & 2) + (n & 1)); # Let us get first three bits in n n = n >> 3 while (n > 7) : n = n >> 1 # Number formed from first three # bits first_3 = ((n & 4) + (n & 2) + (n & 1)) # Printing result print(first_3,last_3) # Driver codeif __name__ == \"__main__\" : n = 86 binToDecimal3(n) # This code is contributed by Ryuga", "e": 33389, "s": 32824, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to print the first// and last 3 bits equivalent// decimal numberstatic void binToDecimal3(int n){ // Number formed from last three // bits int last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first // three bits int first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result Console.WriteLine(first_3 + \" \" + last_3);} // Driver codestatic public void Main (){ int n = 86; binToDecimal3(n);}} // This code is contributed by akt_mit..", "e": 34067, "s": 33389, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to print the first and last// 3 bits equivalent decimal numberfunction binToDecimal3($n){ // Number formed from last three // bits $last_3 = (($n & 4) + ($n & 2) + ($n & 1)); // Let us get first three bits in n $n = $n >> 3; while ($n > 7) $n = $n >> 1; // Number formed from first three // bits $first_3 = (($n & 4) + ($n & 2) + ($n & 1)); // Printing result echo($first_3); echo(\" \"); echo($last_3);} // Driver code$n = 86;binToDecimal3($n); // This code is contributed// by Shivi_Aggarwal?>", "e": 34665, "s": 34067, "text": null }, { "code": " <script> // Javascript implementation of the approach // Function to print the first // and last 3 bits equivalent decimal // number function binToDecimal3(n) { // Number formed from last three // bits var last_3 = ((n & 4) + (n & 2) + (n & 1)); // Let us get first three bits in n n = n >> 3; while (n > 7) n = n >> 1; // Number formed from first three // bits var first_3 = ((n & 4) + (n & 2) + (n & 1)); // Printing result document.write(first_3 + \" \" + last_3); } // Driver code var n = 86; binToDecimal3(n); // This code is contributed by rrrtnx. </script>", "e": 35333, "s": 34665, "text": null }, { "code": null, "e": 35337, "s": 35333, "text": "5 6" }, { "code": null, "e": 35353, "s": 35339, "text": "Sanjit_Prasad" }, { "code": null, "e": 35361, "s": 35353, "text": "ankthon" }, { "code": null, "e": 35367, "s": 35361, "text": "ukasp" }, { "code": null, "e": 35382, "s": 35367, "text": "Shivi_Aggarwal" }, { "code": null, "e": 35399, "s": 35382, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 35405, "s": 35399, "text": "jit_t" }, { "code": null, "e": 35420, "s": 35405, "text": "mohit kumar 29" }, { "code": null, "e": 35429, "s": 35420, "text": "noob2000" }, { "code": null, "e": 35436, "s": 35429, "text": "rrrtnx" }, { "code": null, "e": 35446, "s": 35436, "text": "Bit Magic" }, { "code": null, "e": 35459, "s": 35446, "text": "C++ Programs" }, { "code": null, "e": 35478, "s": 35459, "text": "Technical Scripter" }, { "code": null, "e": 35488, "s": 35478, "text": "Bit Magic" }, { "code": null, "e": 35586, "s": 35488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35637, "s": 35586, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 35695, "s": 35637, "text": "Find the size of Largest Subset with positive Bitwise AND" }, { "code": null, "e": 35776, "s": 35695, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 35840, "s": 35776, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 35894, "s": 35840, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 35929, "s": 35894, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 35973, "s": 35929, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 35999, "s": 35973, "text": "C++ Program for QuickSort" }, { "code": null, "e": 36058, "s": 35999, "text": "How to return multiple values from a function in C or C++?" } ]
Introduction to Deep Learning - GeeksforGeeks
15 Apr, 2019 What is Deep Learning?Deep learning is a branch of machine learning which is completely based on artificial neural networks, as neural network is going to mimic the human brain so deep learning is also a kind of mimic of human brain. In deep learning, we don’t need to explicitly program everything. The concept of deep learning is not new. It has been around for a couple of years now. It’s on hype nowadays because earlier we did not have that much processing power and a lot of data. As in the last 20 years, the processing power increases exponentially, deep learning and machine learning came in the picture.A formal definition of deep learning is- neurons Deep learning is a particular kind of machine learning that achieves great power and flexibility by learning to represent the world as a nested hierarchy of concepts, with each concept defined in relation to simpler concepts, and more abstract representations computed in terms of less abstract ones. In human brain approximately 100 billion neurons all together this is a picture of an individual neuron and each neuron is connected through thousand of their neighbours.The question here is how do we recreate these neurons in a computer. So, we create an artificial structure called an artificial neural net where we have nodes or neurons. We have some neurons for input value and some for output value and in between, there may be lots of neurons interconnected in the hidden layer. Architectures : Deep Neural Network – It is a neural network with a certain level of complexity (having multiple hidden layers in between input and output layers). They are capable of modeling and processing non-linear relationships.Deep Belief Network(DBN) – It is a class of Deep Neural Network. It is multi-layer belief networks.Steps for performing DBN :a. Learn a layer of features from visible units using Contrastive Divergence algorithm.b. Treat activations of previously trained features as visible units and then learn features of features.c. Finally, the whole DBN is trained when the learning for the final hidden layer is achieved.Recurrent (perform same task for every element of a sequence) Neural Network – Allows for parallel and sequential computation. Similar to the human brain (large feedback network of connected neurons). They are able to remember important things about the input they received and hence enables them to be more precise. Deep Neural Network – It is a neural network with a certain level of complexity (having multiple hidden layers in between input and output layers). They are capable of modeling and processing non-linear relationships. Deep Belief Network(DBN) – It is a class of Deep Neural Network. It is multi-layer belief networks.Steps for performing DBN :a. Learn a layer of features from visible units using Contrastive Divergence algorithm.b. Treat activations of previously trained features as visible units and then learn features of features.c. Finally, the whole DBN is trained when the learning for the final hidden layer is achieved. Recurrent (perform same task for every element of a sequence) Neural Network – Allows for parallel and sequential computation. Similar to the human brain (large feedback network of connected neurons). They are able to remember important things about the input they received and hence enables them to be more precise. Difference between Machine Learning and Deep Learning : Working :First, we need to identify the actual problem in order to get the right solution and it should be understood, the feasibility of the Deep Learning should also be checked (whether it should fit Deep Learning or not). Second, we need to identify the relevant data which should correspond to the actual problem and should be prepared accordingly. Third, Choose the Deep Learning Algorithm appropriately. Fourth, Algorithm should be used while training the dataset. Fifth, Final testing should be done on the dataset. Tools used :Anaconda, Jupyter, Pycharm, etc. Languages used :R, Python, Matlab, CPP, Java, Julia, Lisp, Java Script, etc. Real Life Examples : How to recognize square from other shapes? ...a) Check the four lines! ...b) Is it a closed figure? ...c) Does the sides are perpendicular from each other? ...d) Does all sides are equal? So, Deep Learning is a complex task of identifying the shape and broken down into simpler tasks at a larger side. Recognizing an Animal! (Is it a Cat or Dog?) Defining facial features which are important for classification and system will then identify this automatically. (Whereas Machine Learning will manually give out those features for classification) How to recognize square from other shapes? ...a) Check the four lines! ...b) Is it a closed figure? ...c) Does the sides are perpendicular from each other? ...d) Does all sides are equal? So, Deep Learning is a complex task of identifying the shape and broken down into simpler tasks at a larger side. Recognizing an Animal! (Is it a Cat or Dog?) Defining facial features which are important for classification and system will then identify this automatically. (Whereas Machine Learning will manually give out those features for classification) How to recognize square from other shapes? ...a) Check the four lines! ...b) Is it a closed figure? ...c) Does the sides are perpendicular from each other? ...d) Does all sides are equal? So, Deep Learning is a complex task of identifying the shape and broken down into simpler tasks at a larger side. Recognizing an Animal! (Is it a Cat or Dog?) Defining facial features which are important for classification and system will then identify this automatically. (Whereas Machine Learning will manually give out those features for classification) Limitations : Learning through observations only.The issue of biases. Learning through observations only. The issue of biases. Advantages : Best in-class performance on problems.Reduces need for feature engineering.Eliminates unnecessary costs.Identifies defects easily that are difficult to detect. Best in-class performance on problems. Reduces need for feature engineering. Eliminates unnecessary costs. Identifies defects easily that are difficult to detect. Disadvantages : Large amount of data required.Computationally expensive to train.No strong theoretical foundation. Large amount of data required. Computationally expensive to train. No strong theoretical foundation. Applications : Automatic Text Generation – Corpus of text is learned and from this model new text is generated, word-by-word or character-by-character.Then this model is capable of learning how to spell, punctuate, form sentences, or it may even capture the style.Healthcare – Helps in diagnosing various diseases and treating it.Automatic Machine Translation – Certain words, sentences or phrases in one language is transformed into another language (Deep Learning is achieving top results in the areas of text, images).Image Recognition – Recognizes and identifies peoples and objects in images as well as to understand content and context. This area is already being used in Gaming, Retail, Tourism, etc.Predicting Earthquakes – Teaches a computer to perform viscoelastic computations which are used in predicting earthquakes. Automatic Text Generation – Corpus of text is learned and from this model new text is generated, word-by-word or character-by-character.Then this model is capable of learning how to spell, punctuate, form sentences, or it may even capture the style. Healthcare – Helps in diagnosing various diseases and treating it. Automatic Machine Translation – Certain words, sentences or phrases in one language is transformed into another language (Deep Learning is achieving top results in the areas of text, images). Image Recognition – Recognizes and identifies peoples and objects in images as well as to understand content and context. This area is already being used in Gaming, Retail, Tourism, etc. Predicting Earthquakes – Teaches a computer to perform viscoelastic computations which are used in predicting earthquakes. Co-author of this article : ujjwal sharma 1 bhargav kanakiya ayushgangwar Machine Learning Misc Misc Misc Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Activation functions in Neural Networks Introduction to Recurrent Neural Network Support Vector Machine Algorithm Python | Decision tree implementation Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
[ { "code": null, "e": 25993, "s": 25965, "text": "\n15 Apr, 2019" }, { "code": null, "e": 26655, "s": 25993, "text": "What is Deep Learning?Deep learning is a branch of machine learning which is completely based on artificial neural networks, as neural network is going to mimic the human brain so deep learning is also a kind of mimic of human brain. In deep learning, we don’t need to explicitly program everything. The concept of deep learning is not new. It has been around for a couple of years now. It’s on hype nowadays because earlier we did not have that much processing power and a lot of data. As in the last 20 years, the processing power increases exponentially, deep learning and machine learning came in the picture.A formal definition of deep learning is- neurons" }, { "code": null, "e": 26956, "s": 26655, "text": "Deep learning is a particular kind of machine learning that achieves great power and flexibility by learning to represent the world as a nested hierarchy of concepts, with each concept defined in relation to simpler concepts, and more abstract representations computed in terms of less abstract ones." }, { "code": null, "e": 27441, "s": 26956, "text": "In human brain approximately 100 billion neurons all together this is a picture of an individual neuron and each neuron is connected through thousand of their neighbours.The question here is how do we recreate these neurons in a computer. So, we create an artificial structure called an artificial neural net where we have nodes or neurons. We have some neurons for input value and some for output value and in between, there may be lots of neurons interconnected in the hidden layer." }, { "code": null, "e": 27457, "s": 27441, "text": "Architectures :" }, { "code": null, "e": 28402, "s": 27457, "text": "Deep Neural Network – It is a neural network with a certain level of complexity (having multiple hidden layers in between input and output layers). They are capable of modeling and processing non-linear relationships.Deep Belief Network(DBN) – It is a class of Deep Neural Network. It is multi-layer belief networks.Steps for performing DBN :a. Learn a layer of features from visible units using Contrastive Divergence algorithm.b. Treat activations of previously trained features as visible units and then learn features of features.c. Finally, the whole DBN is trained when the learning for the final hidden layer is achieved.Recurrent (perform same task for every element of a sequence) Neural Network – Allows for parallel and sequential computation. Similar to the human brain (large feedback network of connected neurons). They are able to remember important things about the input they received and hence enables them to be more precise." }, { "code": null, "e": 28620, "s": 28402, "text": "Deep Neural Network – It is a neural network with a certain level of complexity (having multiple hidden layers in between input and output layers). They are capable of modeling and processing non-linear relationships." }, { "code": null, "e": 29032, "s": 28620, "text": "Deep Belief Network(DBN) – It is a class of Deep Neural Network. It is multi-layer belief networks.Steps for performing DBN :a. Learn a layer of features from visible units using Contrastive Divergence algorithm.b. Treat activations of previously trained features as visible units and then learn features of features.c. Finally, the whole DBN is trained when the learning for the final hidden layer is achieved." }, { "code": null, "e": 29349, "s": 29032, "text": "Recurrent (perform same task for every element of a sequence) Neural Network – Allows for parallel and sequential computation. Similar to the human brain (large feedback network of connected neurons). They are able to remember important things about the input they received and hence enables them to be more precise." }, { "code": null, "e": 29405, "s": 29349, "text": "Difference between Machine Learning and Deep Learning :" }, { "code": null, "e": 29928, "s": 29405, "text": "Working :First, we need to identify the actual problem in order to get the right solution and it should be understood, the feasibility of the Deep Learning should also be checked (whether it should fit Deep Learning or not). Second, we need to identify the relevant data which should correspond to the actual problem and should be prepared accordingly. Third, Choose the Deep Learning Algorithm appropriately. Fourth, Algorithm should be used while training the dataset. Fifth, Final testing should be done on the dataset." }, { "code": null, "e": 29973, "s": 29928, "text": "Tools used :Anaconda, Jupyter, Pycharm, etc." }, { "code": null, "e": 30050, "s": 29973, "text": "Languages used :R, Python, Matlab, CPP, Java, Julia, Lisp, Java Script, etc." }, { "code": null, "e": 30071, "s": 30050, "text": "Real Life Examples :" }, { "code": null, "e": 30622, "s": 30071, "text": " How to recognize square from other shapes?\n...a) Check the four lines!\n...b) Is it a closed figure?\n...c) Does the sides are perpendicular from each other?\n...d) Does all sides are equal?\n\nSo, Deep Learning is a complex task of identifying the shape and broken down into simpler \ntasks at a larger side.\n\n Recognizing an Animal! (Is it a Cat or Dog?)\nDefining facial features which are important for classification and system will then identify this automatically.\n(Whereas Machine Learning will manually give out those features for classification)\n" }, { "code": null, "e": 31172, "s": 30622, "text": " How to recognize square from other shapes?\n...a) Check the four lines!\n...b) Is it a closed figure?\n...c) Does the sides are perpendicular from each other?\n...d) Does all sides are equal?\n\nSo, Deep Learning is a complex task of identifying the shape and broken down into simpler \ntasks at a larger side.\n\n Recognizing an Animal! (Is it a Cat or Dog?)\nDefining facial features which are important for classification and system will then identify this automatically.\n(Whereas Machine Learning will manually give out those features for classification)" }, { "code": null, "e": 31479, "s": 31172, "text": " How to recognize square from other shapes?\n...a) Check the four lines!\n...b) Is it a closed figure?\n...c) Does the sides are perpendicular from each other?\n...d) Does all sides are equal?\n\nSo, Deep Learning is a complex task of identifying the shape and broken down into simpler \ntasks at a larger side.\n\n" }, { "code": null, "e": 31723, "s": 31479, "text": " Recognizing an Animal! (Is it a Cat or Dog?)\nDefining facial features which are important for classification and system will then identify this automatically.\n(Whereas Machine Learning will manually give out those features for classification)" }, { "code": null, "e": 31737, "s": 31723, "text": "Limitations :" }, { "code": null, "e": 31793, "s": 31737, "text": "Learning through observations only.The issue of biases." }, { "code": null, "e": 31829, "s": 31793, "text": "Learning through observations only." }, { "code": null, "e": 31850, "s": 31829, "text": "The issue of biases." }, { "code": null, "e": 31863, "s": 31850, "text": "Advantages :" }, { "code": null, "e": 32023, "s": 31863, "text": "Best in-class performance on problems.Reduces need for feature engineering.Eliminates unnecessary costs.Identifies defects easily that are difficult to detect." }, { "code": null, "e": 32062, "s": 32023, "text": "Best in-class performance on problems." }, { "code": null, "e": 32100, "s": 32062, "text": "Reduces need for feature engineering." }, { "code": null, "e": 32130, "s": 32100, "text": "Eliminates unnecessary costs." }, { "code": null, "e": 32186, "s": 32130, "text": "Identifies defects easily that are difficult to detect." }, { "code": null, "e": 32202, "s": 32186, "text": "Disadvantages :" }, { "code": null, "e": 32301, "s": 32202, "text": "Large amount of data required.Computationally expensive to train.No strong theoretical foundation." }, { "code": null, "e": 32332, "s": 32301, "text": "Large amount of data required." }, { "code": null, "e": 32368, "s": 32332, "text": "Computationally expensive to train." }, { "code": null, "e": 32402, "s": 32368, "text": "No strong theoretical foundation." }, { "code": null, "e": 32417, "s": 32402, "text": "Applications :" }, { "code": null, "e": 33232, "s": 32417, "text": "Automatic Text Generation – Corpus of text is learned and from this model new text is generated, word-by-word or character-by-character.Then this model is capable of learning how to spell, punctuate, form sentences, or it may even capture the style.Healthcare – Helps in diagnosing various diseases and treating it.Automatic Machine Translation – Certain words, sentences or phrases in one language is transformed into another language (Deep Learning is achieving top results in the areas of text, images).Image Recognition – Recognizes and identifies peoples and objects in images as well as to understand content and context. This area is already being used in Gaming, Retail, Tourism, etc.Predicting Earthquakes – Teaches a computer to perform viscoelastic computations which are used in predicting earthquakes." }, { "code": null, "e": 33482, "s": 33232, "text": "Automatic Text Generation – Corpus of text is learned and from this model new text is generated, word-by-word or character-by-character.Then this model is capable of learning how to spell, punctuate, form sentences, or it may even capture the style." }, { "code": null, "e": 33549, "s": 33482, "text": "Healthcare – Helps in diagnosing various diseases and treating it." }, { "code": null, "e": 33741, "s": 33549, "text": "Automatic Machine Translation – Certain words, sentences or phrases in one language is transformed into another language (Deep Learning is achieving top results in the areas of text, images)." }, { "code": null, "e": 33928, "s": 33741, "text": "Image Recognition – Recognizes and identifies peoples and objects in images as well as to understand content and context. This area is already being used in Gaming, Retail, Tourism, etc." }, { "code": null, "e": 34051, "s": 33928, "text": "Predicting Earthquakes – Teaches a computer to perform viscoelastic computations which are used in predicting earthquakes." }, { "code": null, "e": 34095, "s": 34051, "text": "Co-author of this article : ujjwal sharma 1" }, { "code": null, "e": 34112, "s": 34095, "text": "bhargav kanakiya" }, { "code": null, "e": 34125, "s": 34112, "text": "ayushgangwar" }, { "code": null, "e": 34142, "s": 34125, "text": "Machine Learning" }, { "code": null, "e": 34147, "s": 34142, "text": "Misc" }, { "code": null, "e": 34152, "s": 34147, "text": "Misc" }, { "code": null, "e": 34157, "s": 34152, "text": "Misc" }, { "code": null, "e": 34174, "s": 34157, "text": "Machine Learning" }, { "code": null, "e": 34272, "s": 34174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34295, "s": 34272, "text": "ML | Linear Regression" }, { "code": null, "e": 34335, "s": 34295, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 34376, "s": 34335, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 34409, "s": 34376, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 34447, "s": 34409, "text": "Python | Decision tree implementation" }, { "code": null, "e": 34488, "s": 34447, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 34542, "s": 34488, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 34603, "s": 34542, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 34637, "s": 34603, "text": "How to write Regular Expressions?" } ]
Next Number with distinct digits - GeeksforGeeks
06 Apr, 2022 Given an integer N, the task is to find the next number with distinct digits in it. Examples: Input: N = 20 Output: 21 The next integer with all distinct digits after 20 is 21. Input: N = 2019 Output: 2031 Approach: Count the total number of digits in the number N using the approach discussed in this article.Count the total number of distinct digits in N.If the count of a total number of digits and the number of distinct digits in N is equal, then return the number, otherwise, increment the number by one and repeat the previous steps. Count the total number of digits in the number N using the approach discussed in this article. Count the total number of distinct digits in N. If the count of a total number of digits and the number of distinct digits in N is equal, then return the number, otherwise, increment the number by one and repeat the previous steps. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find next consecutive// Number with all distinct digits#include <bits/stdc++.h>using namespace std; // Function to count distinct// digits in a numberint countDistinct(int n){ // To count the occurrence of digits // in number from 0 to 9 int arr[10] = { 0 }; int count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n) { int r = n % 10; arr[r] = 1; n /= 10; } // Traverse the array arr and count the // distinct digits in the array for (int i = 0; i < 10; i++) { if (arr[i]) count++; } return count;} // Function to return the total number// of digits in the numberint countDigit(int n){ int c = 0; // Iterate over the digits of the number while (n) { int r = n % 10; c++; n /= 10; } return c;} // Function to return the next// number with distinct digitsint nextNumberDistinctDigit(int n){ while (n < INT_MAX) { // Count the distinct digits in N + 1 int distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 int total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1;} // Driver codeint main(){ int n = 2019; cout << nextNumberDistinctDigit(n); return 0;} // Java program to find next consecutive// Number with all distinct digitsclass GFG{ final static int INT_MAX = Integer.MAX_VALUE ; // Function to count distinct // digits in a number static int countDistinct(int n) { // To count the occurrence of digits // in number from 0 to 9 int arr[] = new int[10]; int count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n != 0) { int r = n % 10; arr[r] = 1; n /= 10; } // Traverse the array arr and count the // distinct digits in the array for (int i = 0; i < 10; i++) { if (arr[i] != 0) count++; } return count; } // Function to return the total number // of digits in the number static int countDigit(int n) { int c = 0; // Iterate over the digits of the number while (n != 0) { int r = n % 10; c++; n /= 10; } return c; } // Function to return the next // number with distinct digits static int nextNumberDistinctDigit(int n) { while (n < INT_MAX) { // Count the distinct digits in N + 1 int distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 int total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1; } // Driver code public static void main (String[] args) { int n = 2019; System.out.println(nextNumberDistinctDigit(n)); }} // This code is contributed by AnkitRai01 # Python3 program to find next consecutive# Number with all distinct digitsimport sys INT_MAX = sys.maxsize; # Function to count distinct# digits in a numberdef countDistinct(n): # To count the occurrence of digits # in number from 0 to 9 arr = [0] * 10; count = 0; # Iterate over the digits of the number # Flag those digits as found in the array while (n != 0): r = int(n % 10); arr[r] = 1; n //= 10; # Traverse the array arr and count the # distinct digits in the array for i in range(10): if (arr[i] != 0): count += 1; return count; # Function to return the total number# of digits in the numberdef countDigit(n): c = 0; # Iterate over the digits of the number while (n != 0): r = n % 10; c+=1; n //= 10; return c; # Function to return the next# number with distinct digitsdef nextNumberDistinctDigit(n): while (n < INT_MAX): # Count the distinct digits in N + 1 distinct_digits = countDistinct(n + 1); # Count the total number of digits in N + 1 total_digits = countDigit(n + 1); if (distinct_digits == total_digits): # Return the next consecutive number return n + 1; else: # Increment Number by 1 n += 1; return -1; # Driver codeif __name__ == '__main__': n = 2019; print(nextNumberDistinctDigit(n)); # This code is contributed by PrinciRaj1992 // C# program to find next consecutive// Number with all distinct digitsusing System; class GFG{ readonly static int INT_MAX = int.MaxValue ; // Function to count distinct // digits in a number static int countDistinct(int n) { // To count the occurrence of digits // in number from 0 to 9 int []arr = new int[10]; int count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n != 0) { int r = n % 10; arr[r] = 1; n /= 10; } // Traverse the array arr and count the // distinct digits in the array for (int i = 0; i < 10; i++) { if (arr[i] != 0) count++; } return count; } // Function to return the total number // of digits in the number static int countDigit(int n) { int c = 0; // Iterate over the digits of the number while (n != 0) { int r = n % 10; c++; n /= 10; } return c; } // Function to return the next // number with distinct digits static int nextNumberDistinctDigit(int n) { while (n < INT_MAX) { // Count the distinct digits in N + 1 int distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 int total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1; } // Driver code public static void Main(String[] args) { int n = 2019; Console.WriteLine(nextNumberDistinctDigit(n)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find next consecutive // Number with all distinct digits let INT_MAX = Number.MAX_VALUE; // Function to count distinct // digits in a number function countDistinct(n) { // To count the occurrence of digits // in number from 0 to 9 let arr = new Array(10); arr.fill(0); let count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n != 0) { let r = n % 10; arr[r] = 1; n = parseInt(n / 10, 10); } // Traverse the array arr and count the // distinct digits in the array for (let i = 0; i < 10; i++) { if (arr[i] != 0) count++; } return count; } // Function to return the total number // of digits in the number function countDigit(n) { let c = 0; // Iterate over the digits of the number while (n != 0) { let r = n % 10; c++; n = parseInt(n / 10, 10); } return c; } // Function to return the next // number with distinct digits function nextNumberDistinctDigit(n) { while (n < INT_MAX) { // Count the distinct digits in N + 1 let distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 let total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1; } let n = 2019; document.write(nextNumberDistinctDigit(n)); </script> 2031 Another Approach: Instead of calculating the number of digits each time, we can use set STL 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 the newly created set. For example, let us consider the number 1987, then we can convert the number into a string, C++ int n;cin>>n;string s = to_string(n); After that, initialize a set with the contents of string s. C++ set<int> uniDigits(s.begin(), s.end()); Then we can compare the size of string s and the newly created set uniDigits. Here is the total code C++ Python3 Javascript // CPP program for the above program#include <bits/stdc++.h>using namespace std; // Function to find next number// with digit distinctvoid nextNumberDistinctDigit(int n){ // Iterate from n + 1 to inf for (int i = n + 1;; 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; break; } }} // Driver Codeint main(){ int n = 2019; // input the no. // Function Call nextNumberDistinctDigit(n); return 0;} # Python program for the above program # Function to find next number# with digit distinctimport sys def nextNumberDistinctDigit(n): # Iterate from n + 1 to inf for i in range(n + 1,sys.maxsize): # Convert the no. to # string s = str(i) # Convert string to set using stl uniDigits = set([char for char in s]) # Output if condition satisfies if (len(s) == len(uniDigits)): print(i) break # Driver Coden = 2019 # input the no. # Function CallnextNumberDistinctDigit(n) # This code is contributed by shinjanpatra <script> // JavaScript program for the above program // Function to find next number// with digit distinctfunction nextNumberDistinctDigit(n){ // Iterate from n + 1 to inf for (let i = n + 1;; i++) { // Convert the no. to // string let s = i.toString(); // Convert string to set using stl let uniDigits = new Set(s.split('')); // Output if condition satisfies if (s.length == uniDigits.size) { document.write(i); break; } }} // Driver Code let n = 2019; // input the no. // Function CallnextNumberDistinctDigit(n); // This code is contributed by shinjanpatra </script> 2031 ankthon princiraj1992 svrrrsvr decode2207 shinjanpatra number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 26047, "s": 26019, "text": "\n06 Apr, 2022" }, { "code": null, "e": 26131, "s": 26047, "text": "Given an integer N, the task is to find the next number with distinct digits in it." }, { "code": null, "e": 26142, "s": 26131, "text": "Examples: " }, { "code": null, "e": 26225, "s": 26142, "text": "Input: N = 20 Output: 21 The next integer with all distinct digits after 20 is 21." }, { "code": null, "e": 26255, "s": 26225, "text": "Input: N = 2019 Output: 2031 " }, { "code": null, "e": 26267, "s": 26255, "text": "Approach: " }, { "code": null, "e": 26592, "s": 26267, "text": "Count the total number of digits in the number N using the approach discussed in this article.Count the total number of distinct digits in N.If the count of a total number of digits and the number of distinct digits in N is equal, then return the number, otherwise, increment the number by one and repeat the previous steps." }, { "code": null, "e": 26687, "s": 26592, "text": "Count the total number of digits in the number N using the approach discussed in this article." }, { "code": null, "e": 26735, "s": 26687, "text": "Count the total number of distinct digits in N." }, { "code": null, "e": 26919, "s": 26735, "text": "If the count of a total number of digits and the number of distinct digits in N is equal, then return the number, otherwise, increment the number by one and repeat the previous steps." }, { "code": null, "e": 26972, "s": 26919, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26976, "s": 26972, "text": "C++" }, { "code": null, "e": 26981, "s": 26976, "text": "Java" }, { "code": null, "e": 26989, "s": 26981, "text": "Python3" }, { "code": null, "e": 26992, "s": 26989, "text": "C#" }, { "code": null, "e": 27003, "s": 26992, "text": "Javascript" }, { "code": "// C++ program to find next consecutive// Number with all distinct digits#include <bits/stdc++.h>using namespace std; // Function to count distinct// digits in a numberint countDistinct(int n){ // To count the occurrence of digits // in number from 0 to 9 int arr[10] = { 0 }; int count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n) { int r = n % 10; arr[r] = 1; n /= 10; } // Traverse the array arr and count the // distinct digits in the array for (int i = 0; i < 10; i++) { if (arr[i]) count++; } return count;} // Function to return the total number// of digits in the numberint countDigit(int n){ int c = 0; // Iterate over the digits of the number while (n) { int r = n % 10; c++; n /= 10; } return c;} // Function to return the next// number with distinct digitsint nextNumberDistinctDigit(int n){ while (n < INT_MAX) { // Count the distinct digits in N + 1 int distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 int total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1;} // Driver codeint main(){ int n = 2019; cout << nextNumberDistinctDigit(n); return 0;}", "e": 28512, "s": 27003, "text": null }, { "code": "// Java program to find next consecutive// Number with all distinct digitsclass GFG{ final static int INT_MAX = Integer.MAX_VALUE ; // Function to count distinct // digits in a number static int countDistinct(int n) { // To count the occurrence of digits // in number from 0 to 9 int arr[] = new int[10]; int count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n != 0) { int r = n % 10; arr[r] = 1; n /= 10; } // Traverse the array arr and count the // distinct digits in the array for (int i = 0; i < 10; i++) { if (arr[i] != 0) count++; } return count; } // Function to return the total number // of digits in the number static int countDigit(int n) { int c = 0; // Iterate over the digits of the number while (n != 0) { int r = n % 10; c++; n /= 10; } return c; } // Function to return the next // number with distinct digits static int nextNumberDistinctDigit(int n) { while (n < INT_MAX) { // Count the distinct digits in N + 1 int distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 int total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1; } // Driver code public static void main (String[] args) { int n = 2019; System.out.println(nextNumberDistinctDigit(n)); }} // This code is contributed by AnkitRai01", "e": 30510, "s": 28512, "text": null }, { "code": "# Python3 program to find next consecutive# Number with all distinct digitsimport sys INT_MAX = sys.maxsize; # Function to count distinct# digits in a numberdef countDistinct(n): # To count the occurrence of digits # in number from 0 to 9 arr = [0] * 10; count = 0; # Iterate over the digits of the number # Flag those digits as found in the array while (n != 0): r = int(n % 10); arr[r] = 1; n //= 10; # Traverse the array arr and count the # distinct digits in the array for i in range(10): if (arr[i] != 0): count += 1; return count; # Function to return the total number# of digits in the numberdef countDigit(n): c = 0; # Iterate over the digits of the number while (n != 0): r = n % 10; c+=1; n //= 10; return c; # Function to return the next# number with distinct digitsdef nextNumberDistinctDigit(n): while (n < INT_MAX): # Count the distinct digits in N + 1 distinct_digits = countDistinct(n + 1); # Count the total number of digits in N + 1 total_digits = countDigit(n + 1); if (distinct_digits == total_digits): # Return the next consecutive number return n + 1; else: # Increment Number by 1 n += 1; return -1; # Driver codeif __name__ == '__main__': n = 2019; print(nextNumberDistinctDigit(n)); # This code is contributed by PrinciRaj1992", "e": 31998, "s": 30510, "text": null }, { "code": "// C# program to find next consecutive// Number with all distinct digitsusing System; class GFG{ readonly static int INT_MAX = int.MaxValue ; // Function to count distinct // digits in a number static int countDistinct(int n) { // To count the occurrence of digits // in number from 0 to 9 int []arr = new int[10]; int count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n != 0) { int r = n % 10; arr[r] = 1; n /= 10; } // Traverse the array arr and count the // distinct digits in the array for (int i = 0; i < 10; i++) { if (arr[i] != 0) count++; } return count; } // Function to return the total number // of digits in the number static int countDigit(int n) { int c = 0; // Iterate over the digits of the number while (n != 0) { int r = n % 10; c++; n /= 10; } return c; } // Function to return the next // number with distinct digits static int nextNumberDistinctDigit(int n) { while (n < INT_MAX) { // Count the distinct digits in N + 1 int distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 int total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1; } // Driver code public static void Main(String[] args) { int n = 2019; Console.WriteLine(nextNumberDistinctDigit(n)); }} // This code is contributed by PrinciRaj1992", "e": 34007, "s": 31998, "text": null }, { "code": "<script> // Javascript program to find next consecutive // Number with all distinct digits let INT_MAX = Number.MAX_VALUE; // Function to count distinct // digits in a number function countDistinct(n) { // To count the occurrence of digits // in number from 0 to 9 let arr = new Array(10); arr.fill(0); let count = 0; // Iterate over the digits of the number // Flag those digits as found in the array while (n != 0) { let r = n % 10; arr[r] = 1; n = parseInt(n / 10, 10); } // Traverse the array arr and count the // distinct digits in the array for (let i = 0; i < 10; i++) { if (arr[i] != 0) count++; } return count; } // Function to return the total number // of digits in the number function countDigit(n) { let c = 0; // Iterate over the digits of the number while (n != 0) { let r = n % 10; c++; n = parseInt(n / 10, 10); } return c; } // Function to return the next // number with distinct digits function nextNumberDistinctDigit(n) { while (n < INT_MAX) { // Count the distinct digits in N + 1 let distinct_digits = countDistinct(n + 1); // Count the total number of digits in N + 1 let total_digits = countDigit(n + 1); if (distinct_digits == total_digits) { // Return the next consecutive number return n + 1; } else // Increment Number by 1 n++; } return -1; } let n = 2019; document.write(nextNumberDistinctDigit(n)); </script>", "e": 35946, "s": 34007, "text": null }, { "code": null, "e": 35951, "s": 35946, "text": "2031" }, { "code": null, "e": 35969, "s": 35951, "text": "Another Approach:" }, { "code": null, "e": 36097, "s": 35969, "text": "Instead of calculating the number of digits each time, we can use set STL in order to check if a number has only unique digits." }, { "code": null, "e": 36192, "s": 36097, "text": "Then we can compare the size of string s formed from a given number and the newly created set." }, { "code": null, "e": 36284, "s": 36192, "text": "For example, let us consider the number 1987, then we can convert the number into a string," }, { "code": null, "e": 36288, "s": 36284, "text": "C++" }, { "code": "int n;cin>>n;string s = to_string(n);", "e": 36326, "s": 36288, "text": null }, { "code": null, "e": 36386, "s": 36326, "text": "After that, initialize a set with the contents of string s." }, { "code": null, "e": 36390, "s": 36386, "text": "C++" }, { "code": "set<int> uniDigits(s.begin(), s.end());", "e": 36430, "s": 36390, "text": null }, { "code": null, "e": 36508, "s": 36430, "text": "Then we can compare the size of string s and the newly created set uniDigits." }, { "code": null, "e": 36531, "s": 36508, "text": "Here is the total code" }, { "code": null, "e": 36535, "s": 36531, "text": "C++" }, { "code": null, "e": 36543, "s": 36535, "text": "Python3" }, { "code": null, "e": 36554, "s": 36543, "text": "Javascript" }, { "code": "// CPP program for the above program#include <bits/stdc++.h>using namespace std; // Function to find next number// with digit distinctvoid nextNumberDistinctDigit(int n){ // Iterate from n + 1 to inf for (int i = n + 1;; 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; break; } }} // Driver Codeint main(){ int n = 2019; // input the no. // Function Call nextNumberDistinctDigit(n); return 0;}", "e": 37249, "s": 36554, "text": null }, { "code": "# Python program for the above program # Function to find next number# with digit distinctimport sys def nextNumberDistinctDigit(n): # Iterate from n + 1 to inf for i in range(n + 1,sys.maxsize): # Convert the no. to # string s = str(i) # Convert string to set using stl uniDigits = set([char for char in s]) # Output if condition satisfies if (len(s) == len(uniDigits)): print(i) break # Driver Coden = 2019 # input the no. # Function CallnextNumberDistinctDigit(n) # This code is contributed by shinjanpatra", "e": 37860, "s": 37249, "text": null }, { "code": "<script> // JavaScript program for the above program // Function to find next number// with digit distinctfunction nextNumberDistinctDigit(n){ // Iterate from n + 1 to inf for (let i = n + 1;; i++) { // Convert the no. to // string let s = i.toString(); // Convert string to set using stl let uniDigits = new Set(s.split('')); // Output if condition satisfies if (s.length == uniDigits.size) { document.write(i); break; } }} // Driver Code let n = 2019; // input the no. // Function CallnextNumberDistinctDigit(n); // This code is contributed by shinjanpatra </script>", "e": 38540, "s": 37860, "text": null }, { "code": null, "e": 38545, "s": 38540, "text": "2031" }, { "code": null, "e": 38553, "s": 38545, "text": "ankthon" }, { "code": null, "e": 38567, "s": 38553, "text": "princiraj1992" }, { "code": null, "e": 38576, "s": 38567, "text": "svrrrsvr" }, { "code": null, "e": 38587, "s": 38576, "text": "decode2207" }, { "code": null, "e": 38600, "s": 38587, "text": "shinjanpatra" }, { "code": null, "e": 38614, "s": 38600, "text": "number-digits" }, { "code": null, "e": 38627, "s": 38614, "text": "Mathematical" }, { "code": null, "e": 38640, "s": 38627, "text": "Mathematical" }, { "code": null, "e": 38738, "s": 38640, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38762, "s": 38738, "text": "Merge two sorted arrays" }, { "code": null, "e": 38805, "s": 38762, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38819, "s": 38805, "text": "Prime Numbers" }, { "code": null, "e": 38892, "s": 38819, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 38913, "s": 38892, "text": "Operators in C / C++" }, { "code": null, "e": 38956, "s": 38913, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 38990, "s": 38956, "text": "Program for factorial of a number" }, { "code": null, "e": 39031, "s": 38990, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 39084, "s": 39031, "text": "Find minimum number of coins that make a given value" } ]
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python - GeeksforGeeks
23 Aug, 2021 In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, “%d-%b-%Y-%H:%M:%S”) strftime() is used to convert DateTime into required timestamp format Syntax: datetime.strftime(“%Y-%m-%d-%H:%M:%S”) Here, &Y means year %m means month %d means day %H means hours %M means minutes %S means seconds. First the take DateTime timestamp as a String. Then, convert it into DateTime using strptime(). Now, convert into the necessary format of DateTime using strftime Example 1: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format Python3 # import datetime modulefrom datetime import datetime # consider date in string formatmy_date = "30-May-2020-15:59:02" # convert datetime string into date,month,day and# hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) Output '2020-05-30-15:59:02' Example 2: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format Python3 # import datetime modulefrom datetime import datetime # consider date in string formatmy_date = "30-May-2020-15:59:02" # convert datetime string into date,month,day # and hours:minutes:and seconds format using# strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) # consider date in string formatmy_date = "04-Jan-2021-02:45:12" # convert datetime string into date,month,day # and hours:minutes:and seconds format using # strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) # consider date in string formatmy_date = "23-May-2020-15:59:02" # convert datetime string into date,month,day and # hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S")) 2020-05-30-15:59:02 2021-01-04-02:45:12 2020-05-23-15:59:02 Picked Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25757, "s": 25729, "text": "\n23 Aug, 2021" }, { "code": null, "e": 25912, "s": 25757, "text": "In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used." }, { "code": null, "e": 26032, "s": 25912, "text": "strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds" }, { "code": null, "e": 26040, "s": 26032, "text": "Syntax:" }, { "code": null, "e": 26088, "s": 26040, "text": "datetime.strptime(my_date, “%d-%b-%Y-%H:%M:%S”)" }, { "code": null, "e": 26158, "s": 26088, "text": "strftime() is used to convert DateTime into required timestamp format" }, { "code": null, "e": 26166, "s": 26158, "text": "Syntax:" }, { "code": null, "e": 26205, "s": 26166, "text": "datetime.strftime(“%Y-%m-%d-%H:%M:%S”)" }, { "code": null, "e": 26211, "s": 26205, "text": "Here," }, { "code": null, "e": 26225, "s": 26211, "text": "&Y means year" }, { "code": null, "e": 26241, "s": 26225, "text": "%m means month" }, { "code": null, "e": 26254, "s": 26241, "text": "%d means day" }, { "code": null, "e": 26269, "s": 26254, "text": "%H means hours" }, { "code": null, "e": 26286, "s": 26269, "text": "%M means minutes" }, { "code": null, "e": 26304, "s": 26286, "text": "%S means seconds." }, { "code": null, "e": 26466, "s": 26304, "text": "First the take DateTime timestamp as a String. Then, convert it into DateTime using strptime(). Now, convert into the necessary format of DateTime using strftime" }, { "code": null, "e": 26549, "s": 26466, "text": "Example 1: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format" }, { "code": null, "e": 26557, "s": 26549, "text": "Python3" }, { "code": "# import datetime modulefrom datetime import datetime # consider date in string formatmy_date = \"30-May-2020-15:59:02\" # convert datetime string into date,month,day and# hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\"))", "e": 26939, "s": 26557, "text": null }, { "code": null, "e": 26946, "s": 26939, "text": "Output" }, { "code": null, "e": 26968, "s": 26946, "text": "'2020-05-30-15:59:02'" }, { "code": null, "e": 27051, "s": 26968, "text": "Example 2: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format" }, { "code": null, "e": 27059, "s": 27051, "text": "Python3" }, { "code": "# import datetime modulefrom datetime import datetime # consider date in string formatmy_date = \"30-May-2020-15:59:02\" # convert datetime string into date,month,day # and hours:minutes:and seconds format using# strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\")) # consider date in string formatmy_date = \"04-Jan-2021-02:45:12\" # convert datetime string into date,month,day # and hours:minutes:and seconds format using # strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\")) # consider date in string formatmy_date = \"23-May-2020-15:59:02\" # convert datetime string into date,month,day and # hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, \"%d-%b-%Y-%H:%M:%S\") # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime(\"%Y-%m-%d-%H:%M:%S\"))", "e": 28105, "s": 27059, "text": null }, { "code": null, "e": 28166, "s": 28105, "text": "2020-05-30-15:59:02\n2021-01-04-02:45:12\n2020-05-23-15:59:02\n" }, { "code": null, "e": 28173, "s": 28166, "text": "Picked" }, { "code": null, "e": 28189, "s": 28173, "text": "Python-datetime" }, { "code": null, "e": 28196, "s": 28189, "text": "Python" }, { "code": null, "e": 28294, "s": 28196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28312, "s": 28294, "text": "Python Dictionary" }, { "code": null, "e": 28344, "s": 28312, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28366, "s": 28344, "text": "Enumerate() in Python" }, { "code": null, "e": 28408, "s": 28366, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28434, "s": 28408, "text": "Python String | replace()" }, { "code": null, "e": 28463, "s": 28434, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28500, "s": 28463, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28536, "s": 28500, "text": "Convert integer to string in Python" }, { "code": null, "e": 28578, "s": 28536, "text": "Check if element exists in list in Python" } ]
A Game of Words: Vectorization, Tagging, and Sentiment Analysis | by Madeline McCombe | Towards Data Science
Full disclosure: I haven’t watched or read Game of Thrones, but I am hoping to learn a lot about it by analyzing the text. If you would like more background about the basic text processing, you can read my other article. The text from all 5 books can be found on Kaggle. In this article I will be taking the cleaned text and using it to explain the following concepts: Vectorization: Bag-of-Words, TF-IDF, and Skip-Thought Vectors After Vectorization POS tagging Named Entity Recognition (NER) Chunking and Chinking Sentiment Analysis Other NLP packages Currently, I have a list of lemmatized words, but how can I structure them in a way that a machine will be able to understand? I am going to explore a couple vectorization methods, which turn a list of words into an array of numbers that can be used for different machine learning methods. When doing this, it is important to make sure that stopwords and other non-essential words are removed from the text, so that the array/vector system created will have only important dimensions to model on. One method is called Bag-of-Words, which defines a dictionary of unique words contained in the text, and then finds the count of each word within the text. For example, if I were to collect a list of unique words from A Game of Thrones, and then split the full list into words by chapter, I would end up with an array that has one chapter per row and the counts of each word going across the columns. The drawbacks to this method are that it does not preserve the order of the words ([fall, death] and [fall, love] have very different meanings), and that it doesn’t capture any actual meaning of the words. Also, if we were splitting the text by chapter, chapters with more words would be unintentionally weighted more heavily, as they would have high counts across the row. However, this is still a good way to see a distribution of terms and is useful if you are looking to see how many times a particular word shows up. Here is an implementation of this on the game of thrones text, split by chapter: from sklearn.feature_extraction.text import CountVectorizerbow = CountVectorizer()BOW = bow.fit_transform(page_lemm)bagOFwords = pd.DataFrame(BOW.toarray())bagOFwords.columns = bow.get_feature_names() In this example, page_lemm is a list of length 572 (number of pages), with each element being a string of words on that page. The CountVectorizer() function automatically tokenizes and counts the words in all of the strings. I did some behind the scenes removal of stopwords and lemmatization before using the code above, which you can see on my github. This code creates a dataframe, where each row corresponds to a chapter of the book, and each column corresponds to one unique word within the text. The body of the frame contains the count of each word per chapter. Another method that fixes some of the issues with Bag-of-Words is called TF-IDF, or term frequency-inverse document frequency. TF-IDF is similar to the previous method, except the value in each column for each row is scaled by the number of terms in the document and the relative rarity of the word. Term frequency equals the number of times a word appears in a document divided by the total number of words in the document. Inverse document frequency calculates the weight of rare words in all documents in the corpus, with rare words having a high IDF score, and words that are present in all documents in a corpus having IDF close to zero. This allows words that may have a lot of meaning to still be influential in the final analysis if they are rare. Think of it this way-would it be better to know that the word ‘hand’ is used in all chapters of a book, or would it be more influential to know that ‘death’ only occurs in 10 of them? The TF and IDF are multiplied together to reach the final TF-IDF score. A great step-by-step of this process can be found here. The scikit-learn package (sklearn) in Python has a function TfidfVectorizer() that will compute the TF-IDF values for you, shown here: from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer()got_tfidf = vectorizer.fit_transform(page_lemm)tfidf = pd.DataFrame(got_tfidf.toarray())tfidf.columns = vectorizer.get_feature_names() As you can see, the code for these two methods is very similar and takes the same inputs, but gives different contents within the dataframe. Instead of the count of each word, the TF-IDF score is calculated. Here is a comparison of the top 10 words according to average Bag of Words count and the top 10 words according to average TF-IDF score. There is some overlap, but TF-IDF gives names of characters higher average scores than Bag of Words. I highlighted the words that do not overlap between the two approaches. Skip-Thought Vectors is another method of vectorization that predicts the surroundings of sentences using transfer learning in a neural network. Transfer learning is the concept that a machine can apply what it ‘learns’ from one task onto another task. This is the thought behind almost every machine learning technique, as we are trying to get machines to learn at a rate that is faster and more quantifiable than the way humans learn. For text processing especially, the idea is that an algorithm builds a neural network that learns from thousands of different books and figures out sentence structures, themes, and general patterns. This algorithm can then be applied to a book it hasn’t read yet, and it can predict or model the sentiment or themes within the text. You can read more here about this method and how it compares to TF-IDF. Another method of vectorization that leans heavily on neural networks is word2vec, which calculates the cosine similarity between two words, and plots words in space so that similar words are grouped together. You can read about a neat implementation of this method here. Now that you have an array of numbers, what next? With Bag of Words, you can perform a logistic regression or other classification algorithm to show what documents (rows) within the array are most similar. This can be helpful when trying to see if two articles are related in topic. Skip Thought Vectors and Word2Vec both cluster words based on meaning within a text, which is a method called word embedding. This technique is important because it preserves relationships among words. Especially when dealing with review text data (anything with a numerical rating accompanying the text review), these techniques can yield valuable insights about what the consumers are feeling and thinking. Since A Game of Thrones does not have default values for classification, I have no way of validating a model, I am going to explain alternative methods of analyzing a text below. Part of Speech tagging (POS) is where a part of speech is assigned to each word in a list using context clues. This is useful because the same word with a different part of speech can have two completely different meanings. For example, if you have two sentences [‘A plane can fly’ and ‘There is a fly in the room’], it would be important to define ‘fly’ and ‘fly’ correctly in order to determine how the two sentences are related (aka not at all). Tagging words by part of speech allows you to do chunking and chinking which is explained later. An important note is that POS tagging should be done straight after tokenization and before any words are removed so that sentence structure is preserved and it is more obvious what part of speech the word belongs to. One way to do this is by using nltk.pos_tag(): import nltkdocument = ' '.join(got1[8:10])def preprocess(sent): sent = nltk.word_tokenize(sent) sent = nltk.pos_tag(sent) return sentsent = preprocess(document)print(document)print(sent) [‘“Dead is dead,” he said. “We have no business with the dead.” ‘, ‘“Are they dead?” Royce asked softly. “What proof have we?” ‘] [,...(‘``’, ‘``’), (‘We’, ‘PRP’), (‘have’, ‘VBP’), (‘no’, ‘DT’), (‘business’, ‘NN’), (‘with’, ‘IN’), (‘the’, ‘DT’), (‘dead’, ‘JJ’), (‘.’, ‘.’), (“‘’”, “‘’”),...] Here is a snippet of what was created above, and you can see that adjectives are represented as ‘JJ’, nouns as ‘NN’, and so on. This information will be used when chunking later. Sometimes it is helpful to further define the parts of speech for special words, especially when trying to process articles about current events. Beyond being nouns, ‘London’, ‘Paris’, ‘Moscow’, and ‘Sydney’ are all locations that have specific meaning attached to them. The same goes for names of people, organizations, times, money, percents, and dates among other things. This process is important in text analysis because it can be a way to go about understanding chunks of text. Generally, to apply NER to a text, tokenization and POS tagging must have been performed previously. The nltk package has two methods to do NER built in, both of which are explained well in this article. Another useful way to perform NER and have the capability to visualize and sort the results is through the spaCy package. A good walkthrough of this can be found here. I explored the GOT text using this method, and had some interesting results: import spacyfrom collections import Counterimport en_core_web_smnlp = en_core_web_sm.load()from pprint import pprintdoc = nlp(document3)pprint([(X.text, X.label_) for X in doc.ents]) [(‘George R. R. Martin ‘, ‘PERSON’),(‘Ser Waymar Royce’, ‘PERSON’),(‘fifty’, ‘CARDINAL’),(‘Will’, ‘PERSON’),(‘Royce’, ‘PERSON’),(‘Eight days’, ‘DATE’),(‘nine’, ‘CARDINAL’),(‘Waymar Royce’, ‘PERSON’),(‘Gared’, ‘PERSON’),(‘Gared’, ‘ORG’),(‘forty years’, ‘DATE’),...] In the code above, document3 is the full text of A Game of Thrones in a single string. This package efficiently found and classified all types of entities. It was a bit confused on some instances of Gared (at one point it classified him as PERSON, another as ORG, and another later on as WORK_OF_ART). However, overall this gave more insight into the content of the text than just POS tagging did. A count of how many matches per type of entity and the top entities found is below. Unsurprisingly, there were a lot of names found in the text. labels = [x.label_ for x in doc.ents]items = [x.text for x in doc.ents]print(Counter(labels))print(Counter(items).most_common(5)) Counter({‘CARDINAL’: 340, ‘DATE’: 169, ‘FAC’: 34, ‘GPE’: 195, ‘LAW’: 2, ‘LOC’: 24, ‘MONEY’: 1, ‘NORP’: 32, ‘ORDINAL’: 88, ‘ORG’: 386, ‘PERSON’: 2307, ‘PRODUCT’: 35, ‘QUANTITY’: 23, ‘TIME’: 86, ‘WORK_OF_ART’: 77}) [(‘Jon’, 259), (‘Ned’, 247), (‘Arya’, 145), (‘Robert’, 132), (‘Catelyn’, 128)] Chunking and chinking are two methods used to extract meaningful phrases from a text. They combine POS tagging and Regex to produce text snippets that match the phrase structures requested. One implementation of chunking is to find phrases that provide descriptions of different nouns, called noun phrase chunking. The form of a noun phrase chunk is generally composed of a determinant/possessive, adjectives, a possible verb, and the noun. If you find that your chunks have part that you do not want, or that you’d rather split the text on a specific POS, an easy way to achieve your goal is by chinking. This defines a small chunk (called a chink) that should be removed or split on when chunking. I am not going to explore chinking in this article, but a tutorial can be found here. The easiest way to do specific types of chunking with NLTK is using the nltk.RegexpParser(r‘<><><>’). This allows you to specify your noun phrase formula, and is very easy to interpret. Each <> references the part of speech of one word to match, and normal regex syntax applies within each <>. This is very similar to the nltk.Text().findall(r’<><><>’) concept, but just with POS instead of actual words. A couple of things to note when creating the Regex string to parse is that the part of speech abbreviations (NN=noun, JJ=adjective, PRP=preposition, etc.) can vary between packages, and sometimes it is good to start more specific and then broaden your search. If you’re super lost right now, a good intro to this concept can be found here. Also, it may be a good idea to brush up on sentence structures and parts of speech before so that you can fully interpret what the chunking returns. Here is an example of this applied to GOT: document2 = ' '.join(got1[100:300])big_sent = preprocess(document2) # POS tagging wordspattern = 'NP: {<DT>?<JJ>*<NN.?>+}'cp = nltk.RegexpParser(pattern)cs = cp.parse(big_sent)print(cs) (..., (NP Twilight/NNP) deepened/VBD ./. (NP The/DT cloudless/NN sky/NN) turned/VBD (NP a/DT deep/JJ purple/NN) ,/, (NP the/DT color/NN) of/IN (NP an/DT old/JJ bruise/NN) ,/,...) This is a very similar idea to NER, as you can group NN or NNP (nouns or proper nouns) together to find full names of objects. Also the pattern to match can be any combination of parts of speech, which is useful when looking for certain kinds of phrases. However, if the POS tagging is incorrect, you will not be able to find the types of phrases you are looking for. I only looked for noun phrases here, but there are more types of chunks included in my github code. Sentiment Analysis is how a computer combines everything covered so far and comes up with a way to communicate the overall gist of a passage. It compares the words in a sentence, paragraph, or another subset of text to a list of words in a dictionary and calculates a sentiment score based on how the individual words in a sentence are categorized. This is mostly used in analyzing reviews, articles, or other opinion pieces, but I am going to apply this to GOT today. I am mainly interested in seeing if the overall tone of the book is positive or negative, and it that tone varies between chapters. There are two ways of doing sentiment analysis: you can train and test a model on previously categorized text and then use that to predict whether new text of the same type will be positive or negative, or you can simply use an existing lexicon built into the function that will analyze and report a positive or negative score. Here is an example of the latter or some sentences from the first page of A Game of Thrones: from nltk.sentiment.vader import SentimentIntensityAnalyzernltk.download('vader_lexicon')sid = SentimentIntensityAnalyzer()for sentence in sentences: print(sentence) ss = sid.polarity_scores(sentence) for k in sorted(ss): print('{0}: {1}, '.format(k, ss[k]), end='') print() ...“Do the dead frighten you?” compound: -0.7717, neg: 0.691, neu: 0.309, pos: 0.0, Ser Waymar Royce asked with just the hint of a smile. compound: 0.3612, neg: 0.0, neu: 0.783, pos: 0.217, Gared did not rise to the bait. compound: 0.0, neg: 0.0, neu: 1.0, pos: 0.0,... Since this is analyzing text of a book and not text of reviews, a lot of the sentences are going to have a neutral compound score (0). This is totally fine for my purposes however, because I am just looking for general trends in the language of the book over time. But it is still nice to see that when dead is mentioned a negative score is applied. TextBlob is another useful package that can perform sentiment analysis. Once you turn your text into a TextBlob object (textblob.textBlob()), it has functions to tokenize, lemmatize, tag plain text, and make a WordNet, which quantifies the similarity between words. There are a lot of different text objects specific to this package that allow for really cool transformations, explained here. There is even a correct() function that will attempt to correct spelling mistakes. I am not going to go into most of these in this article, as I am trying to analyze a book which should generally have correct spelling and syntax, however many of these tools would be useful when dealing with particularly messy text data. Here is TextBlob’s version of sentiment analysis on the first page of A Game of Thrones: from textblob import TextBlobdef detect_polarity(text): return TextBlob(text).sentimentfor sentence in sentences: print(sentence) print(detect_polarity(sentence)) “Do the dead frighten you?” Sentiment(polarity=-0.2, subjectivity=0.4) Ser Waymar Royce asked with just the hint of a smile. Sentiment(polarity=0.3, subjectivity=0.1) Gared did not rise to the bait. Sentiment(polarity=0.0, subjectivity=0.0) There is similarity between the sentiment scores of nltk and textblob, but the nltk version has more variability since it is a compound score. The textblob sentiments alternatively have a subjectivity score, which is good for telling how accurately a sentence may be classified. Below is a distribution of the sentiments by page per method. Textblob overall gave higher sentiment ratings, whereas nltk had more variance with the score. If you are trying to gather sentiment from social media text or emojis, the VADER Sentiment Analysis is a tool specifically curated for that task. It has built in slang (lol, omg, nah, meh, etc.) and can even understand emojis. A good walkthrough of how to use it can be found here. Also, if Python is not your go to language for text analysis, there are other methods in different languages/software to do sentiment analysis that are explained here. I only explained functions the nltk, textblob, vaderSentiment, spacy, and sklearn packages in this article, but there are many advantages and disadvantages to them depending on the task you’re trying to accomplish. Some others that may be better suited to your task are Polyglot and Genism. Polyglot is known for having the ability to analyze a large number of languages (supports 16–196 depending on the task). Genism is primarily used for unsupervised learning tasks on text, and will need any preprocessing to be done with a different package. You can find a handy chart with all this information here. One key thing that I’ve learned from writing this article is that there are always at least three ways to accomplish a single task, and determining the best option just depends on what kind of data you are using. Sometimes you are going to prioritize computation time, and other times you will need a package that can do unsupervised learning well. Text processing is a fascinating science, and I cannot wait to see where it leads us in the next few years. In this article I covered vectorization and how that can determine similarity between text, tagging which allows meaning to be attached to words, and sentiment analysis which tells roughly how positive or negative a text is. I have gleaned many insights from Game of Thrones, like there is a lot of death, sir is a common title spelled Ser, and there are not as many instances of dragons as I was led to believe. However, I may be convinced to read the books now! I hope you enjoyed the article! A copy of my code, which has further examples and explanation, can be found here on github! Feel free to take and use the code as you please. My other article ‘Text Preprocessing Is Coming’ can be found here!
[ { "code": null, "e": 541, "s": 172, "text": "Full disclosure: I haven’t watched or read Game of Thrones, but I am hoping to learn a lot about it by analyzing the text. If you would like more background about the basic text processing, you can read my other article. The text from all 5 books can be found on Kaggle. In this article I will be taking the cleaned text and using it to explain the following concepts:" }, { "code": null, "e": 603, "s": 541, "text": "Vectorization: Bag-of-Words, TF-IDF, and Skip-Thought Vectors" }, { "code": null, "e": 623, "s": 603, "text": "After Vectorization" }, { "code": null, "e": 635, "s": 623, "text": "POS tagging" }, { "code": null, "e": 666, "s": 635, "text": "Named Entity Recognition (NER)" }, { "code": null, "e": 688, "s": 666, "text": "Chunking and Chinking" }, { "code": null, "e": 707, "s": 688, "text": "Sentiment Analysis" }, { "code": null, "e": 726, "s": 707, "text": "Other NLP packages" }, { "code": null, "e": 1223, "s": 726, "text": "Currently, I have a list of lemmatized words, but how can I structure them in a way that a machine will be able to understand? I am going to explore a couple vectorization methods, which turn a list of words into an array of numbers that can be used for different machine learning methods. When doing this, it is important to make sure that stopwords and other non-essential words are removed from the text, so that the array/vector system created will have only important dimensions to model on." }, { "code": null, "e": 2227, "s": 1223, "text": "One method is called Bag-of-Words, which defines a dictionary of unique words contained in the text, and then finds the count of each word within the text. For example, if I were to collect a list of unique words from A Game of Thrones, and then split the full list into words by chapter, I would end up with an array that has one chapter per row and the counts of each word going across the columns. The drawbacks to this method are that it does not preserve the order of the words ([fall, death] and [fall, love] have very different meanings), and that it doesn’t capture any actual meaning of the words. Also, if we were splitting the text by chapter, chapters with more words would be unintentionally weighted more heavily, as they would have high counts across the row. However, this is still a good way to see a distribution of terms and is useful if you are looking to see how many times a particular word shows up. Here is an implementation of this on the game of thrones text, split by chapter:" }, { "code": null, "e": 2428, "s": 2227, "text": "from sklearn.feature_extraction.text import CountVectorizerbow = CountVectorizer()BOW = bow.fit_transform(page_lemm)bagOFwords = pd.DataFrame(BOW.toarray())bagOFwords.columns = bow.get_feature_names()" }, { "code": null, "e": 2997, "s": 2428, "text": "In this example, page_lemm is a list of length 572 (number of pages), with each element being a string of words on that page. The CountVectorizer() function automatically tokenizes and counts the words in all of the strings. I did some behind the scenes removal of stopwords and lemmatization before using the code above, which you can see on my github. This code creates a dataframe, where each row corresponds to a chapter of the book, and each column corresponds to one unique word within the text. The body of the frame contains the count of each word per chapter." }, { "code": null, "e": 4200, "s": 2997, "text": "Another method that fixes some of the issues with Bag-of-Words is called TF-IDF, or term frequency-inverse document frequency. TF-IDF is similar to the previous method, except the value in each column for each row is scaled by the number of terms in the document and the relative rarity of the word. Term frequency equals the number of times a word appears in a document divided by the total number of words in the document. Inverse document frequency calculates the weight of rare words in all documents in the corpus, with rare words having a high IDF score, and words that are present in all documents in a corpus having IDF close to zero. This allows words that may have a lot of meaning to still be influential in the final analysis if they are rare. Think of it this way-would it be better to know that the word ‘hand’ is used in all chapters of a book, or would it be more influential to know that ‘death’ only occurs in 10 of them? The TF and IDF are multiplied together to reach the final TF-IDF score. A great step-by-step of this process can be found here. The scikit-learn package (sklearn) in Python has a function TfidfVectorizer() that will compute the TF-IDF values for you, shown here:" }, { "code": null, "e": 4424, "s": 4200, "text": "from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer()got_tfidf = vectorizer.fit_transform(page_lemm)tfidf = pd.DataFrame(got_tfidf.toarray())tfidf.columns = vectorizer.get_feature_names()" }, { "code": null, "e": 4942, "s": 4424, "text": "As you can see, the code for these two methods is very similar and takes the same inputs, but gives different contents within the dataframe. Instead of the count of each word, the TF-IDF score is calculated. Here is a comparison of the top 10 words according to average Bag of Words count and the top 10 words according to average TF-IDF score. There is some overlap, but TF-IDF gives names of characters higher average scores than Bag of Words. I highlighted the words that do not overlap between the two approaches." }, { "code": null, "e": 5784, "s": 4942, "text": "Skip-Thought Vectors is another method of vectorization that predicts the surroundings of sentences using transfer learning in a neural network. Transfer learning is the concept that a machine can apply what it ‘learns’ from one task onto another task. This is the thought behind almost every machine learning technique, as we are trying to get machines to learn at a rate that is faster and more quantifiable than the way humans learn. For text processing especially, the idea is that an algorithm builds a neural network that learns from thousands of different books and figures out sentence structures, themes, and general patterns. This algorithm can then be applied to a book it hasn’t read yet, and it can predict or model the sentiment or themes within the text. You can read more here about this method and how it compares to TF-IDF." }, { "code": null, "e": 6056, "s": 5784, "text": "Another method of vectorization that leans heavily on neural networks is word2vec, which calculates the cosine similarity between two words, and plots words in space so that similar words are grouped together. You can read about a neat implementation of this method here." }, { "code": null, "e": 6927, "s": 6056, "text": "Now that you have an array of numbers, what next? With Bag of Words, you can perform a logistic regression or other classification algorithm to show what documents (rows) within the array are most similar. This can be helpful when trying to see if two articles are related in topic. Skip Thought Vectors and Word2Vec both cluster words based on meaning within a text, which is a method called word embedding. This technique is important because it preserves relationships among words. Especially when dealing with review text data (anything with a numerical rating accompanying the text review), these techniques can yield valuable insights about what the consumers are feeling and thinking. Since A Game of Thrones does not have default values for classification, I have no way of validating a model, I am going to explain alternative methods of analyzing a text below." }, { "code": null, "e": 7738, "s": 6927, "text": "Part of Speech tagging (POS) is where a part of speech is assigned to each word in a list using context clues. This is useful because the same word with a different part of speech can have two completely different meanings. For example, if you have two sentences [‘A plane can fly’ and ‘There is a fly in the room’], it would be important to define ‘fly’ and ‘fly’ correctly in order to determine how the two sentences are related (aka not at all). Tagging words by part of speech allows you to do chunking and chinking which is explained later. An important note is that POS tagging should be done straight after tokenization and before any words are removed so that sentence structure is preserved and it is more obvious what part of speech the word belongs to. One way to do this is by using nltk.pos_tag():" }, { "code": null, "e": 7928, "s": 7738, "text": "import nltkdocument = ' '.join(got1[8:10])def preprocess(sent): sent = nltk.word_tokenize(sent) sent = nltk.pos_tag(sent) return sentsent = preprocess(document)print(document)print(sent)" }, { "code": null, "e": 8058, "s": 7928, "text": "[‘“Dead is dead,” he said. “We have no business with the dead.” ‘, ‘“Are they dead?” Royce asked softly. “What proof have we?” ‘]" }, { "code": null, "e": 8220, "s": 8058, "text": "[,...(‘``’, ‘``’), (‘We’, ‘PRP’), (‘have’, ‘VBP’), (‘no’, ‘DT’), (‘business’, ‘NN’), (‘with’, ‘IN’), (‘the’, ‘DT’), (‘dead’, ‘JJ’), (‘.’, ‘.’), (“‘’”, “‘’”),...]" }, { "code": null, "e": 8399, "s": 8220, "text": "Here is a snippet of what was created above, and you can see that adjectives are represented as ‘JJ’, nouns as ‘NN’, and so on. This information will be used when chunking later." }, { "code": null, "e": 9087, "s": 8399, "text": "Sometimes it is helpful to further define the parts of speech for special words, especially when trying to process articles about current events. Beyond being nouns, ‘London’, ‘Paris’, ‘Moscow’, and ‘Sydney’ are all locations that have specific meaning attached to them. The same goes for names of people, organizations, times, money, percents, and dates among other things. This process is important in text analysis because it can be a way to go about understanding chunks of text. Generally, to apply NER to a text, tokenization and POS tagging must have been performed previously. The nltk package has two methods to do NER built in, both of which are explained well in this article." }, { "code": null, "e": 9332, "s": 9087, "text": "Another useful way to perform NER and have the capability to visualize and sort the results is through the spaCy package. A good walkthrough of this can be found here. I explored the GOT text using this method, and had some interesting results:" }, { "code": null, "e": 9515, "s": 9332, "text": "import spacyfrom collections import Counterimport en_core_web_smnlp = en_core_web_sm.load()from pprint import pprintdoc = nlp(document3)pprint([(X.text, X.label_) for X in doc.ents])" }, { "code": null, "e": 9780, "s": 9515, "text": "[(‘George R. R. Martin ‘, ‘PERSON’),(‘Ser Waymar Royce’, ‘PERSON’),(‘fifty’, ‘CARDINAL’),(‘Will’, ‘PERSON’),(‘Royce’, ‘PERSON’),(‘Eight days’, ‘DATE’),(‘nine’, ‘CARDINAL’),(‘Waymar Royce’, ‘PERSON’),(‘Gared’, ‘PERSON’),(‘Gared’, ‘ORG’),(‘forty years’, ‘DATE’),...]" }, { "code": null, "e": 10323, "s": 9780, "text": "In the code above, document3 is the full text of A Game of Thrones in a single string. This package efficiently found and classified all types of entities. It was a bit confused on some instances of Gared (at one point it classified him as PERSON, another as ORG, and another later on as WORK_OF_ART). However, overall this gave more insight into the content of the text than just POS tagging did. A count of how many matches per type of entity and the top entities found is below. Unsurprisingly, there were a lot of names found in the text." }, { "code": null, "e": 10453, "s": 10323, "text": "labels = [x.label_ for x in doc.ents]items = [x.text for x in doc.ents]print(Counter(labels))print(Counter(items).most_common(5))" }, { "code": null, "e": 10666, "s": 10453, "text": "Counter({‘CARDINAL’: 340, ‘DATE’: 169, ‘FAC’: 34, ‘GPE’: 195, ‘LAW’: 2, ‘LOC’: 24, ‘MONEY’: 1, ‘NORP’: 32, ‘ORDINAL’: 88, ‘ORG’: 386, ‘PERSON’: 2307, ‘PRODUCT’: 35, ‘QUANTITY’: 23, ‘TIME’: 86, ‘WORK_OF_ART’: 77})" }, { "code": null, "e": 10745, "s": 10666, "text": "[(‘Jon’, 259), (‘Ned’, 247), (‘Arya’, 145), (‘Robert’, 132), (‘Catelyn’, 128)]" }, { "code": null, "e": 11531, "s": 10745, "text": "Chunking and chinking are two methods used to extract meaningful phrases from a text. They combine POS tagging and Regex to produce text snippets that match the phrase structures requested. One implementation of chunking is to find phrases that provide descriptions of different nouns, called noun phrase chunking. The form of a noun phrase chunk is generally composed of a determinant/possessive, adjectives, a possible verb, and the noun. If you find that your chunks have part that you do not want, or that you’d rather split the text on a specific POS, an easy way to achieve your goal is by chinking. This defines a small chunk (called a chink) that should be removed or split on when chunking. I am not going to explore chinking in this article, but a tutorial can be found here." }, { "code": null, "e": 12468, "s": 11531, "text": "The easiest way to do specific types of chunking with NLTK is using the nltk.RegexpParser(r‘<><><>’). This allows you to specify your noun phrase formula, and is very easy to interpret. Each <> references the part of speech of one word to match, and normal regex syntax applies within each <>. This is very similar to the nltk.Text().findall(r’<><><>’) concept, but just with POS instead of actual words. A couple of things to note when creating the Regex string to parse is that the part of speech abbreviations (NN=noun, JJ=adjective, PRP=preposition, etc.) can vary between packages, and sometimes it is good to start more specific and then broaden your search. If you’re super lost right now, a good intro to this concept can be found here. Also, it may be a good idea to brush up on sentence structures and parts of speech before so that you can fully interpret what the chunking returns. Here is an example of this applied to GOT:" }, { "code": null, "e": 12654, "s": 12468, "text": "document2 = ' '.join(got1[100:300])big_sent = preprocess(document2) # POS tagging wordspattern = 'NP: {<DT>?<JJ>*<NN.?>+}'cp = nltk.RegexpParser(pattern)cs = cp.parse(big_sent)print(cs)" }, { "code": null, "e": 12833, "s": 12654, "text": "(..., (NP Twilight/NNP) deepened/VBD ./. (NP The/DT cloudless/NN sky/NN) turned/VBD (NP a/DT deep/JJ purple/NN) ,/, (NP the/DT color/NN) of/IN (NP an/DT old/JJ bruise/NN) ,/,...)" }, { "code": null, "e": 13301, "s": 12833, "text": "This is a very similar idea to NER, as you can group NN or NNP (nouns or proper nouns) together to find full names of objects. Also the pattern to match can be any combination of parts of speech, which is useful when looking for certain kinds of phrases. However, if the POS tagging is incorrect, you will not be able to find the types of phrases you are looking for. I only looked for noun phrases here, but there are more types of chunks included in my github code." }, { "code": null, "e": 14323, "s": 13301, "text": "Sentiment Analysis is how a computer combines everything covered so far and comes up with a way to communicate the overall gist of a passage. It compares the words in a sentence, paragraph, or another subset of text to a list of words in a dictionary and calculates a sentiment score based on how the individual words in a sentence are categorized. This is mostly used in analyzing reviews, articles, or other opinion pieces, but I am going to apply this to GOT today. I am mainly interested in seeing if the overall tone of the book is positive or negative, and it that tone varies between chapters. There are two ways of doing sentiment analysis: you can train and test a model on previously categorized text and then use that to predict whether new text of the same type will be positive or negative, or you can simply use an existing lexicon built into the function that will analyze and report a positive or negative score. Here is an example of the latter or some sentences from the first page of A Game of Thrones:" }, { "code": null, "e": 14605, "s": 14323, "text": "from nltk.sentiment.vader import SentimentIntensityAnalyzernltk.download('vader_lexicon')sid = SentimentIntensityAnalyzer()for sentence in sentences: print(sentence) ss = sid.polarity_scores(sentence) for k in sorted(ss): print('{0}: {1}, '.format(k, ss[k]), end='') print()" }, { "code": null, "e": 14875, "s": 14605, "text": "...“Do the dead frighten you?” compound: -0.7717, neg: 0.691, neu: 0.309, pos: 0.0, Ser Waymar Royce asked with just the hint of a smile. compound: 0.3612, neg: 0.0, neu: 0.783, pos: 0.217, Gared did not rise to the bait. compound: 0.0, neg: 0.0, neu: 1.0, pos: 0.0,..." }, { "code": null, "e": 15225, "s": 14875, "text": "Since this is analyzing text of a book and not text of reviews, a lot of the sentences are going to have a neutral compound score (0). This is totally fine for my purposes however, because I am just looking for general trends in the language of the book over time. But it is still nice to see that when dead is mentioned a negative score is applied." }, { "code": null, "e": 16029, "s": 15225, "text": "TextBlob is another useful package that can perform sentiment analysis. Once you turn your text into a TextBlob object (textblob.textBlob()), it has functions to tokenize, lemmatize, tag plain text, and make a WordNet, which quantifies the similarity between words. There are a lot of different text objects specific to this package that allow for really cool transformations, explained here. There is even a correct() function that will attempt to correct spelling mistakes. I am not going to go into most of these in this article, as I am trying to analyze a book which should generally have correct spelling and syntax, however many of these tools would be useful when dealing with particularly messy text data. Here is TextBlob’s version of sentiment analysis on the first page of A Game of Thrones:" }, { "code": null, "e": 16197, "s": 16029, "text": "from textblob import TextBlobdef detect_polarity(text): return TextBlob(text).sentimentfor sentence in sentences: print(sentence) print(detect_polarity(sentence))" }, { "code": null, "e": 16438, "s": 16197, "text": "“Do the dead frighten you?” Sentiment(polarity=-0.2, subjectivity=0.4) Ser Waymar Royce asked with just the hint of a smile. Sentiment(polarity=0.3, subjectivity=0.1) Gared did not rise to the bait. Sentiment(polarity=0.0, subjectivity=0.0)" }, { "code": null, "e": 16874, "s": 16438, "text": "There is similarity between the sentiment scores of nltk and textblob, but the nltk version has more variability since it is a compound score. The textblob sentiments alternatively have a subjectivity score, which is good for telling how accurately a sentence may be classified. Below is a distribution of the sentiments by page per method. Textblob overall gave higher sentiment ratings, whereas nltk had more variance with the score." }, { "code": null, "e": 17325, "s": 16874, "text": "If you are trying to gather sentiment from social media text or emojis, the VADER Sentiment Analysis is a tool specifically curated for that task. It has built in slang (lol, omg, nah, meh, etc.) and can even understand emojis. A good walkthrough of how to use it can be found here. Also, if Python is not your go to language for text analysis, there are other methods in different languages/software to do sentiment analysis that are explained here." }, { "code": null, "e": 17931, "s": 17325, "text": "I only explained functions the nltk, textblob, vaderSentiment, spacy, and sklearn packages in this article, but there are many advantages and disadvantages to them depending on the task you’re trying to accomplish. Some others that may be better suited to your task are Polyglot and Genism. Polyglot is known for having the ability to analyze a large number of languages (supports 16–196 depending on the task). Genism is primarily used for unsupervised learning tasks on text, and will need any preprocessing to be done with a different package. You can find a handy chart with all this information here." }, { "code": null, "e": 18884, "s": 17931, "text": "One key thing that I’ve learned from writing this article is that there are always at least three ways to accomplish a single task, and determining the best option just depends on what kind of data you are using. Sometimes you are going to prioritize computation time, and other times you will need a package that can do unsupervised learning well. Text processing is a fascinating science, and I cannot wait to see where it leads us in the next few years. In this article I covered vectorization and how that can determine similarity between text, tagging which allows meaning to be attached to words, and sentiment analysis which tells roughly how positive or negative a text is. I have gleaned many insights from Game of Thrones, like there is a lot of death, sir is a common title spelled Ser, and there are not as many instances of dragons as I was led to believe. However, I may be convinced to read the books now! I hope you enjoyed the article!" }, { "code": null, "e": 19026, "s": 18884, "text": "A copy of my code, which has further examples and explanation, can be found here on github! Feel free to take and use the code as you please." } ]
Why can C++ templates only be implemented in the header file?
When you instantiate a template in C++, the compiler creates a new class. This class has all the places where you placed the template arguments replaced with the actual argument you pass to it when using it. For example − template<typename T> class MyClass { T foo; T myMethod(T arg1, T arg2) { // Impl } }; And somewhere in your program use this class, MyClass<int> x; The compiler creates a new class upon encountering this for every type argument you pass it. For example, if you created 3 objects with different template arguments you'll get 3 classes, which would be equivalent to − class MyClassInt { int foo; int myMethod(int arg1, int arg2) { // Impl } }; In order to do so, the compiler needs to have access to the implementation of the class and the methods before it encounters such statements, to instantiate them with the template argument (in this case int). If these template class implementations were not in the header, they wouldn't be accessible and hence won't compile.
[ { "code": null, "e": 1284, "s": 1062, "text": "When you instantiate a template in C++, the compiler creates a new class. This class has all the places where you placed the template arguments replaced with the actual argument you pass to it when using it. For example −" }, { "code": null, "e": 1385, "s": 1284, "text": "template<typename T> class MyClass {\n T foo;\n T myMethod(T arg1, T arg2) {\n // Impl\n }\n};" }, { "code": null, "e": 1431, "s": 1385, "text": "And somewhere in your program use this class," }, { "code": null, "e": 1447, "s": 1431, "text": "MyClass<int> x;" }, { "code": null, "e": 1665, "s": 1447, "text": "The compiler creates a new class upon encountering this for every type argument you pass it. For example, if you created 3 objects with different template arguments you'll get 3 classes, which would be equivalent to −" }, { "code": null, "e": 1756, "s": 1665, "text": "class MyClassInt {\n int foo;\n int myMethod(int arg1, int arg2) {\n // Impl\n }\n};" }, { "code": null, "e": 2082, "s": 1756, "text": "In order to do so, the compiler needs to have access to the implementation of the class and the methods before it encounters such statements, to instantiate them with the template argument (in this case int). If these template class implementations were not in the header, they wouldn't be accessible and hence won't compile." } ]
When to use fillInStackTrace() method in Java?
The fillInStackTrace() is an important method of Throwable class in Java. The stack trace can be useful to determine where exactly the exception is thrown. There may be some situations where we need to rethrow an exception and find out where it is rethrown, we can use the fillInStackTrace() method in such scenarios. public Throwable fillInStackTrace() public class FillInStackTraceTest { public static void method1() throws Exception { throw new Exception("This is thrown from method1()"); } public static void method2() throws Throwable { try { method1(); } catch(Exception e) { System.err.println("Inside method2():"); e.printStackTrace(); throw e.fillInStackTrace(); // calling fillInStackTrace() method } } public static void main(String[] args) throws Throwable { try { method2(); } catch (Exception e) { System.err.println("Caught Inside Main method()"); e.printStackTrace(); } } } Inside method2(): java.lang.Exception: This is thrown from method1() at FillInStackTraceTest.method1(FillInStackTraceTest.java:3) at FillInStackTraceTest.method2(FillInStackTraceTest.java:7) at FillInStackTraceTest.main(FillInStackTraceTest.java:18) Caught Inside Main method() java.lang.Exception: This is thrown from method1() at FillInStackTraceTest.method2(FillInStackTraceTest.java:12) at FillInStackTraceTest.main(FillInStackTraceTest.java:18)
[ { "code": null, "e": 1380, "s": 1062, "text": "The fillInStackTrace() is an important method of Throwable class in Java. The stack trace can be useful to determine where exactly the exception is thrown. There may be some situations where we need to rethrow an exception and find out where it is rethrown, we can use the fillInStackTrace() method in such scenarios." }, { "code": null, "e": 1416, "s": 1380, "text": "public Throwable fillInStackTrace()" }, { "code": null, "e": 2081, "s": 1416, "text": "public class FillInStackTraceTest {\n public static void method1() throws Exception {\n throw new Exception(\"This is thrown from method1()\");\n }\n public static void method2() throws Throwable {\n try {\n method1();\n } catch(Exception e) {\n System.err.println(\"Inside method2():\");\n e.printStackTrace();\n throw e.fillInStackTrace(); // calling fillInStackTrace() method\n }\n }\n public static void main(String[] args) throws Throwable {\n try {\n method2();\n } catch (Exception e) {\n System.err.println(\"Caught Inside Main method()\");\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2571, "s": 2081, "text": "Inside method2():\njava.lang.Exception: This is thrown from method1()\n at FillInStackTraceTest.method1(FillInStackTraceTest.java:3)\n at FillInStackTraceTest.method2(FillInStackTraceTest.java:7)\n at FillInStackTraceTest.main(FillInStackTraceTest.java:18)\nCaught Inside Main method()\njava.lang.Exception: This is thrown from method1()\n at FillInStackTraceTest.method2(FillInStackTraceTest.java:12)\n at FillInStackTraceTest.main(FillInStackTraceTest.java:18)" } ]
Access the last value of a given vector in R - GeeksforGeeks
07 Apr, 2021 In this article, we will discuss how to access the last value of a given vector in R Programming Language. So let’s begin by first creating an example vector because to get the last value of a vector we need to first create the vector. R vec1 <- c("John" , "Smith", "Tina" , "Brad" , "Emma")print(vec1) Output: "John" "Smith" "Tina" "Brad" "Emma" Our first vector is a character string with some names, now we have to extract the last name from this vector. To do this task we can use the length() function from the R Language. This not only enables to find out the length of the string but also access to the elements. Syntax: length(x) Parameter: x: vector Example: R vec1 <- c("John" , "Smith", "Tina" , "Brad" , "Emma")length(vec1) Output: [1] 5 Now, let’s use length() function to get the last element of the vector: R vec1 <- c("John" , "Smith", "Tina" , "Brad" , "Emma")length(vec1) # To Extract last element with lengthvec1[length(vec1)] Output: [1] 5 [1] "Emma" To find the last element of the vector we can also use tail() function. Again to demonstrate it let’s first create an example vector. R vec2 <- c(123 , 124 , 125 , 126, 128)print(vec2) Output: 123 124 125 126 128 W have an example vector, and we have to access its last element. Syntax: tail() Parameters: x: data frame n: number of rows to be displayed Here we are passing n=1 so that it will display only the last element in the vector. R vec2 <- c(123 , 124 , 125 , 126)tail(vec2 , 1) Output: 126 Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25478, "s": 25242, "text": "In this article, we will discuss how to access the last value of a given vector in R Programming Language. So let’s begin by first creating an example vector because to get the last value of a vector we need to first create the vector." }, { "code": null, "e": 25480, "s": 25478, "text": "R" }, { "code": "vec1 <- c(\"John\" , \"Smith\", \"Tina\" , \"Brad\" , \"Emma\")print(vec1)", "e": 25545, "s": 25480, "text": null }, { "code": null, "e": 25553, "s": 25545, "text": "Output:" }, { "code": null, "e": 25594, "s": 25553, "text": " \"John\" \"Smith\" \"Tina\" \"Brad\" \"Emma\" " }, { "code": null, "e": 25705, "s": 25594, "text": "Our first vector is a character string with some names, now we have to extract the last name from this vector." }, { "code": null, "e": 25867, "s": 25705, "text": "To do this task we can use the length() function from the R Language. This not only enables to find out the length of the string but also access to the elements." }, { "code": null, "e": 25885, "s": 25867, "text": "Syntax: length(x)" }, { "code": null, "e": 25907, "s": 25885, "text": "Parameter: x: vector" }, { "code": null, "e": 25916, "s": 25907, "text": "Example:" }, { "code": null, "e": 25918, "s": 25916, "text": "R" }, { "code": "vec1 <- c(\"John\" , \"Smith\", \"Tina\" , \"Brad\" , \"Emma\")length(vec1)", "e": 25984, "s": 25918, "text": null }, { "code": null, "e": 25992, "s": 25984, "text": "Output:" }, { "code": null, "e": 25998, "s": 25992, "text": "[1] 5" }, { "code": null, "e": 26070, "s": 25998, "text": "Now, let’s use length() function to get the last element of the vector:" }, { "code": null, "e": 26072, "s": 26070, "text": "R" }, { "code": "vec1 <- c(\"John\" , \"Smith\", \"Tina\" , \"Brad\" , \"Emma\")length(vec1) # To Extract last element with lengthvec1[length(vec1)]", "e": 26195, "s": 26072, "text": null }, { "code": null, "e": 26203, "s": 26195, "text": "Output:" }, { "code": null, "e": 26220, "s": 26203, "text": "[1] 5\n[1] \"Emma\"" }, { "code": null, "e": 26292, "s": 26220, "text": "To find the last element of the vector we can also use tail() function." }, { "code": null, "e": 26354, "s": 26292, "text": "Again to demonstrate it let’s first create an example vector." }, { "code": null, "e": 26356, "s": 26354, "text": "R" }, { "code": "vec2 <- c(123 , 124 , 125 , 126, 128)print(vec2)", "e": 26405, "s": 26356, "text": null }, { "code": null, "e": 26413, "s": 26405, "text": "Output:" }, { "code": null, "e": 26433, "s": 26413, "text": "123 124 125 126 128" }, { "code": null, "e": 26499, "s": 26433, "text": "W have an example vector, and we have to access its last element." }, { "code": null, "e": 26514, "s": 26499, "text": "Syntax: tail()" }, { "code": null, "e": 26527, "s": 26514, "text": "Parameters: " }, { "code": null, "e": 26541, "s": 26527, "text": "x: data frame" }, { "code": null, "e": 26575, "s": 26541, "text": "n: number of rows to be displayed" }, { "code": null, "e": 26660, "s": 26575, "text": "Here we are passing n=1 so that it will display only the last element in the vector." }, { "code": null, "e": 26662, "s": 26660, "text": "R" }, { "code": "vec2 <- c(123 , 124 , 125 , 126)tail(vec2 , 1)", "e": 26709, "s": 26662, "text": null }, { "code": null, "e": 26717, "s": 26709, "text": "Output:" }, { "code": null, "e": 26721, "s": 26717, "text": "126" }, { "code": null, "e": 26728, "s": 26721, "text": "Picked" }, { "code": null, "e": 26746, "s": 26728, "text": "R Vector-Programs" }, { "code": null, "e": 26756, "s": 26746, "text": "R-Vectors" }, { "code": null, "e": 26767, "s": 26756, "text": "R Language" }, { "code": null, "e": 26778, "s": 26767, "text": "R Programs" }, { "code": null, "e": 26876, "s": 26778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26928, "s": 26876, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26966, "s": 26928, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27001, "s": 26966, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27059, "s": 27001, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27108, "s": 27059, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27166, "s": 27108, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27215, "s": 27166, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27265, "s": 27215, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27308, "s": 27265, "text": "Replace Specific Characters in String in R" } ]
Kruskal’s (Minimum Spanning Tree) MST Algorithm
There is a connected graph G(V,E) and the weight or cost for every edge is given. Kruskal’s algorithm will find the minimum spanning tree using the graph and the cost. It is merge tree approach. Initially there are different trees, this algorithm will merge them by taking those edges whose cost is minimum, and form a single tree. In this problem, all of the edges are listed, and sorted based on their cost. From the list, edges with minimum costs are taken out and added in the tree, and every there is a check whether the edge forming cycle or not, if it forms a cycle then discard the edge from list and go for next edge. Time complexity of this algorithm is O(E log E) or O(E log V), where E is number of edges, and V is number of vertices. Time complexity of this algorithm is O(E log E) or O(E log V), where E is number of edges, and V is number of vertices. Input - Adjacency matrix 0 1 3 4 ∞ 5 ∞ 1 0 ∞ 7 2 ∞ ∞ 3 ∞ 0 ∞ 8 ∞ ∞ 4 7 ∞ 0 ∞ ∞ ∞ ∞ 2 8 ∞ 0 2 4 5 ∞ ∞ ∞ 2 0 3 ∞ ∞ ∞ ∞ 4 3 0 Output - Edge: B--A And Cost: 1 Edge: E--B And Cost: 2 Edge: F--E And Cost: 2 Edge: C--A And Cost: 3 Edge: G--F And Cost: 3 Edge: D--A And Cost: 4 Total Cost: 15 Input − The given graph g, and an empty tree t Output − The tree t with selected edges Begin create set for each vertices in graph g for each set of vertex u do add u in the vertexSet[u] done sort the edge list. count := 0 while count <= V – 1 do //as tree must have V – 1 edges ed := edgeList[count] //take an edge from edge list if the starting vertex and ending vertex of ed are in same set then merge vertexSet[start] and vertexSet[end] add the ed into tree t count := count + 1 done End #include<iostream> #define V 7 #define INF 999 using namespace std; //Cost matrix of the graph int costMat[V][V] = { {0, 1, 3, 4, INF, 5, INF}, {1, 0, INF, 7, 2, INF, INF}, {3, INF, 0, INF, 8, INF, INF}, {4, 7, INF, 0, INF, INF, INF}, {INF, 2, 8, INF, 0, 2, 4}, {5, INF, INF, INF, 2, 0, 3}, {INF, INF, INF, INF, 4, 3, 0} }; typedef struct{ int u, v, cost; }edge; void swapping(edge &e1, edge &e2){ edge temp; temp = e1; e1 = e2; e2 = temp; } class Tree{ int n; edge edges[V-1]; //as a tree has vertex-1 edges public: Tree(){ n = 0; } void addEdge(edge e){ edges[n] = e; //add edge e into the tree n++; } void printEdges(){ //print edge, cost and total cost int tCost = 0; for(int i = 0; i<n; i++){ cout << "Edge: " << char(edges[i].u+'A') << "--" << char(edges[i].v+'A'); cout << " And Cost: " << edges[i].cost << endl; tCost += edges[i].cost; } cout << "Total Cost: " << tCost << endl; } }; class VSet{ int n; int set[V];//a set can hold maximum V vertices public: VSet(){ n = -1; } void addVertex(int vert){ set[++n] = vert; //add vertex to the set } int deleteVertex(){ return set[n--]; } friend int findVertex(VSet *vertSetArr, int vert); friend void merge(VSet &set1, VSet &set2); }; void merge(VSet &set1, VSet &set2){ //merge two vertex sets together while(set2.n >= 0) set1.addVertex(set2.deleteVertex()); //addToSet(vSet1, delFromSet(vSet2)); } int findVertex(VSet *vertSetArr, int vert){ //find the vertex in different vertex sets for(int i = 0; i<V; i++) for(int j = 0; j<=vertSetArr[i].n; j++) if(vert == vertSetArr[i].set[j]) return i;//node found in i-th vertex set } int findEdge(edge *edgeList){ //find the edges from the cost matrix of Graph and store to edgeList int count = -1, i, j; for(i = 0; i<V; i++) for(j = 0; j<i; j++) if(costMat[i][j] != INF){ count++; //fill edge list for the position 'count' edgeList[count].u = i; edgeList[count].v = j; edgeList[count].cost = costMat[i][j]; } return count+1; } void sortEdge(edge *edgeList, int n){ //sort the edges of graph in ascending order of cost int flag = 1, i, j; for(i = 0; i<(n-1) && flag; i++){//modified bubble sort is used flag = 0; for(j = 0; j<(n-i-1); j++) if(edgeList[j].cost > edgeList[j+1].cost){ swapping(edgeList[j], edgeList[j+1]); flag = 1; } } } void kruskal(Tree &tr){ int ecount, maxEdge = V*(V-1)/2; //max n(n-1)/2 edges can have in a graph edge edgeList[maxEdge], ed; int uloc, vloc; VSet VSetArray[V]; ecount = findEdge(edgeList); for(int i = 0; i < V; i++) VSetArray[i].addVertex(i);//each set contains one element sortEdge(edgeList, ecount); //ecount number of edges in the graph int count = 0; while(count <= V-1){ ed = edgeList[count]; uloc = findVertex(VSetArray, ed.u); vloc = findVertex(VSetArray, ed.v); if(uloc != vloc){ //check whether source abd dest is in same set or not merge(VSetArray[uloc], VSetArray[vloc]); tr.addEdge(ed); } count++; } } int main(){ Tree tr; kruskal(tr); tr.printEdges(); } Edge: B--A And Cost: 1 Edge: E--B And Cost: 2 Edge: F--E And Cost: 2 Edge: C--A And Cost: 3 Edge: G--F And Cost: 3 Edge: D--A And Cost: 4 Total Cost: 15
[ { "code": null, "e": 1230, "s": 1062, "text": "There is a connected graph G(V,E) and the weight or cost for every edge is given. Kruskal’s algorithm will find the minimum spanning tree using the graph and the cost." }, { "code": null, "e": 1394, "s": 1230, "text": "It is merge tree approach. Initially there are different trees, this algorithm will merge them by taking those edges whose cost is minimum, and form a single tree." }, { "code": null, "e": 1689, "s": 1394, "text": "In this problem, all of the edges are listed, and sorted based on their cost. From the list, edges with minimum costs are taken out and added in the tree, and every there is a check whether the edge forming cycle or not, if it forms a cycle then discard the edge from list and go for next edge." }, { "code": null, "e": 1809, "s": 1689, "text": "Time complexity of this algorithm is O(E log E) or O(E log V), where E is number of edges, and V is number of vertices." }, { "code": null, "e": 1929, "s": 1809, "text": "Time complexity of this algorithm is O(E log E) or O(E log V), where E is number of edges, and V is number of vertices." }, { "code": null, "e": 1954, "s": 1929, "text": "Input - Adjacency matrix" }, { "code": null, "e": 2052, "s": 1954, "text": "0 1 3 4 ∞ 5 ∞\n1 0 ∞ 7 2 ∞ ∞\n3 ∞ 0 ∞ 8 ∞ ∞\n4 7 ∞ 0 ∞ ∞ ∞\n∞ 2 8 ∞ 0 2 4\n5 ∞ ∞ ∞ 2 0 3\n∞ ∞ ∞ ∞ 4 3 0" }, { "code": null, "e": 2061, "s": 2052, "text": "Output -" }, { "code": null, "e": 2222, "s": 2061, "text": "Edge: B--A And Cost: 1\n\nEdge: E--B And Cost: 2\n\nEdge: F--E And Cost: 2\n\nEdge: C--A And Cost: 3 \n\nEdge: G--F And Cost: 3\n\nEdge: D--A And Cost: 4\n\nTotal Cost: 15" }, { "code": null, "e": 2269, "s": 2222, "text": "Input − The given graph g, and an empty tree t" }, { "code": null, "e": 2309, "s": 2269, "text": "Output − The tree t with selected edges" }, { "code": null, "e": 2777, "s": 2309, "text": "Begin\n create set for each vertices in graph g\n for each set of vertex u do\n add u in the vertexSet[u]\n done\n sort the edge list.\n count := 0\n while count <= V – 1 do //as tree must have V – 1 edges\n ed := edgeList[count] //take an edge from edge list\n if the starting vertex and ending vertex of ed are in same set then\n merge vertexSet[start] and vertexSet[end]\n add the ed into tree t\n count := count + 1\n done\nEnd" }, { "code": null, "e": 6103, "s": 2777, "text": "#include<iostream>\n#define V 7\n#define INF 999\nusing namespace std;\n//Cost matrix of the graph\nint costMat[V][V] = {\n {0, 1, 3, 4, INF, 5, INF},\n {1, 0, INF, 7, 2, INF, INF},\n {3, INF, 0, INF, 8, INF, INF},\n {4, 7, INF, 0, INF, INF, INF},\n {INF, 2, 8, INF, 0, 2, 4},\n {5, INF, INF, INF, 2, 0, 3},\n {INF, INF, INF, INF, 4, 3, 0}\n};\ntypedef struct{\n int u, v, cost;\n}edge;\nvoid swapping(edge &e1, edge &e2){\n edge temp;\n temp = e1;\n e1 = e2;\n e2 = temp;\n}\nclass Tree{\n int n;\n edge edges[V-1]; //as a tree has vertex-1 edges\n public:\n Tree(){\n n = 0;\n }\n void addEdge(edge e){\n edges[n] = e; //add edge e into the tree\n n++;\n }\n void printEdges(){ //print edge, cost and total cost\n int tCost = 0;\n for(int i = 0; i<n; i++){\n cout << \"Edge: \" << char(edges[i].u+'A') << \"--\" << char(edges[i].v+'A');\n cout << \" And Cost: \" << edges[i].cost << endl;\n tCost += edges[i].cost;\n }\n cout << \"Total Cost: \" << tCost << endl;\n }\n};\nclass VSet{\n int n;\n int set[V];//a set can hold maximum V vertices\n public:\n VSet(){\n n = -1;\n }\n void addVertex(int vert){\n set[++n] = vert; //add vertex to the set\n }\n int deleteVertex(){\n return set[n--];\n }\n friend int findVertex(VSet *vertSetArr, int vert);\n friend void merge(VSet &set1, VSet &set2);\n};\nvoid merge(VSet &set1, VSet &set2){\n //merge two vertex sets together\n while(set2.n >= 0)\n set1.addVertex(set2.deleteVertex());\n //addToSet(vSet1, delFromSet(vSet2));\n}\nint findVertex(VSet *vertSetArr, int vert){\n //find the vertex in different vertex sets\n for(int i = 0; i<V; i++)\n for(int j = 0; j<=vertSetArr[i].n; j++)\n if(vert == vertSetArr[i].set[j])\n return i;//node found in i-th vertex set\n}\nint findEdge(edge *edgeList){\n //find the edges from the cost matrix of Graph and store to edgeList\n int count = -1, i, j;\n for(i = 0; i<V; i++)\n for(j = 0; j<i; j++)\n if(costMat[i][j] != INF){\n count++;\n //fill edge list for the position 'count'\n edgeList[count].u = i; edgeList[count].v = j;\n edgeList[count].cost = costMat[i][j];\n }\n return count+1;\n}\nvoid sortEdge(edge *edgeList, int n){\n //sort the edges of graph in ascending order of cost\n int flag = 1, i, j;\n for(i = 0; i<(n-1) && flag; i++){//modified bubble sort is used\n flag = 0;\n for(j = 0; j<(n-i-1); j++)\n if(edgeList[j].cost > edgeList[j+1].cost){\n swapping(edgeList[j], edgeList[j+1]);\n flag = 1;\n }\n }\n}\nvoid kruskal(Tree &tr){\n int ecount, maxEdge = V*(V-1)/2; //max n(n-1)/2 edges can have in a graph\n edge edgeList[maxEdge], ed;\n int uloc, vloc;\n VSet VSetArray[V];\n ecount = findEdge(edgeList);\n for(int i = 0; i < V; i++)\n VSetArray[i].addVertex(i);//each set contains one element\n sortEdge(edgeList, ecount); //ecount number of edges in the graph\n int count = 0;\n while(count <= V-1){\n ed = edgeList[count];\n uloc = findVertex(VSetArray, ed.u);\n vloc = findVertex(VSetArray, ed.v);\n if(uloc != vloc){ //check whether source abd dest is in same set or not\n merge(VSetArray[uloc], VSetArray[vloc]);\n tr.addEdge(ed);\n }\n count++;\n }\n}\nint main(){\n Tree tr;\n kruskal(tr);\n tr.printEdges();\n}" }, { "code": null, "e": 6256, "s": 6103, "text": "Edge: B--A And Cost: 1\nEdge: E--B And Cost: 2\nEdge: F--E And Cost: 2\nEdge: C--A And Cost: 3\nEdge: G--F And Cost: 3\nEdge: D--A And Cost: 4\nTotal Cost: 15" } ]
PERT Estimation Technique
Before any activity begins related to the work of a project, every project requires an advanced, accurate time estimate. Without an accurate estimate, no project can be completed within the budget and the target completion date. Developing an estimate is a complex task. If the project is large and has many stakeholders, things can be more complex. Therefore, there have been many initiatives to come up with different techniques for estimation phase of the project in order to make the estimation more accurate. PERT (Program Evaluation and Review Technique) is one of the successful and proven methods among the many other techniques, such as, CPM, Function Point Counting, Top-Down Estimating, WAVE, etc. PERT was initially created by the US Navy in the late 1950s. The pilot project was for developing Ballistic Missiles and there have been thousands of contractors involved. After PERT methodology was employed for this project, it actually ended two years ahead of its initial schedule. At the core, PERT is all about management probabilities. Therefore, PERT involves in many simple statistical methods as well. Sometimes, people categorize and put PERT and CPM together. Although CPM (Critical Path Method) shares some characteristics with PERT, PERT has a different focus. Same as most of other estimation techniques, PERT also breaks down the tasks into detailed activities. Then, a Gantt chart will be prepared illustrating the interdependencies among the activities. Then, a network of activities and their interdependencies are drawn in an illustrative manner. In this map, a node represents each event. The activities are represented as arrows and they are drawn from one event to another, based on the sequence. Next, the Earliest Time (TE) and the Latest Time (TL) are figured for each activity and identify the slack time for each activity. When it comes to deriving the estimates, the PERT model takes a statistical route to do that. We will cover more on this in the next two sections. Following is an example PERT chart: There are three estimation times involved in PERT; Optimistic Time Estimate (TOPT), Most Likely Time Estimate (TLIKELY), and Pessimistic Time Estimate (TPESS). In PERT, these three estimate times are derived for each activity. This way, a range of time is given for each activity with the most probable value, TLIKELY. Following are further details on each estimate: This is the fastest time an activity can be completed. For this, the assumption is made that all the necessary resources are available and all predecessor activities are completed as planned. Most of the times, project managers are asked only to submit one estimate. In that case, this is the estimate that goes to the upper management. This is the maximum time required to complete an activity. In this case, it is assumed that many things go wrong related to the activity. A lot of rework and resource unavailability are assumed when this estimation is derived. BETA probability distribution is what works behind PERT. The expected completion time (E) is calculated as below: E = (TOPT + 4 x TLIEKLY + TPESS) / 6 At the same time, the possible variance (V) of the estimate is calculated as below: V = (TPESS - TOPT)^2 / 6^2 Now, following is the process we follow with the two values: For every activity in the critical path, E and V are calculated. For every activity in the critical path, E and V are calculated. Then, the total of all Es are taken. This is the overall expected completion time for the project. Then, the total of all Es are taken. This is the overall expected completion time for the project. Now, the corresponding V is added to each activity of the critical path. This is the variance for the entire project. This is done only for the activities in the critical path as only the critical path activities can accelerate or delay the project duration. Now, the corresponding V is added to each activity of the critical path. This is the variance for the entire project. This is done only for the activities in the critical path as only the critical path activities can accelerate or delay the project duration. Then, standard deviation of the project is calculated. This equals to the square root of the variance (V). Then, standard deviation of the project is calculated. This equals to the square root of the variance (V). Now, the normal probability distribution is used for calculating the project completion time with the desired probability. Now, the normal probability distribution is used for calculating the project completion time with the desired probability. The best thing about PERT is its ability to integrate the uncertainty in project times estimations into its methodology. It also makes use of many assumption that can accelerate or delay the project progress. Using PERT, project managers can have an idea of the possible time variation for the deliveries and offer delivery dates to the client in a safer manner. 20 Lectures 3.5 hours Richa Maheshwari 15 Lectures 1 hours Ajay 15 Lectures 1 hours Ajay 12 Lectures 2 hours Richa Maheshwari 12 Lectures 1.5 hours Richa Maheshwari 15 Lectures 1 hours Ajay Print Add Notes Bookmark this page
[ { "code": null, "e": 3911, "s": 3682, "text": "Before any activity begins related to the work of a project, every project requires an advanced, accurate time estimate. Without an accurate estimate, no project can be completed within the budget and the target completion date." }, { "code": null, "e": 4032, "s": 3911, "text": "Developing an estimate is a complex task. If the project is large and has many stakeholders, things can be more complex." }, { "code": null, "e": 4196, "s": 4032, "text": "Therefore, there have been many initiatives to come up with different techniques for estimation phase of the project in order to make the estimation more accurate." }, { "code": null, "e": 4391, "s": 4196, "text": "PERT (Program Evaluation and Review Technique) is one of the successful and proven methods among the many other techniques, such as, CPM, Function Point Counting, Top-Down Estimating, WAVE, etc." }, { "code": null, "e": 4563, "s": 4391, "text": "PERT was initially created by the US Navy in the late 1950s. The pilot project was for developing Ballistic Missiles and there have been thousands of contractors involved." }, { "code": null, "e": 4676, "s": 4563, "text": "After PERT methodology was employed for this project, it actually ended two years ahead of its initial schedule." }, { "code": null, "e": 4802, "s": 4676, "text": "At the core, PERT is all about management probabilities. Therefore, PERT involves in many simple statistical methods as well." }, { "code": null, "e": 4965, "s": 4802, "text": "Sometimes, people categorize and put PERT and CPM together. Although CPM (Critical Path Method) shares some characteristics with PERT, PERT has a different focus." }, { "code": null, "e": 5068, "s": 4965, "text": "Same as most of other estimation techniques, PERT also breaks down the tasks into detailed activities." }, { "code": null, "e": 5257, "s": 5068, "text": "Then, a Gantt chart will be prepared illustrating the interdependencies among the activities. Then, a network of activities and their interdependencies are drawn in an illustrative manner." }, { "code": null, "e": 5410, "s": 5257, "text": "In this map, a node represents each event. The activities are represented as arrows and they are drawn from one event to another, based on the sequence." }, { "code": null, "e": 5541, "s": 5410, "text": "Next, the Earliest Time (TE) and the Latest Time (TL) are figured for each activity and identify the slack time for each activity." }, { "code": null, "e": 5688, "s": 5541, "text": "When it comes to deriving the estimates, the PERT model takes a statistical route to do that. We will cover more on this in the next two sections." }, { "code": null, "e": 5724, "s": 5688, "text": "Following is an example PERT chart:" }, { "code": null, "e": 5884, "s": 5724, "text": "There are three estimation times involved in PERT; Optimistic Time Estimate (TOPT), Most Likely Time Estimate (TLIKELY), and Pessimistic Time Estimate (TPESS)." }, { "code": null, "e": 6043, "s": 5884, "text": "In PERT, these three estimate times are derived for each activity. This way, a range of time is given for each activity with the most probable value, TLIKELY." }, { "code": null, "e": 6091, "s": 6043, "text": "Following are further details on each estimate:" }, { "code": null, "e": 6283, "s": 6091, "text": "This is the fastest time an activity can be completed. For this, the assumption is made that all the necessary resources are available and all predecessor activities are completed as planned." }, { "code": null, "e": 6428, "s": 6283, "text": "Most of the times, project managers are asked only to submit one estimate. In that case, this is the estimate that goes to the upper management." }, { "code": null, "e": 6655, "s": 6428, "text": "This is the maximum time required to complete an activity. In this case, it is assumed that many things go wrong related to the activity. A lot of rework and resource unavailability are assumed when this estimation is derived." }, { "code": null, "e": 6769, "s": 6655, "text": "BETA probability distribution is what works behind PERT. The expected completion time (E) is calculated as below:" }, { "code": null, "e": 6806, "s": 6769, "text": "E = (TOPT + 4 x TLIEKLY + TPESS) / 6" }, { "code": null, "e": 6890, "s": 6806, "text": "At the same time, the possible variance (V) of the estimate is calculated as below:" }, { "code": null, "e": 6917, "s": 6890, "text": "V = (TPESS - TOPT)^2 / 6^2" }, { "code": null, "e": 6978, "s": 6917, "text": "Now, following is the process we follow with the two values:" }, { "code": null, "e": 7043, "s": 6978, "text": "For every activity in the critical path, E and V are calculated." }, { "code": null, "e": 7108, "s": 7043, "text": "For every activity in the critical path, E and V are calculated." }, { "code": null, "e": 7207, "s": 7108, "text": "Then, the total of all Es are taken. This is the overall expected completion time for the project." }, { "code": null, "e": 7306, "s": 7207, "text": "Then, the total of all Es are taken. This is the overall expected completion time for the project." }, { "code": null, "e": 7565, "s": 7306, "text": "Now, the corresponding V is added to each activity of the critical path. This is the variance for the entire project. This is done only for the activities in the critical path as only the critical path activities can accelerate or delay the project duration." }, { "code": null, "e": 7824, "s": 7565, "text": "Now, the corresponding V is added to each activity of the critical path. This is the variance for the entire project. This is done only for the activities in the critical path as only the critical path activities can accelerate or delay the project duration." }, { "code": null, "e": 7931, "s": 7824, "text": "Then, standard deviation of the project is calculated. This equals to the square root of the variance (V)." }, { "code": null, "e": 8038, "s": 7931, "text": "Then, standard deviation of the project is calculated. This equals to the square root of the variance (V)." }, { "code": null, "e": 8161, "s": 8038, "text": "Now, the normal probability distribution is used for calculating the project completion time with the desired probability." }, { "code": null, "e": 8284, "s": 8161, "text": "Now, the normal probability distribution is used for calculating the project completion time with the desired probability." }, { "code": null, "e": 8405, "s": 8284, "text": "The best thing about PERT is its ability to integrate the uncertainty in project times estimations into its methodology." }, { "code": null, "e": 8647, "s": 8405, "text": "It also makes use of many assumption that can accelerate or delay the project progress. Using PERT, project managers can have an idea of the possible time variation for the deliveries and offer delivery dates to the client in a safer manner." }, { "code": null, "e": 8682, "s": 8647, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8700, "s": 8682, "text": " Richa Maheshwari" }, { "code": null, "e": 8733, "s": 8700, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 8739, "s": 8733, "text": " Ajay" }, { "code": null, "e": 8772, "s": 8739, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 8778, "s": 8772, "text": " Ajay" }, { "code": null, "e": 8811, "s": 8778, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 8829, "s": 8811, "text": " Richa Maheshwari" }, { "code": null, "e": 8864, "s": 8829, "text": "\n 12 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8882, "s": 8864, "text": " Richa Maheshwari" }, { "code": null, "e": 8915, "s": 8882, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 8921, "s": 8915, "text": " Ajay" }, { "code": null, "e": 8928, "s": 8921, "text": " Print" }, { "code": null, "e": 8939, "s": 8928, "text": " Add Notes" } ]
Data Conversion Using valueOf() method in Java - GeeksforGeeks
30 Mar, 2021 The valueOf() method converts data from its internal form into a human-readable form. It is static method that is overloaded within string for all of Java’s build-in types, so that each type can be converted properly into a string. It is called when a string representation of some other type data is needed-for example during concatenation operation.you can call this method with any data type and get a reasonable String representation valueOf() returns java.lang.Integer, which is the object representative of the integer Few forms of valueOf() : static String valueOf(int num) static String valueOf(float num) static String valueOf(boolean sta) static String valueOf(double num) static String valueOf(char[] data, int offset, int count) static String valueOf(long num) static String valueOf(Object ob) static String valueOf(char chars[]) Returns: It returns string representation of given value valueOf(iNum); // Returns the string representation of int iNum. String.valueOf(sta); // Returns the string representation of the boolean argument. String.valueOf(fNum); // Returns the string representation of the float fnum. String.valueOf(data, 0, 15); // Returns the string representation of a specific subarray of the chararray argument. String.valueOf(data, 0, 5); // Returns the string of charArray 0 to 5 String.valueOf(data, 7, 9); // Returns the string of charArray starting index 7 and total count from 7 is 9 Example 1: Input : 30 // concatenating integer value with a String Output: 3091 Input : 4.56589 // concatenating float value with a String Output: 914.56589 Java // Java program to demonstrate// working of valueOf() methodsclass ValueOfExa { public static void main(String arg[]) { int iNum = 30; double fNum = 4.56789; String s = "91"; // Returns the string representation of int iNum. String sample = String.valueOf(iNum); System.out.println(sample); // concatenating string with iNum System.out.println(sample + s); // Returns the string representation of the float // fnum. sample = String.valueOf(fNum); System.out.println(sample); // concatenating string with fNum System.out.println(s + sample); }} 30 3091 4.56789 914.56789 Example 2: Java // Java program to demonstrate// working of valueOf() methodsclass ValueOfExa { public static void main(String arg[]) { char[] data = { 'G', 'E', 'E', 'K', 'S', ' ', 'F', 'O', 'R', ' ', 'G', 'E', 'E', 'K', 'S' }; String sample; // Returns the string representation // of a specific subarray of the chararray argument sample = String.valueOf(data, 0, 15); System.out.println(sample); // Returns the string of charArray 0 to 5 sample = String.valueOf(data, 0, 5); System.out.println(sample); // Returns the string of charArray starting // index 6 and total count from 6 is 8 sample = String.valueOf(data, 6, 8); System.out.println(sample); }} GEEKS FOR GEEKS GEEKS FOR GEEK Example 3: Input :Geeks for Geeks // check if String value contains a // specific string by method contains("Geeks"); Output:true Java // The following example shows the// usage of <strong>valueOf(boolean sta)</strong method.public class StringValueOfBoolean { public static void main(String[] args) { // declare a String String data = "Geeks for Geeks"; // check if String value contains a specific string boolean bool = data.contains("Geeks"); // print the string equivalent of our boolean check System.out.println(String.valueOf(bool)); }} true Difference between parseInt and valueOf in java The API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int. shaileshpalkumar5 yogeshchanekar9552 Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java Set in Java Overriding in Java LinkedList in Java
[ { "code": null, "e": 24530, "s": 24502, "text": "\n30 Mar, 2021" }, { "code": null, "e": 24763, "s": 24530, "text": "The valueOf() method converts data from its internal form into a human-readable form. It is static method that is overloaded within string for all of Java’s build-in types, so that each type can be converted properly into a string. " }, { "code": null, "e": 25082, "s": 24763, "text": "It is called when a string representation of some other type data is needed-for example during concatenation operation.you can call this method with any data type and get a reasonable String representation valueOf() returns java.lang.Integer, which is the object representative of the integer Few forms of valueOf() : " }, { "code": null, "e": 25374, "s": 25082, "text": "static String valueOf(int num)\nstatic String valueOf(float num)\nstatic String valueOf(boolean sta)\nstatic String valueOf(double num)\nstatic String valueOf(char[] data, int offset, int count)\nstatic String valueOf(long num)\nstatic String valueOf(Object ob)\nstatic String valueOf(char chars[])" }, { "code": null, "e": 25385, "s": 25374, "text": "Returns: " }, { "code": null, "e": 25433, "s": 25385, "text": "It returns string representation of given value" }, { "code": null, "e": 25498, "s": 25433, "text": "valueOf(iNum); // Returns the string representation of int iNum." }, { "code": null, "e": 25581, "s": 25498, "text": "String.valueOf(sta); // Returns the string representation of the boolean argument." }, { "code": null, "e": 25659, "s": 25581, "text": "String.valueOf(fNum); // Returns the string representation of the float fnum." }, { "code": null, "e": 25775, "s": 25659, "text": "String.valueOf(data, 0, 15); // Returns the string representation of a specific subarray of the chararray argument." }, { "code": null, "e": 25845, "s": 25775, "text": "String.valueOf(data, 0, 5); // Returns the string of charArray 0 to 5" }, { "code": null, "e": 25953, "s": 25845, "text": "String.valueOf(data, 7, 9); // Returns the string of charArray starting index 7 and total count from 7 is 9" }, { "code": null, "e": 25964, "s": 25953, "text": "Example 1:" }, { "code": null, "e": 26116, "s": 25964, "text": "Input : 30\n// concatenating integer value with a String \nOutput: 3091\n\nInput : 4.56589\n// concatenating float value with a String \nOutput: 914.56589 " }, { "code": null, "e": 26121, "s": 26116, "text": "Java" }, { "code": "// Java program to demonstrate// working of valueOf() methodsclass ValueOfExa { public static void main(String arg[]) { int iNum = 30; double fNum = 4.56789; String s = \"91\"; // Returns the string representation of int iNum. String sample = String.valueOf(iNum); System.out.println(sample); // concatenating string with iNum System.out.println(sample + s); // Returns the string representation of the float // fnum. sample = String.valueOf(fNum); System.out.println(sample); // concatenating string with fNum System.out.println(s + sample); }}", "e": 26778, "s": 26121, "text": null }, { "code": null, "e": 26805, "s": 26778, "text": "30\n3091\n4.56789\n914.56789\n" }, { "code": null, "e": 26817, "s": 26805, "text": "Example 2: " }, { "code": null, "e": 26822, "s": 26817, "text": "Java" }, { "code": "// Java program to demonstrate// working of valueOf() methodsclass ValueOfExa { public static void main(String arg[]) { char[] data = { 'G', 'E', 'E', 'K', 'S', ' ', 'F', 'O', 'R', ' ', 'G', 'E', 'E', 'K', 'S' }; String sample; // Returns the string representation // of a specific subarray of the chararray argument sample = String.valueOf(data, 0, 15); System.out.println(sample); // Returns the string of charArray 0 to 5 sample = String.valueOf(data, 0, 5); System.out.println(sample); // Returns the string of charArray starting // index 6 and total count from 6 is 8 sample = String.valueOf(data, 6, 8); System.out.println(sample); }}", "e": 27595, "s": 26822, "text": null }, { "code": null, "e": 27627, "s": 27595, "text": "GEEKS FOR GEEKS\nGEEKS\nFOR GEEK\n" }, { "code": null, "e": 27638, "s": 27627, "text": "Example 3:" }, { "code": null, "e": 27758, "s": 27638, "text": "Input :Geeks for Geeks\n// check if String value contains a \n// specific string by method contains(\"Geeks\");\nOutput:true" }, { "code": null, "e": 27763, "s": 27758, "text": "Java" }, { "code": "// The following example shows the// usage of <strong>valueOf(boolean sta)</strong method.public class StringValueOfBoolean { public static void main(String[] args) { // declare a String String data = \"Geeks for Geeks\"; // check if String value contains a specific string boolean bool = data.contains(\"Geeks\"); // print the string equivalent of our boolean check System.out.println(String.valueOf(bool)); }}", "e": 28224, "s": 27763, "text": null }, { "code": null, "e": 28230, "s": 28224, "text": "true\n" }, { "code": null, "e": 28278, "s": 28230, "text": "Difference between parseInt and valueOf in java" }, { "code": null, "e": 28525, "s": 28278, "text": "The API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int. " }, { "code": null, "e": 28543, "s": 28525, "text": "shaileshpalkumar5" }, { "code": null, "e": 28562, "s": 28543, "text": "yogeshchanekar9552" }, { "code": null, "e": 28575, "s": 28562, "text": "Java-Strings" }, { "code": null, "e": 28580, "s": 28575, "text": "Java" }, { "code": null, "e": 28593, "s": 28580, "text": "Java-Strings" }, { "code": null, "e": 28598, "s": 28593, "text": "Java" }, { "code": null, "e": 28696, "s": 28598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28728, "s": 28696, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28747, "s": 28728, "text": "Interfaces in Java" }, { "code": null, "e": 28765, "s": 28747, "text": "ArrayList in Java" }, { "code": null, "e": 28797, "s": 28765, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28817, "s": 28797, "text": "Stack Class in Java" }, { "code": null, "e": 28832, "s": 28817, "text": "Stream In Java" }, { "code": null, "e": 28856, "s": 28832, "text": "Singleton Class in Java" }, { "code": null, "e": 28868, "s": 28856, "text": "Set in Java" }, { "code": null, "e": 28887, "s": 28868, "text": "Overriding in Java" } ]
How to use Boto3 to get a list of all secrets in AWS Secret Manager
Problem Statement: Use boto3 library in Python to get a list of all secrets in AWS Secret Manager Step 1: Import boto3 and botocore exceptions to handle exceptions. Step 1: Import boto3 and botocore exceptions to handle exceptions. Step 2: There are no parameters here. Step 2: There are no parameters here. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 4: Create an AWS client for secretmanager. Step 4: Create an AWS client for secretmanager. Step 5: Call list_secrets function to retrieve all secrets. Step 5: Call list_secrets function to retrieve all secrets. Step 6: It returns the metadata of all secrets. Step 6: It returns the metadata of all secrets. Step 7: Handle the generic exception if something went wrong while getting details of all secrets. Step 7: Handle the generic exception if something went wrong while getting details of all secrets. Use the following code to get the list of all secrets in AWS Secret Manager − import boto3 from botocore.exceptions import ClientError def get_all_secrets(): session = boto3.session.Session() s3_client = session.client('secretmanager') try: response = s3_client.list_secrets() return response except ClientError as e: raise Exception("boto3 client error in get_all_secrets: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in get_all_secrets: " + e.__str__()) a = get_all_secrets() for details in a['SecretList']: print(details['Name']) tests/secrets tests/aws/secrets tests/aws/users
[ { "code": null, "e": 1160, "s": 1062, "text": "Problem Statement: Use boto3 library in Python to get a list of all secrets in AWS Secret Manager" }, { "code": null, "e": 1227, "s": 1160, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1294, "s": 1227, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1332, "s": 1294, "text": "Step 2: There are no parameters here." }, { "code": null, "e": 1370, "s": 1332, "text": "Step 2: There are no parameters here." }, { "code": null, "e": 1565, "s": 1370, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 1760, "s": 1565, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 1808, "s": 1760, "text": "Step 4: Create an AWS client for secretmanager." }, { "code": null, "e": 1856, "s": 1808, "text": "Step 4: Create an AWS client for secretmanager." }, { "code": null, "e": 1916, "s": 1856, "text": "Step 5: Call list_secrets function to retrieve all secrets." }, { "code": null, "e": 1976, "s": 1916, "text": "Step 5: Call list_secrets function to retrieve all secrets." }, { "code": null, "e": 2024, "s": 1976, "text": "Step 6: It returns the metadata of all secrets." }, { "code": null, "e": 2072, "s": 2024, "text": "Step 6: It returns the metadata of all secrets." }, { "code": null, "e": 2171, "s": 2072, "text": "Step 7: Handle the generic exception if something went wrong while getting details of all secrets." }, { "code": null, "e": 2270, "s": 2171, "text": "Step 7: Handle the generic exception if something went wrong while getting details of all secrets." }, { "code": null, "e": 2348, "s": 2270, "text": "Use the following code to get the list of all secrets in AWS Secret Manager −" }, { "code": null, "e": 2867, "s": 2348, "text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef get_all_secrets():\n session = boto3.session.Session()\n s3_client = session.client('secretmanager')\n try:\n response = s3_client.list_secrets()\n return response\n except ClientError as e:\n raise Exception(\"boto3 client error in get_all_secrets: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in get_all_secrets: \" + e.__str__())\n\na = get_all_secrets()\nfor details in a['SecretList']:\nprint(details['Name'])" }, { "code": null, "e": 2915, "s": 2867, "text": "tests/secrets\ntests/aws/secrets\ntests/aws/users" } ]
Intellij Idea - Profiling
Profiler gives insights about your application like its CPU, memory and heap usage. It also gives details about the application threads. This chapter discusses the usage of VisualVM tool for Java application profiling. It can profile entities such as CPU and heap. It is recommended that the readers of this tutorial are familiar with the application profiler concepts. VisualVM is a visual tool that integrates JDK tools and gives you powerful profiling capabilities. It allows you to generate and analyze heap data, track down memory leaks,monitor the garbage collector and perform memory and CPU profiling. Visual interface for local and remote Java applications running on JVM. Visual interface for local and remote Java applications running on JVM. Monitoring of application’s memory usage and application’s runtime behavior. Monitoring of application’s memory usage and application’s runtime behavior. Monitoring of application threads Monitoring of application threads Analyzing the memory allocations to different applications. Analyzing the memory allocations to different applications. Thread dumps − very handy in case of deadlocks and race conditions. Thread dumps − very handy in case of deadlocks and race conditions. Heap dumps − very handy in analyzing the heap memory allocation. Heap dumps − very handy in analyzing the heap memory allocation. In this section, we will learn the steps performed to configure VisualVM. The steps are as follow − Download it from here. Download it from here. Extract the zip file. Extract the zip file. Navigate to etc/visualvm.conf file and add the following line in this file − Navigate to etc/visualvm.conf file and add the following line in this file − visualvm_jdkhome=<path of JDK> If your JDK is installed in the C:\Program Files\Java\jdk-9.0.1 directory then it should look like this − If your JDK is installed in the C:\Program Files\Java\jdk-9.0.1 directory then it should look like this − visualvm_jdkhome="C:\Program Files\Java\jdk-9.0.1" Let us now see how to monitor the application. Consider the following steps to understand the same − Double-click on the visualvm.exe file. Select the application from left pane. Select the monitor tab. You will be directed to a window where you will get the details about CPU, Heap, Classes and threads. To be specific with the usage, hover the mouse over any graph. We can see the usage of Heap in the above screenshot. Java application can contain multiple threads of execution. To know more about threads, select the Threads tab of a particular application. It will give various statistics about threads like number of live threads and daemon threads. The different thread states are Running, Sleeping, Waiting, Park and Monitor. VisualVM supports CPU, memory sampling and memory leak detection. To sample application, select application and choose the sample tab − For CPU sampling, click on the CPU button as show in the following screenshot − For memory profiling, click on the Memory button as shown in the following screenshot − A memory leak occurs when an application, while running, slowly fills up the heap with objects that are not automatically deleted by the program. If an object that is not used by the program is not deleted, then it remains in memory and the GC cannot reclaim its space. If the number of bytes and number of instances in your application were to increase constantly and significantly in your program to the point of using up all the space, this can be an indication of a memory leak. In this section, we will learn how to profile an application. To profile an application, select application from left pane and click the profile tab − To perform CPU profiling, click on the CPU button as shown in the screenshot below − To perform CPU profiling, click on the CPU button as shown in the screenshot below − Print Add Notes Bookmark this page
[ { "code": null, "e": 2354, "s": 2089, "text": "Profiler gives insights about your application like its CPU, memory and heap usage. It also\ngives details about the application threads. This chapter discusses the usage of VisualVM\ntool for Java application profiling. It can profile entities such as CPU and heap." }, { "code": null, "e": 2459, "s": 2354, "text": "It is recommended that the readers of this tutorial are familiar with the application profiler\nconcepts." }, { "code": null, "e": 2699, "s": 2459, "text": "VisualVM is a visual tool that integrates JDK tools and gives you powerful profiling\ncapabilities. It allows you to generate and analyze heap data, track down memory leaks,monitor the garbage collector and perform memory and CPU profiling." }, { "code": null, "e": 2771, "s": 2699, "text": "Visual interface for local and remote Java applications running on JVM." }, { "code": null, "e": 2843, "s": 2771, "text": "Visual interface for local and remote Java applications running on JVM." }, { "code": null, "e": 2920, "s": 2843, "text": "Monitoring of application’s memory usage and application’s runtime behavior." }, { "code": null, "e": 2997, "s": 2920, "text": "Monitoring of application’s memory usage and application’s runtime behavior." }, { "code": null, "e": 3031, "s": 2997, "text": "Monitoring of application threads" }, { "code": null, "e": 3065, "s": 3031, "text": "Monitoring of application threads" }, { "code": null, "e": 3125, "s": 3065, "text": "Analyzing the memory allocations to different applications." }, { "code": null, "e": 3185, "s": 3125, "text": "Analyzing the memory allocations to different applications." }, { "code": null, "e": 3253, "s": 3185, "text": "Thread dumps − very handy in case of deadlocks and race conditions." }, { "code": null, "e": 3321, "s": 3253, "text": "Thread dumps − very handy in case of deadlocks and race conditions." }, { "code": null, "e": 3386, "s": 3321, "text": "Heap dumps − very handy in analyzing the heap memory allocation." }, { "code": null, "e": 3451, "s": 3386, "text": "Heap dumps − very handy in analyzing the heap memory allocation." }, { "code": null, "e": 3551, "s": 3451, "text": "In this section, we will learn the steps performed to configure VisualVM. The steps are as\nfollow −" }, { "code": null, "e": 3574, "s": 3551, "text": "Download it from here." }, { "code": null, "e": 3597, "s": 3574, "text": "Download it from here." }, { "code": null, "e": 3619, "s": 3597, "text": "Extract the zip file." }, { "code": null, "e": 3641, "s": 3619, "text": "Extract the zip file." }, { "code": null, "e": 3718, "s": 3641, "text": "Navigate to etc/visualvm.conf file and add the following line in this file −" }, { "code": null, "e": 3795, "s": 3718, "text": "Navigate to etc/visualvm.conf file and add the following line in this file −" }, { "code": null, "e": 3827, "s": 3795, "text": "visualvm_jdkhome=<path of JDK>\n" }, { "code": null, "e": 3933, "s": 3827, "text": "If your JDK is installed in the C:\\Program Files\\Java\\jdk-9.0.1 directory then\nit should look like this −" }, { "code": null, "e": 4039, "s": 3933, "text": "If your JDK is installed in the C:\\Program Files\\Java\\jdk-9.0.1 directory then\nit should look like this −" }, { "code": null, "e": 4091, "s": 4039, "text": "visualvm_jdkhome=\"C:\\Program Files\\Java\\jdk-9.0.1\"\n" }, { "code": null, "e": 4192, "s": 4091, "text": "Let us now see how to monitor the application. Consider the following steps to understand\nthe same −" }, { "code": null, "e": 4231, "s": 4192, "text": "Double-click on the visualvm.exe file." }, { "code": null, "e": 4270, "s": 4231, "text": "Select the application from left pane." }, { "code": null, "e": 4294, "s": 4270, "text": "Select the monitor tab." }, { "code": null, "e": 4513, "s": 4294, "text": "You will be directed to a window where you will get the details about CPU, Heap, Classes\nand threads. To be specific with the usage, hover the mouse over any graph. We can see\nthe usage of Heap in the above screenshot." }, { "code": null, "e": 4825, "s": 4513, "text": "Java application can contain multiple threads of execution. To know more about threads,\nselect the Threads tab of a particular application. It will give various statistics about\nthreads like number of live threads and daemon threads. The different thread states are\nRunning, Sleeping, Waiting, Park and Monitor." }, { "code": null, "e": 4961, "s": 4825, "text": "VisualVM supports CPU, memory sampling and memory leak detection. To sample application, select application and choose the sample tab −" }, { "code": null, "e": 5041, "s": 4961, "text": "For CPU sampling, click on the CPU button as show in the following screenshot −" }, { "code": null, "e": 5129, "s": 5041, "text": "For memory profiling, click on the Memory button as shown in the following screenshot −" }, { "code": null, "e": 5275, "s": 5129, "text": "A memory leak occurs when an application, while running, slowly fills up the heap with\nobjects that are not automatically deleted by the program." }, { "code": null, "e": 5612, "s": 5275, "text": "If an object that is not used by the program is not deleted, then it remains in memory and\nthe GC cannot reclaim its space. If the number of bytes and number of instances in your\napplication were to increase constantly and significantly in your program to the point of\nusing up all the space, this can be an indication of a memory leak." }, { "code": null, "e": 5763, "s": 5612, "text": "In this section, we will learn how to profile an application. To profile an application, select application from left pane and click the profile tab −" }, { "code": null, "e": 5848, "s": 5763, "text": "To perform CPU profiling, click on the CPU button as shown in the screenshot below −" }, { "code": null, "e": 5933, "s": 5848, "text": "To perform CPU profiling, click on the CPU button as shown in the screenshot below −" }, { "code": null, "e": 5940, "s": 5933, "text": " Print" }, { "code": null, "e": 5951, "s": 5940, "text": " Add Notes" } ]
Java.util.IntSummaryStatistics class with Examples - GeeksforGeeks
24 Jun, 2019 The IntSummaryStatistics class is present in java.util package. It takes a collection of Integer objects and is useful in the circumstances when we are dealing with a stream of integers. It maintains a count of the number of integers it has processed, their sum and various other statistics. The class can also be used with Streams. It is useful in the sense that it maintains a running sum, average, etc. of the integers and hence can be used in the manipulation of statistical data. Class Hierarchy java.lang.Object ↳ java.util.IntSummaryStatistics Constructors IntSummaryStatistics(): A default constructor which initializes the count and sum to zero, and sets max to Integer.MIN_VALUE and min to Integer.MAX_VALUE.Syntax:public IntSummaryStatistics() IntSummaryStatistics(count, min, max, sum): Initializes the various data members with the parameters passed during invocation.Syntax:public IntSummaryStatistics(long count, int min, int max, long sum) throws IllegalArgumentException IntSummaryStatistics(): A default constructor which initializes the count and sum to zero, and sets max to Integer.MIN_VALUE and min to Integer.MAX_VALUE.Syntax:public IntSummaryStatistics() Syntax: public IntSummaryStatistics() IntSummaryStatistics(count, min, max, sum): Initializes the various data members with the parameters passed during invocation.Syntax:public IntSummaryStatistics(long count, int min, int max, long sum) throws IllegalArgumentException Syntax: public IntSummaryStatistics(long count, int min, int max, long sum) throws IllegalArgumentException Methods: accept() – This function adds the passed integer into the statistical data.Syntax:public void accept(int value) combine(): This function combines the statistical data of the passed IntSummaryStatistics object with the current statistical data.Syntax:public void combine(IntSummaryStatistics other) getCount(): This method returns the count of the number of integers processed.Syntax:public final long getCount() getSum(): This method returns the sum of all the integers processed.Syntax:public final long getSum() getAverage(): This method returns the average of all the integers processed.Syntax:public final double getAverage() getMin(): This method returns the minimum integer of all the integers processed.Syntax:public final int getMin() getMax(): This method returns the maximum integer of all the integers processed.Syntax:public final int getMax() toString(): This method returns the string representation of all the statistical data contained in the object.Syntax:public String toString() Example To demonstrate IntSummaryStatistics in action.// Java program to demonstrate// IntSummaryStatistics class import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } // Use various methods to obtain the data System.out.println("The count of values is " + intSummaryStatistics.getCount()); System.out.println("The average of values is " + intSummaryStatistics.getAverage()); System.out.println("The sum of values is " + intSummaryStatistics.getSum()); System.out.println("The maximum of values is " + intSummaryStatistics.getMax()); System.out.println("The minimum of values is " + intSummaryStatistics.getMin()); System.out.println("The string representation is"); System.out.println(intSummaryStatistics.toString()); }}Output:The count of values is 5 The average of values is 30.0 The sum of values is 150 The maximum of values is 50 The minimum of values is 10 The string representation is IntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50} Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.htmlMy Personal Notes arrow_drop_upSave accept() – This function adds the passed integer into the statistical data.Syntax:public void accept(int value) Syntax: public void accept(int value) combine(): This function combines the statistical data of the passed IntSummaryStatistics object with the current statistical data.Syntax:public void combine(IntSummaryStatistics other) Syntax: public void combine(IntSummaryStatistics other) getCount(): This method returns the count of the number of integers processed.Syntax:public final long getCount() Syntax: public final long getCount() getSum(): This method returns the sum of all the integers processed.Syntax:public final long getSum() Syntax: public final long getSum() getAverage(): This method returns the average of all the integers processed.Syntax:public final double getAverage() Syntax: public final double getAverage() getMin(): This method returns the minimum integer of all the integers processed.Syntax:public final int getMin() Syntax: public final int getMin() getMax(): This method returns the maximum integer of all the integers processed.Syntax:public final int getMax() Syntax: public final int getMax() toString(): This method returns the string representation of all the statistical data contained in the object.Syntax:public String toString() Example To demonstrate IntSummaryStatistics in action.// Java program to demonstrate// IntSummaryStatistics class import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } // Use various methods to obtain the data System.out.println("The count of values is " + intSummaryStatistics.getCount()); System.out.println("The average of values is " + intSummaryStatistics.getAverage()); System.out.println("The sum of values is " + intSummaryStatistics.getSum()); System.out.println("The maximum of values is " + intSummaryStatistics.getMax()); System.out.println("The minimum of values is " + intSummaryStatistics.getMin()); System.out.println("The string representation is"); System.out.println(intSummaryStatistics.toString()); }}Output:The count of values is 5 The average of values is 30.0 The sum of values is 150 The maximum of values is 50 The minimum of values is 10 The string representation is IntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50} Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.htmlMy Personal Notes arrow_drop_upSave Syntax: public String toString() Example To demonstrate IntSummaryStatistics in action. // Java program to demonstrate// IntSummaryStatistics class import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } // Use various methods to obtain the data System.out.println("The count of values is " + intSummaryStatistics.getCount()); System.out.println("The average of values is " + intSummaryStatistics.getAverage()); System.out.println("The sum of values is " + intSummaryStatistics.getSum()); System.out.println("The maximum of values is " + intSummaryStatistics.getMax()); System.out.println("The minimum of values is " + intSummaryStatistics.getMin()); System.out.println("The string representation is"); System.out.println(intSummaryStatistics.toString()); }} The count of values is 5 The average of values is 30.0 The sum of values is 150 The maximum of values is 50 The minimum of values is 10 The string representation is IntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50} Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.html Java - util package Java-Classes Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n24 Jun, 2019" }, { "code": null, "e": 24281, "s": 23948, "text": "The IntSummaryStatistics class is present in java.util package. It takes a collection of Integer objects and is useful in the circumstances when we are dealing with a stream of integers. It maintains a count of the number of integers it has processed, their sum and various other statistics. The class can also be used with Streams." }, { "code": null, "e": 24433, "s": 24281, "text": "It is useful in the sense that it maintains a running sum, average, etc. of the integers and hence can be used in the manipulation of statistical data." }, { "code": null, "e": 24449, "s": 24433, "text": "Class Hierarchy" }, { "code": null, "e": 24500, "s": 24449, "text": "java.lang.Object\n↳ java.util.IntSummaryStatistics\n" }, { "code": null, "e": 24513, "s": 24500, "text": "Constructors" }, { "code": null, "e": 24959, "s": 24513, "text": "IntSummaryStatistics(): A default constructor which initializes the count and sum to zero, and sets max to Integer.MIN_VALUE and min to Integer.MAX_VALUE.Syntax:public IntSummaryStatistics()\nIntSummaryStatistics(count, min, max, sum): Initializes the various data members with the parameters passed during invocation.Syntax:public IntSummaryStatistics(long count, int min, int max, long sum)\n throws IllegalArgumentException\n" }, { "code": null, "e": 25151, "s": 24959, "text": "IntSummaryStatistics(): A default constructor which initializes the count and sum to zero, and sets max to Integer.MIN_VALUE and min to Integer.MAX_VALUE.Syntax:public IntSummaryStatistics()\n" }, { "code": null, "e": 25159, "s": 25151, "text": "Syntax:" }, { "code": null, "e": 25190, "s": 25159, "text": "public IntSummaryStatistics()\n" }, { "code": null, "e": 25445, "s": 25190, "text": "IntSummaryStatistics(count, min, max, sum): Initializes the various data members with the parameters passed during invocation.Syntax:public IntSummaryStatistics(long count, int min, int max, long sum)\n throws IllegalArgumentException\n" }, { "code": null, "e": 25453, "s": 25445, "text": "Syntax:" }, { "code": null, "e": 25575, "s": 25453, "text": "public IntSummaryStatistics(long count, int min, int max, long sum)\n throws IllegalArgumentException\n" }, { "code": null, "e": 25584, "s": 25575, "text": "Methods:" }, { "code": null, "e": 28316, "s": 25584, "text": "accept() – This function adds the passed integer into the statistical data.Syntax:public void accept(int value)\ncombine(): This function combines the statistical data of the passed IntSummaryStatistics object with the current statistical data.Syntax:public void combine(IntSummaryStatistics other)\ngetCount(): This method returns the count of the number of integers processed.Syntax:public final long getCount()\ngetSum(): This method returns the sum of all the integers processed.Syntax:public final long getSum()\ngetAverage(): This method returns the average of all the integers processed.Syntax:public final double getAverage()\ngetMin(): This method returns the minimum integer of all the integers processed.Syntax:public final int getMin()\ngetMax(): This method returns the maximum integer of all the integers processed.Syntax:public final int getMax()\ntoString(): This method returns the string representation of all the statistical data contained in the object.Syntax:public String toString()\nExample To demonstrate IntSummaryStatistics in action.// Java program to demonstrate// IntSummaryStatistics class import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } // Use various methods to obtain the data System.out.println(\"The count of values is \" + intSummaryStatistics.getCount()); System.out.println(\"The average of values is \" + intSummaryStatistics.getAverage()); System.out.println(\"The sum of values is \" + intSummaryStatistics.getSum()); System.out.println(\"The maximum of values is \" + intSummaryStatistics.getMax()); System.out.println(\"The minimum of values is \" + intSummaryStatistics.getMin()); System.out.println(\"The string representation is\"); System.out.println(intSummaryStatistics.toString()); }}Output:The count of values is 5\nThe average of values is 30.0\nThe sum of values is 150\nThe maximum of values is 50\nThe minimum of values is 10\nThe string representation is\nIntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50}\nReference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28429, "s": 28316, "text": "accept() – This function adds the passed integer into the statistical data.Syntax:public void accept(int value)\n" }, { "code": null, "e": 28437, "s": 28429, "text": "Syntax:" }, { "code": null, "e": 28468, "s": 28437, "text": "public void accept(int value)\n" }, { "code": null, "e": 28655, "s": 28468, "text": "combine(): This function combines the statistical data of the passed IntSummaryStatistics object with the current statistical data.Syntax:public void combine(IntSummaryStatistics other)\n" }, { "code": null, "e": 28663, "s": 28655, "text": "Syntax:" }, { "code": null, "e": 28712, "s": 28663, "text": "public void combine(IntSummaryStatistics other)\n" }, { "code": null, "e": 28827, "s": 28712, "text": "getCount(): This method returns the count of the number of integers processed.Syntax:public final long getCount()\n" }, { "code": null, "e": 28835, "s": 28827, "text": "Syntax:" }, { "code": null, "e": 28865, "s": 28835, "text": "public final long getCount()\n" }, { "code": null, "e": 28968, "s": 28865, "text": "getSum(): This method returns the sum of all the integers processed.Syntax:public final long getSum()\n" }, { "code": null, "e": 28976, "s": 28968, "text": "Syntax:" }, { "code": null, "e": 29004, "s": 28976, "text": "public final long getSum()\n" }, { "code": null, "e": 29121, "s": 29004, "text": "getAverage(): This method returns the average of all the integers processed.Syntax:public final double getAverage()\n" }, { "code": null, "e": 29129, "s": 29121, "text": "Syntax:" }, { "code": null, "e": 29163, "s": 29129, "text": "public final double getAverage()\n" }, { "code": null, "e": 29277, "s": 29163, "text": "getMin(): This method returns the minimum integer of all the integers processed.Syntax:public final int getMin()\n" }, { "code": null, "e": 29285, "s": 29277, "text": "Syntax:" }, { "code": null, "e": 29312, "s": 29285, "text": "public final int getMin()\n" }, { "code": null, "e": 29426, "s": 29312, "text": "getMax(): This method returns the maximum integer of all the integers processed.Syntax:public final int getMax()\n" }, { "code": null, "e": 29434, "s": 29426, "text": "Syntax:" }, { "code": null, "e": 29461, "s": 29434, "text": "public final int getMax()\n" }, { "code": null, "e": 31337, "s": 29461, "text": "toString(): This method returns the string representation of all the statistical data contained in the object.Syntax:public String toString()\nExample To demonstrate IntSummaryStatistics in action.// Java program to demonstrate// IntSummaryStatistics class import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } // Use various methods to obtain the data System.out.println(\"The count of values is \" + intSummaryStatistics.getCount()); System.out.println(\"The average of values is \" + intSummaryStatistics.getAverage()); System.out.println(\"The sum of values is \" + intSummaryStatistics.getSum()); System.out.println(\"The maximum of values is \" + intSummaryStatistics.getMax()); System.out.println(\"The minimum of values is \" + intSummaryStatistics.getMin()); System.out.println(\"The string representation is\"); System.out.println(intSummaryStatistics.toString()); }}Output:The count of values is 5\nThe average of values is 30.0\nThe sum of values is 150\nThe maximum of values is 50\nThe minimum of values is 10\nThe string representation is\nIntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50}\nReference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31345, "s": 31337, "text": "Syntax:" }, { "code": null, "e": 31371, "s": 31345, "text": "public String toString()\n" }, { "code": null, "e": 31426, "s": 31371, "text": "Example To demonstrate IntSummaryStatistics in action." }, { "code": "// Java program to demonstrate// IntSummaryStatistics class import java.util.*; public class IntSummaryStatisticsDemo { public static void main(String[] args) { IntSummaryStatistics intSummaryStatistics = new IntSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the IntSummaryStatistics object intSummaryStatistics.accept(iterator.next()); } // Use various methods to obtain the data System.out.println(\"The count of values is \" + intSummaryStatistics.getCount()); System.out.println(\"The average of values is \" + intSummaryStatistics.getAverage()); System.out.println(\"The sum of values is \" + intSummaryStatistics.getSum()); System.out.println(\"The maximum of values is \" + intSummaryStatistics.getMax()); System.out.println(\"The minimum of values is \" + intSummaryStatistics.getMin()); System.out.println(\"The string representation is\"); System.out.println(intSummaryStatistics.toString()); }}", "e": 32736, "s": 31426, "text": null }, { "code": null, "e": 32976, "s": 32736, "text": "The count of values is 5\nThe average of values is 30.0\nThe sum of values is 150\nThe maximum of values is 50\nThe minimum of values is 10\nThe string representation is\nIntSummaryStatistics{count=5, sum=150, min=10, average=30.000000, max=50}\n" }, { "code": null, "e": 33066, "s": 32976, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.html" }, { "code": null, "e": 33086, "s": 33066, "text": "Java - util package" }, { "code": null, "e": 33099, "s": 33086, "text": "Java-Classes" }, { "code": null, "e": 33104, "s": 33099, "text": "Java" }, { "code": null, "e": 33109, "s": 33104, "text": "Java" }, { "code": null, "e": 33207, "s": 33109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33222, "s": 33207, "text": "Stream In Java" }, { "code": null, "e": 33268, "s": 33222, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 33289, "s": 33268, "text": "Constructors in Java" }, { "code": null, "e": 33308, "s": 33289, "text": "Exceptions in Java" }, { "code": null, "e": 33325, "s": 33308, "text": "Generics in Java" }, { "code": null, "e": 33355, "s": 33325, "text": "Functional Interfaces in Java" }, { "code": null, "e": 33398, "s": 33355, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 33427, "s": 33398, "text": "HashMap get() Method in Java" }, { "code": null, "e": 33448, "s": 33427, "text": "Introduction to Java" } ]
How To Adjust Position of Axis Labels in Matplotlib? - GeeksforGeeks
11 Dec, 2020 In this article, we will see how to adjust positions of the x-axis and y-axis labels in Matplotlib which is a library for plotting in python language. By default, these labels are placed in the middle, but we can alter these positions using the “loc” parameter in set_xlabel and set_ylabel function of matplotlib. Note: “loc” parameter is only available in Matplotlib version 3.3.0 onwards. Let’s understand with step wise: Step 1: First, let’s import all the required libraries. Python3 import matplotlib.pyplot as pltimport numpy as np Step 2: Now we will create fake data using the NumPy library. Here we are using the sample sub-module from the random module to create a dataset of random values. Python3 from random import sampledata = sample(range(1, 1000), 100) Step 3: Now we have created data let’s plot this data using the default options of matplotlib and then start experimenting with its positions. We can clearly see that these labels are in the center by default. The bins parameter tells you the number of bins that your data will be divided into. Matplotlib allows you to adjust the transparency of a graph plot using the alpha attribute. By default, alpha=1 Python3 fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel("X-Label" , fontsize = 16)ax.set_ylabel("Y-label" , fontsize = 16) Output: The default position of labels Here we will move the y-label to the bottom and x-label to the extreme right using the loc parameter. Python3 fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel("X-Label", fontsize = 16, loc = "right") ax.set_ylabel("Y-Label", fontsize = 16, loc = "bottom") Output: Y-label to the bottom and X-label to extreme right Let’s take another example here we will move the y-label to the top. Python3 fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel("X-Label", fontsize = 16, loc = "right") ax.set_ylabel("Y-Label", fontsize = 16, loc = "top") Output: Y-label to the top and X-label to extreme right Python-matplotlib Technical Scripter 2020 Python Technical Scripter 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": 31657, "s": 31629, "text": "\n11 Dec, 2020" }, { "code": null, "e": 31972, "s": 31657, "text": "In this article, we will see how to adjust positions of the x-axis and y-axis labels in Matplotlib which is a library for plotting in python language. By default, these labels are placed in the middle, but we can alter these positions using the “loc” parameter in set_xlabel and set_ylabel function of matplotlib. " }, { "code": null, "e": 32049, "s": 31972, "text": "Note: “loc” parameter is only available in Matplotlib version 3.3.0 onwards." }, { "code": null, "e": 32082, "s": 32049, "text": "Let’s understand with step wise:" }, { "code": null, "e": 32090, "s": 32082, "text": "Step 1:" }, { "code": null, "e": 32138, "s": 32090, "text": "First, let’s import all the required libraries." }, { "code": null, "e": 32146, "s": 32138, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport numpy as np", "e": 32196, "s": 32146, "text": null }, { "code": null, "e": 32204, "s": 32196, "text": "Step 2:" }, { "code": null, "e": 32359, "s": 32204, "text": "Now we will create fake data using the NumPy library. Here we are using the sample sub-module from the random module to create a dataset of random values." }, { "code": null, "e": 32367, "s": 32359, "text": "Python3" }, { "code": "from random import sampledata = sample(range(1, 1000), 100)", "e": 32427, "s": 32367, "text": null }, { "code": null, "e": 32435, "s": 32427, "text": "Step 3:" }, { "code": null, "e": 32835, "s": 32435, "text": "Now we have created data let’s plot this data using the default options of matplotlib and then start experimenting with its positions. We can clearly see that these labels are in the center by default. The bins parameter tells you the number of bins that your data will be divided into. Matplotlib allows you to adjust the transparency of a graph plot using the alpha attribute. By default, alpha=1 " }, { "code": null, "e": 32843, "s": 32835, "text": "Python3" }, { "code": "fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel(\"X-Label\" , fontsize = 16)ax.set_ylabel(\"Y-label\" , fontsize = 16)", "e": 32989, "s": 32843, "text": null }, { "code": null, "e": 32997, "s": 32989, "text": "Output:" }, { "code": null, "e": 33028, "s": 32997, "text": "The default position of labels" }, { "code": null, "e": 33130, "s": 33028, "text": "Here we will move the y-label to the bottom and x-label to the extreme right using the loc parameter." }, { "code": null, "e": 33138, "s": 33130, "text": "Python3" }, { "code": "fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel(\"X-Label\", fontsize = 16, loc = \"right\") ax.set_ylabel(\"Y-Label\", fontsize = 16, loc = \"bottom\")", "e": 33342, "s": 33138, "text": null }, { "code": null, "e": 33350, "s": 33342, "text": "Output:" }, { "code": null, "e": 33401, "s": 33350, "text": "Y-label to the bottom and X-label to extreme right" }, { "code": null, "e": 33470, "s": 33401, "text": "Let’s take another example here we will move the y-label to the top." }, { "code": null, "e": 33478, "s": 33470, "text": "Python3" }, { "code": "fig, ax = plt.subplots() ax.hist( data, bins = 100, alpha = 0.6) ax.set_xlabel(\"X-Label\", fontsize = 16, loc = \"right\") ax.set_ylabel(\"Y-Label\", fontsize = 16, loc = \"top\")", "e": 33680, "s": 33478, "text": null }, { "code": null, "e": 33688, "s": 33680, "text": "Output:" }, { "code": null, "e": 33736, "s": 33688, "text": "Y-label to the top and X-label to extreme right" }, { "code": null, "e": 33754, "s": 33736, "text": "Python-matplotlib" }, { "code": null, "e": 33778, "s": 33754, "text": "Technical Scripter 2020" }, { "code": null, "e": 33785, "s": 33778, "text": "Python" }, { "code": null, "e": 33804, "s": 33785, "text": "Technical Scripter" }, { "code": null, "e": 33902, "s": 33804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33930, "s": 33902, "text": "Read JSON file using Python" }, { "code": null, "e": 33980, "s": 33930, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34002, "s": 33980, "text": "Python map() function" }, { "code": null, "e": 34046, "s": 34002, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 34064, "s": 34046, "text": "Python Dictionary" }, { "code": null, "e": 34087, "s": 34064, "text": "Taking input in Python" }, { "code": null, "e": 34122, "s": 34087, "text": "Read a file line by line in Python" }, { "code": null, "e": 34154, "s": 34122, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34176, "s": 34154, "text": "Enumerate() in Python" } ]
How to Detect Swipe Direction in Android? - GeeksforGeeks
05 Aug, 2021 Detecting gestures is a very important feature that many app developers focus on. There can be a number of gestures that could be required to perform certain actions. For example, a user might need to swipe the screen from left to right to unlock the screen. Similarly, vice-versa might be needed. In such cases, it is necessary to detect the direction of the swipe or gesture made by the user. Similarly, most gaming applications depend heavily on user gestures to perform desired actions. So through this article, we will show you how you could detect the swipe direction of the user input on the screen. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Add this in the Main code (MainActivity.kt) Refer to the comments inside the code for better understanding. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.GestureDetectorimport android.view.MotionEventimport android.widget.Toastimport kotlin.math.abs class MainActivity : AppCompatActivity(), GestureDetector.OnGestureListener { // Declaring gesture detector, swipe threshold, and swipe velocity threshold private lateinit var gestureDetector: GestureDetector private val swipeThreshold = 100 private val swipeVelocityThreshold = 100 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the gesture detector gestureDetector = GestureDetector(this) } // Override this method to recognize touch event override fun onTouchEvent(event: MotionEvent): Boolean { return if (gestureDetector.onTouchEvent(event)) { true } else { super.onTouchEvent(event) } } // All the below methods are GestureDetector.OnGestureListener members // Except onFling, all must "return false" if Boolean return type // and "return" if no return type override fun onDown(e: MotionEvent?): Boolean { return false } override fun onShowPress(e: MotionEvent?) { return } override fun onSingleTapUp(e: MotionEvent?): Boolean { return false } override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean { return false } override fun onLongPress(e: MotionEvent?) { return } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { try { val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (abs(diffX) > abs(diffY)) { if (abs(diffX) > swipeThreshold && abs(velocityX) > swipeVelocityThreshold) { if (diffX > 0) { Toast.makeText(applicationContext, "Left to Right swipe gesture", Toast.LENGTH_SHORT).show() } else { Toast.makeText(applicationContext, "Right to Left swipe gesture", Toast.LENGTH_SHORT).show() } } } } catch (exception: Exception) { exception.printStackTrace() } return true }} No layout code is needed (activity_main.xml) 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" tools:context=".MainActivity"></androidx.constraintlayout.widget.ConstraintLayout> Output: Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? Flutter - Custom Bottom Navigation Bar How to Change the Background Color After Clicking the Button in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25036, "s": 25008, "text": "\n05 Aug, 2021" }, { "code": null, "e": 25643, "s": 25036, "text": "Detecting gestures is a very important feature that many app developers focus on. There can be a number of gestures that could be required to perform certain actions. For example, a user might need to swipe the screen from left to right to unlock the screen. Similarly, vice-versa might be needed. In such cases, it is necessary to detect the direction of the swipe or gesture made by the user. Similarly, most gaming applications depend heavily on user gestures to perform desired actions. So through this article, we will show you how you could detect the swipe direction of the user input on the screen." }, { "code": null, "e": 25690, "s": 25643, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 25929, "s": 25690, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 25981, "s": 25929, "text": "Step 2: Add this in the Main code (MainActivity.kt)" }, { "code": null, "e": 26045, "s": 25981, "text": "Refer to the comments inside the code for better understanding." }, { "code": null, "e": 26052, "s": 26045, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.GestureDetectorimport android.view.MotionEventimport android.widget.Toastimport kotlin.math.abs class MainActivity : AppCompatActivity(), GestureDetector.OnGestureListener { // Declaring gesture detector, swipe threshold, and swipe velocity threshold private lateinit var gestureDetector: GestureDetector private val swipeThreshold = 100 private val swipeVelocityThreshold = 100 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the gesture detector gestureDetector = GestureDetector(this) } // Override this method to recognize touch event override fun onTouchEvent(event: MotionEvent): Boolean { return if (gestureDetector.onTouchEvent(event)) { true } else { super.onTouchEvent(event) } } // All the below methods are GestureDetector.OnGestureListener members // Except onFling, all must \"return false\" if Boolean return type // and \"return\" if no return type override fun onDown(e: MotionEvent?): Boolean { return false } override fun onShowPress(e: MotionEvent?) { return } override fun onSingleTapUp(e: MotionEvent?): Boolean { return false } override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean { return false } override fun onLongPress(e: MotionEvent?) { return } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { try { val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (abs(diffX) > abs(diffY)) { if (abs(diffX) > swipeThreshold && abs(velocityX) > swipeVelocityThreshold) { if (diffX > 0) { Toast.makeText(applicationContext, \"Left to Right swipe gesture\", Toast.LENGTH_SHORT).show() } else { Toast.makeText(applicationContext, \"Right to Left swipe gesture\", Toast.LENGTH_SHORT).show() } } } } catch (exception: Exception) { exception.printStackTrace() } return true }}", "e": 28477, "s": 26052, "text": null }, { "code": null, "e": 28522, "s": 28477, "text": "No layout code is needed (activity_main.xml)" }, { "code": null, "e": 28526, "s": 28522, "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\" tools:context=\".MainActivity\"></androidx.constraintlayout.widget.ConstraintLayout>", "e": 28948, "s": 28526, "text": null }, { "code": null, "e": 28956, "s": 28948, "text": "Output:" }, { "code": null, "e": 28964, "s": 28956, "text": "Android" }, { "code": null, "e": 28971, "s": 28964, "text": "Kotlin" }, { "code": null, "e": 28979, "s": 28971, "text": "Android" }, { "code": null, "e": 29077, "s": 28979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29086, "s": 29077, "text": "Comments" }, { "code": null, "e": 29099, "s": 29086, "text": "Old Comments" }, { "code": null, "e": 29141, "s": 29099, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29179, "s": 29141, "text": "Android Listview in Java with Example" }, { "code": null, "e": 29229, "s": 29179, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29268, "s": 29229, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29341, "s": 29268, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 29360, "s": 29341, "text": "Android UI Layouts" }, { "code": null, "e": 29373, "s": 29360, "text": "Kotlin Array" }, { "code": null, "e": 29415, "s": 29373, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29442, "s": 29415, "text": "Kotlin Setters and Getters" } ]
An interesting method to print reverse of a linked list - GeeksforGeeks
24 Sep, 2021 We are given a linked list, we need to print the linked list in reverse order.Examples: Input : list : 5-> 15-> 20-> 25 Output : Reversed Linked list : 25-> 20-> 15-> 5 Input : list : 85-> 15-> 4-> 20 Output : Reversed Linked list : 20-> 4-> 15-> 85 Input : list : 85 Output : Reversed Linked list : 85 For printing a list in reverse order, we have already discussed Iterative and Recursive Methods to Reverse.In this post, an interesting method is discussed, that doesn’t require recursion and does no modifications to list. The function also visits every node of linked list only once. Trick : Idea behind printing a list in reverse order without any recursive function or loop is to use Carriage return (“r”). For this, we should have knowledge of length of list. Now, we should print n-1 blank space and then print 1st element then “r”, further again n-2 blank space and 2nd node then “r” and so on.. Carriage return (“r”) : It commands a printer (cursor or the display of a system console), to move the position of the cursor to the first position on the same line. // C program to print reverse of list #include <stdio.h> #include <stdlib.h> /* Link list node */ struct Node { int data; struct Node* next; }; /* Function to reverse the linked list */ void printReverse(struct Node** head_ref, int n) { int j = 0; struct Node* current = *head_ref; while (current != NULL) { // For each node, print proper number // of spaces before printing it for (int i = 0; i < 2 * (n - j); i++) printf(" "); // use of carriage return to move back // and print. printf("%d\r", current->data); current = current->next; j++; } } /* Function to push a node */ void push(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } /* Function to print linked list and find its length */ int printList(struct Node* head) { // i for finding length of list int i = 0; struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; i++; } return i; } /* Driver program to test above function*/ int main() { /* Start with the empty list */ struct Node* head = NULL; // list nodes are as 6 5 4 3 2 1 push(&head, 1); push(&head, 2); push(&head, 3); push(&head, 4); push(&head, 5); push(&head, 6); printf("Given linked list:\n"); // printlist print the list and // return the size of list int n = printList(head); // print reverse list with help // of carriage return function printf("\nReversed Linked list:\n"); printReverse(&head, n); printf("\n"); return 0; } Java C# Python3 // Java program to print reverse of listimport java.io.*;import java.util.*; // Represents node of a linkedlistclass Node { int data; Node next; Node(int val) { data = val; next = null; }} public class GFG { /* Function to reverse the linked list */ static void printReverse(Node head, int n) { int j = 0; Node current = head; while (current != null) { // For each node, print proper number // of spaces before printing it for (int i = 0; i < 2 * (n - j); i++) System.out.print(" "); // use of carriage return to move back // and print. System.out.print("\r" + current.data); current = current.next; j++; } } /* Function to push a node */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; head = new_node; return head; } /* Function to print linked list and find its length */ static int printList(Node head) { // i for finding length of list int i = 0; Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; i++; } return i; } // Driver code public static void main(String args[]) { /* Start with the empty list */ Node head = null; // list nodes are as 6 5 4 3 2 1 head = push(head, 1); head = push(head, 2); head = push(head, 3); head = push(head, 4); head = push(head, 5); head = push(head, 6); System.out.println("Given linked list: "); // printlist print the list and // return the size of list int n = printList(head); // print reverse list with help // of carriage return function System.out.println("Reversed Linked list: "); printReverse(head, n); System.out.println(); }} // This code is contributed by rachana soma // C# program to print reverse of listusing System; // Represents node of a linkedlistpublic class Node { public int data; public Node next; public Node(int val) { data = val; next = null; }} public class GFG{ /* Function to reverse the linked list */ static void printReverse(Node head, int n) { int j = 0; Node current = head; while (current != null) { // For each node, print proper number // of spaces before printing it for (int i = 0; i < 2 * (n - j); i++) Console.Write(" "); // use of carriage return to move back // and print. Console.Write("\r" + current.data); current = current.next; j++; } } /* Function to push a node */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; head = new_node; return head; } /* Function to print linked list and find its length */ static int printList(Node head) { // i for finding length of list int i = 0; Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; i++; } return i; } // Driver code public static void Main(String []args) { /* Start with the empty list */ Node head = null; // list nodes are as 6 5 4 3 2 1 head = push(head, 1); head = push(head, 2); head = push(head, 3); head = push(head, 4); head = push(head, 5); head = push(head, 6); Console.WriteLine("Given linked list: "); // printlist print the list and // return the size of list int n = printList(head); // print reverse list with help // of carriage return function Console.WriteLine("Reversed Linked list: "); printReverse(head, n); Console.WriteLine(); }} // This code is contributed by Arnab Kundu # Python3 program to print reverse of list # Link list node class Node: def __init__(self): self.data= 0 self.next=None # Function to reverse the linked list def printReverse( head_ref, n): j = 0 current = head_ref while (current != None): i = 0 # For each node, print proper number # of spaces before printing it while ( i < 2 * (n - j) ): print(end=" ") i = i + 1 # use of carriage return to move back # and print. print( current.data, end = "\r") current = current.next j = j + 1 # Function to push a node def push( head_ref, new_data): new_node = Node() new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref; # Function to print linked list and find its# length def printList( head): # i for finding length of list i = 0 temp = head while (temp != None): print( temp.data,end = " ") temp = temp.next i = i + 1 return i # Driver program to test above function # Start with the empty list head = None # list nodes are as 6 5 4 3 2 1head = push(head, 1)head = push(head, 2)head = push(head, 3)head = push(head, 4)head = push(head, 5)head = push(head, 6) print("Given linked list:") # printlist print the list and# return the size of listn = printList(head) # print reverse list with help# of carriage return functionprint("\nReversed Linked list:")printReverse(head, n)print() # This code is contributed by Arnab Kundu Output: Given linked list: 6 5 4 3 2 1 Reversed Linked List: 1 2 3 4 5 6 Input and Output Illustration : Input : 6 5 4 3 2 1 1st Iteration _ _ _ _ _ 6 2nd Iteration _ _ _ _ 5 6 3rd Iteration _ _ _ 4 5 6 4th Iteration _ _ 3 4 5 6 5th Iteration _ 2 3 4 5 6 Final Output 1 2 3 4 5 6NOTE:Above program may not work on online compiler because they do not support anything like carriage return on their console. Reference : stackoverflow/Carriage returnThis article is contributed by Shivam Pradhan (anuj_charm). 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. rachana soma andrew1234 rajeev0719singh kashishsoda Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Program to implement Singly Linked List in C++ using class Delete a node in a Doubly Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list Linked List Implementation in C# Priority Queue using Linked List
[ { "code": null, "e": 26313, "s": 26285, "text": "\n24 Sep, 2021" }, { "code": null, "e": 26403, "s": 26313, "text": "We are given a linked list, we need to print the linked list in reverse order.Examples: " }, { "code": null, "e": 26622, "s": 26403, "text": "Input : list : 5-> 15-> 20-> 25 \nOutput : Reversed Linked list : 25-> 20-> 15-> 5\n\nInput : list : 85-> 15-> 4-> 20 \nOutput : Reversed Linked list : 20-> 4-> 15-> 85\n\nInput : list : 85\nOutput : Reversed Linked list : 85" }, { "code": null, "e": 26907, "s": 26622, "text": "For printing a list in reverse order, we have already discussed Iterative and Recursive Methods to Reverse.In this post, an interesting method is discussed, that doesn’t require recursion and does no modifications to list. The function also visits every node of linked list only once." }, { "code": null, "e": 27393, "s": 26909, "text": "Trick : Idea behind printing a list in reverse order without any recursive function or loop is to use Carriage return (“r”). For this, we should have knowledge of length of list. Now, we should print n-1 blank space and then print 1st element then “r”, further again n-2 blank space and 2nd node then “r” and so on.. Carriage return (“r”) : It commands a printer (cursor or the display of a system console), to move the position of the cursor to the first position on the same line. " }, { "code": null, "e": 29206, "s": 27393, "text": "\n// C program to print reverse of list\n#include <stdio.h>\n#include <stdlib.h>\n \n/* Link list node */\nstruct Node {\n int data;\n struct Node* next;\n};\n \n/* Function to reverse the linked list */\nvoid printReverse(struct Node** head_ref, int n)\n{\n int j = 0;\n struct Node* current = *head_ref;\n while (current != NULL) {\n \n // For each node, print proper number\n // of spaces before printing it\n for (int i = 0; i < 2 * (n - j); i++)\n printf(\" \");\n \n // use of carriage return to move back\n // and print.\n printf(\"%d\\r\", current->data);\n \n current = current->next;\n j++;\n }\n}\n \n/* Function to push a node */\nvoid push(struct Node** head_ref, int new_data)\n{\n struct Node* new_node = \n (struct Node*)malloc(sizeof(struct Node));\n \n new_node->data = new_data;\n new_node->next = (*head_ref);\n (*head_ref) = new_node;\n}\n \n/* Function to print linked list and find its\n length */\nint printList(struct Node* head)\n{\n // i for finding length of list\n int i = 0;\n struct Node* temp = head;\n while (temp != NULL) {\n printf(\"%d \", temp->data);\n temp = temp->next;\n i++;\n }\n return i;\n}\n \n/* Driver program to test above function*/\nint main()\n{\n /* Start with the empty list */\n struct Node* head = NULL;\n // list nodes are as 6 5 4 3 2 1\n push(&head, 1);\n push(&head, 2);\n push(&head, 3);\n push(&head, 4);\n push(&head, 5);\n push(&head, 6);\n \n printf(\"Given linked list:\\n\");\n // printlist print the list and\n // return the size of list\n int n = printList(head);\n \n // print reverse list with help\n // of carriage return function\n printf(\"\\nReversed Linked list:\\n\");\n printReverse(&head, n);\n printf(\"\\n\");\n return 0;\n}\n" }, { "code": null, "e": 29211, "s": 29206, "text": "Java" }, { "code": null, "e": 29214, "s": 29211, "text": "C#" }, { "code": null, "e": 29222, "s": 29214, "text": "Python3" }, { "code": "// Java program to print reverse of listimport java.io.*;import java.util.*; // Represents node of a linkedlistclass Node { int data; Node next; Node(int val) { data = val; next = null; }} public class GFG { /* Function to reverse the linked list */ static void printReverse(Node head, int n) { int j = 0; Node current = head; while (current != null) { // For each node, print proper number // of spaces before printing it for (int i = 0; i < 2 * (n - j); i++) System.out.print(\" \"); // use of carriage return to move back // and print. System.out.print(\"\\r\" + current.data); current = current.next; j++; } } /* Function to push a node */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; head = new_node; return head; } /* Function to print linked list and find its length */ static int printList(Node head) { // i for finding length of list int i = 0; Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; i++; } return i; } // Driver code public static void main(String args[]) { /* Start with the empty list */ Node head = null; // list nodes are as 6 5 4 3 2 1 head = push(head, 1); head = push(head, 2); head = push(head, 3); head = push(head, 4); head = push(head, 5); head = push(head, 6); System.out.println(\"Given linked list: \"); // printlist print the list and // return the size of list int n = printList(head); // print reverse list with help // of carriage return function System.out.println(\"Reversed Linked list: \"); printReverse(head, n); System.out.println(); }} // This code is contributed by rachana soma", "e": 31436, "s": 29222, "text": null }, { "code": "// C# program to print reverse of listusing System; // Represents node of a linkedlistpublic class Node { public int data; public Node next; public Node(int val) { data = val; next = null; }} public class GFG{ /* Function to reverse the linked list */ static void printReverse(Node head, int n) { int j = 0; Node current = head; while (current != null) { // For each node, print proper number // of spaces before printing it for (int i = 0; i < 2 * (n - j); i++) Console.Write(\" \"); // use of carriage return to move back // and print. Console.Write(\"\\r\" + current.data); current = current.next; j++; } } /* Function to push a node */ static Node push(Node head, int data) { Node new_node = new Node(data); new_node.next = head; head = new_node; return head; } /* Function to print linked list and find its length */ static int printList(Node head) { // i for finding length of list int i = 0; Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; i++; } return i; } // Driver code public static void Main(String []args) { /* Start with the empty list */ Node head = null; // list nodes are as 6 5 4 3 2 1 head = push(head, 1); head = push(head, 2); head = push(head, 3); head = push(head, 4); head = push(head, 5); head = push(head, 6); Console.WriteLine(\"Given linked list: \"); // printlist print the list and // return the size of list int n = printList(head); // print reverse list with help // of carriage return function Console.WriteLine(\"Reversed Linked list: \"); printReverse(head, n); Console.WriteLine(); }} // This code is contributed by Arnab Kundu", "e": 33560, "s": 31436, "text": null }, { "code": "# Python3 program to print reverse of list # Link list node class Node: def __init__(self): self.data= 0 self.next=None # Function to reverse the linked list def printReverse( head_ref, n): j = 0 current = head_ref while (current != None): i = 0 # For each node, print proper number # of spaces before printing it while ( i < 2 * (n - j) ): print(end=\" \") i = i + 1 # use of carriage return to move back # and print. print( current.data, end = \"\\r\") current = current.next j = j + 1 # Function to push a node def push( head_ref, new_data): new_node = Node() new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref; # Function to print linked list and find its# length def printList( head): # i for finding length of list i = 0 temp = head while (temp != None): print( temp.data,end = \" \") temp = temp.next i = i + 1 return i # Driver program to test above function # Start with the empty list head = None # list nodes are as 6 5 4 3 2 1head = push(head, 1)head = push(head, 2)head = push(head, 3)head = push(head, 4)head = push(head, 5)head = push(head, 6) print(\"Given linked list:\") # printlist print the list and# return the size of listn = printList(head) # print reverse list with help# of carriage return functionprint(\"\\nReversed Linked list:\")printReverse(head, n)print() # This code is contributed by Arnab Kundu", "e": 35149, "s": 33560, "text": null }, { "code": null, "e": 35159, "s": 35149, "text": "Output: " }, { "code": null, "e": 35224, "s": 35159, "text": "Given linked list:\n6 5 4 3 2 1\nReversed Linked List:\n1 2 3 4 5 6" }, { "code": null, "e": 35557, "s": 35224, "text": "Input and Output Illustration : Input : 6 5 4 3 2 1 1st Iteration _ _ _ _ _ 6 2nd Iteration _ _ _ _ 5 6 3rd Iteration _ _ _ 4 5 6 4th Iteration _ _ 3 4 5 6 5th Iteration _ 2 3 4 5 6 Final Output 1 2 3 4 5 6NOTE:Above program may not work on online compiler because they do not support anything like carriage return on their console." }, { "code": null, "e": 36034, "s": 35557, "text": "Reference : stackoverflow/Carriage returnThis article is contributed by Shivam Pradhan (anuj_charm). 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": 36047, "s": 36034, "text": "rachana soma" }, { "code": null, "e": 36058, "s": 36047, "text": "andrew1234" }, { "code": null, "e": 36074, "s": 36058, "text": "rajeev0719singh" }, { "code": null, "e": 36086, "s": 36074, "text": "kashishsoda" }, { "code": null, "e": 36098, "s": 36086, "text": "Linked List" }, { "code": null, "e": 36110, "s": 36098, "text": "Linked List" }, { "code": null, "e": 36208, "s": 36110, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36249, "s": 36208, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 36299, "s": 36249, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 36339, "s": 36299, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 36410, "s": 36339, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 36469, "s": 36410, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 36507, "s": 36469, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 36548, "s": 36507, "text": "Real-time application of Data Structures" }, { "code": null, "e": 36602, "s": 36548, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 36635, "s": 36602, "text": "Linked List Implementation in C#" } ]
JAXB Java Object to XML Conversion Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAXB (Java Architecture for XML Binding) API allows us to convert Java Object to XML file or simple XML string. JAXB provides two main features – that are marshalling and unmarshalling. Marshalling allows us to convert Java objects to XML whereas unmarshalling used to convert XML to Object. Here we will see how to marshal an object. Add jaxb-api dependency in pom.xml. <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <!-- API, java.xml.bind module --> <dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <version>2.3.2</version> </dependency> <!-- Runtime, com.sun.xml.bind module --> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.2</version> </dependency> Creating a Java class, it’s going to be converted to an XML. Book.java public class Book { private int id; private String name; private double price; // constructor // getters and setters // tostring } Java Object to XML conversion using JAXB marshaller. Here we are simply converting the object to an XML string. import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.StringWriter; public class ObjectToXML { public static void main(String[] args) { Book book = new Book(1,"Java",200); createXML(book); } private static void createXML(Book book) { try { JAXBContext jaxbContext = JAXBContext.newInstance(Book.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter sw = new StringWriter(); marshaller.marshal(book, sw); System.out.println(sw.toString()); } catch (JAXBException e) { e.printStackTrace(); } } } Output: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Book> <id>1</id> <name>Java</name> <price>200.0</price> </Book> We can also save the converted XML into a physical file using the marshal(Object obj, File location) overloaded method. import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.File; public class ObjectToXML { public static void main(String[] args) { Book book = new Book(1,"Java",200); createXMLFile(book); } private static void createXMLFile(Book book) { try { File file = new File("book.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Book.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(book, file); } catch (JAXBException e) { e.printStackTrace(); } } } as an output, you can see the generated book.xml in your specified directory. Java13 Text Blocks JAXB XML to Java Obeject JAXB Architecture Happy Learning 🙂 JAXB XML to Java Object Conversion Example JAXB Map to XML Conversion Example Python String to int Conversion Example Java String to int conversion Example 4 ways to create an Object in Java Java – How to read CSV file and Map to Java Object How to convert Java Object to JSON How to convert JSON to Java Object Example How to convert JSON to Java Map Object Binary To Decimal Conversion Java Program Binary To Hexadecimal Conversion Java Program Decimal To Binary Conversion Java Program Decimal To Hex Conversion Java Program Decimal To Octal Conversion Java Program Octal To Decimal Conversion Java Program JAXB XML to Java Object Conversion Example JAXB Map to XML Conversion Example Python String to int Conversion Example Java String to int conversion Example 4 ways to create an Object in Java Java – How to read CSV file and Map to Java Object How to convert Java Object to JSON How to convert JSON to Java Object Example How to convert JSON to Java Map Object Binary To Decimal Conversion Java Program Binary To Hexadecimal Conversion Java Program Decimal To Binary Conversion Java Program Decimal To Hex Conversion Java Program Decimal To Octal Conversion Java Program Octal To Decimal Conversion Java Program Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 510, "s": 398, "text": "JAXB (Java Architecture for XML Binding) API allows us to convert Java Object to XML file or simple XML string." }, { "code": null, "e": 690, "s": 510, "text": "JAXB provides two main features – that are marshalling and unmarshalling. Marshalling allows us to convert Java objects to XML whereas unmarshalling used to convert XML to Object." }, { "code": null, "e": 733, "s": 690, "text": "Here we will see how to marshal an object." }, { "code": null, "e": 769, "s": 733, "text": "Add jaxb-api dependency in pom.xml." }, { "code": null, "e": 907, "s": 769, "text": "<dependency>\n <groupId>javax.xml.bind</groupId>\n <artifactId>jaxb-api</artifactId>\n <version>2.3.1</version>\n</dependency>" }, { "code": null, "e": 1348, "s": 907, "text": "<!-- API, java.xml.bind module -->\n <dependency>\n <groupId>jakarta.xml.bind</groupId>\n <artifactId>jakarta.xml.bind-api</artifactId>\n <version>2.3.2</version>\n </dependency>\n\n <!-- Runtime, com.sun.xml.bind module -->\n <dependency>\n <groupId>org.glassfish.jaxb</groupId>\n <artifactId>jaxb-runtime</artifactId>\n <version>2.3.2</version>\n </dependency>" }, { "code": null, "e": 1409, "s": 1348, "text": "Creating a Java class, it’s going to be converted to an XML." }, { "code": null, "e": 1419, "s": 1409, "text": "Book.java" }, { "code": null, "e": 1575, "s": 1419, "text": "public class Book {\n private int id;\n private String name;\n private double price;\n\n // constructor\n // getters and setters\n // tostring\n}" }, { "code": null, "e": 1687, "s": 1575, "text": "Java Object to XML conversion using JAXB marshaller. Here we are simply converting the object to an XML string." }, { "code": null, "e": 2495, "s": 1687, "text": "import javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.Marshaller;\nimport java.io.StringWriter;\n\npublic class ObjectToXML {\n\n public static void main(String[] args) {\n Book book = new Book(1,\"Java\",200);\n createXML(book);\n }\n\n private static void createXML(Book book) {\n try\n {\n JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);\n Marshaller marshaller = jaxbContext.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n StringWriter sw = new StringWriter();\n marshaller.marshal(book, sw);\n System.out.println(sw.toString());\n } catch (JAXBException e) {\n e.printStackTrace();\n }\n }\n}\n" }, { "code": null, "e": 2503, "s": 2495, "text": "Output:" }, { "code": null, "e": 2636, "s": 2503, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<Book>\n <id>1</id>\n <name>Java</name>\n <price>200.0</price>\n</Book>" }, { "code": null, "e": 2756, "s": 2636, "text": "We can also save the converted XML into a physical file using the marshal(Object obj, File location) overloaded method." }, { "code": null, "e": 3514, "s": 2756, "text": "import javax.xml.bind.JAXBContext;\nimport javax.xml.bind.JAXBException;\nimport javax.xml.bind.Marshaller;\nimport java.io.File;\n\npublic class ObjectToXML {\n\n public static void main(String[] args) {\n Book book = new Book(1,\"Java\",200);\n createXMLFile(book);\n }\n\n private static void createXMLFile(Book book) {\n try\n {\n File file = new File(\"book.xml\");\n JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);\n Marshaller marshaller = jaxbContext.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n marshaller.marshal(book, file);\n } catch (JAXBException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 3592, "s": 3514, "text": "as an output, you can see the generated book.xml in your specified directory." }, { "code": null, "e": 3611, "s": 3592, "text": "Java13 Text Blocks" }, { "code": null, "e": 3636, "s": 3611, "text": "JAXB XML to Java Obeject" }, { "code": null, "e": 3654, "s": 3636, "text": "JAXB Architecture" }, { "code": null, "e": 3671, "s": 3654, "text": "Happy Learning 🙂" }, { "code": null, "e": 4283, "s": 3671, "text": "\nJAXB XML to Java Object Conversion Example\nJAXB Map to XML Conversion Example\nPython String to int Conversion Example\nJava String to int conversion Example\n4 ways to create an Object in Java\nJava – How to read CSV file and Map to Java Object\nHow to convert Java Object to JSON\nHow to convert JSON to Java Object Example\nHow to convert JSON to Java Map Object\nBinary To Decimal Conversion Java Program\nBinary To Hexadecimal Conversion Java Program\nDecimal To Binary Conversion Java Program\nDecimal To Hex Conversion Java Program\nDecimal To Octal Conversion Java Program\nOctal To Decimal Conversion Java Program\n" }, { "code": null, "e": 4326, "s": 4283, "text": "JAXB XML to Java Object Conversion Example" }, { "code": null, "e": 4361, "s": 4326, "text": "JAXB Map to XML Conversion Example" }, { "code": null, "e": 4401, "s": 4361, "text": "Python String to int Conversion Example" }, { "code": null, "e": 4439, "s": 4401, "text": "Java String to int conversion Example" }, { "code": null, "e": 4474, "s": 4439, "text": "4 ways to create an Object in Java" }, { "code": null, "e": 4525, "s": 4474, "text": "Java – How to read CSV file and Map to Java Object" }, { "code": null, "e": 4560, "s": 4525, "text": "How to convert Java Object to JSON" }, { "code": null, "e": 4603, "s": 4560, "text": "How to convert JSON to Java Object Example" }, { "code": null, "e": 4642, "s": 4603, "text": "How to convert JSON to Java Map Object" }, { "code": null, "e": 4684, "s": 4642, "text": "Binary To Decimal Conversion Java Program" }, { "code": null, "e": 4730, "s": 4684, "text": "Binary To Hexadecimal Conversion Java Program" }, { "code": null, "e": 4772, "s": 4730, "text": "Decimal To Binary Conversion Java Program" }, { "code": null, "e": 4811, "s": 4772, "text": "Decimal To Hex Conversion Java Program" }, { "code": null, "e": 4852, "s": 4811, "text": "Decimal To Octal Conversion Java Program" }, { "code": null, "e": 4893, "s": 4852, "text": "Octal To Decimal Conversion Java Program" }, { "code": null, "e": 4899, "s": 4897, "text": "Δ" }, { "code": null, "e": 4923, "s": 4899, "text": " Install Java on Mac OS" }, { "code": null, "e": 4951, "s": 4923, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 4980, "s": 4951, "text": " Install Minikube on Windows" }, { "code": null, "e": 5015, "s": 4980, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 5042, "s": 5015, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 5069, "s": 5042, "text": " Install Gradle on Windows" }, { "code": null, "e": 5098, "s": 5069, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 5124, "s": 5098, "text": " Install PuTTY on windows" }, { "code": null, "e": 5150, "s": 5124, "text": " Install Mysql on Windows" }, { "code": null, "e": 5186, "s": 5150, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 5220, "s": 5186, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 5246, "s": 5220, "text": " Install Maven on Windows" }, { "code": null, "e": 5271, "s": 5246, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 5305, "s": 5271, "text": " Install Maven on Windows Command" }, { "code": null, "e": 5340, "s": 5305, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 5364, "s": 5340, "text": " Install Ant on Windows" }, { "code": null, "e": 5393, "s": 5364, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 5425, "s": 5393, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 5458, "s": 5425, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 5483, "s": 5458, "text": " Java8 – Install Windows" }, { "code": null, "e": 5500, "s": 5483, "text": " Java8 – foreach" }, { "code": null, "e": 5528, "s": 5500, "text": " Java8 – forEach with index" }, { "code": null, "e": 5559, "s": 5528, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 5591, "s": 5559, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 5611, "s": 5591, "text": " Java8 – GroupingBy" }, { "code": null, "e": 5631, "s": 5611, "text": " Java8 – SummingInt" }, { "code": null, "e": 5655, "s": 5631, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 5685, "s": 5655, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 5717, "s": 5685, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 5753, "s": 5717, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 5797, "s": 5753, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 5829, "s": 5797, "text": " Howto – Convert List to String" }, { "code": null, "e": 5870, "s": 5829, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 5907, "s": 5870, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5947, "s": 5907, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 5976, "s": 5947, "text": " Howto – Convert List to Map" }, { "code": null, "e": 6008, "s": 5976, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 6028, "s": 6008, "text": " Howto – Sort a Map" }, { "code": null, "e": 6050, "s": 6028, "text": " Howto – Filter a Map" }, { "code": null, "e": 6080, "s": 6050, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 6131, "s": 6080, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 6167, "s": 6131, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 6199, "s": 6167, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 6234, "s": 6199, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 6257, "s": 6234, "text": " Howto – Merge Streams" }, { "code": null, "e": 6304, "s": 6257, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 6329, "s": 6304, "text": " Howto -Get Stream count" }, { "code": null, "e": 6373, "s": 6329, "text": " Howto – Get Min and Max values in a Stream" } ]
jQuery multiple select plugin for Bootstrap - GeeksforGeeks
17 Aug, 2021 jQuery provides a variety of plugins for bootstrap for distinctive purposes which can be easily integrated into a web application, making the websites and applications look more attractive and reliable. Plugins can be included in two ways i.e. individually by using Bootstrap’s individual *.js files, or all at once, utilizing bootstrap.js. Bootstrap multiselect is also one of the jQuery plugins for Bootstrap, which enables the client to choose more than one alternative from a dropdown list, at once. Utilizing the multiple select plugins, dropdown alternatives act as checkboxes, so that the client can choose multiple alternatives, unlike normal dropdown where only one alternative can be chosen. The plugin is based on the Twitter Bootstrap system and comes with numerous features. In runtime, simple HTML select can be effortlessly changed into a Bootstrap button by utilizing the same. You need to add the following resources to your HTML file to use the bootstrap multiple select jQuery plugin in your website. Stylesheet to enable the alternatives to be opened as a dropdown. <link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css” rel=”stylesheet”> Include Bootstrap and jQuery files as scripts. <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js”></script> <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js”></script> Bootstrap CDN links to enable the multi-select feature in the dropdown list. <script src=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js”> </script> <link href=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css” rel=”stylesheet” > Now create an HTML dropdown with a list of alternatives. <select id=”checkboxes” multiple=”multiple”> <option value=”Array”>Array</option> <option value=”Linked list”>Linked list</option> <option value=”Strings”>Strings</option> <option value=”Stack”>Stack</option> <option value=”Queue”>Queue</option> <option value=”Graph”>Graph</option> <option value=”Tree”>Tree</option> <option value=”Maps”>Maps</option> </select> And don’t forget to initialize the plugin by calling the multiselect() function. $(‘#checkboxes’).multiselect(); After initializing the plugin, the selected dropdown component ($(‘#checkboxes’)) will be replaced with a bootstrap button that shows available options with checkboxes. Example: HTML <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"> </script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" > <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"> </script> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" rel="stylesheet"> <style> .container { margin-top: 30px; color: green; font-size: 20px; } </style> </head> <body> <br> <p class="container"><b>GeeksforGeeks</b></p> <div class="container"> <b>Select your choice:</b> <select id="checkboxes" multiple="multiple"> <option value="Linked list">Linked list</option> <option value="Array">Array</option> <option value="Strings">Strings</option> <option value="Stack">Stack</option> <option value="Queue">Queue</option> <option value="Graph">Graph</option> <option value="Tree">Tree</option> <option value="Maps">Maps</option> </select> </div> <script> $(document).ready(function() { $('#checkboxes').multiselect(); }); </script> </body> </html> Output: Now, as you can see in the output, a multi-select dropdown list is created where the client can choose multiple alternatives at once, by utilizing the multiple select plugins, integrated by following the above steps. supported browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 HTML-Basics jQuery-Plugin Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25566, "s": 25538, "text": "\n17 Aug, 2021" }, { "code": null, "e": 25770, "s": 25566, "text": "jQuery provides a variety of plugins for bootstrap for distinctive purposes which can be easily integrated into a web application, making the websites and applications look more attractive and reliable. " }, { "code": null, "e": 25908, "s": 25770, "text": "Plugins can be included in two ways i.e. individually by using Bootstrap’s individual *.js files, or all at once, utilizing bootstrap.js." }, { "code": null, "e": 26461, "s": 25908, "text": "Bootstrap multiselect is also one of the jQuery plugins for Bootstrap, which enables the client to choose more than one alternative from a dropdown list, at once. Utilizing the multiple select plugins, dropdown alternatives act as checkboxes, so that the client can choose multiple alternatives, unlike normal dropdown where only one alternative can be chosen. The plugin is based on the Twitter Bootstrap system and comes with numerous features. In runtime, simple HTML select can be effortlessly changed into a Bootstrap button by utilizing the same." }, { "code": null, "e": 26587, "s": 26461, "text": "You need to add the following resources to your HTML file to use the bootstrap multiple select jQuery plugin in your website." }, { "code": null, "e": 26653, "s": 26587, "text": "Stylesheet to enable the alternatives to be opened as a dropdown." }, { "code": null, "e": 26754, "s": 26653, "text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css” rel=”stylesheet”>" }, { "code": null, "e": 26801, "s": 26754, "text": "Include Bootstrap and jQuery files as scripts." }, { "code": null, "e": 26977, "s": 26801, "text": "<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js”></script> <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js”></script>" }, { "code": null, "e": 27054, "s": 26977, "text": "Bootstrap CDN links to enable the multi-select feature in the dropdown list." }, { "code": null, "e": 27305, "s": 27054, "text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js”> </script> <link href=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css” rel=”stylesheet” >" }, { "code": null, "e": 27362, "s": 27305, "text": "Now create an HTML dropdown with a list of alternatives." }, { "code": null, "e": 27725, "s": 27362, "text": "<select id=”checkboxes” multiple=”multiple”> <option value=”Array”>Array</option> <option value=”Linked list”>Linked list</option> <option value=”Strings”>Strings</option> <option value=”Stack”>Stack</option> <option value=”Queue”>Queue</option> <option value=”Graph”>Graph</option> <option value=”Tree”>Tree</option> <option value=”Maps”>Maps</option> </select>" }, { "code": null, "e": 27806, "s": 27725, "text": "And don’t forget to initialize the plugin by calling the multiselect() function." }, { "code": null, "e": 27839, "s": 27806, "text": "$(‘#checkboxes’).multiselect(); " }, { "code": null, "e": 28008, "s": 27839, "text": "After initializing the plugin, the selected dropdown component ($(‘#checkboxes’)) will be replaced with a bootstrap button that shows available options with checkboxes." }, { "code": null, "e": 28017, "s": 28008, "text": "Example:" }, { "code": null, "e": 28022, "s": 28017, "text": "HTML" }, { "code": "<html> <head> <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js\"> </script> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\" > <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js\"> </script> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css\" rel=\"stylesheet\"> <style> .container { margin-top: 30px; color: green; font-size: 20px; } </style> </head> <body> <br> <p class=\"container\"><b>GeeksforGeeks</b></p> <div class=\"container\"> <b>Select your choice:</b> <select id=\"checkboxes\" multiple=\"multiple\"> <option value=\"Linked list\">Linked list</option> <option value=\"Array\">Array</option> <option value=\"Strings\">Strings</option> <option value=\"Stack\">Stack</option> <option value=\"Queue\">Queue</option> <option value=\"Graph\">Graph</option> <option value=\"Tree\">Tree</option> <option value=\"Maps\">Maps</option> </select> </div> <script> $(document).ready(function() { $('#checkboxes').multiselect(); }); </script> </body> </html>", "e": 29574, "s": 28022, "text": null }, { "code": null, "e": 29799, "s": 29574, "text": "Output: Now, as you can see in the output, a multi-select dropdown list is created where the client can choose multiple alternatives at once, by utilizing the multiple select plugins, integrated by following the above steps." }, { "code": null, "e": 29818, "s": 29799, "text": "supported browser:" }, { "code": null, "e": 29832, "s": 29818, "text": "Google Chrome" }, { "code": null, "e": 29847, "s": 29832, "text": "Microsoft Edge" }, { "code": null, "e": 29855, "s": 29847, "text": "Firefox" }, { "code": null, "e": 29861, "s": 29855, "text": "Opera" }, { "code": null, "e": 29868, "s": 29861, "text": "Safari" }, { "code": null, "e": 29880, "s": 29868, "text": "ysachin2314" }, { "code": null, "e": 29892, "s": 29880, "text": "HTML-Basics" }, { "code": null, "e": 29906, "s": 29892, "text": "jQuery-Plugin" }, { "code": null, "e": 29913, "s": 29906, "text": "Picked" }, { "code": null, "e": 29923, "s": 29913, "text": "Bootstrap" }, { "code": null, "e": 29940, "s": 29923, "text": "Web Technologies" }, { "code": null, "e": 30038, "s": 29940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30047, "s": 30038, "text": "Comments" }, { "code": null, "e": 30060, "s": 30047, "text": "Old Comments" }, { "code": null, "e": 30123, "s": 30060, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 30164, "s": 30123, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 30197, "s": 30164, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 30223, "s": 30197, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 30272, "s": 30223, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 30314, "s": 30272, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30347, "s": 30314, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30409, "s": 30347, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30452, "s": 30409, "text": "How to fetch data from an API in ReactJS ?" } ]
wish - Unix, Linux Command
\L’|0u-1v|’ \L’|0u-1v’\l’75u+3n_’\L’0u+1v-0u’\l’|0u-1.5n_’ \L’|0u-1v’\L’0u+1v-0u’\l’|0u-1.5n_’ Wish is a simple program consisting of the Tcl command language, the Tk toolkit, and a main program that reads commands from standard input or from a file. It creates a main window and then processes Tcl commands. If wish is invoked with no arguments, or with a first argument that starts with ‘‘-’’, then it reads Tcl commands interactively from standard input. It will continue processing commands until all windows have been deleted or until end-of-file is reached on standard input. If there exists a file .wishrc in the home directory of the user, wish evaluates the file as a Tcl script just before reading the first command from standard input. If wish is invoked with an initial fileName argument, then fileName is treated as the name of a script file. Wish will evaluate the script in fileName (which presumably creates a user interface), then it will respond to events until all windows have been deleted. Commands will not be read from standard input. There is no automatic evaluation of .wishrc when the name of a script file is presented on the wish command line, but the script file can always source it if desired. Wish automatically processes all of the command-line options described in the OPTIONS summary above. Any other command-line arguments besides these are passed through to the application using the argc and argv variables described later. The name of the application, which is used for purposes such as send commands, is taken from the -name option, if it is specified; otherwise it is taken from fileName, if it is specified, or from the command name by which wish was invoked. In the last two cases, if the name contains a ‘‘/’’ character, then only the characters after the last slash are used as the application name. The class of the application, which is used for purposes such as specifying options with a RESOURCE_MANAGER property or .Xdefaults file, is the same as its name except that the first letter is capitalized. Wish sets the following Tcl variables: If you create a Tcl script in a file whose first line is #!/usr/local/bin/wish An even better approach is to start your script files with the following three lines: #!/bin/sh # the next line restarts using wish \ exec wish "$0" "$@" The end of a script file may be marked either by the physical end of the medium, or by the character, ’\032’ (’\u001a’, control-Z). If this character is present in the file, the wish application will read text up to but not including the character. An application that requires this character in the file may encode it as ‘‘\032’’, ‘‘\x1a’’, or ‘‘\u001a’’; or may generate it by use of commands such as format or binary. \L’|0u-1v|’ When wish is invoked interactively it normally prompts for each command with ‘‘% ’’. You can change the prompt by setting the variables tcl_prompt1 and tcl_prompt2. If variable tcl_prompt1 exists then it must consist of a Tcl script to output a prompt; instead of outputting a prompt wish will evaluate the script in tcl_prompt1. The variable tcl_prompt2 is used in a similar way when a newline is typed but the current command isn’t yet complete; if tcl_prompt2 isn’t set then no prompt is output for incomplete commands. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10595, "s": 10577, "text": " \n\\L’|0u-1v|’\n\n" }, { "code": null, "e": 10692, "s": 10597, "text": " \n\n\n\n\\L’|0u-1v’\\l’75u+3n_’\\L’0u+1v-0u’\\l’|0u-1.5n_’\n\n\n\\L’|0u-1v’\\L’0u+1v-0u’\\l’|0u-1.5n_’\n\n\n" }, { "code": null, "e": 11348, "s": 10694, "text": "\nWish is a simple program consisting of the Tcl command\nlanguage, the Tk toolkit, and a main program that reads commands\nfrom standard input or from a file.\nIt creates a main window and then processes Tcl commands.\nIf wish is invoked with no arguments, or with a first argument\nthat starts with ‘‘-’’, then it reads Tcl commands interactively from\nstandard input.\nIt will continue processing commands until all windows have been\ndeleted or until end-of-file is reached on standard input.\nIf there exists a file .wishrc in the home directory of\nthe user, wish evaluates the file as a Tcl script\njust before reading the first command from standard input.\n" }, { "code": null, "e": 11828, "s": 11348, "text": "\nIf wish is invoked with an initial fileName argument, then\nfileName is treated as the name of a script file.\nWish will evaluate the script in fileName (which\npresumably creates a user interface), then it will respond to events\nuntil all windows have been deleted.\nCommands will not be read from standard input.\nThere is no automatic evaluation of .wishrc when the name\nof a script file is presented on the wish command line,\nbut the script file can always source it if desired.\n" }, { "code": null, "e": 12069, "s": 11830, "text": "\nWish automatically processes all of the command-line options\ndescribed in the OPTIONS summary above.\nAny other command-line arguments besides these are passed through\nto the application using the argc and argv variables\ndescribed later.\n" }, { "code": null, "e": 12458, "s": 12071, "text": "\nThe name of the application, which is used for purposes such as\nsend commands, is taken from the -name option,\nif it is specified; otherwise it is taken from fileName,\nif it is specified, or from the command name by which\nwish was invoked. In the last two cases, if the name contains a ‘‘/’’\ncharacter, then only the characters after the last slash are used\nas the application name.\n" }, { "code": null, "e": 12666, "s": 12458, "text": "\nThe class of the application, which is used for purposes such as\nspecifying options with a RESOURCE_MANAGER property or .Xdefaults\nfile, is the same as its name except that the first letter is\ncapitalized.\n" }, { "code": null, "e": 12709, "s": 12668, "text": "\nWish sets the following Tcl variables:\n" }, { "code": null, "e": 12770, "s": 12711, "text": "\nIf you create a Tcl script in a file whose first line is\n" }, { "code": null, "e": 12793, "s": 12770, "text": "#!/usr/local/bin/wish\n" }, { "code": null, "e": 12881, "s": 12793, "text": "\nAn even better approach is to start your script files with the\nfollowing three lines:\n" }, { "code": null, "e": 12950, "s": 12881, "text": "#!/bin/sh\n# the next line restarts using wish \\\nexec wish \"$0\" \"$@\"\n" }, { "code": null, "e": 13379, "s": 12950, "text": "\n\n\n\nThe end of a script file may be marked either by the physical end of\nthe medium, or by the character, ’\\032’ (’\\u001a’, control-Z).\nIf this character is present in the file, the wish application\nwill read text up to but not including the character. An application\nthat requires this character in the file may encode it as\n‘‘\\032’’, ‘‘\\x1a’’, or ‘‘\\u001a’’; or may generate it by use of commands\nsuch as format or binary.\n\n\n" }, { "code": null, "e": 13397, "s": 13379, "text": " \n\\L’|0u-1v|’\n\n" }, { "code": null, "e": 13927, "s": 13399, "text": "\nWhen wish is invoked interactively it normally prompts for each\ncommand with ‘‘% ’’. You can change the prompt by setting the\nvariables tcl_prompt1 and tcl_prompt2. If variable\ntcl_prompt1 exists then it must consist of a Tcl script\nto output a prompt; instead of outputting a prompt wish\nwill evaluate the script in tcl_prompt1.\nThe variable tcl_prompt2 is used in a similar way when\na newline is typed but the current command isn’t yet complete;\nif tcl_prompt2 isn’t set then no prompt is output for\nincomplete commands.\n" }, { "code": null, "e": 13946, "s": 13929, "text": "\nAdvertisements\n" }, { "code": null, "e": 13981, "s": 13946, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 14009, "s": 13981, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14043, "s": 14009, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14060, "s": 14043, "text": " Frahaan Hussain" }, { "code": null, "e": 14093, "s": 14060, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 14104, "s": 14093, "text": " Pradeep D" }, { "code": null, "e": 14139, "s": 14104, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14155, "s": 14139, "text": " Musab Zayadneh" }, { "code": null, "e": 14188, "s": 14155, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 14200, "s": 14188, "text": " GUHARAJANM" }, { "code": null, "e": 14232, "s": 14200, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 14240, "s": 14232, "text": " Uplatz" }, { "code": null, "e": 14247, "s": 14240, "text": " Print" }, { "code": null, "e": 14258, "s": 14247, "text": " Add Notes" } ]
How to set the space between cells in a table with JavaScript?
To set the space between cells in a table with JavaScript, use the borderSpacing property. Set the spacing using this property. You can try to run the following code to learn how to set the space between table cells − Live Demo <!DOCTYPE html> <html> <body> <table id="newTable" border="2"> <tr> <th>EmpID</th> <th>EmpName</th> <th>EmpDept</th> </tr> <tr> <td>001</td> <td>Amit</td> <td>IT</td> </tr> <tr> <td>002</td> <td>John</td> <td>Finance</td> </tr> <tr> <td>003</td> <td>David</td> <td>Marketing</td> </tr> </table> <br> <button onclick="display()">Click to set space between cells</button> <script> function display() { document.getElementById("newTable").style.borderSpacing = "15px"; } </script> </body> </html>
[ { "code": null, "e": 1190, "s": 1062, "text": "To set the space between cells in a table with JavaScript, use the borderSpacing property. Set the spacing using this property." }, { "code": null, "e": 1280, "s": 1190, "text": "You can try to run the following code to learn how to set the space between table cells −" }, { "code": null, "e": 1290, "s": 1280, "text": "Live Demo" }, { "code": null, "e": 2075, "s": 1290, "text": "<!DOCTYPE html>\n<html>\n <body>\n <table id=\"newTable\" border=\"2\">\n <tr>\n <th>EmpID</th>\n <th>EmpName</th>\n <th>EmpDept</th>\n </tr>\n <tr>\n <td>001</td>\n <td>Amit</td>\n <td>IT</td>\n </tr>\n <tr>\n <td>002</td>\n <td>John</td>\n <td>Finance</td>\n </tr>\n <tr>\n <td>003</td>\n <td>David</td>\n <td>Marketing</td>\n </tr>\n </table>\n <br>\n <button onclick=\"display()\">Click to set space between cells</button>\n <script>\n function display() {\n document.getElementById(\"newTable\").style.borderSpacing = \"15px\";\n }\n </script>\n </body>\n</html>" } ]
How to create a child window and communicate with parents in Tkinter?
Unlike other Python libraries, Tkinter has many features that are used to create a full-fledged application. It supports multiple window operations and threading for processing the operation on Windows. Following the thread, we will create an application that will pull the data from root window and put it into a child window. The concept of child window can be referred to as Dialog Boxes which present some information to the user during the happening of an event. The child window in Tkinter is created very easily by using Toplevel(root) constructor. In this example, we will create an entry widget along with a button in the main window. Further, the data stored in the entry widget will be pulled by a button that displays the input value in a new window or child window. #Import tkinter library from tkinter import * from tkinter import ttk #Create an instance of tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x250") win.title("Main Window") #Define a function to Open a new window def open_win(): child_win= Toplevel(win) child_win.title("Child Window") child_win.geometry("750x250") content= entry.get() Label(child_win, text=content, font=('Bell MT', 20, 'bold')).pack() win.withdraw() #Create an Entry Widget entry=ttk.Entry(win, width= 40) entry.pack(ipady=4,pady=20) #Let us create a button in the Main window button= ttk.Button(win, text="OK",command=open_win) button.pack(pady=20) win.mainloop() When we execute the above code, it will show a window with an entry widget and a button to open a new window. Write something in the entry widget and click the OK button,
[ { "code": null, "e": 1265, "s": 1062, "text": "Unlike other Python libraries, Tkinter has many features that are used to create a full-fledged application. It supports multiple window operations and threading for processing the operation on Windows." }, { "code": null, "e": 1618, "s": 1265, "text": "Following the thread, we will create an application that will pull the data from root window and put it into a child window. The concept of child window can be referred to as Dialog Boxes which present some information to the user during the happening of an event. The child window in Tkinter is created very easily by using Toplevel(root) constructor." }, { "code": null, "e": 1841, "s": 1618, "text": "In this example, we will create an entry widget along with a button in the main window. Further, the data stored in the entry widget will be pulled by a button that displays the input value in a new window or child window." }, { "code": null, "e": 2532, "s": 1841, "text": "#Import tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\nwin.title(\"Main Window\")\n#Define a function to Open a new window\ndef open_win():\n child_win= Toplevel(win)\n child_win.title(\"Child Window\")\n child_win.geometry(\"750x250\")\n content= entry.get()\n Label(child_win, text=content, font=('Bell MT', 20, 'bold')).pack()\n win.withdraw()\n#Create an Entry Widget\nentry=ttk.Entry(win, width= 40)\nentry.pack(ipady=4,pady=20)\n#Let us create a button in the Main window\nbutton= ttk.Button(win, text=\"OK\",command=open_win)\nbutton.pack(pady=20)\nwin.mainloop()" }, { "code": null, "e": 2642, "s": 2532, "text": "When we execute the above code, it will show a window with an entry widget and a button to open a new window." }, { "code": null, "e": 2703, "s": 2642, "text": "Write something in the entry widget and click the OK button," } ]
How to calculate the number of elements greater than a certain value in a vector in R?
In data analysis, sometimes we need to count the number of values that are greater than or less than a certain value, and this certain value could be a threshold. For example, we might have a vector that contain values for blood pressure of people and we might want check how many values are greater than 120. In this type of situation, we can use length function as shown in the below examples. Live Demo x1<-1:10 x1 [1] 1 2 3 4 5 6 7 8 9 10 length(x1[x1>1]) [1] 9 Live Demo x2<-rpois(100,10) x2 [1] 7 8 8 11 11 10 5 8 10 7 13 12 14 13 13 11 6 17 17 13 18 8 13 11 11 [26] 10 10 7 9 10 10 6 11 12 12 10 5 12 14 8 7 5 8 15 9 6 10 10 5 8 [51] 10 10 7 7 11 16 7 9 14 9 16 8 14 3 10 13 11 7 9 6 4 9 14 14 12 [76] 15 10 9 9 11 9 9 14 10 14 9 11 6 9 14 8 7 9 11 9 10 7 12 5 8 length(x2[x2>5]) [1] 93 Live Demo x3<-rpois(120,5) x3 [1] 4 3 5 0 3 1 1 5 7 6 8 7 4 7 9 11 2 7 3 4 1 5 7 8 5 [26] 6 8 5 5 4 4 8 4 5 9 4 9 3 4 8 8 3 10 3 6 4 4 2 6 4 [51] 7 3 4 3 6 8 2 5 7 4 6 7 6 7 5 5 4 3 8 9 7 4 4 4 1 [76] 3 5 5 5 7 8 4 6 7 4 3 5 2 6 4 6 7 6 3 5 10 7 6 4 5 [101] 10 10 7 7 3 11 7 9 3 8 1 8 5 9 3 6 5 9 5 4 length(x3[x3>5]) [1] 42 Live Demo x4<-sample(0:9,120,replace=TRUE) x4 [1] 2 4 5 3 4 3 6 3 2 3 7 5 7 8 0 2 6 0 3 3 1 8 2 1 5 5 3 4 6 3 5 2 6 1 3 9 3 [38] 2 8 6 8 4 9 0 9 2 8 0 5 8 1 5 5 1 2 7 6 8 9 8 8 2 0 0 2 2 2 4 7 2 9 2 5 7 [75] 5 4 2 8 7 3 4 5 2 8 0 2 3 4 6 3 3 3 5 8 4 9 4 8 6 2 9 0 2 6 3 1 2 8 8 4 5 [112] 8 5 7 2 4 0 4 4 0 length(x4[x4>0]) [1] 108 Live Demo x5<-sample(1:10,120,replace=TRUE) x5 [1] 2 5 9 6 1 2 5 8 6 2 2 10 6 2 4 10 6 9 10 7 9 9 7 2 7 [26] 10 9 5 2 9 4 2 2 8 5 1 7 2 3 2 2 5 2 1 2 7 3 4 9 5 [51] 8 5 9 1 1 8 2 1 1 1 5 10 1 4 9 8 9 4 9 3 1 5 1 9 6 [76] 6 5 3 9 5 3 9 2 2 8 2 5 6 4 4 1 7 2 7 4 7 2 6 1 10 [101] 10 4 3 7 4 6 1 6 9 4 8 2 4 7 1 5 5 1 6 2 length(x5[x5>1]) [1] 107 Live Demo x6<-round(rnorm(120,5,0.8),0) x6 [1] 5 5 5 5 5 5 5 5 5 4 3 5 5 5 5 5 3 5 6 3 5 5 5 6 6 6 5 5 5 5 4 5 5 6 6 5 6 [38] 5 4 5 5 5 7 6 6 5 5 6 5 5 4 4 4 6 5 4 6 6 4 5 5 7 7 5 6 5 5 6 4 5 4 6 4 6 [75] 6 5 4 4 5 6 6 6 5 5 4 5 4 4 3 6 6 7 5 6 5 5 5 5 6 7 4 5 4 6 5 7 4 6 5 5 4 [112] 6 5 5 6 5 6 5 5 6 length(x6[x6>5]) [1] 31 Live Demo x7<-round(rexp(120,1.2),0) x7 [1] 0 1 0 1 2 0 0 2 1 0 1 0 0 0 2 0 1 2 2 0 1 0 2 1 3 1 0 0 0 0 1 0 0 2 1 4 1 [38] 0 1 2 0 1 0 1 3 1 0 3 0 0 2 1 1 2 1 1 0 1 1 2 1 0 1 1 0 1 2 0 1 0 0 1 1 1 [75] 2 0 1 0 0 2 0 3 0 2 1 1 0 3 1 1 0 0 1 3 1 1 1 2 0 0 0 0 1 2 0 0 1 0 0 3 1 [112] 2 0 0 1 1 0 0 1 0 length(x7[x7>1]) [1] 21 Live Demo x8<-round(runif(120,2,5),0) x8 [1] 3 3 4 3 5 2 2 4 4 2 3 4 3 3 4 4 5 4 5 5 2 4 3 4 3 3 3 5 2 3 3 2 3 3 5 3 4 [38] 5 4 2 3 3 2 4 2 4 3 4 4 2 3 3 3 4 4 5 4 5 4 3 3 3 5 4 5 3 3 2 5 2 4 3 3 4 [75] 4 4 2 4 4 2 4 2 5 4 3 3 3 3 4 2 4 5 4 3 4 2 2 2 4 3 5 4 3 5 3 4 5 5 3 2 3 [112] 3 4 4 3 2 4 4 2 2 length(x8[x8>4]) [1] 19 Live Demo x9<-sample(100:120,120,replace=TRUE) x9 [1] 103 107 100 103 119 113 104 114 107 116 102 116 115 103 104 103 106 110 [19] 101 106 120 108 111 100 101 107 101 119 113 117 107 119 114 118 115 118 [37] 107 110 116 118 102 118 106 113 112 112 104 119 112 120 115 113 104 120 [55] 105 113 112 119 117 118 103 116 120 107 115 108 105 104 106 106 106 107 [73] 107 112 114 113 111 101 100 107 115 116 111 106 111 108 102 109 108 102 [91] 109 109 112 118 119 109 116 112 101 103 114 119 106 117 120 113 101 118 [109] 109 103 106 109 119 113 111 108 106 106 111 103 length(x9[x9>118]) [1] 11 Live Demo x10<-sample(1001:9999,120) x10 [1] 3488 7457 9491 7422 2716 8570 3510 7737 1234 9748 1222 7851 9055 7677 2331 [16] 1511 3830 7976 3207 6283 8621 8166 1846 8450 6794 2995 5714 4353 6299 5056 [31] 3793 2882 4625 6558 4089 5635 5463 4580 7773 6027 2602 1970 9832 1240 9925 [46] 2786 9829 3931 9500 9508 2617 1652 7741 1560 3448 9895 1329 8854 5187 2161 [61] 2404 4165 7624 1123 5403 8007 5057 5184 3152 8221 2635 5477 9033 6386 6171 [76] 3779 5946 2944 4102 5216 9475 6895 4553 6728 3989 7808 1869 8465 9322 5939 [91] 9161 9620 7835 3986 8397 5404 7229 5472 3104 3584 5423 3961 5396 6813 1986 [106] 7241 7724 6955 6082 8359 1904 3839 7441 6690 9601 8432 4561 7033 2314 3743 length(x10[x10>5000]) [1] 68
[ { "code": null, "e": 1458, "s": 1062, "text": "In data analysis, sometimes we need to count the number of values that are greater than or less than a certain value, and this certain value could be a threshold. For example, we might have a vector that contain values for blood pressure of people and we might want check how many values are greater than 120. In this type of situation, we can use length function as shown in the below examples." }, { "code": null, "e": 1469, "s": 1458, "text": " Live Demo" }, { "code": null, "e": 1481, "s": 1469, "text": "x1<-1:10\nx1" }, { "code": null, "e": 1506, "s": 1481, "text": "[1] 1 2 3 4 5 6 7 8 9 10" }, { "code": null, "e": 1523, "s": 1506, "text": "length(x1[x1>1])" }, { "code": null, "e": 1530, "s": 1523, "text": "[1] 9\n" }, { "code": null, "e": 1541, "s": 1530, "text": " Live Demo" }, { "code": null, "e": 1562, "s": 1541, "text": "x2<-rpois(100,10)\nx2" }, { "code": null, "e": 1835, "s": 1562, "text": "[1] 7 8 8 11 11 10 5 8 10 7 13 12 14 13 13 11 6 17 17 13 18 8 13 11 11\n[26] 10 10 7 9 10 10 6 11 12 12 10 5 12 14 8 7 5 8 15 9 6 10 10 5 8\n[51] 10 10 7 7 11 16 7 9 14 9 16 8 14 3 10 13 11 7 9 6 4 9 14 14 12\n[76] 15 10 9 9 11 9 9 14 10 14 9 11 6 9 14 8 7 9 11 9 10 7 12 5 8" }, { "code": null, "e": 1852, "s": 1835, "text": "length(x2[x2>5])" }, { "code": null, "e": 1859, "s": 1852, "text": "[1] 93" }, { "code": null, "e": 1870, "s": 1859, "text": " Live Demo" }, { "code": null, "e": 1890, "s": 1870, "text": "x3<-rpois(120,5)\nx3" }, { "code": null, "e": 2161, "s": 1890, "text": "[1] 4 3 5 0 3 1 1 5 7 6 8 7 4 7 9 11 2 7 3 4 1 5 7 8 5\n[26] 6 8 5 5 4 4 8 4 5 9 4 9 3 4 8 8 3 10 3 6 4 4 2 6 4\n[51] 7 3 4 3 6 8 2 5 7 4 6 7 6 7 5 5 4 3 8 9 7 4 4 4 1\n[76] 3 5 5 5 7 8 4 6 7 4 3 5 2 6 4 6 7 6 3 5 10 7 6 4 5\n[101] 10 10 7 7 3 11 7 9 3 8 1 8 5 9 3 6 5 9 5 4" }, { "code": null, "e": 2178, "s": 2161, "text": "length(x3[x3>5])" }, { "code": null, "e": 2185, "s": 2178, "text": "[1] 42" }, { "code": null, "e": 2196, "s": 2185, "text": " Live Demo" }, { "code": null, "e": 2232, "s": 2196, "text": "x4<-sample(0:9,120,replace=TRUE)\nx4" }, { "code": null, "e": 2492, "s": 2232, "text": "[1] 2 4 5 3 4 3 6 3 2 3 7 5 7 8 0 2 6 0 3 3 1 8 2 1 5 5 3 4 6 3 5 2 6 1 3 9 3\n[38] 2 8 6 8 4 9 0 9 2 8 0 5 8 1 5 5 1 2 7 6 8 9 8 8 2 0 0 2 2 2 4 7 2 9 2 5 7\n[75] 5 4 2 8 7 3 4 5 2 8 0 2 3 4 6 3 3 3 5 8 4 9 4 8 6 2 9 0 2 6 3 1 2 8 8 4 5\n[112] 8 5 7 2 4 0 4 4 0" }, { "code": null, "e": 2509, "s": 2492, "text": "length(x4[x4>0])" }, { "code": null, "e": 2517, "s": 2509, "text": "[1] 108" }, { "code": null, "e": 2528, "s": 2517, "text": " Live Demo" }, { "code": null, "e": 2565, "s": 2528, "text": "x5<-sample(1:10,120,replace=TRUE)\nx5" }, { "code": null, "e": 2837, "s": 2565, "text": "[1] 2 5 9 6 1 2 5 8 6 2 2 10 6 2 4 10 6 9 10 7 9 9 7 2 7\n[26] 10 9 5 2 9 4 2 2 8 5 1 7 2 3 2 2 5 2 1 2 7 3 4 9 5\n[51] 8 5 9 1 1 8 2 1 1 1 5 10 1 4 9 8 9 4 9 3 1 5 1 9 6\n[76] 6 5 3 9 5 3 9 2 2 8 2 5 6 4 4 1 7 2 7 4 7 2 6 1 10\n[101] 10 4 3 7 4 6 1 6 9 4 8 2 4 7 1 5 5 1 6 2" }, { "code": null, "e": 2854, "s": 2837, "text": "length(x5[x5>1])" }, { "code": null, "e": 2862, "s": 2854, "text": "[1] 107" }, { "code": null, "e": 2873, "s": 2862, "text": " Live Demo" }, { "code": null, "e": 2906, "s": 2873, "text": "x6<-round(rnorm(120,5,0.8),0)\nx6" }, { "code": null, "e": 3166, "s": 2906, "text": "[1] 5 5 5 5 5 5 5 5 5 4 3 5 5 5 5 5 3 5 6 3 5 5 5 6 6 6 5 5 5 5 4 5 5 6 6 5 6\n[38] 5 4 5 5 5 7 6 6 5 5 6 5 5 4 4 4 6 5 4 6 6 4 5 5 7 7 5 6 5 5 6 4 5 4 6 4 6\n[75] 6 5 4 4 5 6 6 6 5 5 4 5 4 4 3 6 6 7 5 6 5 5 5 5 6 7 4 5 4 6 5 7 4 6 5 5 4\n[112] 6 5 5 6 5 6 5 5 6" }, { "code": null, "e": 3183, "s": 3166, "text": "length(x6[x6>5])" }, { "code": null, "e": 3190, "s": 3183, "text": "[1] 31" }, { "code": null, "e": 3201, "s": 3190, "text": " Live Demo" }, { "code": null, "e": 3231, "s": 3201, "text": "x7<-round(rexp(120,1.2),0)\nx7" }, { "code": null, "e": 3491, "s": 3231, "text": "[1] 0 1 0 1 2 0 0 2 1 0 1 0 0 0 2 0 1 2 2 0 1 0 2 1 3 1 0 0 0 0 1 0 0 2 1 4 1\n[38] 0 1 2 0 1 0 1 3 1 0 3 0 0 2 1 1 2 1 1 0 1 1 2 1 0 1 1 0 1 2 0 1 0 0 1 1 1\n[75] 2 0 1 0 0 2 0 3 0 2 1 1 0 3 1 1 0 0 1 3 1 1 1 2 0 0 0 0 1 2 0 0 1 0 0 3 1\n[112] 2 0 0 1 1 0 0 1 0" }, { "code": null, "e": 3508, "s": 3491, "text": "length(x7[x7>1])" }, { "code": null, "e": 3515, "s": 3508, "text": "[1] 21" }, { "code": null, "e": 3526, "s": 3515, "text": " Live Demo" }, { "code": null, "e": 3557, "s": 3526, "text": "x8<-round(runif(120,2,5),0)\nx8" }, { "code": null, "e": 3817, "s": 3557, "text": "[1] 3 3 4 3 5 2 2 4 4 2 3 4 3 3 4 4 5 4 5 5 2 4 3 4 3 3 3 5 2 3 3 2 3 3 5 3 4\n[38] 5 4 2 3 3 2 4 2 4 3 4 4 2 3 3 3 4 4 5 4 5 4 3 3 3 5 4 5 3 3 2 5 2 4 3 3 4\n[75] 4 4 2 4 4 2 4 2 5 4 3 3 3 3 4 2 4 5 4 3 4 2 2 2 4 3 5 4 3 5 3 4 5 5 3 2 3\n[112] 3 4 4 3 2 4 4 2 2" }, { "code": null, "e": 3834, "s": 3817, "text": "length(x8[x8>4])" }, { "code": null, "e": 3841, "s": 3834, "text": "[1] 19" }, { "code": null, "e": 3852, "s": 3841, "text": " Live Demo" }, { "code": null, "e": 3892, "s": 3852, "text": "x9<-sample(100:120,120,replace=TRUE)\nx9" }, { "code": null, "e": 4407, "s": 3892, "text": "[1] 103 107 100 103 119 113 104 114 107 116 102 116 115 103 104 103 106 110\n[19] 101 106 120 108 111 100 101 107 101 119 113 117 107 119 114 118 115 118\n[37] 107 110 116 118 102 118 106 113 112 112 104 119 112 120 115 113 104 120\n[55] 105 113 112 119 117 118 103 116 120 107 115 108 105 104 106 106 106 107\n[73] 107 112 114 113 111 101 100 107 115 116 111 106 111 108 102 109 108 102\n[91] 109 109 112 118 119 109 116 112 101 103 114 119 106 117 120 113 101 118\n[109] 109 103 106 109 119 113 111 108 106 106 111 103" }, { "code": null, "e": 4426, "s": 4407, "text": "length(x9[x9>118])" }, { "code": null, "e": 4433, "s": 4426, "text": "[1] 11" }, { "code": null, "e": 4444, "s": 4433, "text": " Live Demo" }, { "code": null, "e": 4475, "s": 4444, "text": "x10<-sample(1001:9999,120)\nx10" }, { "code": null, "e": 5115, "s": 4475, "text": "[1] 3488 7457 9491 7422 2716 8570 3510 7737 1234 9748 1222 7851 9055 7677 2331\n[16] 1511 3830 7976 3207 6283 8621 8166 1846 8450 6794 2995 5714 4353 6299 5056\n[31] 3793 2882 4625 6558 4089 5635 5463 4580 7773 6027 2602 1970 9832 1240 9925\n[46] 2786 9829 3931 9500 9508 2617 1652 7741 1560 3448 9895 1329 8854 5187 2161\n[61] 2404 4165 7624 1123 5403 8007 5057 5184 3152 8221 2635 5477 9033 6386 6171\n[76] 3779 5946 2944 4102 5216 9475 6895 4553 6728 3989 7808 1869 8465 9322 5939\n[91] 9161 9620 7835 3986 8397 5404 7229 5472 3104 3584 5423 3961 5396 6813 1986\n[106] 7241 7724 6955 6082 8359 1904 3839 7441 6690 9601 8432 4561 7033 2314 3743" }, { "code": null, "e": 5137, "s": 5115, "text": "length(x10[x10>5000])" }, { "code": null, "e": 5144, "s": 5137, "text": "[1] 68" } ]
How to wrap the text within the width of the window in JavaFX?
In JavaFX, the text node is represented by the Javafx.scene.text.Text class. To insert/display text in JavaFx window you need to − Instantiate the Text class. Instantiate the Text class. Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor. Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor. Add the created node to the Group object. Add the created node to the Group object. If the length of the lines in the text you have passed, longer than the width of the window part of the text will be chopped as shown below − As a solution you can wrap the text within the width of the window by setting the value to the property wrapping with, using the setWrappingWidth() method. This method accepts a double value representing the width (in pixels) of the text. If you pass a value that is less than the width of the window, the text will be wrapped within it(the given width). import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Scanner; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class WrappingTheText extends Application { public void start(Stage stage) throws FileNotFoundException { //Reading the contents of a text file. InputStream inputStream = new FileInputStream("D:\\sample.txt"); Scanner sc = new Scanner(inputStream); StringBuffer sb = new StringBuffer(); while(sc.hasNext()) { sb.append(" "+sc.nextLine()+"\n"); } //Creating a text object Text text = new Text(10.0, 25.0, sb.toString()); //Wrapping the text text.setWrappingWidth(590); //Setting the stage Group root = new Group(text); Scene scene = new Scene(root, 595, 300, Color.BEIGE); stage.setTitle("Wrapping The Text"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } } Assume following are the contents of the sample.txt file − JavaFX is a Java library used to build Rich Internet Applications. The applications written using this library can run consistently across multiple platforms. The applications developed using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.. To develop GUI Applications using Java programming language, the programmers rely on libraries such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers can now develop GUI applications effectively with rich content. Font Name: Brush Script MT
[ { "code": null, "e": 1193, "s": 1062, "text": "In JavaFX, the text node is represented by the Javafx.scene.text.Text class. To\ninsert/display text in JavaFx window you need to −" }, { "code": null, "e": 1221, "s": 1193, "text": "Instantiate the Text class." }, { "code": null, "e": 1249, "s": 1221, "text": "Instantiate the Text class." }, { "code": null, "e": 1382, "s": 1249, "text": "Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor." }, { "code": null, "e": 1515, "s": 1382, "text": "Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor." }, { "code": null, "e": 1557, "s": 1515, "text": "Add the created node to the Group object." }, { "code": null, "e": 1599, "s": 1557, "text": "Add the created node to the Group object." }, { "code": null, "e": 1741, "s": 1599, "text": "If the length of the lines in the text you have passed, longer than the width of the window part of the text will be chopped as shown below −" }, { "code": null, "e": 1897, "s": 1741, "text": "As a solution you can wrap the text within the width of the window by setting the value to the property wrapping with, using the setWrappingWidth() method." }, { "code": null, "e": 2096, "s": 1897, "text": "This method accepts a double value representing the width (in pixels) of the text. If you pass a value that is less than the width of the window, the text will be wrapped within it(the given width)." }, { "code": null, "e": 3346, "s": 2096, "text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\nimport java.util.Scanner;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.scene.text.Text;\npublic class WrappingTheText extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //Reading the contents of a text file.\n InputStream inputStream = new FileInputStream(\"D:\\\\sample.txt\");\n Scanner sc = new Scanner(inputStream);\n StringBuffer sb = new StringBuffer();\n while(sc.hasNext()) {\n sb.append(\" \"+sc.nextLine()+\"\\n\");\n }\n //Creating a text object\n Text text = new Text(10.0, 25.0, sb.toString());\n //Wrapping the text\n text.setWrappingWidth(590);\n //Setting the stage\n Group root = new Group(text);\n Scene scene = new Scene(root, 595, 300, Color.BEIGE);\n stage.setTitle(\"Wrapping The Text\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" }, { "code": null, "e": 3405, "s": 3346, "text": "Assume following are the contents of the sample.txt file −" }, { "code": null, "e": 3954, "s": 3405, "text": "JavaFX is a Java library used to build Rich Internet Applications. The applications written \nusing this library can run consistently across multiple platforms. The applications developed \nusing JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc..\nTo develop GUI Applications using Java programming language, the programmers rely on libraries \nsuch as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers \ncan now develop GUI applications effectively with rich content." }, { "code": null, "e": 3981, "s": 3954, "text": "Font Name: Brush Script MT" } ]
Tutorial on LSTMs: A Computational Perspective | by Manu Rastogi | Towards Data Science
1. Introduction2. Why Do we need RNNs?3. RNN Training and Inference4. Structure of an RNN5. Time Unrolling6. Vanishing Gradient7. Long Short-Term Memory (LSTM)8. LSTM equations9. Understanding the LSTM dimensionalities10. Time Unroll and Multiple Layers11. Example: Sentiment Analysis using LSTM12. Testing your knowledge In recent times there has been a lot of interest in embedding deep learning models into hardware. Energy is of paramount importance when it comes to deep learning model deployment especially at the edge. There is a great blog post on why energy matters for AI@Edge by Pete Warden on “Why the future of Machine Learning is Tiny”. Energy optimizations for programs (or models) can only be done with a good understanding of the underlying computations. Over the last few years of working with deep learning folks — hardware architects, micro-kernel coders, model developers, platform programmers, and interviewees (especially interviewees) I have discovered that people understand LSTMs from a qualitative perspective but not well from a quantitative position. If you don’t understand something well you would not be able to optimize it. This lack of understanding has contributed to the LSTMs starting to fall out of favor. This tutorial tries to bridge that gap between the qualitative and quantitative by explaining the computations required by LSTMs through the equations. Also, this is a way for me to consolidate my understanding of LSTM from a computational perspective. Hopefully, it would also be useful to other people working with LSTMs in different capacities. NOTE: The disclaimer here is that neither am I claiming to be an expert on LSTMs nor am I claiming to be completely correct in my understanding. Feel free to drop a comment if there is something that is not correct or confusing. Recurrent Neural Networks (RNNs) are required because we would like to design networks that can recognize (or operate) on sequences. Convolutional Neural Networks (CNNs) don’t care about the order of the images that they recognize. RNN, on the other hand, is used for sequences such as videos, handwriting recognition, etc. This is illustrated with a high-level cartoonish diagram below in Figure 1. In a nutshell, we need RNNs if we are trying to recognize a sequence like a video, handwriting or speech. A cautionary note, we are still not talking about the LSTMs. We are still trying to understand the RNN. We will move to the LSTMs a bit later. RNNs are required when we are trying to work with sequences. In case you skipped the previous section we are first trying to understand the workings of a vanilla RNN. If you are trying to understand LSTMs I would encourage and urge you to read through this section. In this section, we would understand the following: Structure of an RNN.Time unrolling Structure of an RNN. Time unrolling We will build on these concepts to understand the LSTM based networks better. Shown in figure 2 is a simplistic RNN structure. The diagram is inspired by the deep learning book (specifically chapter 10 figure 10.3 on page 373). A few things to note in the figure: I have stated the variables for each node in red color in the parenthesis. In the next diagram and the following section I will use the variables (in equations) so please take a few seconds and absorb these. The direction of the arrow from the expected output to the loss is not a typo. Variables U, V, W are the weight matrices of this network. The yellow blob in the feedback path (indicated by the green arrow) indicates the unit delay. If you are from DSP think of this as (z^-1) The feedback (indicated by the green arrow) is what makes this toy example qualify as an RNN. Before we get into the equations. Let’s look at the diagram and understand what is happening. At the beginning of the universe. Input ‘x(t=0)’gets multiplied with the matrix U resulting in x(t=0)*U .The feedback from the last time step gets multiplied to the matrix W. Since this is the initial stage the feedback value is zero (to keep it simple). Hence the feedback value is h(t=-1)*W = 0. Thus the product is 0+x(t=0)*U = x(t=0)*UNow, this gets multiplied with the matrix V resulting in x(t=0)*U*V.For the next time step, this value will get stored in h(t) and will not be a non-zero. At the beginning of the universe. Input ‘x(t=0)’gets multiplied with the matrix U resulting in x(t=0)*U . The feedback from the last time step gets multiplied to the matrix W. Since this is the initial stage the feedback value is zero (to keep it simple). Hence the feedback value is h(t=-1)*W = 0. Thus the product is 0+x(t=0)*U = x(t=0)*U Now, this gets multiplied with the matrix V resulting in x(t=0)*U*V. For the next time step, this value will get stored in h(t) and will not be a non-zero. Thus the above can also be summarized as the following equations: In the above equations, we ignored the non-linearities and the biases. Adding those in the equations look like the following. Don’t worry if these look complicated. RNNs have a feedback loop in their structure. This is what allows for them to work with sequences. Time unrolling is an important concept to grasp for understanding RNNs and understanding LSTMs. RNNs can also be represented as time unrolled version of themselves. It is another way of representing them nothing has changed in terms of the equations. Time unroll is just another representation and not a transformation. The reason we want to represent them this way is because it makes it easier to derive forward and backward pass equations. Time unrolling is illustrated in the figure below: In the figure above the left side, the RNN structure is the same as we saw before. The right side is time-unrolled representation. A few key takeaways from this figure: The weight matrices U, V, W don’t change with time unroll. This means that once the RNN is trained the weight matrices are fixed during inference and not time-dependent. In other words, the same weight matrices (U, V, W) are used in every time step.The lightly shaded h(..) on both sides indicate the time steps before h(t-1) and after h(t+1).The above figure shows the forward (or the inference) pass of the RNN. At every time step, there is an input and a corresponding output.In the forward pass, the “information” (or the memory) is passed onto the next stage through the variable h. The weight matrices U, V, W don’t change with time unroll. This means that once the RNN is trained the weight matrices are fixed during inference and not time-dependent. In other words, the same weight matrices (U, V, W) are used in every time step. The lightly shaded h(..) on both sides indicate the time steps before h(t-1) and after h(t+1). The above figure shows the forward (or the inference) pass of the RNN. At every time step, there is an input and a corresponding output. In the forward pass, the “information” (or the memory) is passed onto the next stage through the variable h. RNNs can be represented as time unrolled versions. This is just a representation and not a transformation. The weight matrices U, V, W are not time dependent in the forward pass. RNNs suffer from the problem of preserving the context for long-range sequences. In other words, RNNs are unable to work with sequences that are very long (think long sentences or long speeches). The effect of a given input on the hidden layer (and thus the output) either decays exponentially (or blows and saturates) as a function of time (or sequence length). The vanishing gradient problem is illustrated in the figure below from Alex Graves’ thesis. The shades of the nodes indicate the sensitivity of the network nodes to the input at a given time. Darker the shade the greater is the sensitivity and vice-versa. As sown the sensitivity decays as we move from timestep =1 to timestep=7 very fast. The network forgets the first input. This is the key motivation for using LSTMs. The vanishing gradient problem has resulted in several attempts by researchers to propose solutions. The most effective of those is the LSTM or the long short-term memory proposed by Hochreiter in 1997. Vanilla RNNs suffer from insenstivty to input for long seqences (sequence length approximately greater than 10 time steps). LSTMs proposed in 1997 remain the most popular solution for overcoming this short coming of the RNNs. LSTMs were proposed by Hochreiter in 1997 as a method of alleviating the pain points associated with the vanilla RNNs. Several blogs and images describe LSTMs. As you can see there is a significant variation in how the LSTMs are described. In this post, I want to describe them through the equations. I find them easier to understand through equations. There are excellent blogs out there for understanding them intuitively I highly recommend checking them out: (a) Christopher Olah’s blog. (b) LSTM from Wikipedia © Shi Yan’s blog on Medium (d) LSTMs from the deep learning book (e) Nvidia’s blog on accelerating LSTMs The figure below shows the input and outputs of an LSTM for a single timestep. This is one timestep input, output and the equations for a time unrolled representation. The LSTM has an input x(t) which can be the output of a CNN or the input sequence directly. h(t-1) and c(t-1) are the inputs from the previous timestep LSTM. o(t) is the output of the LSTM for this timestep. The LSTM also generates the c(t) and h(t) for the consumption of the next time step LSTM. Note that the LSTM equations also generate f(t), i(t), c’(t) these are for internal consumption of the LSTM and are used for generating c(t) and h(t). There are a few key points to note from the above: The above equations are for only a one-time step. This means that these equations will have to be recomputed for the next time step. Thus if we have a sequence of 10 timesteps then the above equations will be computed 10 times for each timestep respectively.The weight matrices (Wf, Wi, Wo, Wc, Uf, Ui, Uo, Uc) and biases (bf, bi, bo, bc) are not time-dependent. This means that these weight matrices don’t change from one time step to another. In other words to calculate the outputs of different timesteps same weight matrices are used. The above equations are for only a one-time step. This means that these equations will have to be recomputed for the next time step. Thus if we have a sequence of 10 timesteps then the above equations will be computed 10 times for each timestep respectively. The weight matrices (Wf, Wi, Wo, Wc, Uf, Ui, Uo, Uc) and biases (bf, bi, bo, bc) are not time-dependent. This means that these weight matrices don’t change from one time step to another. In other words to calculate the outputs of different timesteps same weight matrices are used. The pseudo-code snippet below shows LSTM time computation for ten timesteps. Code snippet illustrating the LSTM computation for 10 timesteps. The weight matrices of an LSTM network do not change from one timestep to another. There are 6 equations that make up an LSTM. If an LSTM is learning a sequence of length ‘seq_len’. Then these six equations will be computed a total of ‘seq_len’. Essentially for everytime step the equations will be computed. Armed with the understanding of the computations required for a single timestep of an LSTM we move to the next aspect — dimensionalities. In my experience, the LSTM dimensionalities are one of the key contributors to the confusion around LSTMs. Plus it’s one my favorite interview questions to ask ;) Let take a look at the LSTM equations again in the figure below. As you already know these are the LSTM equations for a single timestep: Let’s start with an easy one x(t). This is the input signal/feature vector/CNN output. I am assuming that x(t) comes from an embedding layer (think word2vec) and has an input dimensionality of [80x1]. This implies that Wf has a dimensionality of [Some_Value x 80]. Thus so far we have: x(t) is [80 X 1] — input assumption Wf is [Some_value X 80 ] — Matrix multiplication laws. Let’s make another assumption the output dimensionality of the LSTM is [12x1]. Assume this is the number of output classes. Thus at every timestep, the LSTM generates an output o(t) of size [12 x 1]. Now since o(t) is [12 x 1] then h(t) has to be [12x1] because h(t) is calculated by doing an element by element multiplication (look at the last equation on how h(t) is calculated from o(t) and c(t)). Since o(t) is [12x1] then c(t) has to be [12x1]. If c(t) is [12x1] then f(t), c(t-1), i(t) and c’(t) have to be [12x1]. Why? Because both h(t) and c(t) are calculated by element wise multiplication. Thus we have: o(t) is [12 X 1] — output assumption h(t) and c(t) are [12x1] — Because h(t) is calculated by element-wise multiplication of o(t) and tanh(c(t)) in the equations. f(t), c(t-1), i(t) and c’(t) are [12x1] — Because c(t) is [12x1] and is estimated by element wise operations requiring the same size. Since f(t) is of dimension [12x1] then the product of Wf and x(t) has to be [12x1]. We know that x(t) is [80x1] (because we assumed that) then Wf has to be [12x80]. Also looking at the equation for f(t) we realize that the bias term bf is [12x1]. Thus we have: x(t) is [80 X 1] — input assumption o(t) is [12 X 1] — output assumption h(t) and c(t) are [12x1] — Because h(t) is calculated by element-wise multiplication of o(t) and tanh(c(t)) in the equations. f(t), c(t-1), i(t) and c’(t) are [12x1] — Because c(t) is [12x1] and is estimated by element wise operations requiring the same size. Wf is [12x80] — Because f(t) is [12x1] and x(t) is [80x1] bf is [12x1] — Because all other terms are [12x1]. The above might seem a bit more complicated than it has to be. Take a moment and work through it yourself. Trust me it ain’t that confusing. Now onto the confusing part :) Just kidding! In the calculation of f(t) the product of Uf and h(t-1) also has to be [12x1]. Now we know based on the previous discussion that h(t-1) is [12x1]. h(t) and h(t-1) will have the same dimensionality of [12x1]. Thus Uf will have a dimensionality of [12x12]. All Ws (Wf, Wi, Wo, Wc) will have the same dimension of [12x80] and all biases (bf, bi, bc, bo) will have the same dimension of [12x1] and all Us (Uf, Ui, Uo, Uc) will have the same dimension of [12x12]. Therefore: x(t) is [80 X 1] — input assumption o(t) is [12 X 1] — output assumption Wf, Wi, Wc, Wo each have dimensions of [12x80] Uf, Ui, Uc, Uo each have dimension of [12x12] bf, bi, bc, bo each have dimensions of [12x1] ht, ot, ct, ft, it each have a dimension of [12x1] The total weight matrix size of the LSTM is Weights_LSTM = 4*[12x80] + 4*[12x12] + 4*[12x1] = 4*[Output_Dim x Input_Dim] + 4*[Output_Dim2] + 4*[Input_Dim] = 4*[960] + 4*[144] + 4*[12] = 3840 + 576+48= 4,464 Lets verify paste the following code into your python setup Notice the number of params for the LSTM is 4464. Which is what we got through our calculations too! Before we move into the next section, I want to emphasize a key aspect. LSTMs have two things that define them: The input dimension and the output dimensionality (and the time unroll which I will get to in a bit). In literature (papers/blogs/code document) there is a lot of ambiguity in nomenclature. Some places it is called the number of Units, hidden dimension, output dimensionality, number of LSTM units, etc. I am no debating which is correct or which is wrong just that in my opinion these generally mean the same thing — the output dimensionality. So far we have looked at the weight matrix size. The weight matrices are consolidated stored as a single matrix by most frameworks. The figure below illustrates this weight matrix and the corresponding dimensions. NOTE: Depending on which framework you are using the weight matrices will be stored in a different order. As an example, Pytorch may save Wi before Wf or Caffe may store Wo first. There are two parameters that define an LSTM for a timestep. The input dimension and the output dimension. The weight matrix size is of the size: 4*Output_Dim*(Output_Dim + Input_Dim + 1) [Thanks Cless for catching the typo]. There is a lot of ambiguity when it comes to LSTMs — number of units, hidden dimension and output dimensionality. Just remember that there are two parameters that define an LSTM — input dimensionality and the output dimensionality. In the figures below there are two separate LSTM networks. Both networks are shown to be unrolled for three timesteps. The first network in figure (A) is a single layer network whereas the network in figure (B) is a two-layer network. In the case of the first single-layer network, we initialize the h and c and each timestep an output is generated along with the h and c to be consumed by the next timestep. Note even though at the last timestep h(t) and c(t) is discarded I have shown them for the sake of completion. As we discussed before the weights (Ws, Us, and bs) are the same for the three timesteps. The two-layer network has two LSTM layers. The output of the first layer will be the input of the second layer. They both have their weight matrices and respective hs, cs, and os. I indicate this through the use of the superscripts. Let’s take a look at a very simple albeit realistic LSTM network to see how this would work. The task is simple we have to come up with a network that tells us whether or not a given sentence is negative or positive. To keep things simple, we will assume that the sentences are fixed length. If the actual sentence has fewer words than the expected length you pad zeros and if it has more words than the sequence length you truncate the sentence. In our case, we will restrict the sentence length to be 3 words. Why 3 words? just a number I like because it is easier for me to draw the diagrams :). On a serious note, you would use plot the histogram of the number of words in a sentence in your dataset and choose a value depending on the shape of the histogram. Sentences that are largen than predetermined word count will be truncated and sentences that have fewer words will be padded with zero or a null word. Anyways back to our example. We are sticking to three words. We will use an embedding layer which converts an English word into a numerical vector of size [80x1]. Why 80? because I like the number 80:) Anyways the network is shown below in the figure. We will try and categorize a sentence — “I am happy”. At t=0 the first word “I” gets converted to a numerical vector of length [80x1] by the embedding layer. and passes through the LSTM followed by a fully connected layer. Then at time t=1, the second word goes through the network followed by the last word “happy” at t=2. We would like the network to wait for the entire sentence to let us know about the sentiment. We don’t want it to be overeager and tell us the sentiment at every word. This is why in the figure below the output from the LSTM is shown only at the last step. Keras calls this parameter as return_sequence. Setting this to False or True will determine whether or not the LSTM and subsequently the network generates an output at very timestep or for every word in our example. A key thing that I would like to underscore here is that just because you set the return sequences to false doesn’t mean that the LSTM equations are being modified. They are still calculating the h(t), c(t) for every timestep. Thus the amount of computation doesn’t reduce. Here is an example from Keras for sentiment analysis on IMDB dataset: https://github.com/keras-team/keras/blob/master/examples/imdb_lstm.py Let’s try and consolidate what we have learned so far. In this section, I am listing a bunch of questions for some sample/toy networks. It helps me feel better if I can test if my understanding is correct hence this format in this section. Alternatively, you can also use these for interview preparation around LSTMs :) Sample LSTM Network # 1 How many LSTM layers are there in this network? — The network has one layer. Don’t get confused with multiple LSTM boxes, they represent the different timesteps, there is only one layer.As shown what is the sequence length or the number of timesteps? — The number of timesteps is 3. Look at the time indices.If the input dimension i.e. x(t) is [18x1] and o(t) is [19x1] what are the dimensions of h(t), c(t)? — h(t) and c(t) will be of the dimension [19x1] How many LSTM layers are there in this network? — The network has one layer. Don’t get confused with multiple LSTM boxes, they represent the different timesteps, there is only one layer. As shown what is the sequence length or the number of timesteps? — The number of timesteps is 3. Look at the time indices. If the input dimension i.e. x(t) is [18x1] and o(t) is [19x1] what are the dimensions of h(t), c(t)? — h(t) and c(t) will be of the dimension [19x1] Sample LSTM Network # 2 How many LSTM layers are there in this network? — The total number of LSTM layers is 5.As shown what is the sequence length or the number of timesteps? — This network has a sequence length of 1.If x(t) is [45x1] and h1(int) is [25x1] what are the dimensions of — c1(int) and o1(t) ? — c1(t) and o1(t) will have the same dimensions as h1(t) i.e [25x1]If x(t) is [4x1], h1(int) is [5x1] and o2(t) is of the size [4x1]. What is the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is [4*output_dim*(input_dim+output_dim+1)]. The input dim for LSTM0 is [4x1], output_dim for LSTM0 is [5x1]. The input to LSTM1 is the output of LSTM0 thus the input dim of LSTM1 is same as the output_dim of LSTM0 i.e. [5x1]. The output dim of LSTM1 is [4x1]. Thus LSTM0 is [4*6*(5+4+1)]=288 and LSTM1 is [4*4*(5+4+1)] = 160.If x(t) is [10x1], h1(int) is [7x1] what is the input dimension of LSTM1? — Look at the explanation above. We need to know the output dimensionality of LSTM0 before we can calculate this.If x(t) is [6x1], h1(int) is [4x1], o2(t) is [3x1], o3(t) is [5x1], o4(t) is [9x1] and o5(t) is [10x1] what is total weight size of the network? — The weight matrix of an LSTM for a single timestep is given as [4*output_dim*(input_dim+output_dim+1)]. Work by estimating the input ouput dimensionalities of a single layer. How many LSTM layers are there in this network? — The total number of LSTM layers is 5. As shown what is the sequence length or the number of timesteps? — This network has a sequence length of 1. If x(t) is [45x1] and h1(int) is [25x1] what are the dimensions of — c1(int) and o1(t) ? — c1(t) and o1(t) will have the same dimensions as h1(t) i.e [25x1] If x(t) is [4x1], h1(int) is [5x1] and o2(t) is of the size [4x1]. What is the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is [4*output_dim*(input_dim+output_dim+1)]. The input dim for LSTM0 is [4x1], output_dim for LSTM0 is [5x1]. The input to LSTM1 is the output of LSTM0 thus the input dim of LSTM1 is same as the output_dim of LSTM0 i.e. [5x1]. The output dim of LSTM1 is [4x1]. Thus LSTM0 is [4*6*(5+4+1)]=288 and LSTM1 is [4*4*(5+4+1)] = 160. If x(t) is [10x1], h1(int) is [7x1] what is the input dimension of LSTM1? — Look at the explanation above. We need to know the output dimensionality of LSTM0 before we can calculate this. If x(t) is [6x1], h1(int) is [4x1], o2(t) is [3x1], o3(t) is [5x1], o4(t) is [9x1] and o5(t) is [10x1] what is total weight size of the network? — The weight matrix of an LSTM for a single timestep is given as [4*output_dim*(input_dim+output_dim+1)]. Work by estimating the input ouput dimensionalities of a single layer. Sample LSTM Network # 3 How many layers are in this network? — There are two layersWhat is the sequence length as shown in this network? — Each layer is unrolled 2 times.If x(t) is [80x1] and h1(int) is [10x1] what will be the dimensions of o(t), h1(t), c1(t), f(t), i(t). These are not shown in the figure, but you should be able to label this. — o(t), h1(t), c1(t), f1(t), i1(t) will have the same dimension as h1(t) i.e. [10x1]If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What are the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+output_dim+1). LSTM0 will be 4*5*(4+5+1) i.e. 200. LSTM2 will be 4*6*(5+5+1) = 264.If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What is the total number of multiply and accumulate operations? — I am leaving this one for the reader. If enough folks ask then I will answer :) How many layers are in this network? — There are two layers What is the sequence length as shown in this network? — Each layer is unrolled 2 times. If x(t) is [80x1] and h1(int) is [10x1] what will be the dimensions of o(t), h1(t), c1(t), f(t), i(t). These are not shown in the figure, but you should be able to label this. — o(t), h1(t), c1(t), f1(t), i1(t) will have the same dimension as h1(t) i.e. [10x1] If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What are the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+output_dim+1). LSTM0 will be 4*5*(4+5+1) i.e. 200. LSTM2 will be 4*6*(5+5+1) = 264. If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What is the total number of multiply and accumulate operations? — I am leaving this one for the reader. If enough folks ask then I will answer :) Sample LSTM Network # 4 How many layers are there? — There are 3 layers.As shown how many timesteps is this network unrolled? — Each layer is unrolled 3 times.How many equations will be executed in all for this network? — Each LSTM requires 6 equations (some texts consolidate to 5 equations). Then 6 equations/time step/LSTM. Therefore 6 equations * 3 LSTM Layers * 3 timesteps = 54 equationsIf x(t) is [10x1] what other information would you need to estimate the weight matrix of LSTM1? What about LSTM2? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+out_dim+1). Thus for each LSTM, we need both input_dim and the output_dim. The output of LSTM is the input of LSTM1. We have the input dimension of [10x1] so we need the output dimension or o1(int) dimension and the output dimensions of LSTM1 i.e. o2(t). Similarly for the LSTM2, we need to know, o2(t) and o3(t). How many layers are there? — There are 3 layers. As shown how many timesteps is this network unrolled? — Each layer is unrolled 3 times. How many equations will be executed in all for this network? — Each LSTM requires 6 equations (some texts consolidate to 5 equations). Then 6 equations/time step/LSTM. Therefore 6 equations * 3 LSTM Layers * 3 timesteps = 54 equations If x(t) is [10x1] what other information would you need to estimate the weight matrix of LSTM1? What about LSTM2? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+out_dim+1). Thus for each LSTM, we need both input_dim and the output_dim. The output of LSTM is the input of LSTM1. We have the input dimension of [10x1] so we need the output dimension or o1(int) dimension and the output dimensions of LSTM1 i.e. o2(t). Similarly for the LSTM2, we need to know, o2(t) and o3(t). The blogs and papers around LSTMs often talk about it at a qualitative level. In this article, I have tried to explain the LSTM operation from a computation perspective. Understanding LSTMs from a computational perspective is crucial, especially for machine learning accelerator designers. DL Interview Preparation Christopher Olah’s blog. Shi Yan’s blog LSTMs from the deep learning book Nvidia’s blog on accelerating LSTMs LSTMs on Machine Learning Mastery Pete Warden’s blog on “Why the future of Machine Learning is Tiny”.
[ { "code": null, "e": 368, "s": 46, "text": "1. Introduction2. Why Do we need RNNs?3. RNN Training and Inference4. Structure of an RNN5. Time Unrolling6. Vanishing Gradient7. Long Short-Term Memory (LSTM)8. LSTM equations9. Understanding the LSTM dimensionalities10. Time Unroll and Multiple Layers11. Example: Sentiment Analysis using LSTM12. Testing your knowledge" }, { "code": null, "e": 1638, "s": 368, "text": "In recent times there has been a lot of interest in embedding deep learning models into hardware. Energy is of paramount importance when it comes to deep learning model deployment especially at the edge. There is a great blog post on why energy matters for AI@Edge by Pete Warden on “Why the future of Machine Learning is Tiny”. Energy optimizations for programs (or models) can only be done with a good understanding of the underlying computations. Over the last few years of working with deep learning folks — hardware architects, micro-kernel coders, model developers, platform programmers, and interviewees (especially interviewees) I have discovered that people understand LSTMs from a qualitative perspective but not well from a quantitative position. If you don’t understand something well you would not be able to optimize it. This lack of understanding has contributed to the LSTMs starting to fall out of favor. This tutorial tries to bridge that gap between the qualitative and quantitative by explaining the computations required by LSTMs through the equations. Also, this is a way for me to consolidate my understanding of LSTM from a computational perspective. Hopefully, it would also be useful to other people working with LSTMs in different capacities." }, { "code": null, "e": 1867, "s": 1638, "text": "NOTE: The disclaimer here is that neither am I claiming to be an expert on LSTMs nor am I claiming to be completely correct in my understanding. Feel free to drop a comment if there is something that is not correct or confusing." }, { "code": null, "e": 2267, "s": 1867, "text": "Recurrent Neural Networks (RNNs) are required because we would like to design networks that can recognize (or operate) on sequences. Convolutional Neural Networks (CNNs) don’t care about the order of the images that they recognize. RNN, on the other hand, is used for sequences such as videos, handwriting recognition, etc. This is illustrated with a high-level cartoonish diagram below in Figure 1." }, { "code": null, "e": 2516, "s": 2267, "text": "In a nutshell, we need RNNs if we are trying to recognize a sequence like a video, handwriting or speech. A cautionary note, we are still not talking about the LSTMs. We are still trying to understand the RNN. We will move to the LSTMs a bit later." }, { "code": null, "e": 2577, "s": 2516, "text": "RNNs are required when we are trying to work with sequences." }, { "code": null, "e": 2782, "s": 2577, "text": "In case you skipped the previous section we are first trying to understand the workings of a vanilla RNN. If you are trying to understand LSTMs I would encourage and urge you to read through this section." }, { "code": null, "e": 2834, "s": 2782, "text": "In this section, we would understand the following:" }, { "code": null, "e": 2869, "s": 2834, "text": "Structure of an RNN.Time unrolling" }, { "code": null, "e": 2890, "s": 2869, "text": "Structure of an RNN." }, { "code": null, "e": 2905, "s": 2890, "text": "Time unrolling" }, { "code": null, "e": 2983, "s": 2905, "text": "We will build on these concepts to understand the LSTM based networks better." }, { "code": null, "e": 3133, "s": 2983, "text": "Shown in figure 2 is a simplistic RNN structure. The diagram is inspired by the deep learning book (specifically chapter 10 figure 10.3 on page 373)." }, { "code": null, "e": 3169, "s": 3133, "text": "A few things to note in the figure:" }, { "code": null, "e": 3377, "s": 3169, "text": "I have stated the variables for each node in red color in the parenthesis. In the next diagram and the following section I will use the variables (in equations) so please take a few seconds and absorb these." }, { "code": null, "e": 3456, "s": 3377, "text": "The direction of the arrow from the expected output to the loss is not a typo." }, { "code": null, "e": 3515, "s": 3456, "text": "Variables U, V, W are the weight matrices of this network." }, { "code": null, "e": 3653, "s": 3515, "text": "The yellow blob in the feedback path (indicated by the green arrow) indicates the unit delay. If you are from DSP think of this as (z^-1)" }, { "code": null, "e": 3747, "s": 3653, "text": "The feedback (indicated by the green arrow) is what makes this toy example qualify as an RNN." }, { "code": null, "e": 3841, "s": 3747, "text": "Before we get into the equations. Let’s look at the diagram and understand what is happening." }, { "code": null, "e": 4335, "s": 3841, "text": "At the beginning of the universe. Input ‘x(t=0)’gets multiplied with the matrix U resulting in x(t=0)*U .The feedback from the last time step gets multiplied to the matrix W. Since this is the initial stage the feedback value is zero (to keep it simple). Hence the feedback value is h(t=-1)*W = 0. Thus the product is 0+x(t=0)*U = x(t=0)*UNow, this gets multiplied with the matrix V resulting in x(t=0)*U*V.For the next time step, this value will get stored in h(t) and will not be a non-zero." }, { "code": null, "e": 4441, "s": 4335, "text": "At the beginning of the universe. Input ‘x(t=0)’gets multiplied with the matrix U resulting in x(t=0)*U ." }, { "code": null, "e": 4676, "s": 4441, "text": "The feedback from the last time step gets multiplied to the matrix W. Since this is the initial stage the feedback value is zero (to keep it simple). Hence the feedback value is h(t=-1)*W = 0. Thus the product is 0+x(t=0)*U = x(t=0)*U" }, { "code": null, "e": 4745, "s": 4676, "text": "Now, this gets multiplied with the matrix V resulting in x(t=0)*U*V." }, { "code": null, "e": 4832, "s": 4745, "text": "For the next time step, this value will get stored in h(t) and will not be a non-zero." }, { "code": null, "e": 4898, "s": 4832, "text": "Thus the above can also be summarized as the following equations:" }, { "code": null, "e": 5063, "s": 4898, "text": "In the above equations, we ignored the non-linearities and the biases. Adding those in the equations look like the following. Don’t worry if these look complicated." }, { "code": null, "e": 5162, "s": 5063, "text": "RNNs have a feedback loop in their structure. This is what allows for them to work with sequences." }, { "code": null, "e": 5258, "s": 5162, "text": "Time unrolling is an important concept to grasp for understanding RNNs and understanding LSTMs." }, { "code": null, "e": 5656, "s": 5258, "text": "RNNs can also be represented as time unrolled version of themselves. It is another way of representing them nothing has changed in terms of the equations. Time unroll is just another representation and not a transformation. The reason we want to represent them this way is because it makes it easier to derive forward and backward pass equations. Time unrolling is illustrated in the figure below:" }, { "code": null, "e": 5787, "s": 5656, "text": "In the figure above the left side, the RNN structure is the same as we saw before. The right side is time-unrolled representation." }, { "code": null, "e": 5825, "s": 5787, "text": "A few key takeaways from this figure:" }, { "code": null, "e": 6413, "s": 5825, "text": "The weight matrices U, V, W don’t change with time unroll. This means that once the RNN is trained the weight matrices are fixed during inference and not time-dependent. In other words, the same weight matrices (U, V, W) are used in every time step.The lightly shaded h(..) on both sides indicate the time steps before h(t-1) and after h(t+1).The above figure shows the forward (or the inference) pass of the RNN. At every time step, there is an input and a corresponding output.In the forward pass, the “information” (or the memory) is passed onto the next stage through the variable h." }, { "code": null, "e": 6663, "s": 6413, "text": "The weight matrices U, V, W don’t change with time unroll. This means that once the RNN is trained the weight matrices are fixed during inference and not time-dependent. In other words, the same weight matrices (U, V, W) are used in every time step." }, { "code": null, "e": 6758, "s": 6663, "text": "The lightly shaded h(..) on both sides indicate the time steps before h(t-1) and after h(t+1)." }, { "code": null, "e": 6895, "s": 6758, "text": "The above figure shows the forward (or the inference) pass of the RNN. At every time step, there is an input and a corresponding output." }, { "code": null, "e": 7004, "s": 6895, "text": "In the forward pass, the “information” (or the memory) is passed onto the next stage through the variable h." }, { "code": null, "e": 7183, "s": 7004, "text": "RNNs can be represented as time unrolled versions. This is just a representation and not a transformation. The weight matrices U, V, W are not time dependent in the forward pass." }, { "code": null, "e": 7923, "s": 7183, "text": "RNNs suffer from the problem of preserving the context for long-range sequences. In other words, RNNs are unable to work with sequences that are very long (think long sentences or long speeches). The effect of a given input on the hidden layer (and thus the output) either decays exponentially (or blows and saturates) as a function of time (or sequence length). The vanishing gradient problem is illustrated in the figure below from Alex Graves’ thesis. The shades of the nodes indicate the sensitivity of the network nodes to the input at a given time. Darker the shade the greater is the sensitivity and vice-versa. As sown the sensitivity decays as we move from timestep =1 to timestep=7 very fast. The network forgets the first input." }, { "code": null, "e": 8170, "s": 7923, "text": "This is the key motivation for using LSTMs. The vanishing gradient problem has resulted in several attempts by researchers to propose solutions. The most effective of those is the LSTM or the long short-term memory proposed by Hochreiter in 1997." }, { "code": null, "e": 8396, "s": 8170, "text": "Vanilla RNNs suffer from insenstivty to input for long seqences (sequence length approximately greater than 10 time steps). LSTMs proposed in 1997 remain the most popular solution for overcoming this short coming of the RNNs." }, { "code": null, "e": 8515, "s": 8396, "text": "LSTMs were proposed by Hochreiter in 1997 as a method of alleviating the pain points associated with the vanilla RNNs." }, { "code": null, "e": 8858, "s": 8515, "text": "Several blogs and images describe LSTMs. As you can see there is a significant variation in how the LSTMs are described. In this post, I want to describe them through the equations. I find them easier to understand through equations. There are excellent blogs out there for understanding them intuitively I highly recommend checking them out:" }, { "code": null, "e": 8887, "s": 8858, "text": "(a) Christopher Olah’s blog." }, { "code": null, "e": 8911, "s": 8887, "text": "(b) LSTM from Wikipedia" }, { "code": null, "e": 8938, "s": 8911, "text": "© Shi Yan’s blog on Medium" }, { "code": null, "e": 8976, "s": 8938, "text": "(d) LSTMs from the deep learning book" }, { "code": null, "e": 9016, "s": 8976, "text": "(e) Nvidia’s blog on accelerating LSTMs" }, { "code": null, "e": 9482, "s": 9016, "text": "The figure below shows the input and outputs of an LSTM for a single timestep. This is one timestep input, output and the equations for a time unrolled representation. The LSTM has an input x(t) which can be the output of a CNN or the input sequence directly. h(t-1) and c(t-1) are the inputs from the previous timestep LSTM. o(t) is the output of the LSTM for this timestep. The LSTM also generates the c(t) and h(t) for the consumption of the next time step LSTM." }, { "code": null, "e": 9633, "s": 9482, "text": "Note that the LSTM equations also generate f(t), i(t), c’(t) these are for internal consumption of the LSTM and are used for generating c(t) and h(t)." }, { "code": null, "e": 9684, "s": 9633, "text": "There are a few key points to note from the above:" }, { "code": null, "e": 10223, "s": 9684, "text": "The above equations are for only a one-time step. This means that these equations will have to be recomputed for the next time step. Thus if we have a sequence of 10 timesteps then the above equations will be computed 10 times for each timestep respectively.The weight matrices (Wf, Wi, Wo, Wc, Uf, Ui, Uo, Uc) and biases (bf, bi, bo, bc) are not time-dependent. This means that these weight matrices don’t change from one time step to another. In other words to calculate the outputs of different timesteps same weight matrices are used." }, { "code": null, "e": 10482, "s": 10223, "text": "The above equations are for only a one-time step. This means that these equations will have to be recomputed for the next time step. Thus if we have a sequence of 10 timesteps then the above equations will be computed 10 times for each timestep respectively." }, { "code": null, "e": 10763, "s": 10482, "text": "The weight matrices (Wf, Wi, Wo, Wc, Uf, Ui, Uo, Uc) and biases (bf, bi, bo, bc) are not time-dependent. This means that these weight matrices don’t change from one time step to another. In other words to calculate the outputs of different timesteps same weight matrices are used." }, { "code": null, "e": 10840, "s": 10763, "text": "The pseudo-code snippet below shows LSTM time computation for ten timesteps." }, { "code": null, "e": 10905, "s": 10840, "text": "Code snippet illustrating the LSTM computation for 10 timesteps." }, { "code": null, "e": 11214, "s": 10905, "text": "The weight matrices of an LSTM network do not change from one timestep to another. There are 6 equations that make up an LSTM. If an LSTM is learning a sequence of length ‘seq_len’. Then these six equations will be computed a total of ‘seq_len’. Essentially for everytime step the equations will be computed." }, { "code": null, "e": 11515, "s": 11214, "text": "Armed with the understanding of the computations required for a single timestep of an LSTM we move to the next aspect — dimensionalities. In my experience, the LSTM dimensionalities are one of the key contributors to the confusion around LSTMs. Plus it’s one my favorite interview questions to ask ;)" }, { "code": null, "e": 11652, "s": 11515, "text": "Let take a look at the LSTM equations again in the figure below. As you already know these are the LSTM equations for a single timestep:" }, { "code": null, "e": 11917, "s": 11652, "text": "Let’s start with an easy one x(t). This is the input signal/feature vector/CNN output. I am assuming that x(t) comes from an embedding layer (think word2vec) and has an input dimensionality of [80x1]. This implies that Wf has a dimensionality of [Some_Value x 80]." }, { "code": null, "e": 11938, "s": 11917, "text": "Thus so far we have:" }, { "code": null, "e": 11974, "s": 11938, "text": "x(t) is [80 X 1] — input assumption" }, { "code": null, "e": 12029, "s": 11974, "text": "Wf is [Some_value X 80 ] — Matrix multiplication laws." }, { "code": null, "e": 12229, "s": 12029, "text": "Let’s make another assumption the output dimensionality of the LSTM is [12x1]. Assume this is the number of output classes. Thus at every timestep, the LSTM generates an output o(t) of size [12 x 1]." }, { "code": null, "e": 12629, "s": 12229, "text": "Now since o(t) is [12 x 1] then h(t) has to be [12x1] because h(t) is calculated by doing an element by element multiplication (look at the last equation on how h(t) is calculated from o(t) and c(t)). Since o(t) is [12x1] then c(t) has to be [12x1]. If c(t) is [12x1] then f(t), c(t-1), i(t) and c’(t) have to be [12x1]. Why? Because both h(t) and c(t) are calculated by element wise multiplication." }, { "code": null, "e": 12643, "s": 12629, "text": "Thus we have:" }, { "code": null, "e": 12680, "s": 12643, "text": "o(t) is [12 X 1] — output assumption" }, { "code": null, "e": 12806, "s": 12680, "text": "h(t) and c(t) are [12x1] — Because h(t) is calculated by element-wise multiplication of o(t) and tanh(c(t)) in the equations." }, { "code": null, "e": 12940, "s": 12806, "text": "f(t), c(t-1), i(t) and c’(t) are [12x1] — Because c(t) is [12x1] and is estimated by element wise operations requiring the same size." }, { "code": null, "e": 13187, "s": 12940, "text": "Since f(t) is of dimension [12x1] then the product of Wf and x(t) has to be [12x1]. We know that x(t) is [80x1] (because we assumed that) then Wf has to be [12x80]. Also looking at the equation for f(t) we realize that the bias term bf is [12x1]." }, { "code": null, "e": 13201, "s": 13187, "text": "Thus we have:" }, { "code": null, "e": 13237, "s": 13201, "text": "x(t) is [80 X 1] — input assumption" }, { "code": null, "e": 13274, "s": 13237, "text": "o(t) is [12 X 1] — output assumption" }, { "code": null, "e": 13400, "s": 13274, "text": "h(t) and c(t) are [12x1] — Because h(t) is calculated by element-wise multiplication of o(t) and tanh(c(t)) in the equations." }, { "code": null, "e": 13534, "s": 13400, "text": "f(t), c(t-1), i(t) and c’(t) are [12x1] — Because c(t) is [12x1] and is estimated by element wise operations requiring the same size." }, { "code": null, "e": 13592, "s": 13534, "text": "Wf is [12x80] — Because f(t) is [12x1] and x(t) is [80x1]" }, { "code": null, "e": 13643, "s": 13592, "text": "bf is [12x1] — Because all other terms are [12x1]." }, { "code": null, "e": 13784, "s": 13643, "text": "The above might seem a bit more complicated than it has to be. Take a moment and work through it yourself. Trust me it ain’t that confusing." }, { "code": null, "e": 13829, "s": 13784, "text": "Now onto the confusing part :) Just kidding!" }, { "code": null, "e": 14084, "s": 13829, "text": "In the calculation of f(t) the product of Uf and h(t-1) also has to be [12x1]. Now we know based on the previous discussion that h(t-1) is [12x1]. h(t) and h(t-1) will have the same dimensionality of [12x1]. Thus Uf will have a dimensionality of [12x12]." }, { "code": null, "e": 14288, "s": 14084, "text": "All Ws (Wf, Wi, Wo, Wc) will have the same dimension of [12x80] and all biases (bf, bi, bc, bo) will have the same dimension of [12x1] and all Us (Uf, Ui, Uo, Uc) will have the same dimension of [12x12]." }, { "code": null, "e": 14299, "s": 14288, "text": "Therefore:" }, { "code": null, "e": 14335, "s": 14299, "text": "x(t) is [80 X 1] — input assumption" }, { "code": null, "e": 14372, "s": 14335, "text": "o(t) is [12 X 1] — output assumption" }, { "code": null, "e": 14419, "s": 14372, "text": "Wf, Wi, Wc, Wo each have dimensions of [12x80]" }, { "code": null, "e": 14465, "s": 14419, "text": "Uf, Ui, Uc, Uo each have dimension of [12x12]" }, { "code": null, "e": 14511, "s": 14465, "text": "bf, bi, bc, bo each have dimensions of [12x1]" }, { "code": null, "e": 14562, "s": 14511, "text": "ht, ot, ct, ft, it each have a dimension of [12x1]" }, { "code": null, "e": 14606, "s": 14562, "text": "The total weight matrix size of the LSTM is" }, { "code": null, "e": 14654, "s": 14606, "text": "Weights_LSTM = 4*[12x80] + 4*[12x12] + 4*[12x1]" }, { "code": null, "e": 14717, "s": 14654, "text": "= 4*[Output_Dim x Input_Dim] + 4*[Output_Dim2] + 4*[Input_Dim]" }, { "code": null, "e": 14769, "s": 14717, "text": "= 4*[960] + 4*[144] + 4*[12] = 3840 + 576+48= 4,464" }, { "code": null, "e": 14829, "s": 14769, "text": "Lets verify paste the following code into your python setup" }, { "code": null, "e": 14930, "s": 14829, "text": "Notice the number of params for the LSTM is 4464. Which is what we got through our calculations too!" }, { "code": null, "e": 15487, "s": 14930, "text": "Before we move into the next section, I want to emphasize a key aspect. LSTMs have two things that define them: The input dimension and the output dimensionality (and the time unroll which I will get to in a bit). In literature (papers/blogs/code document) there is a lot of ambiguity in nomenclature. Some places it is called the number of Units, hidden dimension, output dimensionality, number of LSTM units, etc. I am no debating which is correct or which is wrong just that in my opinion these generally mean the same thing — the output dimensionality." }, { "code": null, "e": 15701, "s": 15487, "text": "So far we have looked at the weight matrix size. The weight matrices are consolidated stored as a single matrix by most frameworks. The figure below illustrates this weight matrix and the corresponding dimensions." }, { "code": null, "e": 15881, "s": 15701, "text": "NOTE: Depending on which framework you are using the weight matrices will be stored in a different order. As an example, Pytorch may save Wi before Wf or Caffe may store Wo first." }, { "code": null, "e": 16339, "s": 15881, "text": "There are two parameters that define an LSTM for a timestep. The input dimension and the output dimension. The weight matrix size is of the size: 4*Output_Dim*(Output_Dim + Input_Dim + 1) [Thanks Cless for catching the typo]. There is a lot of ambiguity when it comes to LSTMs — number of units, hidden dimension and output dimensionality. Just remember that there are two parameters that define an LSTM — input dimensionality and the output dimensionality." }, { "code": null, "e": 16574, "s": 16339, "text": "In the figures below there are two separate LSTM networks. Both networks are shown to be unrolled for three timesteps. The first network in figure (A) is a single layer network whereas the network in figure (B) is a two-layer network." }, { "code": null, "e": 16949, "s": 16574, "text": "In the case of the first single-layer network, we initialize the h and c and each timestep an output is generated along with the h and c to be consumed by the next timestep. Note even though at the last timestep h(t) and c(t) is discarded I have shown them for the sake of completion. As we discussed before the weights (Ws, Us, and bs) are the same for the three timesteps." }, { "code": null, "e": 17182, "s": 16949, "text": "The two-layer network has two LSTM layers. The output of the first layer will be the input of the second layer. They both have their weight matrices and respective hs, cs, and os. I indicate this through the use of the superscripts." }, { "code": null, "e": 17781, "s": 17182, "text": "Let’s take a look at a very simple albeit realistic LSTM network to see how this would work. The task is simple we have to come up with a network that tells us whether or not a given sentence is negative or positive. To keep things simple, we will assume that the sentences are fixed length. If the actual sentence has fewer words than the expected length you pad zeros and if it has more words than the sequence length you truncate the sentence. In our case, we will restrict the sentence length to be 3 words. Why 3 words? just a number I like because it is easier for me to draw the diagrams :)." }, { "code": null, "e": 18097, "s": 17781, "text": "On a serious note, you would use plot the histogram of the number of words in a sentence in your dataset and choose a value depending on the shape of the histogram. Sentences that are largen than predetermined word count will be truncated and sentences that have fewer words will be padded with zero or a null word." }, { "code": null, "e": 18349, "s": 18097, "text": "Anyways back to our example. We are sticking to three words. We will use an embedding layer which converts an English word into a numerical vector of size [80x1]. Why 80? because I like the number 80:) Anyways the network is shown below in the figure." }, { "code": null, "e": 19420, "s": 18349, "text": "We will try and categorize a sentence — “I am happy”. At t=0 the first word “I” gets converted to a numerical vector of length [80x1] by the embedding layer. and passes through the LSTM followed by a fully connected layer. Then at time t=1, the second word goes through the network followed by the last word “happy” at t=2. We would like the network to wait for the entire sentence to let us know about the sentiment. We don’t want it to be overeager and tell us the sentiment at every word. This is why in the figure below the output from the LSTM is shown only at the last step. Keras calls this parameter as return_sequence. Setting this to False or True will determine whether or not the LSTM and subsequently the network generates an output at very timestep or for every word in our example. A key thing that I would like to underscore here is that just because you set the return sequences to false doesn’t mean that the LSTM equations are being modified. They are still calculating the h(t), c(t) for every timestep. Thus the amount of computation doesn’t reduce." }, { "code": null, "e": 19490, "s": 19420, "text": "Here is an example from Keras for sentiment analysis on IMDB dataset:" }, { "code": null, "e": 19560, "s": 19490, "text": "https://github.com/keras-team/keras/blob/master/examples/imdb_lstm.py" }, { "code": null, "e": 19880, "s": 19560, "text": "Let’s try and consolidate what we have learned so far. In this section, I am listing a bunch of questions for some sample/toy networks. It helps me feel better if I can test if my understanding is correct hence this format in this section. Alternatively, you can also use these for interview preparation around LSTMs :)" }, { "code": null, "e": 19904, "s": 19880, "text": "Sample LSTM Network # 1" }, { "code": null, "e": 20361, "s": 19904, "text": "How many LSTM layers are there in this network? — The network has one layer. Don’t get confused with multiple LSTM boxes, they represent the different timesteps, there is only one layer.As shown what is the sequence length or the number of timesteps? — The number of timesteps is 3. Look at the time indices.If the input dimension i.e. x(t) is [18x1] and o(t) is [19x1] what are the dimensions of h(t), c(t)? — h(t) and c(t) will be of the dimension [19x1]" }, { "code": null, "e": 20548, "s": 20361, "text": "How many LSTM layers are there in this network? — The network has one layer. Don’t get confused with multiple LSTM boxes, they represent the different timesteps, there is only one layer." }, { "code": null, "e": 20671, "s": 20548, "text": "As shown what is the sequence length or the number of timesteps? — The number of timesteps is 3. Look at the time indices." }, { "code": null, "e": 20820, "s": 20671, "text": "If the input dimension i.e. x(t) is [18x1] and o(t) is [19x1] what are the dimensions of h(t), c(t)? — h(t) and c(t) will be of the dimension [19x1]" }, { "code": null, "e": 20844, "s": 20820, "text": "Sample LSTM Network # 2" }, { "code": null, "e": 22187, "s": 20844, "text": "How many LSTM layers are there in this network? — The total number of LSTM layers is 5.As shown what is the sequence length or the number of timesteps? — This network has a sequence length of 1.If x(t) is [45x1] and h1(int) is [25x1] what are the dimensions of — c1(int) and o1(t) ? — c1(t) and o1(t) will have the same dimensions as h1(t) i.e [25x1]If x(t) is [4x1], h1(int) is [5x1] and o2(t) is of the size [4x1]. What is the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is [4*output_dim*(input_dim+output_dim+1)]. The input dim for LSTM0 is [4x1], output_dim for LSTM0 is [5x1]. The input to LSTM1 is the output of LSTM0 thus the input dim of LSTM1 is same as the output_dim of LSTM0 i.e. [5x1]. The output dim of LSTM1 is [4x1]. Thus LSTM0 is [4*6*(5+4+1)]=288 and LSTM1 is [4*4*(5+4+1)] = 160.If x(t) is [10x1], h1(int) is [7x1] what is the input dimension of LSTM1? — Look at the explanation above. We need to know the output dimensionality of LSTM0 before we can calculate this.If x(t) is [6x1], h1(int) is [4x1], o2(t) is [3x1], o3(t) is [5x1], o4(t) is [9x1] and o5(t) is [10x1] what is total weight size of the network? — The weight matrix of an LSTM for a single timestep is given as [4*output_dim*(input_dim+output_dim+1)]. Work by estimating the input ouput dimensionalities of a single layer." }, { "code": null, "e": 22275, "s": 22187, "text": "How many LSTM layers are there in this network? — The total number of LSTM layers is 5." }, { "code": null, "e": 22383, "s": 22275, "text": "As shown what is the sequence length or the number of timesteps? — This network has a sequence length of 1." }, { "code": null, "e": 22540, "s": 22383, "text": "If x(t) is [45x1] and h1(int) is [25x1] what are the dimensions of — c1(int) and o1(t) ? — c1(t) and o1(t) will have the same dimensions as h1(t) i.e [25x1]" }, { "code": null, "e": 23025, "s": 22540, "text": "If x(t) is [4x1], h1(int) is [5x1] and o2(t) is of the size [4x1]. What is the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is [4*output_dim*(input_dim+output_dim+1)]. The input dim for LSTM0 is [4x1], output_dim for LSTM0 is [5x1]. The input to LSTM1 is the output of LSTM0 thus the input dim of LSTM1 is same as the output_dim of LSTM0 i.e. [5x1]. The output dim of LSTM1 is [4x1]. Thus LSTM0 is [4*6*(5+4+1)]=288 and LSTM1 is [4*4*(5+4+1)] = 160." }, { "code": null, "e": 23213, "s": 23025, "text": "If x(t) is [10x1], h1(int) is [7x1] what is the input dimension of LSTM1? — Look at the explanation above. We need to know the output dimensionality of LSTM0 before we can calculate this." }, { "code": null, "e": 23535, "s": 23213, "text": "If x(t) is [6x1], h1(int) is [4x1], o2(t) is [3x1], o3(t) is [5x1], o4(t) is [9x1] and o5(t) is [10x1] what is total weight size of the network? — The weight matrix of an LSTM for a single timestep is given as [4*output_dim*(input_dim+output_dim+1)]. Work by estimating the input ouput dimensionalities of a single layer." }, { "code": null, "e": 23559, "s": 23535, "text": "Sample LSTM Network # 3" }, { "code": null, "e": 24441, "s": 23559, "text": "How many layers are in this network? — There are two layersWhat is the sequence length as shown in this network? — Each layer is unrolled 2 times.If x(t) is [80x1] and h1(int) is [10x1] what will be the dimensions of o(t), h1(t), c1(t), f(t), i(t). These are not shown in the figure, but you should be able to label this. — o(t), h1(t), c1(t), f1(t), i1(t) will have the same dimension as h1(t) i.e. [10x1]If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What are the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+output_dim+1). LSTM0 will be 4*5*(4+5+1) i.e. 200. LSTM2 will be 4*6*(5+5+1) = 264.If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What is the total number of multiply and accumulate operations? — I am leaving this one for the reader. If enough folks ask then I will answer :)" }, { "code": null, "e": 24501, "s": 24441, "text": "How many layers are in this network? — There are two layers" }, { "code": null, "e": 24589, "s": 24501, "text": "What is the sequence length as shown in this network? — Each layer is unrolled 2 times." }, { "code": null, "e": 24850, "s": 24589, "text": "If x(t) is [80x1] and h1(int) is [10x1] what will be the dimensions of o(t), h1(t), c1(t), f(t), i(t). These are not shown in the figure, but you should be able to label this. — o(t), h1(t), c1(t), f1(t), i1(t) will have the same dimension as h1(t) i.e. [10x1]" }, { "code": null, "e": 25122, "s": 24850, "text": "If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What are the size of the weight matrices for LSTM0 and LSTM1? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+output_dim+1). LSTM0 will be 4*5*(4+5+1) i.e. 200. LSTM2 will be 4*6*(5+5+1) = 264." }, { "code": null, "e": 25327, "s": 25122, "text": "If x(t+1) is [4x1], o1(t+1) is [5x1] and o2(t+1) is [6x1]. What is the total number of multiply and accumulate operations? — I am leaving this one for the reader. If enough folks ask then I will answer :)" }, { "code": null, "e": 25351, "s": 25327, "text": "Sample LSTM Network # 4" }, { "code": null, "e": 26215, "s": 25351, "text": "How many layers are there? — There are 3 layers.As shown how many timesteps is this network unrolled? — Each layer is unrolled 3 times.How many equations will be executed in all for this network? — Each LSTM requires 6 equations (some texts consolidate to 5 equations). Then 6 equations/time step/LSTM. Therefore 6 equations * 3 LSTM Layers * 3 timesteps = 54 equationsIf x(t) is [10x1] what other information would you need to estimate the weight matrix of LSTM1? What about LSTM2? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+out_dim+1). Thus for each LSTM, we need both input_dim and the output_dim. The output of LSTM is the input of LSTM1. We have the input dimension of [10x1] so we need the output dimension or o1(int) dimension and the output dimensions of LSTM1 i.e. o2(t). Similarly for the LSTM2, we need to know, o2(t) and o3(t)." }, { "code": null, "e": 26264, "s": 26215, "text": "How many layers are there? — There are 3 layers." }, { "code": null, "e": 26352, "s": 26264, "text": "As shown how many timesteps is this network unrolled? — Each layer is unrolled 3 times." }, { "code": null, "e": 26587, "s": 26352, "text": "How many equations will be executed in all for this network? — Each LSTM requires 6 equations (some texts consolidate to 5 equations). Then 6 equations/time step/LSTM. Therefore 6 equations * 3 LSTM Layers * 3 timesteps = 54 equations" }, { "code": null, "e": 27082, "s": 26587, "text": "If x(t) is [10x1] what other information would you need to estimate the weight matrix of LSTM1? What about LSTM2? — The weight matrix of an LSTM is given by 4*output_dim*(input_dim+out_dim+1). Thus for each LSTM, we need both input_dim and the output_dim. The output of LSTM is the input of LSTM1. We have the input dimension of [10x1] so we need the output dimension or o1(int) dimension and the output dimensions of LSTM1 i.e. o2(t). Similarly for the LSTM2, we need to know, o2(t) and o3(t)." }, { "code": null, "e": 27372, "s": 27082, "text": "The blogs and papers around LSTMs often talk about it at a qualitative level. In this article, I have tried to explain the LSTM operation from a computation perspective. Understanding LSTMs from a computational perspective is crucial, especially for machine learning accelerator designers." }, { "code": null, "e": 27397, "s": 27372, "text": "DL Interview Preparation" }, { "code": null, "e": 27422, "s": 27397, "text": "Christopher Olah’s blog." }, { "code": null, "e": 27437, "s": 27422, "text": "Shi Yan’s blog" }, { "code": null, "e": 27471, "s": 27437, "text": "LSTMs from the deep learning book" }, { "code": null, "e": 27507, "s": 27471, "text": "Nvidia’s blog on accelerating LSTMs" }, { "code": null, "e": 27541, "s": 27507, "text": "LSTMs on Machine Learning Mastery" } ]
Python 3 - Number round() Method
Following is the syntax for the round() method − round( x [, n] ) x − This is a numeric expression. n − Represents number of digits from decimal point up to which x is to be rounded. Default is 0. This method returns x rounded to n digits from the decimal point. The following example shows the usage of round() method. #!/usr/bin/python3 print ("round(70.23456) : ", round(70.23456)) print ("round(56.659,1) : ", round(56.659,1)) print ("round(80.264, 2) : ", round(80.264, 2)) print ("round(100.000056, 3) : ", round(100.000056, 3)) print ("round(-100.000056, 3) : ", round(-100.000056, 3)) When we run the above program, it produces the following result − round(70.23456) : 70 round(56.659,1) : 56.7 round(80.264, 2) : 80.26 round(100.000056, 3) : 100.0 round(-100.000056, 3) : -100.0 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": 2389, "s": 2340, "text": "Following is the syntax for the round() method −" }, { "code": null, "e": 2408, "s": 2389, "text": "round( x [, n] )\n" }, { "code": null, "e": 2442, "s": 2408, "text": "x − This is a numeric expression." }, { "code": null, "e": 2539, "s": 2442, "text": "n − Represents number of digits from decimal point up to which x is to be rounded. Default is 0." }, { "code": null, "e": 2605, "s": 2539, "text": "This method returns x rounded to n digits from the decimal point." }, { "code": null, "e": 2662, "s": 2605, "text": "The following example shows the usage of round() method." }, { "code": null, "e": 2936, "s": 2662, "text": "#!/usr/bin/python3\n\nprint (\"round(70.23456) : \", round(70.23456))\nprint (\"round(56.659,1) : \", round(56.659,1))\nprint (\"round(80.264, 2) : \", round(80.264, 2))\nprint (\"round(100.000056, 3) : \", round(100.000056, 3))\nprint (\"round(-100.000056, 3) : \", round(-100.000056, 3))" }, { "code": null, "e": 3002, "s": 2936, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3137, "s": 3002, "text": "round(70.23456) : 70\nround(56.659,1) : 56.7\nround(80.264, 2) : 80.26\nround(100.000056, 3) : 100.0\nround(-100.000056, 3) : -100.0\n" }, { "code": null, "e": 3174, "s": 3137, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3190, "s": 3174, "text": " Malhar Lathkar" }, { "code": null, "e": 3223, "s": 3190, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3242, "s": 3223, "text": " Arnab Chakraborty" }, { "code": null, "e": 3277, "s": 3242, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3299, "s": 3277, "text": " In28Minutes Official" }, { "code": null, "e": 3333, "s": 3299, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3361, "s": 3333, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3396, "s": 3361, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3410, "s": 3396, "text": " Lets Kode It" }, { "code": null, "e": 3443, "s": 3410, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3460, "s": 3443, "text": " Abhilash Nelson" }, { "code": null, "e": 3467, "s": 3460, "text": " Print" }, { "code": null, "e": 3478, "s": 3467, "text": " Add Notes" } ]
How to load a hyperlink from one iframe to another iframe ? - GeeksforGeeks
25 Jul, 2021 HTML Iframe or inline frame allows embedment of multiple HTML pages in an HTML page. In this article, we will see how to change the content of one iframe using hyperlinks in another iframe. This can be achieved by the proper usage of the name attribute in the iframe tag and the target attribute in the anchor tag. The name attribute allows each inline frame to have its own unique name while the target attribute tells the hyperlinks, where the page has to be opened when the link is clicked. Our problem will be solved if we keep the value of the target as the name of the destination iframe where the hyperlink contents should be displayed. We will create an HTML page consisting of two iframes. Give each iframe a unique name. Create another HTML page with multiple hyperlinks in it. Add the name of the second iframe in the target attribute of every hyperlink. Click the links in the first iframe, and you should see the pages opening in the second iframe. Example: The HTML document will embed two iframes inside it. index.html <!DOCTYPE html><html> <body> <center> <h2>Hello world!!</h2> <br /> <iframe src="iframe1.html" name="iframe1" width="70%" height="250"> </iframe> <br /><br /> <iframe src="" name="iframe2" width="70%" height="300"> </iframe> </center> </body></html> The following code is the content for “iframe1.html” used in the above code. iframe1.html <!DOCTYPE html><html> <body> <center> <h1 style="color: green">GeeksforGeeks</h1> <p> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20210720232031/gfglogo-300x300.png" target="iframe2">GfG Logo</a> </p> <p> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20210720234436/gfglogo2-300x300.jpg" target="iframe2">GfG Logo 2</a> </p> <p> <a href="https://www.youtube.com/embed/sa9l-dTv9Gk" target="iframe2"> GfG youtube video </a> </p> <p>click the above links to see changes in the frame below</p> </center> </body></html> Output: This page will contain hyperlinks, each targeting the second iframe. iframe to another iframe Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML-Questions HTML-Tags HTML Web Technologies 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 Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26273, "s": 26245, "text": "\n25 Jul, 2021" }, { "code": null, "e": 26464, "s": 26273, "text": "HTML Iframe or inline frame allows embedment of multiple HTML pages in an HTML page. In this article, we will see how to change the content of one iframe using hyperlinks in another iframe. " }, { "code": null, "e": 26918, "s": 26464, "text": "This can be achieved by the proper usage of the name attribute in the iframe tag and the target attribute in the anchor tag. The name attribute allows each inline frame to have its own unique name while the target attribute tells the hyperlinks, where the page has to be opened when the link is clicked. Our problem will be solved if we keep the value of the target as the name of the destination iframe where the hyperlink contents should be displayed." }, { "code": null, "e": 26973, "s": 26918, "text": "We will create an HTML page consisting of two iframes." }, { "code": null, "e": 27005, "s": 26973, "text": "Give each iframe a unique name." }, { "code": null, "e": 27062, "s": 27005, "text": "Create another HTML page with multiple hyperlinks in it." }, { "code": null, "e": 27140, "s": 27062, "text": "Add the name of the second iframe in the target attribute of every hyperlink." }, { "code": null, "e": 27236, "s": 27140, "text": "Click the links in the first iframe, and you should see the pages opening in the second iframe." }, { "code": null, "e": 27297, "s": 27236, "text": "Example: The HTML document will embed two iframes inside it." }, { "code": null, "e": 27308, "s": 27297, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <body> <center> <h2>Hello world!!</h2> <br /> <iframe src=\"iframe1.html\" name=\"iframe1\" width=\"70%\" height=\"250\"> </iframe> <br /><br /> <iframe src=\"\" name=\"iframe2\" width=\"70%\" height=\"300\"> </iframe> </center> </body></html>", "e": 27671, "s": 27308, "text": null }, { "code": null, "e": 27748, "s": 27671, "text": "The following code is the content for “iframe1.html” used in the above code." }, { "code": null, "e": 27761, "s": 27748, "text": "iframe1.html" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color: green\">GeeksforGeeks</h1> <p> <a href=\"https://media.geeksforgeeks.org/wp-content/uploads/20210720232031/gfglogo-300x300.png\" target=\"iframe2\">GfG Logo</a> </p> <p> <a href=\"https://media.geeksforgeeks.org/wp-content/uploads/20210720234436/gfglogo2-300x300.jpg\" target=\"iframe2\">GfG Logo 2</a> </p> <p> <a href=\"https://www.youtube.com/embed/sa9l-dTv9Gk\" target=\"iframe2\"> GfG youtube video </a> </p> <p>click the above links to see changes in the frame below</p> </center> </body></html>", "e": 28417, "s": 27761, "text": null }, { "code": null, "e": 28494, "s": 28417, "text": "Output: This page will contain hyperlinks, each targeting the second iframe." }, { "code": null, "e": 28519, "s": 28494, "text": "iframe to another iframe" }, { "code": null, "e": 28656, "s": 28519, "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": 28672, "s": 28656, "text": "HTML-Attributes" }, { "code": null, "e": 28687, "s": 28672, "text": "HTML-Questions" }, { "code": null, "e": 28697, "s": 28687, "text": "HTML-Tags" }, { "code": null, "e": 28702, "s": 28697, "text": "HTML" }, { "code": null, "e": 28719, "s": 28702, "text": "Web Technologies" }, { "code": null, "e": 28724, "s": 28719, "text": "HTML" }, { "code": null, "e": 28822, "s": 28724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28846, "s": 28822, "text": "REST API (Introduction)" }, { "code": null, "e": 28887, "s": 28846, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28924, "s": 28887, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28953, "s": 28924, "text": "Form validation using jQuery" }, { "code": null, "e": 28973, "s": 28953, "text": "Angular File Upload" }, { "code": null, "e": 29013, "s": 28973, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29046, "s": 29013, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29091, "s": 29046, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29134, "s": 29091, "text": "How to fetch data from an API in ReactJS ?" } ]
C# String CopyTo() Method
The CopyTo() method in C# is used to copy a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters. public void CopyTo (int srcIndex, char[] dest, int desIndex, int count); Above, srcIndex − Index of the first character in this instance to copy. dest − Array of Unicode characters to which characters in this instance are copied. destIndex − The index in destination at which the copy operation begins. Count − Number of characters in this instance to copy to destination. Let us now see an example - Live Demo using System; public class Demo { public static void Main() { string str = "JohnAndJacob"; Console.WriteLine("String = "+str); char[] destArr = new char[20]; str.CopyTo(1, destArr, 0, 4); Console.Write(destArr); } } String = JohnAndJacob ohnA Let us now see another example - Live Demo using System; public class Demo { public static void Main() { string str = "JohnAndJacob"; Console.WriteLine("String = "+str); char[] destArr = new char[20]; destArr[0] = 'A'; destArr[1] = 'B'; destArr[2] = 'C'; destArr[3] = 'D'; Console.WriteLine(destArr); str.CopyTo(2, destArr, 3, 4); Console.Write(destArr); } } This will produce the following output - String = JohnAndJacob ABCD ABChnAn
[ { "code": null, "e": 1239, "s": 1062, "text": "The CopyTo() method in C# is used to copy a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters." }, { "code": null, "e": 1312, "s": 1239, "text": "public void CopyTo (int srcIndex, char[] dest, int desIndex, int count);" }, { "code": null, "e": 1319, "s": 1312, "text": "Above," }, { "code": null, "e": 1385, "s": 1319, "text": "srcIndex − Index of the first character in this instance to copy." }, { "code": null, "e": 1469, "s": 1385, "text": "dest − Array of Unicode characters to which characters in this instance are copied." }, { "code": null, "e": 1542, "s": 1469, "text": "destIndex − The index in destination at which the copy operation begins." }, { "code": null, "e": 1612, "s": 1542, "text": "Count − Number of characters in this instance to copy to destination." }, { "code": null, "e": 1640, "s": 1612, "text": "Let us now see an example -" }, { "code": null, "e": 1651, "s": 1640, "text": " Live Demo" }, { "code": null, "e": 1903, "s": 1651, "text": "using System;\npublic class Demo {\n public static void Main() {\n string str = \"JohnAndJacob\";\n Console.WriteLine(\"String = \"+str);\n char[] destArr = new char[20];\n str.CopyTo(1, destArr, 0, 4);\n Console.Write(destArr);\n }\n}" }, { "code": null, "e": 1930, "s": 1903, "text": "String = JohnAndJacob\nohnA" }, { "code": null, "e": 1963, "s": 1930, "text": "Let us now see another example -" }, { "code": null, "e": 1974, "s": 1963, "text": " Live Demo" }, { "code": null, "e": 2356, "s": 1974, "text": "using System;\npublic class Demo {\n public static void Main() {\n string str = \"JohnAndJacob\";\n Console.WriteLine(\"String = \"+str);\n char[] destArr = new char[20];\n destArr[0] = 'A';\n destArr[1] = 'B';\n destArr[2] = 'C';\n destArr[3] = 'D';\n Console.WriteLine(destArr);\n str.CopyTo(2, destArr, 3, 4);\n Console.Write(destArr);\n }\n}" }, { "code": null, "e": 2397, "s": 2356, "text": "This will produce the following output -" }, { "code": null, "e": 2432, "s": 2397, "text": "String = JohnAndJacob\nABCD\nABChnAn" } ]
Central Limit Theorem — Clearly Explained | by Indhumathy Chelliah | Towards Data Science
Central Limit Theorem is one of the important concepts in Inferential Statistics. Inferential Statistics means drawing inferences about the population from the sample. When we draw a random sample from the population and calculate the mean of the sample, it will likely differ from the population mean due to sampling fluctuation. The variation between a sample statistic and population parameter is known as sampling error. Due to this sampling error, it may be difficult to draw inferences about population parameter from sample statistics. Central Limit Theorem is one of the important concepts in inferential statistics, which helps us to draw inferences about the population parameter from sample statistic. Let us learn about the central limit theorem in detail in this article. Refer to my story of Inferential Statistics — to know the basics of probability and probability distributions Statistic, ParameterSampling DistributionStandard ErrorSampling Distribution PropertiesCentral Limit TheoremConfidence IntervalVisualizing Sampling distribution Statistic, Parameter Sampling Distribution Standard Error Sampling Distribution Properties Central Limit Theorem Confidence Interval Visualizing Sampling distribution Statistic → The values which represent the characteristics of the sample known as Statistic. Parameter → The values which represent the characteristics of the population known as Parameter. (The values which we infer from statistic for the population) Statistic →Sample Standard Deviation S, Sample Mean X Parameter →Population Standard Deviation σ, Population Mean μ We draw inferences from statistic to parameter. Sampling → It means drawing representative samples from the population. Sampling Distribution → A sampling distribution is the distribution of all possible values of a sample statistic for a given sample drawn from a population. Sampling distribution of mean is the distribution of sample means for a given size sample selected from the population. We will draw random samples(s1,s2...sn) from the population. We will calculate the mean of the samples (ms1,ms2,ms2....msn). Then we will calculate the mean of the sampling means. (ms) ms=(ms1+ms2+...msn)/n n →sample size. [Now we have calculated the mean of the sampling mean. Next, we have to calculate the standard deviation of the sampling mean] Variability of sample means in the sampling distribution is the Standard Error. The standard deviation of the sampling distribution is known as the Standard Error of the mean. Standard Error of mean = Standard deviation of population/sqrt(n) n- sample size [Standard error decreases when sample size increases. So large samples help in reducing standard error] The mean of the sampling mean is equal to the population mean. The mean of the sampling mean is equal to the population mean. [When we draw many random samples from the population, the variations will cancel out. So, the mean of sampling mean equals to population mean] 2. Standard Deviation of Sampling Distribution is equal to the standard deviation of population divided by the square root of the sample size. Central Limit Theorem states that even if the population distribution is not normal, the sampling distribution will be normally distributed if we take sufficiently large samples from the population.[ For most distributions, n>30 will give a sampling distribution which is nearly normal] Sampling distribution properties also hold good for the central limit theorem. We can say that the population mean will lie between a certain range by using a confidence interval. Confidence Interval is the range of values that the population parameter can take. Confidence Interval of Population Mean= Sample Mean + (confidence level value ) * Standard Error of the mean Z → Z scores associated with the confidence level. Mostly used confidence level 99% Confidence Level → Z score = 2.5895% Confidence Level → Z score = 1.9690% Confidence Level → Z score =1.65 Example: Let’s say we have to calculate the mean of marks of all students in a school. Let’s say we have to calculate the mean of marks of all students in a school. No of students = 1000. population1=np.random.randint(0,100,1000) 2. Checking the Population distribution sns.distplot(population1,hist=False) The population is not normally distributed. 3. We will draw random samples of size less than 30 from the population. sample_means1=[]for i in range(0,25): sample=np.random.choice(population1,size=20) sample_means1.append(np.mean(sample))sample_m1=np.array(sample_means1) 4. Sampling distribution sns.distplot(sample_means1,hist=False)plt.title(“Sampling distribution of sample mean”)plt.axvline(sample_m1.mean(),color=’green’,linestyle=’ — ‘)plt.xlabel(“Sample Mean”) The sampling distribution is close to a normal distribution 5. Let’s check the sampling mean and standard error. print (“Sampling mean: “,round(sample_m1.mean(),2))print (“Standard Error: “,round(sample_m1.std(),2))#Output:Sampling mean: 47.96Standard Error: 6.39 Standard Error = 6.39. Let’s increase the sample size and check whether the standard error decreases. 6. Take sample size greater than 30 and calculate sampling mean sample_means2=[]for i in range(0,100): sample=np.random.choice(population1,size=50) sample_means2.append(np.mean(sample))sample_m2=np.array(sample_means2) 7. Sampling distribution sns.distplot(sample_means2,hist=False)plt.title(“Sampling distribution of sample mean”)plt.axvline(sample_m2.mean(),color=’green’,linestyle=’ — ‘)plt.xlabel(“Sample Mean”) The sampling distribution is normal now. 8. Calculate sampling mean and standard error print (“Sampling mean: “,round(sample_m2.mean(),2))print (“Standard Error: “,round(sample_m2.std(),2))# Output:Sampling mean: 48.17Standard Error: 3.89 After increasing the sample size, the standard error decreases. Now the Standard Error is 3.89. 9. Let’s verify our population mean print (“Population Mean: “,round(population1.mean(),2))#Output:Population Mean: 48.03 We have calculated the sampling mean as 48.17 which is approximately equal to the population mean 48.03 10. Calculating Confidence Interval at 99% confidence level. Lower_limit=sample_m2.mean()- (2.58 * (sample_m2.std()))print (round(Lower_limit,2))#Output: 38.14Upper_limit=sample_m2.mean()+ (2.58 * (sample_m2.std()))print (round(Upper_limit),2)#Output: 58.19 Confidence Interval = 38.14 — 58.19 In this article, I have covered the central limit theorem, sampling distributions, standard error, and confidence interval. Hope you all like it. Thanks for reading! pub.towardsai.net pub.towardsai.net medium.com pub.towardsai.net Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter. Become a Medium Member by Clicking here: https://indhumathychelliah.medium.com/membership
[ { "code": null, "e": 340, "s": 172, "text": "Central Limit Theorem is one of the important concepts in Inferential Statistics. Inferential Statistics means drawing inferences about the population from the sample." }, { "code": null, "e": 597, "s": 340, "text": "When we draw a random sample from the population and calculate the mean of the sample, it will likely differ from the population mean due to sampling fluctuation. The variation between a sample statistic and population parameter is known as sampling error." }, { "code": null, "e": 885, "s": 597, "text": "Due to this sampling error, it may be difficult to draw inferences about population parameter from sample statistics. Central Limit Theorem is one of the important concepts in inferential statistics, which helps us to draw inferences about the population parameter from sample statistic." }, { "code": null, "e": 957, "s": 885, "text": "Let us learn about the central limit theorem in detail in this article." }, { "code": null, "e": 1067, "s": 957, "text": "Refer to my story of Inferential Statistics — to know the basics of probability and probability distributions" }, { "code": null, "e": 1228, "s": 1067, "text": "Statistic, ParameterSampling DistributionStandard ErrorSampling Distribution PropertiesCentral Limit TheoremConfidence IntervalVisualizing Sampling distribution" }, { "code": null, "e": 1249, "s": 1228, "text": "Statistic, Parameter" }, { "code": null, "e": 1271, "s": 1249, "text": "Sampling Distribution" }, { "code": null, "e": 1286, "s": 1271, "text": "Standard Error" }, { "code": null, "e": 1319, "s": 1286, "text": "Sampling Distribution Properties" }, { "code": null, "e": 1341, "s": 1319, "text": "Central Limit Theorem" }, { "code": null, "e": 1361, "s": 1341, "text": "Confidence Interval" }, { "code": null, "e": 1395, "s": 1361, "text": "Visualizing Sampling distribution" }, { "code": null, "e": 1488, "s": 1395, "text": "Statistic → The values which represent the characteristics of the sample known as Statistic." }, { "code": null, "e": 1647, "s": 1488, "text": "Parameter → The values which represent the characteristics of the population known as Parameter. (The values which we infer from statistic for the population)" }, { "code": null, "e": 1701, "s": 1647, "text": "Statistic →Sample Standard Deviation S, Sample Mean X" }, { "code": null, "e": 1763, "s": 1701, "text": "Parameter →Population Standard Deviation σ, Population Mean μ" }, { "code": null, "e": 1811, "s": 1763, "text": "We draw inferences from statistic to parameter." }, { "code": null, "e": 1883, "s": 1811, "text": "Sampling → It means drawing representative samples from the population." }, { "code": null, "e": 2040, "s": 1883, "text": "Sampling Distribution → A sampling distribution is the distribution of all possible values of a sample statistic for a given sample drawn from a population." }, { "code": null, "e": 2160, "s": 2040, "text": "Sampling distribution of mean is the distribution of sample means for a given size sample selected from the population." }, { "code": null, "e": 2221, "s": 2160, "text": "We will draw random samples(s1,s2...sn) from the population." }, { "code": null, "e": 2285, "s": 2221, "text": "We will calculate the mean of the samples (ms1,ms2,ms2....msn)." }, { "code": null, "e": 2345, "s": 2285, "text": "Then we will calculate the mean of the sampling means. (ms)" }, { "code": null, "e": 2367, "s": 2345, "text": "ms=(ms1+ms2+...msn)/n" }, { "code": null, "e": 2383, "s": 2367, "text": "n →sample size." }, { "code": null, "e": 2510, "s": 2383, "text": "[Now we have calculated the mean of the sampling mean. Next, we have to calculate the standard deviation of the sampling mean]" }, { "code": null, "e": 2686, "s": 2510, "text": "Variability of sample means in the sampling distribution is the Standard Error. The standard deviation of the sampling distribution is known as the Standard Error of the mean." }, { "code": null, "e": 2752, "s": 2686, "text": "Standard Error of mean = Standard deviation of population/sqrt(n)" }, { "code": null, "e": 2767, "s": 2752, "text": "n- sample size" }, { "code": null, "e": 2871, "s": 2767, "text": "[Standard error decreases when sample size increases. So large samples help in reducing standard error]" }, { "code": null, "e": 2934, "s": 2871, "text": "The mean of the sampling mean is equal to the population mean." }, { "code": null, "e": 2997, "s": 2934, "text": "The mean of the sampling mean is equal to the population mean." }, { "code": null, "e": 3141, "s": 2997, "text": "[When we draw many random samples from the population, the variations will cancel out. So, the mean of sampling mean equals to population mean]" }, { "code": null, "e": 3284, "s": 3141, "text": "2. Standard Deviation of Sampling Distribution is equal to the standard deviation of population divided by the square root of the sample size." }, { "code": null, "e": 3571, "s": 3284, "text": "Central Limit Theorem states that even if the population distribution is not normal, the sampling distribution will be normally distributed if we take sufficiently large samples from the population.[ For most distributions, n>30 will give a sampling distribution which is nearly normal]" }, { "code": null, "e": 3650, "s": 3571, "text": "Sampling distribution properties also hold good for the central limit theorem." }, { "code": null, "e": 3751, "s": 3650, "text": "We can say that the population mean will lie between a certain range by using a confidence interval." }, { "code": null, "e": 3834, "s": 3751, "text": "Confidence Interval is the range of values that the population parameter can take." }, { "code": null, "e": 3943, "s": 3834, "text": "Confidence Interval of Population Mean= Sample Mean + (confidence level value ) * Standard Error of the mean" }, { "code": null, "e": 3994, "s": 3943, "text": "Z → Z scores associated with the confidence level." }, { "code": null, "e": 4023, "s": 3994, "text": "Mostly used confidence level" }, { "code": null, "e": 4134, "s": 4023, "text": "99% Confidence Level → Z score = 2.5895% Confidence Level → Z score = 1.9690% Confidence Level → Z score =1.65" }, { "code": null, "e": 4143, "s": 4134, "text": "Example:" }, { "code": null, "e": 4221, "s": 4143, "text": "Let’s say we have to calculate the mean of marks of all students in a school." }, { "code": null, "e": 4299, "s": 4221, "text": "Let’s say we have to calculate the mean of marks of all students in a school." }, { "code": null, "e": 4322, "s": 4299, "text": "No of students = 1000." }, { "code": null, "e": 4364, "s": 4322, "text": "population1=np.random.randint(0,100,1000)" }, { "code": null, "e": 4404, "s": 4364, "text": "2. Checking the Population distribution" }, { "code": null, "e": 4441, "s": 4404, "text": "sns.distplot(population1,hist=False)" }, { "code": null, "e": 4485, "s": 4441, "text": "The population is not normally distributed." }, { "code": null, "e": 4558, "s": 4485, "text": "3. We will draw random samples of size less than 30 from the population." }, { "code": null, "e": 4712, "s": 4558, "text": "sample_means1=[]for i in range(0,25): sample=np.random.choice(population1,size=20) sample_means1.append(np.mean(sample))sample_m1=np.array(sample_means1)" }, { "code": null, "e": 4737, "s": 4712, "text": "4. Sampling distribution" }, { "code": null, "e": 4909, "s": 4737, "text": "sns.distplot(sample_means1,hist=False)plt.title(“Sampling distribution of sample mean”)plt.axvline(sample_m1.mean(),color=’green’,linestyle=’ — ‘)plt.xlabel(“Sample Mean”)" }, { "code": null, "e": 4969, "s": 4909, "text": "The sampling distribution is close to a normal distribution" }, { "code": null, "e": 5022, "s": 4969, "text": "5. Let’s check the sampling mean and standard error." }, { "code": null, "e": 5175, "s": 5022, "text": "print (“Sampling mean: “,round(sample_m1.mean(),2))print (“Standard Error: “,round(sample_m1.std(),2))#Output:Sampling mean: 47.96Standard Error: 6.39" }, { "code": null, "e": 5277, "s": 5175, "text": "Standard Error = 6.39. Let’s increase the sample size and check whether the standard error decreases." }, { "code": null, "e": 5341, "s": 5277, "text": "6. Take sample size greater than 30 and calculate sampling mean" }, { "code": null, "e": 5496, "s": 5341, "text": "sample_means2=[]for i in range(0,100): sample=np.random.choice(population1,size=50) sample_means2.append(np.mean(sample))sample_m2=np.array(sample_means2)" }, { "code": null, "e": 5521, "s": 5496, "text": "7. Sampling distribution" }, { "code": null, "e": 5693, "s": 5521, "text": "sns.distplot(sample_means2,hist=False)plt.title(“Sampling distribution of sample mean”)plt.axvline(sample_m2.mean(),color=’green’,linestyle=’ — ‘)plt.xlabel(“Sample Mean”)" }, { "code": null, "e": 5734, "s": 5693, "text": "The sampling distribution is normal now." }, { "code": null, "e": 5780, "s": 5734, "text": "8. Calculate sampling mean and standard error" }, { "code": null, "e": 5934, "s": 5780, "text": "print (“Sampling mean: “,round(sample_m2.mean(),2))print (“Standard Error: “,round(sample_m2.std(),2))# Output:Sampling mean: 48.17Standard Error: 3.89" }, { "code": null, "e": 6030, "s": 5934, "text": "After increasing the sample size, the standard error decreases. Now the Standard Error is 3.89." }, { "code": null, "e": 6066, "s": 6030, "text": "9. Let’s verify our population mean" }, { "code": null, "e": 6152, "s": 6066, "text": "print (“Population Mean: “,round(population1.mean(),2))#Output:Population Mean: 48.03" }, { "code": null, "e": 6256, "s": 6152, "text": "We have calculated the sampling mean as 48.17 which is approximately equal to the population mean 48.03" }, { "code": null, "e": 6317, "s": 6256, "text": "10. Calculating Confidence Interval at 99% confidence level." }, { "code": null, "e": 6514, "s": 6317, "text": "Lower_limit=sample_m2.mean()- (2.58 * (sample_m2.std()))print (round(Lower_limit,2))#Output: 38.14Upper_limit=sample_m2.mean()+ (2.58 * (sample_m2.std()))print (round(Upper_limit),2)#Output: 58.19" }, { "code": null, "e": 6550, "s": 6514, "text": "Confidence Interval = 38.14 — 58.19" }, { "code": null, "e": 6696, "s": 6550, "text": "In this article, I have covered the central limit theorem, sampling distributions, standard error, and confidence interval. Hope you all like it." }, { "code": null, "e": 6716, "s": 6696, "text": "Thanks for reading!" }, { "code": null, "e": 6734, "s": 6716, "text": "pub.towardsai.net" }, { "code": null, "e": 6752, "s": 6734, "text": "pub.towardsai.net" }, { "code": null, "e": 6763, "s": 6752, "text": "medium.com" }, { "code": null, "e": 6781, "s": 6763, "text": "pub.towardsai.net" }, { "code": null, "e": 6925, "s": 6781, "text": "Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter." } ]