title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Turn an image by 90 degree
12 Jun, 2022 Given an image, how will you turn it by 90 degrees? A vague question. Minimize the browser and try your solution before going further. An image can be treated as 2D matrix which can be stored in a buffer. We are provided with matrix dimensions and it’s base address. How can we turn it? For example see the below picture, * * * ^ * * * * * * | * * * * * * | * * * * * * | * * * After rotating right, it appears (observe arrow direction) * * * * * * * * * * * * — — — > * * * * * * * * * * * * The idea is simple. Transform each row of source matrix into required column of final image. We will use an auxiliary buffer to transform the image. From the above picture, we can observe that first row of source ------> last column of destination second row of source ------> last but-one column of destination so ... on last row of source ------> first column of destination In pictorial form, we can represent the above transformations of an (m x n) matrix into (n x m) matrix, If you have not attempted, atleast try your pseudo code now. It will be easy to write our pseudo code. In C/C++ we will usually traverse matrix on row major order. Each row is transformed into different column of final image. We need to construct columns of final image. See the following algorithm (transformation) for (r = 0; r < m; r++) { for (c = 0; c < n; c++) { // Hint: Map each source element indices into // indices of destination matrix element. dest_buffer [ c ] [ m - r - 1 ] = source_buffer [ r ] [ c ]; } } Note that there are various ways to implement the algorithm based on traversal of matrix, row major or column major order. We have two matrices and two ways (row and column major) to traverse each matrix. Hence, there can atleast be 4 different ways of transformation of source matrix into final matrix. C++ C // C++ program to turn an// image by 90 Degree#include <bits/stdc++.h>using namespace std;void displayMatrix(unsigned int const *p, unsigned int row, unsigned int col); void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col); void displayMatrix(unsigned int const *p, unsigned int r, unsigned int c){ unsigned int row, col; cout << "\n\n"; for (row = 0; row < r; row++) { for (col = 0; col < c; col++) cout << * (p + row * c + col) << "\t"; cout << "\n"; } cout << "\n\n";} void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col){ unsigned int r, c; for (r = 0; r < row; r++) { for (c = 0; c < col; c++) { *(pD + c * row + (row - r - 1)) = *(pS + r * col + c); } }} // Driver Codeint main(){ // declarations unsigned int image[][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; unsigned int *pSource; unsigned int *pDestination; unsigned int m, n; // setting initial values // and memory allocation m = 3, n = 4, pSource = (unsigned int *)image; pDestination = (unsigned int *)malloc (sizeof(int) * m * n); // process each buffer displayMatrix(pSource, m, n); rotate(pSource, pDestination, m, n); displayMatrix(pDestination, n, m); free(pDestination); return 0;} // This code is contributed by rathbhupendra // C program to turn an// image by 90 Degree#include <stdio.h>#include <stdlib.h> void displayMatrix(unsigned int const *p, unsigned int row, unsigned int col); void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col); void displayMatrix(unsigned int const *p, unsigned int r, unsigned int c){ unsigned int row, col; printf("\n\n"); for (row = 0; row < r; row++) { for (col = 0; col < c; col++) printf("%d\t", * (p + row * c + col)); printf("\n"); } printf("\n\n");} void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col){ unsigned int r, c; for (r = 0; r < row; r++) { for (c = 0; c < col; c++) { *(pD + c * row + (row - r - 1)) = *(pS + r * col + c); } }} // Driver Codeint main(){ // declarations unsigned int image[][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}}; unsigned int *pSource; unsigned int *pDestination; unsigned int m, n; // setting initial values // and memory allocation m = 3, n = 4, pSource = (unsigned int *)image; pDestination = (unsigned int *)malloc (sizeof(int) * m * n); // process each buffer displayMatrix(pSource, m, n); rotate(pSource, pDestination, m, n); displayMatrix(pDestination, n, m); free(pDestination); getchar(); return 0;} Output : 1 2 3 4 5 6 7 8 9 10 11 12 9 5 1 10 6 2 11 7 3 12 8 4 Time Complexity: O(N*M), as we are using nested loops for traversing the matrix. Auxiliary Space: O(N*M), as we are using extra space for matrix. Inplace rotate square matrix by 90 degrees Compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rathbhupendra rohitsingh07052 surwaseshrikant1729 rotation Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jun, 2022" }, { "code": null, "e": 374, "s": 52, "text": "Given an image, how will you turn it by 90 degrees? A vague question. Minimize the browser and try your solution before going further. An image can be treated as 2D matrix which can be stored in a buffer. We are provided with matrix dimensions and it’s base address. How can we turn it? For example see the below picture," }, { "code": null, "e": 430, "s": 374, "text": "* * * ^ * * *\n* * * | * * *\n* * * | * * *\n* * * | * * *" }, { "code": null, "e": 489, "s": 430, "text": "After rotating right, it appears (observe arrow direction)" }, { "code": null, "e": 545, "s": 489, "text": "* * * *\n* * * *\n* * * *\n— — — >\n* * * *\n* * * *\n* * * *" }, { "code": null, "e": 738, "s": 545, "text": "The idea is simple. Transform each row of source matrix into required column of final image. We will use an auxiliary buffer to transform the image. From the above picture, we can observe that" }, { "code": null, "e": 922, "s": 738, "text": "first row of source ------> last column of destination\nsecond row of source ------> last but-one column of destination\nso ... on\nlast row of source ------> first column of destination" }, { "code": null, "e": 1026, "s": 922, "text": "In pictorial form, we can represent the above transformations of an (m x n) matrix into (n x m) matrix," }, { "code": null, "e": 1344, "s": 1028, "text": "If you have not attempted, atleast try your pseudo code now. It will be easy to write our pseudo code. In C/C++ we will usually traverse matrix on row major order. Each row is transformed into different column of final image. We need to construct columns of final image. See the following algorithm (transformation)" }, { "code": null, "e": 1577, "s": 1344, "text": "for (r = 0; r < m; r++)\n{\n for (c = 0; c < n; c++)\n {\n // Hint: Map each source element indices into\n // indices of destination matrix element.\n dest_buffer [ c ] [ m - r - 1 ] = source_buffer [ r ] [ c ];\n }\n}" }, { "code": null, "e": 1881, "s": 1577, "text": "Note that there are various ways to implement the algorithm based on traversal of matrix, row major or column major order. We have two matrices and two ways (row and column major) to traverse each matrix. Hence, there can atleast be 4 different ways of transformation of source matrix into final matrix." }, { "code": null, "e": 1885, "s": 1881, "text": "C++" }, { "code": null, "e": 1887, "s": 1885, "text": "C" }, { "code": "// C++ program to turn an// image by 90 Degree#include <bits/stdc++.h>using namespace std;void displayMatrix(unsigned int const *p, unsigned int row, unsigned int col); void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col); void displayMatrix(unsigned int const *p, unsigned int r, unsigned int c){ unsigned int row, col; cout << \"\\n\\n\"; for (row = 0; row < r; row++) { for (col = 0; col < c; col++) cout << * (p + row * c + col) << \"\\t\"; cout << \"\\n\"; } cout << \"\\n\\n\";} void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col){ unsigned int r, c; for (r = 0; r < row; r++) { for (c = 0; c < col; c++) { *(pD + c * row + (row - r - 1)) = *(pS + r * col + c); } }} // Driver Codeint main(){ // declarations unsigned int image[][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; unsigned int *pSource; unsigned int *pDestination; unsigned int m, n; // setting initial values // and memory allocation m = 3, n = 4, pSource = (unsigned int *)image; pDestination = (unsigned int *)malloc (sizeof(int) * m * n); // process each buffer displayMatrix(pSource, m, n); rotate(pSource, pDestination, m, n); displayMatrix(pDestination, n, m); free(pDestination); return 0;} // This code is contributed by rathbhupendra", "e": 3571, "s": 1887, "text": null }, { "code": "// C program to turn an// image by 90 Degree#include <stdio.h>#include <stdlib.h> void displayMatrix(unsigned int const *p, unsigned int row, unsigned int col); void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col); void displayMatrix(unsigned int const *p, unsigned int r, unsigned int c){ unsigned int row, col; printf(\"\\n\\n\"); for (row = 0; row < r; row++) { for (col = 0; col < c; col++) printf(\"%d\\t\", * (p + row * c + col)); printf(\"\\n\"); } printf(\"\\n\\n\");} void rotate(unsigned int *pS, unsigned int *pD, unsigned int row, unsigned int col){ unsigned int r, c; for (r = 0; r < row; r++) { for (c = 0; c < col; c++) { *(pD + c * row + (row - r - 1)) = *(pS + r * col + c); } }} // Driver Codeint main(){ // declarations unsigned int image[][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}}; unsigned int *pSource; unsigned int *pDestination; unsigned int m, n; // setting initial values // and memory allocation m = 3, n = 4, pSource = (unsigned int *)image; pDestination = (unsigned int *)malloc (sizeof(int) * m * n); // process each buffer displayMatrix(pSource, m, n); rotate(pSource, pDestination, m, n); displayMatrix(pDestination, n, m); free(pDestination); getchar(); return 0;}", "e": 5205, "s": 3571, "text": null }, { "code": null, "e": 5214, "s": 5205, "text": "Output :" }, { "code": null, "e": 5351, "s": 5214, "text": "1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n\n\n\n\n9 5 1 \n10 6 2 \n11 7 3 \n12 8 4 " }, { "code": null, "e": 5432, "s": 5351, "text": "Time Complexity: O(N*M), as we are using nested loops for traversing the matrix." }, { "code": null, "e": 5497, "s": 5432, "text": "Auxiliary Space: O(N*M), as we are using extra space for matrix." }, { "code": null, "e": 5684, "s": 5497, "text": "Inplace rotate square matrix by 90 degrees Compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5698, "s": 5684, "text": "rathbhupendra" }, { "code": null, "e": 5714, "s": 5698, "text": "rohitsingh07052" }, { "code": null, "e": 5734, "s": 5714, "text": "surwaseshrikant1729" }, { "code": null, "e": 5743, "s": 5734, "text": "rotation" }, { "code": null, "e": 5750, "s": 5743, "text": "Matrix" }, { "code": null, "e": 5757, "s": 5750, "text": "Matrix" } ]
Java program to calculate the power of a Given number using recursion
You can calculate the power where the base and exponent are given, using recursion as shown in the following program. import java.util.Scanner; public class PowerUsingRecursion { public static int power(int base, int exp){ if (exp !=0){ return (base * power(base, exp-1)); }else { return 1; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the base number ::"); int base = sc.nextInt(); System.out.println("Enter the exponent number ::"); int exp = sc.nextInt(); System.out.println(power(base, exp)); } } Enter the base number :: 5 Enter the exponent number :: 5
[ { "code": null, "e": 1305, "s": 1187, "text": "You can calculate the power where the base and exponent are given, using recursion as shown in the following program." }, { "code": null, "e": 1834, "s": 1305, "text": "import java.util.Scanner;\npublic class PowerUsingRecursion {\n public static int power(int base, int exp){\n if (exp !=0){\n return (base * power(base, exp-1));\n }else {\n return 1;\n }\n }\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the base number ::\");\n int base = sc.nextInt();\n System.out.println(\"Enter the exponent number ::\");\n int exp = sc.nextInt();\n System.out.println(power(base, exp));\n }\n}" }, { "code": null, "e": 1892, "s": 1834, "text": "Enter the base number ::\n5\nEnter the exponent number ::\n5" } ]
PyQt5 – Set icon size of item icon in ComboBox
22 Apr, 2020 In this article we will see how we can set the icon size to the item of combo box. By default there is no icon set to the icon in the combo box although we can set icon to each item with the help of setItemIcon method, sometimes there is a need for adjusting the icon size. In order to change the icon size of items icon we will use setIconSize method. Syntax : combobox.setIconSize(size) Argument : It takes QSize object as argument Action It will set icon size to the item Below is the implementation – # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating editable combo box self.combo_box.setEditable(True) # index index = 0 # icon icon = QIcon('logo.png') # adding icon to the given index self.combo_box.setItemIcon(index, icon) # size size = QSize(10, 10) # setting icon size self.combo_box.setIconSize(size) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-ComboBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 302, "s": 28, "text": "In this article we will see how we can set the icon size to the item of combo box. By default there is no icon set to the icon in the combo box although we can set icon to each item with the help of setItemIcon method, sometimes there is a need for adjusting the icon size." }, { "code": null, "e": 381, "s": 302, "text": "In order to change the icon size of items icon we will use setIconSize method." }, { "code": null, "e": 417, "s": 381, "text": "Syntax : combobox.setIconSize(size)" }, { "code": null, "e": 462, "s": 417, "text": "Argument : It takes QSize object as argument" }, { "code": null, "e": 503, "s": 462, "text": "Action It will set icon size to the item" }, { "code": null, "e": 533, "s": 503, "text": "Below is the implementation –" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating editable combo box self.combo_box.setEditable(True) # index index = 0 # icon icon = QIcon('logo.png') # adding icon to the given index self.combo_box.setItemIcon(index, icon) # size size = QSize(10, 10) # setting icon size self.combo_box.setIconSize(size) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1882, "s": 533, "text": null }, { "code": null, "e": 1891, "s": 1882, "text": "Output :" }, { "code": null, "e": 1913, "s": 1891, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 1924, "s": 1913, "text": "Python-gui" }, { "code": null, "e": 1936, "s": 1924, "text": "Python-PyQt" }, { "code": null, "e": 1943, "s": 1936, "text": "Python" } ]
StringBuilder reverse() in Java with Examples
19 Aug, 2019 The reverse() method of StringBuilder is used to reverse the characters in the StringBuilder. The method helps to this character sequence to be replaced by the reverse of the sequence. Syntax: public java.lang.AbstractStringBuilder reverse() Returns:This method returns StringBuilder object after reversing the characters. Below programs illustrate the java.lang.StringBuilder.replace() method:Example 1: // Java program to demonstrate// the reverse() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("String = " + str.toString()); // reverse the string StringBuilder reverseStr = str.reverse(); // print string System.out.println("Reverse String = " + reverseStr.toString()); }} Output: String = WelcomeGeeks Reverse String = skeeGemocleW Example 2: // Java program to demonstrate// the reverse() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("AAAABBBCCCC"); // print string System.out.println("String = " + str.toString()); // reverse the string StringBuilder reverseStr = str.reverse(); // print string System.out.println("Reverse String = " + reverseStr.toString()); }} Output: String = AAAABBBCCCC Reverse String = CCCCBBBAAAA References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#reverse() Akanksha_Rai Java-Functions Java-StringBuilder Reverse Java Java Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Aug, 2019" }, { "code": null, "e": 237, "s": 52, "text": "The reverse() method of StringBuilder is used to reverse the characters in the StringBuilder. The method helps to this character sequence to be replaced by the reverse of the sequence." }, { "code": null, "e": 245, "s": 237, "text": "Syntax:" }, { "code": null, "e": 294, "s": 245, "text": "public java.lang.AbstractStringBuilder reverse()" }, { "code": null, "e": 375, "s": 294, "text": "Returns:This method returns StringBuilder object after reversing the characters." }, { "code": null, "e": 457, "s": 375, "text": "Below programs illustrate the java.lang.StringBuilder.replace() method:Example 1:" }, { "code": "// Java program to demonstrate// the reverse() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string System.out.println(\"String = \" + str.toString()); // reverse the string StringBuilder reverseStr = str.reverse(); // print string System.out.println(\"Reverse String = \" + reverseStr.toString()); }}", "e": 1046, "s": 457, "text": null }, { "code": null, "e": 1054, "s": 1046, "text": "Output:" }, { "code": null, "e": 1107, "s": 1054, "text": "String = WelcomeGeeks\nReverse String = skeeGemocleW\n" }, { "code": null, "e": 1118, "s": 1107, "text": "Example 2:" }, { "code": "// Java program to demonstrate// the reverse() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"AAAABBBCCCC\"); // print string System.out.println(\"String = \" + str.toString()); // reverse the string StringBuilder reverseStr = str.reverse(); // print string System.out.println(\"Reverse String = \" + reverseStr.toString()); }}", "e": 1706, "s": 1118, "text": null }, { "code": null, "e": 1714, "s": 1706, "text": "Output:" }, { "code": null, "e": 1765, "s": 1714, "text": "String = AAAABBBCCCC\nReverse String = CCCCBBBAAAA\n" }, { "code": null, "e": 1858, "s": 1765, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#reverse()" }, { "code": null, "e": 1871, "s": 1858, "text": "Akanksha_Rai" }, { "code": null, "e": 1886, "s": 1871, "text": "Java-Functions" }, { "code": null, "e": 1905, "s": 1886, "text": "Java-StringBuilder" }, { "code": null, "e": 1913, "s": 1905, "text": "Reverse" }, { "code": null, "e": 1918, "s": 1913, "text": "Java" }, { "code": null, "e": 1923, "s": 1918, "text": "Java" }, { "code": null, "e": 1931, "s": 1923, "text": "Reverse" }, { "code": null, "e": 2029, "s": 1931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2044, "s": 2029, "text": "Stream In Java" }, { "code": null, "e": 2065, "s": 2044, "text": "Introduction to Java" }, { "code": null, "e": 2086, "s": 2065, "text": "Constructors in Java" }, { "code": null, "e": 2105, "s": 2086, "text": "Exceptions in Java" }, { "code": null, "e": 2122, "s": 2105, "text": "Generics in Java" }, { "code": null, "e": 2152, "s": 2122, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2178, "s": 2152, "text": "Java Programming Examples" }, { "code": null, "e": 2194, "s": 2178, "text": "Strings in Java" }, { "code": null, "e": 2231, "s": 2194, "text": "Differences between JDK, JRE and JVM" } ]
Number of triangles formed by joining vertices of n-sided polygon with two common sides and no common sides
31 May, 2022 Given N-sided polygon we need to find the total number of triangles formed by joining the vertices of the given polygon with exactly two sides being common and no side being common.Examples: Input : N = 6 Output : 6 2 The image below is of a triangle forming inside a Hexagon by joining vertices as shown above. The triangle formed has two sides (AB and BC) common with that of a polygon. Similarly BC and CD can make one triangle. With this, we can say that there will be a total of 6 triangles possible having two sides common with that of a polygon. The second image of a hexagon, a triangle is formed with no side common with that of a polygon. There will be just 2 triangles possible, BFD and ACE. Triangle with two side common and no side common of the Hexagon Number of triangles formed are 6 and 2 with two side common and with no side common respectively.Input : N = 7 Output : 7 7 Approach : To make a triangle two side common with a polygon we will take any one side of a n-sided polygon, take one vertex of the chosen side and join an edge adjacent to the vertex of the other vertex. Traversing through each vertex and adjoining an edge adjacent to the vertex of the other vertex ,there will be N number of triangles having two side common. Now, to calculate the number of triangles with no side common subtract the total number of triangles with one side common and the total number of triangles with two side from the total number of triangles possible in a polygon. Triangles with no common side = Total triangles ( nC3 ) – one side common triangles ( n * ( n – 4 ) – two side common triangles ( n ). Thus number of triangles with no common side with the polygon would be equal to n * ( n – 4 ) * ( n – 5 ) / 6. Note:To calculate the number of triangles having one side common with that of a polygon click hereBelow is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above problem#include <bits/stdc++.h>using namespace std; // Function to find the number of trianglesvoid findTriangles(int n){ int num = n; // print the number of triangles // having two side common cout << num << " "; // print the number of triangles // having no side common cout << num * (num - 4) * (num - 5) / 6;} // Driver codeint main(){ // initialize the number // of sides of a polygon int n; n = 6; findTriangles(n); return 0;} // Java program to implement// the above problemimport java.io.*; class GFG{ // Function to find the number of trianglesstatic void findTriangles(int n){ int num = n; // print the number of triangles // having two side common System.out.print( num + " "); // print the number of triangles // having no side common System.out.print( num * (num - 4) * (num - 5) / 6);} // Driver codepublic static void main (String[] args){ // initialize the number // of sides of a polygon int n; n = 6; findTriangles(n);}} // This code is contributed by anuj_67.. # Python3 program to implement# the above problem # Function to find the number of trianglesdef findTriangles(n): num = n # print the number of triangles # having two side common print(num, end = " ") # print the number of triangles # having no side common print(num * (num - 4) * (num - 5) // 6) # Driver code # initialize the number# of sides of a polygonn = 6; findTriangles(n) # This code is contributed by Mohit Kumar // C# program to implement// the above problemusing System; class GFG{ // Function to find the number of trianglesstatic void findTriangles(int n){ int num = n; // print the number of triangles // having two side common Console.Write( num + " "); // print the number of triangles // having no side common Console.WriteLine( num * (num - 4) * (num - 5) / 6);} // Driver codepublic static void Main (){ // initialize the number // of sides of a polygon int n; n = 6; findTriangles(n);}} // This code is contributed by anuj_67.. <script> // javascript program to implement// the above problem // Function to find the number of triangles function findTriangles(n){ var num = n; // print the number of triangles // having two side common document.write( num + " "); // print the number of triangles // having no side common document.write( num * (num - 4) * (num - 5) / 6);} // Driver code// initialize the number// of sides of a polygonvar n;n = 6; findTriangles(n); // This code is contributed by 29AjayKumar </script> 6 2 Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 vt_m nidhi_biet 29AjayKumar subhamkumarm348 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2022" }, { "code": null, "e": 221, "s": 28, "text": "Given N-sided polygon we need to find the total number of triangles formed by joining the vertices of the given polygon with exactly two sides being common and no side being common.Examples: " }, { "code": null, "e": 735, "s": 221, "text": "Input : N = 6 Output : 6 2 The image below is of a triangle forming inside a Hexagon by joining vertices as shown above. The triangle formed has two sides (AB and BC) common with that of a polygon. Similarly BC and CD can make one triangle. With this, we can say that there will be a total of 6 triangles possible having two sides common with that of a polygon. The second image of a hexagon, a triangle is formed with no side common with that of a polygon. There will be just 2 triangles possible, BFD and ACE. " }, { "code": null, "e": 799, "s": 735, "text": "Triangle with two side common and no side common of the Hexagon" }, { "code": null, "e": 925, "s": 799, "text": "Number of triangles formed are 6 and 2 with two side common and with no side common respectively.Input : N = 7 Output : 7 7 " }, { "code": null, "e": 940, "s": 927, "text": "Approach : " }, { "code": null, "e": 1134, "s": 940, "text": "To make a triangle two side common with a polygon we will take any one side of a n-sided polygon, take one vertex of the chosen side and join an edge adjacent to the vertex of the other vertex." }, { "code": null, "e": 1291, "s": 1134, "text": "Traversing through each vertex and adjoining an edge adjacent to the vertex of the other vertex ,there will be N number of triangles having two side common." }, { "code": null, "e": 1519, "s": 1291, "text": "Now, to calculate the number of triangles with no side common subtract the total number of triangles with one side common and the total number of triangles with two side from the total number of triangles possible in a polygon." }, { "code": null, "e": 1654, "s": 1519, "text": "Triangles with no common side = Total triangles ( nC3 ) – one side common triangles ( n * ( n – 4 ) – two side common triangles ( n )." }, { "code": null, "e": 1765, "s": 1654, "text": "Thus number of triangles with no common side with the polygon would be equal to n * ( n – 4 ) * ( n – 5 ) / 6." }, { "code": null, "e": 1916, "s": 1765, "text": "Note:To calculate the number of triangles having one side common with that of a polygon click hereBelow is the implementation of the above approach: " }, { "code": null, "e": 1920, "s": 1916, "text": "C++" }, { "code": null, "e": 1925, "s": 1920, "text": "Java" }, { "code": null, "e": 1933, "s": 1925, "text": "Python3" }, { "code": null, "e": 1936, "s": 1933, "text": "C#" }, { "code": null, "e": 1947, "s": 1936, "text": "Javascript" }, { "code": "// C++ program to implement// the above problem#include <bits/stdc++.h>using namespace std; // Function to find the number of trianglesvoid findTriangles(int n){ int num = n; // print the number of triangles // having two side common cout << num << \" \"; // print the number of triangles // having no side common cout << num * (num - 4) * (num - 5) / 6;} // Driver codeint main(){ // initialize the number // of sides of a polygon int n; n = 6; findTriangles(n); return 0;}", "e": 2463, "s": 1947, "text": null }, { "code": "// Java program to implement// the above problemimport java.io.*; class GFG{ // Function to find the number of trianglesstatic void findTriangles(int n){ int num = n; // print the number of triangles // having two side common System.out.print( num + \" \"); // print the number of triangles // having no side common System.out.print( num * (num - 4) * (num - 5) / 6);} // Driver codepublic static void main (String[] args){ // initialize the number // of sides of a polygon int n; n = 6; findTriangles(n);}} // This code is contributed by anuj_67..", "e": 3050, "s": 2463, "text": null }, { "code": "# Python3 program to implement# the above problem # Function to find the number of trianglesdef findTriangles(n): num = n # print the number of triangles # having two side common print(num, end = \" \") # print the number of triangles # having no side common print(num * (num - 4) * (num - 5) // 6) # Driver code # initialize the number# of sides of a polygonn = 6; findTriangles(n) # This code is contributed by Mohit Kumar", "e": 3501, "s": 3050, "text": null }, { "code": "// C# program to implement// the above problemusing System; class GFG{ // Function to find the number of trianglesstatic void findTriangles(int n){ int num = n; // print the number of triangles // having two side common Console.Write( num + \" \"); // print the number of triangles // having no side common Console.WriteLine( num * (num - 4) * (num - 5) / 6);} // Driver codepublic static void Main (){ // initialize the number // of sides of a polygon int n; n = 6; findTriangles(n);}} // This code is contributed by anuj_67..", "e": 4067, "s": 3501, "text": null }, { "code": "<script> // javascript program to implement// the above problem // Function to find the number of triangles function findTriangles(n){ var num = n; // print the number of triangles // having two side common document.write( num + \" \"); // print the number of triangles // having no side common document.write( num * (num - 4) * (num - 5) / 6);} // Driver code// initialize the number// of sides of a polygonvar n;n = 6; findTriangles(n); // This code is contributed by 29AjayKumar </script>", "e": 4581, "s": 4067, "text": null }, { "code": null, "e": 4585, "s": 4581, "text": "6 2" }, { "code": null, "e": 4609, "s": 4587, "text": "Time Complexity: O(1)" }, { "code": null, "e": 4632, "s": 4609, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 4647, "s": 4632, "text": "mohit kumar 29" }, { "code": null, "e": 4652, "s": 4647, "text": "vt_m" }, { "code": null, "e": 4663, "s": 4652, "text": "nidhi_biet" }, { "code": null, "e": 4675, "s": 4663, "text": "29AjayKumar" }, { "code": null, "e": 4691, "s": 4675, "text": "subhamkumarm348" }, { "code": null, "e": 4701, "s": 4691, "text": "Geometric" }, { "code": null, "e": 4714, "s": 4701, "text": "Mathematical" }, { "code": null, "e": 4727, "s": 4714, "text": "Mathematical" }, { "code": null, "e": 4737, "s": 4727, "text": "Geometric" } ]
Working with wav files in Python using Pydub
18 Jan, 2022 Audio files are a widespread means of transferring information. So let’s see how to work with audio files using Python. Python provides a module called pydub to work with audio files. pydub is a Python library to work with only .wav files. By using this library we can play, split, merge, edit our .wav audio files. This module does not come built-in with Python. To install it type the below command in the terminal. pip install pydub Following are some functionalities that can be performed by pydub: Playing audio file.We can get certain information of file like length channels.Increase/Decrease volume of given .wav file.Merging two or more audio files.Exporting an audio file.Splitting an audio file. Playing audio file. We can get certain information of file like length channels. Increase/Decrease volume of given .wav file. Merging two or more audio files. Exporting an audio file. Splitting an audio file. For accessing input Sound files click here. Let’s see the code for some functionalities of pydub library: 1) Playing Audio File: This is done using play() method. Python3 # import required librariesfrom pydub import AudioSegment from pydub.playback import play # Import an audio file # Format parameter only# for readability wav_file = AudioSegment.from_file(file = "Sample.wav", format = "wav") # Play the audio fileplay(wav_file) Output: 2) Knowing about .wav file: for this we will use attributes of audio file object. Python3 # import required libraryfrom pydub import AudioSegment # import the audio filewav_file = AudioSegment.from_file(file="Sample.wav", format="wav") # data type fo the fileprint(type(wav_file)) # OUTPUT: <class 'pydub.audio_segment.AudioSegment'> # To find frame rate of song/fileprint(wav_file.frame_rate) # OUTPUT: 22050 # To know about channels of fileprint(wav_file.channels) # OUTPUT: 1 # Find the number of bytes per sample print(wav_file.sample_width ) # OUTPUT : 2 # Find Maximum amplitude print(wav_file.max)# OUTPUT 17106 # To know length of audio fileprint(len(wav_file))# OUTPUT 60000 '''We can change the attrinbutes of file by changeed_audio_segment = audio_segment.set_ATTRIBUTENAME(x) '''wav_file_new = wav_file.set_frame_rate(50) print(wav_file_new.frame_rate) Output: <class 'pydub.audio_segment.AudioSegment'> 22050 1 2 17106 60000 50 3) Increasing/Decreasing volume of the file: By using ‘+’ and ‘-‘ operator. Python3 # import required libraryimport pydub from pydub.playback import play wav_file = pydub.AudioSegment.from_file(file = "Sample.wav", format = "wav") # Increase the volume by 10 dB new_wav_file = wav_file + 10 # Reducing volume by 5silent_wav_file = wav_file - 5 # Playing silent fileplay(silent_wav_file) # Playing original fileplay(wav_file) # Playing louder fileplay(new_wav_file) # Feel the difference! Output: 4) Merging files: This is done using ‘+’ operator. Python3 # import required librariesfrom pydub import AudioSegmentfrom pydub.playback import play wav_file_1 = AudioSegment.from_file("noice.wav") wav_file_2 = AudioSegment.from_file("Sample.wav") # Combine the two audio files wav_file_3 = wav_file_1 + wav_file_2 # play the sound play(wav_file_3) Output: 5) Exporting files: This is done using export() method. Python3 # import libraryfrom pydub import AudioSegment # Import audio file wav_file = AudioSegment.from_file("Sample.wav") ''' You can do anything like remixing and export I'm increasing volume just for sake of my simplicity Increase by 10 decibels '''louder_wav_file = wav_file + 10 # Export louder audio file louder_wav_file.export(out_f = "louder_wav_file.wav", format = "wav") Output: 6) Splitting Audio: Splitting audio using split_to_mono() method. Python3 # import required librariesfrom pydub import AudioSegment from pydub.playback import play # importing audio filea = AudioSegment.from_file("pzm12.wav") # Split stereo to mono b = a.split_to_mono() print(b) print(b[0].channels ) b[0].export(out_f="outNow.wav",format="wav") Output: [<pydub.audio_segment.AudioSegment object at 0x000001358727E860>, <pydub.audio_segment.AudioSegment object at 0x000001358721F978>] 1 gabaa406 python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2022" }, { "code": null, "e": 344, "s": 28, "text": "Audio files are a widespread means of transferring information. So let’s see how to work with audio files using Python. Python provides a module called pydub to work with audio files. pydub is a Python library to work with only .wav files. By using this library we can play, split, merge, edit our .wav audio files." }, { "code": null, "e": 446, "s": 344, "text": "This module does not come built-in with Python. To install it type the below command in the terminal." }, { "code": null, "e": 465, "s": 446, "text": "pip install pydub\n" }, { "code": null, "e": 532, "s": 465, "text": "Following are some functionalities that can be performed by pydub:" }, { "code": null, "e": 736, "s": 532, "text": "Playing audio file.We can get certain information of file like length channels.Increase/Decrease volume of given .wav file.Merging two or more audio files.Exporting an audio file.Splitting an audio file." }, { "code": null, "e": 756, "s": 736, "text": "Playing audio file." }, { "code": null, "e": 817, "s": 756, "text": "We can get certain information of file like length channels." }, { "code": null, "e": 862, "s": 817, "text": "Increase/Decrease volume of given .wav file." }, { "code": null, "e": 895, "s": 862, "text": "Merging two or more audio files." }, { "code": null, "e": 920, "s": 895, "text": "Exporting an audio file." }, { "code": null, "e": 945, "s": 920, "text": "Splitting an audio file." }, { "code": null, "e": 1051, "s": 945, "text": "For accessing input Sound files click here. Let’s see the code for some functionalities of pydub library:" }, { "code": null, "e": 1108, "s": 1051, "text": "1) Playing Audio File: This is done using play() method." }, { "code": null, "e": 1116, "s": 1108, "text": "Python3" }, { "code": "# import required librariesfrom pydub import AudioSegment from pydub.playback import play # Import an audio file # Format parameter only# for readability wav_file = AudioSegment.from_file(file = \"Sample.wav\", format = \"wav\") # Play the audio fileplay(wav_file)", "e": 1415, "s": 1116, "text": null }, { "code": null, "e": 1423, "s": 1415, "text": "Output:" }, { "code": null, "e": 1505, "s": 1423, "text": "2) Knowing about .wav file: for this we will use attributes of audio file object." }, { "code": null, "e": 1513, "s": 1505, "text": "Python3" }, { "code": "# import required libraryfrom pydub import AudioSegment # import the audio filewav_file = AudioSegment.from_file(file=\"Sample.wav\", format=\"wav\") # data type fo the fileprint(type(wav_file)) # OUTPUT: <class 'pydub.audio_segment.AudioSegment'> # To find frame rate of song/fileprint(wav_file.frame_rate) # OUTPUT: 22050 # To know about channels of fileprint(wav_file.channels) # OUTPUT: 1 # Find the number of bytes per sample print(wav_file.sample_width ) # OUTPUT : 2 # Find Maximum amplitude print(wav_file.max)# OUTPUT 17106 # To know length of audio fileprint(len(wav_file))# OUTPUT 60000 '''We can change the attrinbutes of file by changeed_audio_segment = audio_segment.set_ATTRIBUTENAME(x) '''wav_file_new = wav_file.set_frame_rate(50) print(wav_file_new.frame_rate)", "e": 2305, "s": 1513, "text": null }, { "code": null, "e": 2313, "s": 2305, "text": "Output:" }, { "code": null, "e": 2382, "s": 2313, "text": "<class 'pydub.audio_segment.AudioSegment'>\n22050\n1\n2\n17106\n60000\n50\n" }, { "code": null, "e": 2458, "s": 2382, "text": "3) Increasing/Decreasing volume of the file: By using ‘+’ and ‘-‘ operator." }, { "code": null, "e": 2466, "s": 2458, "text": "Python3" }, { "code": "# import required libraryimport pydub from pydub.playback import play wav_file = pydub.AudioSegment.from_file(file = \"Sample.wav\", format = \"wav\") # Increase the volume by 10 dB new_wav_file = wav_file + 10 # Reducing volume by 5silent_wav_file = wav_file - 5 # Playing silent fileplay(silent_wav_file) # Playing original fileplay(wav_file) # Playing louder fileplay(new_wav_file) # Feel the difference!", "e": 2922, "s": 2466, "text": null }, { "code": null, "e": 2930, "s": 2922, "text": "Output:" }, { "code": null, "e": 2981, "s": 2930, "text": "4) Merging files: This is done using ‘+’ operator." }, { "code": null, "e": 2989, "s": 2981, "text": "Python3" }, { "code": "# import required librariesfrom pydub import AudioSegmentfrom pydub.playback import play wav_file_1 = AudioSegment.from_file(\"noice.wav\") wav_file_2 = AudioSegment.from_file(\"Sample.wav\") # Combine the two audio files wav_file_3 = wav_file_1 + wav_file_2 # play the sound play(wav_file_3)", "e": 3282, "s": 2989, "text": null }, { "code": null, "e": 3290, "s": 3282, "text": "Output:" }, { "code": null, "e": 3346, "s": 3290, "text": "5) Exporting files: This is done using export() method." }, { "code": null, "e": 3354, "s": 3346, "text": "Python3" }, { "code": "# import libraryfrom pydub import AudioSegment # Import audio file wav_file = AudioSegment.from_file(\"Sample.wav\") ''' You can do anything like remixing and export I'm increasing volume just for sake of my simplicity Increase by 10 decibels '''louder_wav_file = wav_file + 10 # Export louder audio file louder_wav_file.export(out_f = \"louder_wav_file.wav\", format = \"wav\")", "e": 3770, "s": 3354, "text": null }, { "code": null, "e": 3778, "s": 3770, "text": "Output:" }, { "code": null, "e": 3844, "s": 3778, "text": "6) Splitting Audio: Splitting audio using split_to_mono() method." }, { "code": null, "e": 3852, "s": 3844, "text": "Python3" }, { "code": "# import required librariesfrom pydub import AudioSegment from pydub.playback import play # importing audio filea = AudioSegment.from_file(\"pzm12.wav\") # Split stereo to mono b = a.split_to_mono() print(b) print(b[0].channels ) b[0].export(out_f=\"outNow.wav\",format=\"wav\")", "e": 4131, "s": 3852, "text": null }, { "code": null, "e": 4139, "s": 4131, "text": "Output:" }, { "code": null, "e": 4273, "s": 4139, "text": "[<pydub.audio_segment.AudioSegment object at 0x000001358727E860>, <pydub.audio_segment.AudioSegment object at 0x000001358721F978>]\n1\n" }, { "code": null, "e": 4282, "s": 4273, "text": "gabaa406" }, { "code": null, "e": 4297, "s": 4282, "text": "python-modules" }, { "code": null, "e": 4312, "s": 4297, "text": "python-utility" }, { "code": null, "e": 4319, "s": 4312, "text": "Python" } ]
How to use MetaMask to Deploy a Smart contract in Solidity (Blockchain)?
11 May, 2022 Smart contracts are self-executing contracts. They were first proposed by Nick Szabo in the 90s. They are set of rules and protocols which two parties agree upon and have to follow. One of the main features is that they are immutable once deployed on the blockchain. It is widely used in the Ethereum blockchain. The main language used for writing smart contracts in Solidity. To write and execute solidity codes, the most common IDE used is an online IDE known as REMIX. You can either open it online on https://remix.ethereum.org/ or install it in your system from https://github.com/ethereum/remix-ide. You can also use Mist (the Ethereum DApp browser). After you write the code and compile it you can deploy it in 3 ways – JavaScriptVM (https://www.geeksforgeeks.org/hello-world-smart-contract-in-remix-ide/) Injected Web3 Web3 Provider This article explains how to deploy your contract by using MetaMask as Injected Web3. MetaMask is a type of Ethereum wallet that bridges the gap between the user interfaces for Ethereum (e.g. Mist browsers, DApps) and the regular web (e.g. Chrome, Firefox, websites). Its function is to inject a JavaScript library called web3.js into the namespace of each page your browser loads. Web3.js is written by the Ethereum core team. MetaMask is mainly used as a plugin in chrome. You can add it from here or download it directly from this link. After adding MetaMask as an extension in chrome and creating an account, set up your account as follows – Step 1: Select Ropsten Test Network from a list of available networks as below: Step 2: Request test ether form here. Step 3: MetaMask is ready for deployment. To know more about MetaMask visit the MetaMask official guide. Step 1: Open Remix IDE in your browser. After opening click on + and write the filename as follows: Step 2: Write the following sample code for testing and compile by clicking on the compile button as shown: Solidity pragma solidity ^0.4.26; // Creating a contractcontract shreyansh_05{ // Defining a function to // return a string function get_output() public pure returns (string) { return ("Hi, your contract ran successfully"); }} Step 3: After compilation and move to deploy section just below the compilation and select Injected Web3 in place of JavaScriptVM as shown below – Step 4: Now your contract is ready to be deployed. Click on deploy button and the MetaMask will ask for confirmation as follows – Step 5: After confirmation, the deployed contract will look like – Step 6: Expand the deployed contract as below and get the output using the get_output() function: Step 7: Now, to verify whether your transaction (process) executed successfully, you can check your balance on MetaMask. Now your contract is completely ready to function. Make sure the compiler version matches the version of your solidity code. This is the basic implementation of MetaMask with solidity. Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Solidity - Mappings Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network How to Install Solidity in Windows? Top 10 Programming Languages for Blockchain Development Solidity - Enums and Structs Solidity - Constructors Solidity - Mappings How to Install Solidity in Windows? Solidity - Enums and Structs Storage vs Memory in Solidity
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2022" }, { "code": null, "e": 431, "s": 54, "text": "Smart contracts are self-executing contracts. They were first proposed by Nick Szabo in the 90s. They are set of rules and protocols which two parties agree upon and have to follow. One of the main features is that they are immutable once deployed on the blockchain. It is widely used in the Ethereum blockchain. The main language used for writing smart contracts in Solidity." }, { "code": null, "e": 713, "s": 431, "text": "To write and execute solidity codes, the most common IDE used is an online IDE known as REMIX. You can either open it online on https://remix.ethereum.org/ or install it in your system from https://github.com/ethereum/remix-ide. You can also use Mist (the Ethereum DApp browser). " }, { "code": null, "e": 783, "s": 713, "text": "After you write the code and compile it you can deploy it in 3 ways –" }, { "code": null, "e": 869, "s": 783, "text": "JavaScriptVM (https://www.geeksforgeeks.org/hello-world-smart-contract-in-remix-ide/)" }, { "code": null, "e": 883, "s": 869, "text": "Injected Web3" }, { "code": null, "e": 897, "s": 883, "text": "Web3 Provider" }, { "code": null, "e": 983, "s": 897, "text": "This article explains how to deploy your contract by using MetaMask as Injected Web3." }, { "code": null, "e": 1165, "s": 983, "text": "MetaMask is a type of Ethereum wallet that bridges the gap between the user interfaces for Ethereum (e.g. Mist browsers, DApps) and the regular web (e.g. Chrome, Firefox, websites)." }, { "code": null, "e": 1437, "s": 1165, "text": "Its function is to inject a JavaScript library called web3.js into the namespace of each page your browser loads. Web3.js is written by the Ethereum core team. MetaMask is mainly used as a plugin in chrome. You can add it from here or download it directly from this link." }, { "code": null, "e": 1543, "s": 1437, "text": "After adding MetaMask as an extension in chrome and creating an account, set up your account as follows –" }, { "code": null, "e": 1623, "s": 1543, "text": "Step 1: Select Ropsten Test Network from a list of available networks as below:" }, { "code": null, "e": 1661, "s": 1623, "text": "Step 2: Request test ether form here." }, { "code": null, "e": 1766, "s": 1661, "text": "Step 3: MetaMask is ready for deployment. To know more about MetaMask visit the MetaMask official guide." }, { "code": null, "e": 1866, "s": 1766, "text": "Step 1: Open Remix IDE in your browser. After opening click on + and write the filename as follows:" }, { "code": null, "e": 1974, "s": 1866, "text": "Step 2: Write the following sample code for testing and compile by clicking on the compile button as shown:" }, { "code": null, "e": 1983, "s": 1974, "text": "Solidity" }, { "code": "pragma solidity ^0.4.26; // Creating a contractcontract shreyansh_05{ // Defining a function to // return a string function get_output() public pure returns (string) { return (\"Hi, your contract ran successfully\"); }}", "e": 2213, "s": 1983, "text": null }, { "code": null, "e": 2360, "s": 2213, "text": "Step 3: After compilation and move to deploy section just below the compilation and select Injected Web3 in place of JavaScriptVM as shown below –" }, { "code": null, "e": 2492, "s": 2360, "text": "Step 4: Now your contract is ready to be deployed. Click on deploy button and the MetaMask will ask for confirmation as follows – " }, { "code": null, "e": 2559, "s": 2492, "text": "Step 5: After confirmation, the deployed contract will look like –" }, { "code": null, "e": 2657, "s": 2559, "text": "Step 6: Expand the deployed contract as below and get the output using the get_output() function:" }, { "code": null, "e": 2778, "s": 2657, "text": "Step 7: Now, to verify whether your transaction (process) executed successfully, you can check your balance on MetaMask." }, { "code": null, "e": 2964, "s": 2778, "text": "Now your contract is completely ready to function. Make sure the compiler version matches the version of your solidity code. This is the basic implementation of MetaMask with solidity. " }, { "code": null, "e": 2975, "s": 2964, "text": "Blockchain" }, { "code": null, "e": 2984, "s": 2975, "text": "Solidity" }, { "code": null, "e": 3082, "s": 2984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3102, "s": 3082, "text": "Solidity - Mappings" }, { "code": null, "e": 3174, "s": 3102, "text": "Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network" }, { "code": null, "e": 3210, "s": 3174, "text": "How to Install Solidity in Windows?" }, { "code": null, "e": 3266, "s": 3210, "text": "Top 10 Programming Languages for Blockchain Development" }, { "code": null, "e": 3295, "s": 3266, "text": "Solidity - Enums and Structs" }, { "code": null, "e": 3319, "s": 3295, "text": "Solidity - Constructors" }, { "code": null, "e": 3339, "s": 3319, "text": "Solidity - Mappings" }, { "code": null, "e": 3375, "s": 3339, "text": "How to Install Solidity in Windows?" }, { "code": null, "e": 3404, "s": 3375, "text": "Solidity - Enums and Structs" } ]
SimpleExpandableListAdapter in Android with Example
25 Sep, 2020 Android ExpandableListView is a view that is used to shows items as a vertically scrolling two-level list. The basic difference with ListView is it allows two levels of the display which are groups that can be easily expanded and collapsed by touching to view and their respective children’s items. In order to show the view, ExpandableListViewAdapter is used in android. In many apps, an ExpandableListView facility is required. For example: In a “city” app(for any city), if the user wants to see a list of engineering colleges/list of art colleges/list of medical colleges, etc., List of vegetables/List of fruits/List of Nuts etc., for a “jiomart” kind of app List of Hatchback/List of crosscut/List of Sedan etc., for a “Uber” kind of app Methods Description Current state indicator for each item If the child is the last child for a group, the state state_last will be set To represent the state either expanded or collapsed.state_expanded is the state if the group is expanded, state_collapsed if the state of the group is collapsed, state_empty if there are no groups. Interfaces Description Let us see the ways to implement SimpleExpandableListAdapter in Android with a List of vegetables/List of fruits/List of Nuts in the ExpandableListAdapter. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Create the dimens.xml file Go to app > res > values > right-click > New > Values Resource File and name the file as dimens. In this file dimension related information is given here. Below is the code for the dimens.xml file. XML <resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen></resources> Step 3: Working with the XML files To design the UI, code is present under the res\layout folder in the form of XML. They are used in the Activity files and once the XML file is in scope inside the activity, one can access the components present in the XML. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. XML <!-- RelativeLayout places the components vertically one by one. Necessary parameters also specified so that elegant output can be seen --><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <!-- ExpandableListView is used in relativelayout The android:indicatorLeft is the left bound for an items indicator.--> <ExpandableListView android:id="@+id/expandableListViewSample" android:layout_width="match_parent" android:layout_height="match_parent" android:divider="@android:color/darker_gray" android:dividerHeight="0.5dp" android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft" /> </RelativeLayout><!-- Note: We cannot use the value wrap_content for the android:layout_height attribute of the ExpandableListView in XML. --> Go to app > res > layout > New > Layout Resource File and name the file as list_group. Below is the code for the list_group.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/listTitle" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft" android:paddingTop="10dp" android:paddingBottom="10dp" android:textColor="@android:color/black" /> </LinearLayout> Next is for layout row for child items. This is done via a list_item.xml file. Go to app > res > layout > New > Layout Resource File and name the file as list_item. Below is the code for the list_item.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/expandedListItem" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" android:paddingTop="10dp" android:paddingBottom="10dp" /> </LinearLayout> With the above XML, UI design elements are complete. Next is, a java file to populate the contents of the list. Step 4: Working with the Java files Go to app > java > your package name > Right-click > New > Java Class and name the file as ExpandableListDataItems. Below is the code for the ExpandableListDataItems.java file. Comments are added inside the code to understand the code in more detail. Java import java.util.ArrayList;import java.util.HashMap;import java.util.List; public class ExpandableListDataItems { public static HashMap<String, List<String>> getData() { HashMap<String, List<String>> expandableDetailList = new HashMap<String, List<String>>(); // As we are populating List of fruits, vegetables and nuts, using them here // We can modify them as per our choice. // And also choice of fruits/vegetables/nuts can be changed List<String> fruits = new ArrayList<String>(); fruits.add("Apple"); fruits.add("Orange"); fruits.add("Guava"); fruits.add("Papaya"); fruits.add("Pineapple"); List<String> vegetables = new ArrayList<String>(); vegetables.add("Tomato"); vegetables.add("Potato"); vegetables.add("Carrot"); vegetables.add("Cabbage"); vegetables.add("Cauliflower"); List<String> nuts = new ArrayList<String>(); nuts.add("Cashews"); nuts.add("Badam"); nuts.add("Pista"); nuts.add("Raisin"); nuts.add("Walnut"); // Fruits are grouped under Fruits Items. Similarly the rest two are under // Vegetable Items and Nuts Items respecitively. // i.e. expandableDetailList object is used to map the group header strings to // their respective children using an ArrayList of Strings. expandableDetailList.put("Fruits Items", fruits); expandableDetailList.put("Vegetable Items", vegetables); expandableDetailList.put("Nuts Items", nuts); return expandableDetailList; }} Go to app > java > your package name > Right-click > New > Java Class and name the file as CustomizedExpandableListAdapter. Below is the code for the CustomizedExpandableListAdapter.java file. This java class extends BaseExpandableListAdapter and it overrides the methods which are required for the ExpandableListView. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.graphics.Typeface;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseExpandableListAdapter;import android.widget.TextView;import java.util.HashMap;import java.util.List; public class CustomizedExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private List<String> expandableTitleList; private HashMap<String, List<String>> expandableDetailList; // constructor public CustomizedExpandableListAdapter(Context context, List<String> expandableListTitle, HashMap<String, List<String>> expandableListDetail) { this.context = context; this.expandableTitleList = expandableListTitle; this.expandableDetailList = expandableListDetail; } @Override // Gets the data associated with the given child within the given group. public Object getChild(int lstPosn, int expanded_ListPosition) { return this.expandableDetailList.get(this.expandableTitleList.get(lstPosn)).get(expanded_ListPosition); } @Override // Gets the ID for the given child within the given group. // This ID must be unique across all children within the group. Hence we can pick the child uniquely public long getChildId(int listPosition, int expanded_ListPosition) { return expanded_ListPosition; } @Override // Gets a View that displays the data for the given child within the given group. public View getChildView(int lstPosn, final int expanded_ListPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String expandedListText = (String) getChild(lstPosn, expanded_ListPosition); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.list_item, null); } TextView expandedListTextView = (TextView) convertView.findViewById(R.id.expandedListItem); expandedListTextView.setText(expandedListText); return convertView; } @Override // Gets the number of children in a specified group. public int getChildrenCount(int listPosition) { return this.expandableDetailList.get(this.expandableTitleList.get(listPosition)).size(); } @Override // Gets the data associated with the given group. public Object getGroup(int listPosition) { return this.expandableTitleList.get(listPosition); } @Override // Gets the number of groups. public int getGroupCount() { return this.expandableTitleList.size(); } @Override // Gets the ID for the group at the given position. This group ID must be unique across groups. public long getGroupId(int listPosition) { return listPosition; } @Override // Gets a View that displays the given group. // This View is only for the group--the Views for the group's children // will be fetched using getChildView() public View getGroupView(int listPosition, boolean isExpanded, View convertView, ViewGroup parent) { String listTitle = (String) getGroup(listPosition); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.list_group, null); } TextView listTitleTextView = (TextView) convertView.findViewById(R.id.listTitle); listTitleTextView.setTypeface(null, Typeface.BOLD); listTitleTextView.setText(listTitle); return convertView; } @Override // Indicates whether the child and group IDs are stable across changes to the underlying data. public boolean hasStableIds() { return false; } @Override // Whether the child at the specified position is selectable. public boolean isChildSelectable(int listPosition, int expandedListPosition) { return true; }} Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.ExpandableListAdapter;import android.widget.ExpandableListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashMap;import java.util.List; public class MainActivity extends AppCompatActivity { ExpandableListView expandableListViewExample; ExpandableListAdapter expandableListAdapter; List<String> expandableTitleList; HashMap<String, List<String>> expandableDetailList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); expandableListViewExample = (ExpandableListView) findViewById(R.id.expandableListViewSample); expandableDetailList = ExpandableListDataItems.getData(); expandableTitleList = new ArrayList<String>(expandableDetailList.keySet()); expandableListAdapter = new CustomizedExpandableListAdapter(this, expandableTitleList, expandableDetailList); expandableListViewExample.setAdapter(expandableListAdapter); // This method is called when the group is expanded expandableListViewExample.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { Toast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + " List Expanded.", Toast.LENGTH_SHORT).show(); } }); // This method is called when the group is collapsed expandableListViewExample.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() { @Override public void onGroupCollapse(int groupPosition) { Toast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + " List Collapsed.", Toast.LENGTH_SHORT).show(); } }); // This method is called when the child in any group is clicked // via a toast method, it is shown to display the selected child item as a sample // we may need to add further steps according to the requirements expandableListViewExample.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Toast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + " -> " + expandableDetailList.get( expandableTitleList.get(groupPosition)).get( childPosition), Toast.LENGTH_SHORT ).show(); return false; } }); }} ExpandableListView is a very useful mandatory feature used in many apps. In mobile app sizes and in the available space, in order to show multiple items, one should need features like ExpandableListView and ExpandableListAdapter the view can be fit perfectly. As the scrolling is available, we can keep information on many levels. The methods support expanding the header, collapsing the header, selecting the child items perfectly as seen in the emulator output. For simplicity, we have provided with Toast messages. Depends upon the requirements, we can able to add further coding to match with it. android Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Sep, 2020" }, { "code": null, "e": 497, "s": 54, "text": "Android ExpandableListView is a view that is used to shows items as a vertically scrolling two-level list. The basic difference with ListView is it allows two levels of the display which are groups that can be easily expanded and collapsed by touching to view and their respective children’s items. In order to show the view, ExpandableListViewAdapter is used in android. In many apps, an ExpandableListView facility is required. For example:" }, { "code": null, "e": 637, "s": 497, "text": "In a “city” app(for any city), if the user wants to see a list of engineering colleges/list of art colleges/list of medical colleges, etc.," }, { "code": null, "e": 718, "s": 637, "text": "List of vegetables/List of fruits/List of Nuts etc., for a “jiomart” kind of app" }, { "code": null, "e": 798, "s": 718, "text": "List of Hatchback/List of crosscut/List of Sedan etc., for a “Uber” kind of app" }, { "code": null, "e": 806, "s": 798, "text": "Methods" }, { "code": null, "e": 818, "s": 806, "text": "Description" }, { "code": null, "e": 874, "s": 818, "text": "Current state indicator for each item If the child is " }, { "code": null, "e": 935, "s": 874, "text": "the last child for a group, the state state_last will be set" }, { "code": null, "e": 1009, "s": 935, "text": "To represent the state either expanded or collapsed.state_expanded is the" }, { "code": null, "e": 1084, "s": 1009, "text": "state if the group is expanded, state_collapsed if the state of the group " }, { "code": null, "e": 1134, "s": 1084, "text": "is collapsed, state_empty if there are no groups." }, { "code": null, "e": 1145, "s": 1134, "text": "Interfaces" }, { "code": null, "e": 1157, "s": 1145, "text": "Description" }, { "code": null, "e": 1478, "s": 1157, "text": "Let us see the ways to implement SimpleExpandableListAdapter in Android with a List of vegetables/List of fruits/List of Nuts in the ExpandableListAdapter. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 1507, "s": 1478, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1669, "s": 1507, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1704, "s": 1669, "text": "Step 2: Create the dimens.xml file" }, { "code": null, "e": 1902, "s": 1704, "text": "Go to app > res > values > right-click > New > Values Resource File and name the file as dimens. In this file dimension related information is given here. Below is the code for the dimens.xml file." }, { "code": null, "e": 1906, "s": 1902, "text": "XML" }, { "code": "<resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name=\"activity_horizontal_margin\">16dp</dimen> <dimen name=\"activity_vertical_margin\">16dp</dimen></resources>", "e": 2113, "s": 1906, "text": null }, { "code": null, "e": 2148, "s": 2113, "text": "Step 3: Working with the XML files" }, { "code": null, "e": 2495, "s": 2148, "text": "To design the UI, code is present under the res\\layout folder in the form of XML. They are used in the Activity files and once the XML file is in scope inside the activity, one can access the components present in the XML. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2499, "s": 2495, "text": "XML" }, { "code": "<!-- RelativeLayout places the components vertically one by one. Necessary parameters also specified so that elegant output can be seen --><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\" android:paddingTop=\"@dimen/activity_vertical_margin\" android:paddingRight=\"@dimen/activity_horizontal_margin\" android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\"> <!-- ExpandableListView is used in relativelayout The android:indicatorLeft is the left bound for an items indicator.--> <ExpandableListView android:id=\"@+id/expandableListViewSample\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:divider=\"@android:color/darker_gray\" android:dividerHeight=\"0.5dp\" android:indicatorLeft=\"?android:attr/expandableListPreferredItemIndicatorLeft\" /> </RelativeLayout><!-- Note: We cannot use the value wrap_content for the android:layout_height attribute of the ExpandableListView in XML. -->", "e": 3738, "s": 2499, "text": null }, { "code": null, "e": 3872, "s": 3738, "text": "Go to app > res > layout > New > Layout Resource File and name the file as list_group. Below is the code for the list_group.xml file." }, { "code": null, "e": 3876, "s": 3872, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/listTitle\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:paddingLeft=\"?android:attr/expandableListPreferredItemPaddingLeft\" android:paddingTop=\"10dp\" android:paddingBottom=\"10dp\" android:textColor=\"@android:color/black\" /> </LinearLayout>", "e": 4464, "s": 3876, "text": null }, { "code": null, "e": 4675, "s": 4464, "text": "Next is for layout row for child items. This is done via a list_item.xml file. Go to app > res > layout > New > Layout Resource File and name the file as list_item. Below is the code for the list_item.xml file." }, { "code": null, "e": 4679, "s": 4675, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/expandedListItem\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:paddingLeft=\"?android:attr/expandableListPreferredChildPaddingLeft\" android:paddingTop=\"10dp\" android:paddingBottom=\"10dp\" /> </LinearLayout>", "e": 5227, "s": 4679, "text": null }, { "code": null, "e": 5339, "s": 5227, "text": "With the above XML, UI design elements are complete. Next is, a java file to populate the contents of the list." }, { "code": null, "e": 5375, "s": 5339, "text": "Step 4: Working with the Java files" }, { "code": null, "e": 5626, "s": 5375, "text": "Go to app > java > your package name > Right-click > New > Java Class and name the file as ExpandableListDataItems. Below is the code for the ExpandableListDataItems.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5631, "s": 5626, "text": "Java" }, { "code": "import java.util.ArrayList;import java.util.HashMap;import java.util.List; public class ExpandableListDataItems { public static HashMap<String, List<String>> getData() { HashMap<String, List<String>> expandableDetailList = new HashMap<String, List<String>>(); // As we are populating List of fruits, vegetables and nuts, using them here // We can modify them as per our choice. // And also choice of fruits/vegetables/nuts can be changed List<String> fruits = new ArrayList<String>(); fruits.add(\"Apple\"); fruits.add(\"Orange\"); fruits.add(\"Guava\"); fruits.add(\"Papaya\"); fruits.add(\"Pineapple\"); List<String> vegetables = new ArrayList<String>(); vegetables.add(\"Tomato\"); vegetables.add(\"Potato\"); vegetables.add(\"Carrot\"); vegetables.add(\"Cabbage\"); vegetables.add(\"Cauliflower\"); List<String> nuts = new ArrayList<String>(); nuts.add(\"Cashews\"); nuts.add(\"Badam\"); nuts.add(\"Pista\"); nuts.add(\"Raisin\"); nuts.add(\"Walnut\"); // Fruits are grouped under Fruits Items. Similarly the rest two are under // Vegetable Items and Nuts Items respecitively. // i.e. expandableDetailList object is used to map the group header strings to // their respective children using an ArrayList of Strings. expandableDetailList.put(\"Fruits Items\", fruits); expandableDetailList.put(\"Vegetable Items\", vegetables); expandableDetailList.put(\"Nuts Items\", nuts); return expandableDetailList; }}", "e": 7231, "s": 5631, "text": null }, { "code": null, "e": 7624, "s": 7231, "text": "Go to app > java > your package name > Right-click > New > Java Class and name the file as CustomizedExpandableListAdapter. Below is the code for the CustomizedExpandableListAdapter.java file. This java class extends BaseExpandableListAdapter and it overrides the methods which are required for the ExpandableListView. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 7629, "s": 7624, "text": "Java" }, { "code": "import android.content.Context;import android.graphics.Typeface;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseExpandableListAdapter;import android.widget.TextView;import java.util.HashMap;import java.util.List; public class CustomizedExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private List<String> expandableTitleList; private HashMap<String, List<String>> expandableDetailList; // constructor public CustomizedExpandableListAdapter(Context context, List<String> expandableListTitle, HashMap<String, List<String>> expandableListDetail) { this.context = context; this.expandableTitleList = expandableListTitle; this.expandableDetailList = expandableListDetail; } @Override // Gets the data associated with the given child within the given group. public Object getChild(int lstPosn, int expanded_ListPosition) { return this.expandableDetailList.get(this.expandableTitleList.get(lstPosn)).get(expanded_ListPosition); } @Override // Gets the ID for the given child within the given group. // This ID must be unique across all children within the group. Hence we can pick the child uniquely public long getChildId(int listPosition, int expanded_ListPosition) { return expanded_ListPosition; } @Override // Gets a View that displays the data for the given child within the given group. public View getChildView(int lstPosn, final int expanded_ListPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String expandedListText = (String) getChild(lstPosn, expanded_ListPosition); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.list_item, null); } TextView expandedListTextView = (TextView) convertView.findViewById(R.id.expandedListItem); expandedListTextView.setText(expandedListText); return convertView; } @Override // Gets the number of children in a specified group. public int getChildrenCount(int listPosition) { return this.expandableDetailList.get(this.expandableTitleList.get(listPosition)).size(); } @Override // Gets the data associated with the given group. public Object getGroup(int listPosition) { return this.expandableTitleList.get(listPosition); } @Override // Gets the number of groups. public int getGroupCount() { return this.expandableTitleList.size(); } @Override // Gets the ID for the group at the given position. This group ID must be unique across groups. public long getGroupId(int listPosition) { return listPosition; } @Override // Gets a View that displays the given group. // This View is only for the group--the Views for the group's children // will be fetched using getChildView() public View getGroupView(int listPosition, boolean isExpanded, View convertView, ViewGroup parent) { String listTitle = (String) getGroup(listPosition); if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) this.context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.list_group, null); } TextView listTitleTextView = (TextView) convertView.findViewById(R.id.listTitle); listTitleTextView.setTypeface(null, Typeface.BOLD); listTitleTextView.setText(listTitle); return convertView; } @Override // Indicates whether the child and group IDs are stable across changes to the underlying data. public boolean hasStableIds() { return false; } @Override // Whether the child at the specified position is selectable. public boolean isChildSelectable(int listPosition, int expandedListPosition) { return true; }}", "e": 11757, "s": 7629, "text": null }, { "code": null, "e": 11882, "s": 11757, "text": " Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 11887, "s": 11882, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.ExpandableListAdapter;import android.widget.ExpandableListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashMap;import java.util.List; public class MainActivity extends AppCompatActivity { ExpandableListView expandableListViewExample; ExpandableListAdapter expandableListAdapter; List<String> expandableTitleList; HashMap<String, List<String>> expandableDetailList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); expandableListViewExample = (ExpandableListView) findViewById(R.id.expandableListViewSample); expandableDetailList = ExpandableListDataItems.getData(); expandableTitleList = new ArrayList<String>(expandableDetailList.keySet()); expandableListAdapter = new CustomizedExpandableListAdapter(this, expandableTitleList, expandableDetailList); expandableListViewExample.setAdapter(expandableListAdapter); // This method is called when the group is expanded expandableListViewExample.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { Toast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + \" List Expanded.\", Toast.LENGTH_SHORT).show(); } }); // This method is called when the group is collapsed expandableListViewExample.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() { @Override public void onGroupCollapse(int groupPosition) { Toast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + \" List Collapsed.\", Toast.LENGTH_SHORT).show(); } }); // This method is called when the child in any group is clicked // via a toast method, it is shown to display the selected child item as a sample // we may need to add further steps according to the requirements expandableListViewExample.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Toast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + \" -> \" + expandableDetailList.get( expandableTitleList.get(groupPosition)).get( childPosition), Toast.LENGTH_SHORT ).show(); return false; } }); }}", "e": 14792, "s": 11887, "text": null }, { "code": null, "e": 15393, "s": 14792, "text": "ExpandableListView is a very useful mandatory feature used in many apps. In mobile app sizes and in the available space, in order to show multiple items, one should need features like ExpandableListView and ExpandableListAdapter the view can be fit perfectly. As the scrolling is available, we can keep information on many levels. The methods support expanding the header, collapsing the header, selecting the child items perfectly as seen in the emulator output. For simplicity, we have provided with Toast messages. Depends upon the requirements, we can able to add further coding to match with it." }, { "code": null, "e": 15401, "s": 15393, "text": "android" }, { "code": null, "e": 15408, "s": 15401, "text": "Picked" }, { "code": null, "e": 15416, "s": 15408, "text": "Android" }, { "code": null, "e": 15421, "s": 15416, "text": "Java" }, { "code": null, "e": 15426, "s": 15421, "text": "Java" }, { "code": null, "e": 15434, "s": 15426, "text": "Android" }, { "code": null, "e": 15532, "s": 15434, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15601, "s": 15532, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 15632, "s": 15601, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 15675, "s": 15632, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 15707, "s": 15675, "text": "Android SDK and it's Components" }, { "code": null, "e": 15746, "s": 15707, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 15761, "s": 15746, "text": "Arrays in Java" }, { "code": null, "e": 15805, "s": 15761, "text": "Split() String method in Java with examples" }, { "code": null, "e": 15841, "s": 15805, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 15866, "s": 15841, "text": "Reverse a string in Java" } ]
Mindtree Interview Experience for Software Engineer C1 (Off-Campus)
05 Apr, 2021 INTERVIEW PROCESS: Assessment – 21st March 2021(Aptitude, Logical, Coding(Imp) on WeCreateProblems Platform) –>Result Same day NightEnglish Skill Assessment (Mettl) – 22nd March 2021 –>Result after 4 daysTechnical Round 1 – 27th March 2021 (WeCreateProblems platform)Technical Round 2-28th March 2021 (WeCreateProblems platform)HR Round- 3rd April 2021 (WeCreateProblems platform) Assessment – 21st March 2021(Aptitude, Logical, Coding(Imp) on WeCreateProblems Platform) –>Result Same day Night English Skill Assessment (Mettl) – 22nd March 2021 –>Result after 4 days Technical Round 1 – 27th March 2021 (WeCreateProblems platform) Technical Round 2-28th March 2021 (WeCreateProblems platform) HR Round- 3rd April 2021 (WeCreateProblems platform) Technical Round 1: Questions: Introduce YourselfDiff b/w for and for-each and which is efficientWhy we need sortingExplain in brief about sorting techniques(I said I don’t remember all. I can explain Merge sort and Bubble sort)Write Pseudocode/logic for Both and walkthrough it.Write logic to print prime numbers up to N and I wrote the logic and explained him then he asked Are you sure it will pass all basic testcases? I replied if you allow me I’ll share my screen and I’ll try to execute it in an online compiler.I am done. All the best for your Future. Introduce Yourself Diff b/w for and for-each and which is efficient Why we need sorting Explain in brief about sorting techniques(I said I don’t remember all. I can explain Merge sort and Bubble sort) Write Pseudocode/logic for Both and walkthrough it. Write logic to print prime numbers up to N and I wrote the logic and explained him then he asked Are you sure it will pass all basic testcases? I replied if you allow me I’ll share my screen and I’ll try to execute it in an online compiler. I am done. All the best for your Future. I got the result of Technical Round 1 on the same day and My Technical round 2 is scheduled to next day morning 9 am. Technical Round 2 – 28th March 2021 (WeCreateProblems platform) I am a Technical lead from Mindtree. Can you tell me about YourselfTell me about OOPSYou are familiar with java right? Tell me How you achieve Data Abstraction and Explain me in detail?I’ll give you some I/p and O/p Pattern and write the logic and Explain me line by lineI/P - [1,2,3,4,5,6,7,8,9] O/P - [3,2,1,6,5,4,9,8,7]I wrote the logic with little Mistakes and Interviewer tried to confuse me, but I am confident with my logic. So I explained to him what my approach to solve that problem.Any questions for me? I am a Technical lead from Mindtree. Can you tell me about Yourself Tell me about OOPS You are familiar with java right? Tell me How you achieve Data Abstraction and Explain me in detail? I’ll give you some I/p and O/p Pattern and write the logic and Explain me line by lineI/P - [1,2,3,4,5,6,7,8,9] O/P - [3,2,1,6,5,4,9,8,7]I wrote the logic with little Mistakes and Interviewer tried to confuse me, but I am confident with my logic. So I explained to him what my approach to solve that problem. I/P - [1,2,3,4,5,6,7,8,9] O/P - [3,2,1,6,5,4,9,8,7] I wrote the logic with little Mistakes and Interviewer tried to confuse me, but I am confident with my logic. So I explained to him what my approach to solve that problem. Any questions for me? Nice talking to you. Bye. I got the result of Technical round 2 after 2 days. I am shortlisted for HR. HR Round – 3rd April 2021 (WeCreateProblems platform) Tell me something about yourselfWhat do you do in your free timeDid you attended any interviews earlier? I said I attended TCS and got selected.Then why you are wasting a position in TCS? I said I haven’t accepted the offer and I am waiting for Mindtree.Why you want to join Mindtree?You know about bond?Are you flexible ?Are you available to relocate to any of the Mindtree office locations?Do you have valid pan card?Any questions for me? Tell me something about yourself What do you do in your free time Did you attended any interviews earlier? I said I attended TCS and got selected. Then why you are wasting a position in TCS? I said I haven’t accepted the offer and I am waiting for Mindtree. Why you want to join Mindtree? You know about bond? Are you flexible ? Are you available to relocate to any of the Mindtree office locations? Do you have valid pan card? Any questions for me? Thanks This is all about My Mindtree Interview Experience for C1 Software Engineer position. Thanks GfG for making this platform to share interview experiences. This platform helped me a lot. I’ll soon share My TCS Interview experience also. Marketing Mindtree Off-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Samsung RnD Coding Round Questions Write It Up: Share Your Interview Experiences Tiger Analytics Interview Experience for Data Analyst (On-Campus) Nagarro Interview Experience Amazon Interview Experience for SDE-1
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Apr, 2021" }, { "code": null, "e": 74, "s": 54, "text": "INTERVIEW PROCESS: " }, { "code": null, "e": 437, "s": 74, "text": "Assessment – 21st March 2021(Aptitude, Logical, Coding(Imp) on WeCreateProblems Platform) –>Result Same day NightEnglish Skill Assessment (Mettl) – 22nd March 2021 –>Result after 4 daysTechnical Round 1 – 27th March 2021 (WeCreateProblems platform)Technical Round 2-28th March 2021 (WeCreateProblems platform)HR Round- 3rd April 2021 (WeCreateProblems platform)" }, { "code": null, "e": 552, "s": 437, "text": "Assessment – 21st March 2021(Aptitude, Logical, Coding(Imp) on WeCreateProblems Platform) –>Result Same day Night" }, { "code": null, "e": 625, "s": 552, "text": "English Skill Assessment (Mettl) – 22nd March 2021 –>Result after 4 days" }, { "code": null, "e": 689, "s": 625, "text": "Technical Round 1 – 27th March 2021 (WeCreateProblems platform)" }, { "code": null, "e": 751, "s": 689, "text": "Technical Round 2-28th March 2021 (WeCreateProblems platform)" }, { "code": null, "e": 804, "s": 751, "text": "HR Round- 3rd April 2021 (WeCreateProblems platform)" }, { "code": null, "e": 823, "s": 804, "text": "Technical Round 1:" }, { "code": null, "e": 834, "s": 823, "text": "Questions:" }, { "code": null, "e": 1363, "s": 834, "text": "Introduce YourselfDiff b/w for and for-each and which is efficientWhy we need sortingExplain in brief about sorting techniques(I said I don’t remember all. I can explain Merge sort and Bubble sort)Write Pseudocode/logic for Both and walkthrough it.Write logic to print prime numbers up to N and I wrote the logic and explained him then he asked Are you sure it will pass all basic testcases? I replied if you allow me I’ll share my screen and I’ll try to execute it in an online compiler.I am done. All the best for your Future." }, { "code": null, "e": 1382, "s": 1363, "text": "Introduce Yourself" }, { "code": null, "e": 1431, "s": 1382, "text": "Diff b/w for and for-each and which is efficient" }, { "code": null, "e": 1451, "s": 1431, "text": "Why we need sorting" }, { "code": null, "e": 1564, "s": 1451, "text": "Explain in brief about sorting techniques(I said I don’t remember all. I can explain Merge sort and Bubble sort)" }, { "code": null, "e": 1616, "s": 1564, "text": "Write Pseudocode/logic for Both and walkthrough it." }, { "code": null, "e": 1857, "s": 1616, "text": "Write logic to print prime numbers up to N and I wrote the logic and explained him then he asked Are you sure it will pass all basic testcases? I replied if you allow me I’ll share my screen and I’ll try to execute it in an online compiler." }, { "code": null, "e": 1898, "s": 1857, "text": "I am done. All the best for your Future." }, { "code": null, "e": 2016, "s": 1898, "text": "I got the result of Technical Round 1 on the same day and My Technical round 2 is scheduled to next day morning 9 am." }, { "code": null, "e": 2080, "s": 2016, "text": "Technical Round 2 – 28th March 2021 (WeCreateProblems platform)" }, { "code": null, "e": 2595, "s": 2080, "text": "I am a Technical lead from Mindtree. Can you tell me about YourselfTell me about OOPSYou are familiar with java right? Tell me How you achieve Data Abstraction and Explain me in detail?I’ll give you some I/p and O/p Pattern and write the logic and Explain me line by lineI/P - [1,2,3,4,5,6,7,8,9]\nO/P - [3,2,1,6,5,4,9,8,7]I wrote the logic with little Mistakes and Interviewer tried to confuse me, but I am confident with my logic. So I explained to him what my approach to solve that problem.Any questions for me?" }, { "code": null, "e": 2663, "s": 2595, "text": "I am a Technical lead from Mindtree. Can you tell me about Yourself" }, { "code": null, "e": 2682, "s": 2663, "text": "Tell me about OOPS" }, { "code": null, "e": 2783, "s": 2682, "text": "You are familiar with java right? Tell me How you achieve Data Abstraction and Explain me in detail?" }, { "code": null, "e": 3092, "s": 2783, "text": "I’ll give you some I/p and O/p Pattern and write the logic and Explain me line by lineI/P - [1,2,3,4,5,6,7,8,9]\nO/P - [3,2,1,6,5,4,9,8,7]I wrote the logic with little Mistakes and Interviewer tried to confuse me, but I am confident with my logic. So I explained to him what my approach to solve that problem." }, { "code": null, "e": 3144, "s": 3092, "text": "I/P - [1,2,3,4,5,6,7,8,9]\nO/P - [3,2,1,6,5,4,9,8,7]" }, { "code": null, "e": 3316, "s": 3144, "text": "I wrote the logic with little Mistakes and Interviewer tried to confuse me, but I am confident with my logic. So I explained to him what my approach to solve that problem." }, { "code": null, "e": 3338, "s": 3316, "text": "Any questions for me?" }, { "code": null, "e": 3364, "s": 3338, "text": "Nice talking to you. Bye." }, { "code": null, "e": 3441, "s": 3364, "text": "I got the result of Technical round 2 after 2 days. I am shortlisted for HR." }, { "code": null, "e": 3495, "s": 3441, "text": "HR Round – 3rd April 2021 (WeCreateProblems platform)" }, { "code": null, "e": 3936, "s": 3495, "text": "Tell me something about yourselfWhat do you do in your free timeDid you attended any interviews earlier? I said I attended TCS and got selected.Then why you are wasting a position in TCS? I said I haven’t accepted the offer and I am waiting for Mindtree.Why you want to join Mindtree?You know about bond?Are you flexible ?Are you available to relocate to any of the Mindtree office locations?Do you have valid pan card?Any questions for me?" }, { "code": null, "e": 3969, "s": 3936, "text": "Tell me something about yourself" }, { "code": null, "e": 4002, "s": 3969, "text": "What do you do in your free time" }, { "code": null, "e": 4083, "s": 4002, "text": "Did you attended any interviews earlier? I said I attended TCS and got selected." }, { "code": null, "e": 4194, "s": 4083, "text": "Then why you are wasting a position in TCS? I said I haven’t accepted the offer and I am waiting for Mindtree." }, { "code": null, "e": 4225, "s": 4194, "text": "Why you want to join Mindtree?" }, { "code": null, "e": 4246, "s": 4225, "text": "You know about bond?" }, { "code": null, "e": 4265, "s": 4246, "text": "Are you flexible ?" }, { "code": null, "e": 4336, "s": 4265, "text": "Are you available to relocate to any of the Mindtree office locations?" }, { "code": null, "e": 4364, "s": 4336, "text": "Do you have valid pan card?" }, { "code": null, "e": 4386, "s": 4364, "text": "Any questions for me?" }, { "code": null, "e": 4393, "s": 4386, "text": "Thanks" }, { "code": null, "e": 4479, "s": 4393, "text": "This is all about My Mindtree Interview Experience for C1 Software Engineer position." }, { "code": null, "e": 4629, "s": 4479, "text": "Thanks GfG for making this platform to share interview experiences. This platform helped me a lot. I’ll soon share My TCS Interview experience also. " }, { "code": null, "e": 4639, "s": 4629, "text": "Marketing" }, { "code": null, "e": 4648, "s": 4639, "text": "Mindtree" }, { "code": null, "e": 4659, "s": 4648, "text": "Off-Campus" }, { "code": null, "e": 4681, "s": 4659, "text": "Interview Experiences" }, { "code": null, "e": 4779, "s": 4681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4849, "s": 4779, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 4922, "s": 4849, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 4960, "s": 4922, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 5016, "s": 4960, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 5060, "s": 5016, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 5095, "s": 5060, "text": "Samsung RnD Coding Round Questions" }, { "code": null, "e": 5141, "s": 5095, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 5207, "s": 5141, "text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)" }, { "code": null, "e": 5236, "s": 5207, "text": "Nagarro Interview Experience" } ]
What is Context in Android? - GeeksforGeeks
10 Sep, 2020 Android apps are popular for a long time and it is evolving to a greater level as user’s expectations are that they need to view the data that they want in an easier smoother view. Hence, the android developers must know the important terminologies before developing the app. In Android Programming we generally come across a word context. So what exactly is this context and why is it so important? To answer this question lets first see what the literal meaning of context is: The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood Looking at this definition we come across two things: The context tells us about the surrounding information. It is very important to understand the environment which we want to understand. Similarly when we talk about the Android Programming context can be understood as something which gives us the context of the current state of our application. We can break the context and its use into three major points: It allows us to access resources. It allows us to interact with other Android components by sending messages. It gives you information about your app environment. In the official Android documentation, context is defined as: Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc. Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a suitable time. Except for these things there are also many other things, he wants to do during the time of stay. So how does he get these things? He will ask the room-service person to bring these things for him. Right? So here the room-service person is the context considering you are the single activity and the hotel to be your app, finally, the breakfast, lunch & dinner have to be the resources. 1. It is the context of the current/active state of the application. Usually, the app got multiple screens like display/inquiry/add/delete screens(General requirement of a basic app). So when the user is searching for something, the context is an inquiry screen in this case. 2. It is used to get information about the activity and application. The inquiry screen’s context specifies that the user is in inquiry activity, and he/she can submit queries related to the app 3. It is used to get access to resources, databases, and shared preferences, etc. Via Rest services, API calls can be consumed in android apps. Rest Services usually hold database data and provide the output in JSON format to the android app. The context for the respective screen helps to get hold of database data and the shared data across screens 4. Both the Activity and Application classes extend the Context class. In android, context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the context class. There are mainly two types of context are available in Android. Application Context and Activity Context Application Context and Activity Context The Overall view of the App hierarchy looks like the following: It can be seen in the above image that in “Sample Application”, nearest Context is Application Context. In “Activity1” and “Activity2”, both Activity Context (Here it is Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application Context.The nearest Context to both is their Activity Context only. This context is tied to the life cycle of an application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext(). Some use cases of Application Context are: If it is necessary to create a singleton object During the necessity of a library in an activity It is used to return the context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a context and often we use “this” to pass the activity context or “getApplicationContext” to pass the application context. This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext(). Example: Java import android.app.Application; public class GlobalExampleClass extends Application{ private String globalName; private String globalEmail; public String getName() { return globalName; } public void setName(String aName) { globalName = aName; } public String getEmail() { return globalEmail; } public void setEmail(String aEmail) { globalEmail = aEmail; }} Inside the activity class, set the name and email of GlobalExampleClass, which can be accessed from another activity. Let us see via the below steps. Java // Activity 1public class <your activity1> extends Activity { ........ ........ private <yourapplicationname> globarVar; ........ @Override public void onCreate(Bundle savedInstanceState) { ....... final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext(); // In this activity set name and email and can reuse in other activities globalExampleVariable.setName("getApplicationContext example"); globalExampleVariable.setEmail("xxxxxx@gmail.com"); .......} // Activity 2 public class <your activity2> extends Activity { ........ ........ private <yourapplicationname> globarVar; ....... @Override public void onCreate(Bundle savedInstanceState) { ....... final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext(); // As in activity1, name and email is set, we can retrieve it here final String globalName = globalExampleVariable.getName(); final String globalEmail = globalExampleVariable.getEmail(); .......} So, whenever the variable scope is required throughout the application, we can get it by means of getApplicationContext(). Following is a list of functionalities of Application Context. List of functionalities of Application Context: Load Resource Values Start a Service Bind to a Service Send a Broadcast Register BroadcastReceiver It is the activity context meaning each and every screen got an activity. For example, EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity only. It is tied to the life cycle of activity. It is used for the current context. The method of invoking the Activity Context is getContext(). Some use cases of Activity Context are: The user is creating an object whose lifecycle is attached to an activity. Whenever inside an activity for UI related kind of operations like toast, dialogue, etc., It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the context from only the current running activity. Example: Java @Overridepublic void onItemClick(AdapterView<?> parent, View view, int pos, long id) { .... // view.getContext() refers to the current activity view // Here it is used to start the activity Intent intent = new Intent(view.getContext(), <your java classname>.class); intent.putExtra(pid, ID); view.getContext().startActivity(intent);} List of functionalities of Activity Context: Load Resource Values Layout Inflation Start an Activity Show a Dialog Start a Service Bind to a Service Send a Broadcast Register BroadcastReceiver From the functionalities of both Application and Activity, we can see that the difference is that the Application Context is no way related to UI. It should be used only to start a service or load resource values etc. Apart from getApplicationContext() and getContext(), getBaseContext() or this are the different terminologies used throughout the app development. Let us see with an example The base context is set by the constructor or setBaseContext().This method is only valid if we have a ContextWrapper. Android provides a ContextWrapper class that is created around an existing Context using: ContextWrapper wrapper = new ContextWrapper(context); The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context” Example: Java public <YourHandler>(Context ctx) { // if the context is instanceof ContextWrapper while (ctx instanceof ContextWrapper) { // use getBaseContext() final Context baseContext = ((ContextWrapper)context).getBaseContext(); if (baseContext == null) { break; } // And then we can assign to context and reuse that ctx = baseContext; } .....} “this” argument is of a type “Context”. To explain this context let’s take an example to show a Toast Message using “this”. Example: Java // Show a simple toast message, that can be done after doing some activities// Toast.makeText(this, "Action got completed", Toast.LENGTH_SHORT).show();import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class ExampleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_example); // Displaying Toast with Hello Javatpoint message Toast.makeText(this,"Action done",Toast.LENGTH_SHORT).show(); } } Output: Another example to start the activity using “this”: Java public class FirstActivity extends AppCompatActivity { public static final String New_Message = "Your message to go for next screen"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); } // There must be some button and on click of // that below method can be invoked public void sendMessageToNextScreen(View view) { // Here it is used with "this" Intent intent = new Intent(this, SecondActivity.class); EditText editText = (EditText) findViewById(R.id.editText); String message = editText.getText().toString(); intent.putExtra(New_Message, message); // Start the SecondActivity startActivity(intent); }} Document References: https://developer.android.com/reference/android/content/Context https://developer.android.com/reference/android/content/Context#getApplicationContext() android Android Java Java 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? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 26517, "s": 26489, "text": "\n10 Sep, 2020" }, { "code": null, "e": 26998, "s": 26517, "text": "Android apps are popular for a long time and it is evolving to a greater level as user’s expectations are that they need to view the data that they want in an easier smoother view. Hence, the android developers must know the important terminologies before developing the app. In Android Programming we generally come across a word context. So what exactly is this context and why is it so important? To answer this question lets first see what the literal meaning of context is: " }, { "code": null, "e": 27121, "s": 26998, "text": "The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood" }, { "code": null, "e": 27176, "s": 27121, "text": "Looking at this definition we come across two things: " }, { "code": null, "e": 27232, "s": 27176, "text": "The context tells us about the surrounding information." }, { "code": null, "e": 27312, "s": 27232, "text": "It is very important to understand the environment which we want to understand." }, { "code": null, "e": 27535, "s": 27312, "text": "Similarly when we talk about the Android Programming context can be understood as something which gives us the context of the current state of our application. We can break the context and its use into three major points: " }, { "code": null, "e": 27569, "s": 27535, "text": "It allows us to access resources." }, { "code": null, "e": 27645, "s": 27569, "text": "It allows us to interact with other Android components by sending messages." }, { "code": null, "e": 27698, "s": 27645, "text": "It gives you information about your app environment." }, { "code": null, "e": 27762, "s": 27698, "text": "In the official Android documentation, context is defined as: " }, { "code": null, "e": 28098, "s": 27762, "text": "Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc." }, { "code": null, "e": 28573, "s": 28098, "text": "Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a suitable time. Except for these things there are also many other things, he wants to do during the time of stay. So how does he get these things? He will ask the room-service person to bring these things for him. Right? So here the room-service person is the context considering you are the single activity and the hotel to be your app, finally, the breakfast, lunch & dinner have to be the resources." }, { "code": null, "e": 28642, "s": 28573, "text": "1. It is the context of the current/active state of the application." }, { "code": null, "e": 28849, "s": 28642, "text": "Usually, the app got multiple screens like display/inquiry/add/delete screens(General requirement of a basic app). So when the user is searching for something, the context is an inquiry screen in this case." }, { "code": null, "e": 28918, "s": 28849, "text": "2. It is used to get information about the activity and application." }, { "code": null, "e": 29044, "s": 28918, "text": "The inquiry screen’s context specifies that the user is in inquiry activity, and he/she can submit queries related to the app" }, { "code": null, "e": 29126, "s": 29044, "text": "3. It is used to get access to resources, databases, and shared preferences, etc." }, { "code": null, "e": 29395, "s": 29126, "text": "Via Rest services, API calls can be consumed in android apps. Rest Services usually hold database data and provide the output in JSON format to the android app. The context for the respective screen helps to get hold of database data and the shared data across screens" }, { "code": null, "e": 29466, "s": 29395, "text": "4. Both the Activity and Application classes extend the Context class." }, { "code": null, "e": 29683, "s": 29466, "text": "In android, context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the context class. " }, { "code": null, "e": 29748, "s": 29683, "text": "There are mainly two types of context are available in Android. " }, { "code": null, "e": 29789, "s": 29748, "text": "Application Context and Activity Context" }, { "code": null, "e": 29814, "s": 29789, "text": "Application Context and " }, { "code": null, "e": 29831, "s": 29814, "text": "Activity Context" }, { "code": null, "e": 29895, "s": 29831, "text": "The Overall view of the App hierarchy looks like the following:" }, { "code": null, "e": 30218, "s": 29895, "text": "It can be seen in the above image that in “Sample Application”, nearest Context is Application Context. In “Activity1” and “Activity2”, both Activity Context (Here it is Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application Context.The nearest Context to both is their Activity Context only." }, { "code": null, "e": 30413, "s": 30218, "text": "This context is tied to the life cycle of an application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext(). Some use cases of Application Context are:" }, { "code": null, "e": 30461, "s": 30413, "text": "If it is necessary to create a singleton object" }, { "code": null, "e": 30510, "s": 30461, "text": "During the necessity of a library in an activity" }, { "code": null, "e": 31033, "s": 30510, "text": "It is used to return the context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a context and often we use “this” to pass the activity context or “getApplicationContext” to pass the application context. This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext()." }, { "code": null, "e": 31042, "s": 31033, "text": "Example:" }, { "code": null, "e": 31047, "s": 31042, "text": "Java" }, { "code": "import android.app.Application; public class GlobalExampleClass extends Application{ private String globalName; private String globalEmail; public String getName() { return globalName; } public void setName(String aName) { globalName = aName; } public String getEmail() { return globalEmail; } public void setEmail(String aEmail) { globalEmail = aEmail; }}", "e": 31475, "s": 31047, "text": null }, { "code": null, "e": 31625, "s": 31475, "text": "Inside the activity class, set the name and email of GlobalExampleClass, which can be accessed from another activity. Let us see via the below steps." }, { "code": null, "e": 31630, "s": 31625, "text": "Java" }, { "code": "// Activity 1public class <your activity1> extends Activity { ........ ........ private <yourapplicationname> globarVar; ........ @Override public void onCreate(Bundle savedInstanceState) { ....... final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext(); // In this activity set name and email and can reuse in other activities globalExampleVariable.setName(\"getApplicationContext example\"); globalExampleVariable.setEmail(\"xxxxxx@gmail.com\"); .......} // Activity 2 public class <your activity2> extends Activity { ........ ........ private <yourapplicationname> globarVar; ....... @Override public void onCreate(Bundle savedInstanceState) { ....... final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext(); // As in activity1, name and email is set, we can retrieve it here final String globalName = globalExampleVariable.getName(); final String globalEmail = globalExampleVariable.getEmail(); .......}", "e": 32685, "s": 31630, "text": null }, { "code": null, "e": 32871, "s": 32685, "text": "So, whenever the variable scope is required throughout the application, we can get it by means of getApplicationContext(). Following is a list of functionalities of Application Context." }, { "code": null, "e": 32919, "s": 32871, "text": "List of functionalities of Application Context:" }, { "code": null, "e": 32940, "s": 32919, "text": "Load Resource Values" }, { "code": null, "e": 32956, "s": 32940, "text": "Start a Service" }, { "code": null, "e": 32974, "s": 32956, "text": "Bind to a Service" }, { "code": null, "e": 32991, "s": 32974, "text": "Send a Broadcast" }, { "code": null, "e": 33018, "s": 32991, "text": "Register BroadcastReceiver" }, { "code": null, "e": 33336, "s": 33018, "text": "It is the activity context meaning each and every screen got an activity. For example, EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity only. It is tied to the life cycle of activity. It is used for the current context. The method of invoking the Activity Context is getContext(). " }, { "code": null, "e": 33377, "s": 33336, "text": " Some use cases of Activity Context are:" }, { "code": null, "e": 33452, "s": 33377, "text": "The user is creating an object whose lifecycle is attached to an activity." }, { "code": null, "e": 33542, "s": 33452, "text": "Whenever inside an activity for UI related kind of operations like toast, dialogue, etc.," }, { "code": null, "e": 33710, "s": 33542, "text": "It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the context from only the current running activity." }, { "code": null, "e": 33719, "s": 33710, "text": "Example:" }, { "code": null, "e": 33724, "s": 33719, "text": "Java" }, { "code": "@Overridepublic void onItemClick(AdapterView<?> parent, View view, int pos, long id) { .... // view.getContext() refers to the current activity view // Here it is used to start the activity Intent intent = new Intent(view.getContext(), <your java classname>.class); intent.putExtra(pid, ID); view.getContext().startActivity(intent);}", "e": 34066, "s": 33724, "text": null }, { "code": null, "e": 34111, "s": 34066, "text": "List of functionalities of Activity Context:" }, { "code": null, "e": 34132, "s": 34111, "text": "Load Resource Values" }, { "code": null, "e": 34149, "s": 34132, "text": "Layout Inflation" }, { "code": null, "e": 34167, "s": 34149, "text": "Start an Activity" }, { "code": null, "e": 34181, "s": 34167, "text": "Show a Dialog" }, { "code": null, "e": 34197, "s": 34181, "text": "Start a Service" }, { "code": null, "e": 34215, "s": 34197, "text": "Bind to a Service" }, { "code": null, "e": 34232, "s": 34215, "text": "Send a Broadcast" }, { "code": null, "e": 34259, "s": 34232, "text": "Register BroadcastReceiver" }, { "code": null, "e": 34651, "s": 34259, "text": "From the functionalities of both Application and Activity, we can see that the difference is that the Application Context is no way related to UI. It should be used only to start a service or load resource values etc. Apart from getApplicationContext() and getContext(), getBaseContext() or this are the different terminologies used throughout the app development. Let us see with an example" }, { "code": null, "e": 34860, "s": 34651, "text": "The base context is set by the constructor or setBaseContext().This method is only valid if we have a ContextWrapper. Android provides a ContextWrapper class that is created around an existing Context using: " }, { "code": null, "e": 34915, "s": 34860, "text": "ContextWrapper wrapper = new ContextWrapper(context); " }, { "code": null, "e": 35030, "s": 34915, "text": "The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context” " }, { "code": null, "e": 35039, "s": 35030, "text": "Example:" }, { "code": null, "e": 35044, "s": 35039, "text": "Java" }, { "code": "public <YourHandler>(Context ctx) { // if the context is instanceof ContextWrapper while (ctx instanceof ContextWrapper) { // use getBaseContext() final Context baseContext = ((ContextWrapper)context).getBaseContext(); if (baseContext == null) { break; } // And then we can assign to context and reuse that ctx = baseContext; } .....}", "e": 35410, "s": 35044, "text": null }, { "code": null, "e": 35535, "s": 35410, "text": "“this” argument is of a type “Context”. To explain this context let’s take an example to show a Toast Message using “this”." }, { "code": null, "e": 35544, "s": 35535, "text": "Example:" }, { "code": null, "e": 35549, "s": 35544, "text": "Java" }, { "code": "// Show a simple toast message, that can be done after doing some activities// Toast.makeText(this, \"Action got completed\", Toast.LENGTH_SHORT).show();import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class ExampleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_example); // Displaying Toast with Hello Javatpoint message Toast.makeText(this,\"Action done\",Toast.LENGTH_SHORT).show(); } }", "e": 36194, "s": 35549, "text": null }, { "code": null, "e": 36202, "s": 36194, "text": "Output:" }, { "code": null, "e": 36254, "s": 36202, "text": "Another example to start the activity using “this”:" }, { "code": null, "e": 36259, "s": 36254, "text": "Java" }, { "code": "public class FirstActivity extends AppCompatActivity { public static final String New_Message = \"Your message to go for next screen\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); } // There must be some button and on click of // that below method can be invoked public void sendMessageToNextScreen(View view) { // Here it is used with \"this\" Intent intent = new Intent(this, SecondActivity.class); EditText editText = (EditText) findViewById(R.id.editText); String message = editText.getText().toString(); intent.putExtra(New_Message, message); // Start the SecondActivity startActivity(intent); }}", "e": 37047, "s": 36259, "text": null }, { "code": null, "e": 37068, "s": 37047, "text": "Document References:" }, { "code": null, "e": 37132, "s": 37068, "text": "https://developer.android.com/reference/android/content/Context" }, { "code": null, "e": 37220, "s": 37132, "text": "https://developer.android.com/reference/android/content/Context#getApplicationContext()" }, { "code": null, "e": 37228, "s": 37220, "text": "android" }, { "code": null, "e": 37236, "s": 37228, "text": "Android" }, { "code": null, "e": 37241, "s": 37236, "text": "Java" }, { "code": null, "e": 37246, "s": 37241, "text": "Java" }, { "code": null, "e": 37254, "s": 37246, "text": "Android" }, { "code": null, "e": 37352, "s": 37254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37390, "s": 37352, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 37429, "s": 37390, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 37479, "s": 37429, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 37505, "s": 37479, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 37556, "s": 37505, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 37571, "s": 37556, "text": "Arrays in Java" }, { "code": null, "e": 37615, "s": 37571, "text": "Split() String method in Java with examples" }, { "code": null, "e": 37637, "s": 37615, "text": "For-each loop in Java" }, { "code": null, "e": 37652, "s": 37637, "text": "Stream In Java" } ]
If memory allocation using new is failed in C++ then how it should be handled? - GeeksforGeeks
20 Jul, 2021 In this article, if memory allocation using new is failed in C++ then how it should be handled? When an object of a class is created dynamically using new operator, the object occupies memory in the heap. Below are the major thing that must be keep in mind: What if sufficient memory is not available in the heap memory, and how it should be handled? If memory is not allocated then how to avoid the project crash? Below is the program that occupies a large amount of memory so that the problem will occur. Use memory allocation statements in the try and catch block and for preventing memory crash and throw the exception when memory allocation is failed. Program 1: C++ // C++ program to illustrate memory// failure when very large memory// is allocated#include <iostream>using namespace std; // Driver Codeint main(){ // Allocate huge amount of memory long MEMORY_SIZE = 0x7fffffff; // Put memory allocation statement // in the try catch block try { char* ptr = new char[MEMORY_SIZE]; // When memory allocation fails, // below line is not be executed // & control will go in catch block cout << "Memory is allocated" << " Successfully" << endl; } // Catch Block handle error catch (const bad_alloc& e) { cout << "Memory Allocation" << " is failed: " << e.what() << endl; } return 0;} Memory Allocation is failed: std::bad_alloc The above memory failure issue can be resolved without using the try-catch block. It can be fixed by using nothrow version of the new operator: The nothrow constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure but return a null pointer instead. By default, when the new operator is used to attempt to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown. But when nothrow is used as an argument for new, and it returns a null pointer instead. This constant (nothrow) is just a value of type nothrow_t, with the only purpose of triggering an overloaded version of the function operator new (or operator new[]) that takes an argument of this type. Below is the implementation of memory allocation using nothrow operator: Program 2: C++ // C++ program to handle memory failure// when very large memory is allocated#include <iostream>using namespace std; // Drive Codeint main(){ // Allocate huge amount of memory long MEMORY_SIZE = 0x7fffffff; // Allocate memory dynamically // using "new" with "nothrow" // version of new char* addr = new (std::nothrow) char[MEMORY_SIZE]; // Check if addr is having // proper address or not if (addr) { cout << "Memory is allocated" << " Successfully" << endl; } else { // This part will be executed if // large memory is allocated and // failure occurs cout << "Memory allocation" << " fails" << endl; } return 0;} Memory allocation fails manikarora059 C++-new and delete C-Dynamic Memory Allocation memory-management 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++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25368, "s": 25340, "text": "\n20 Jul, 2021" }, { "code": null, "e": 25626, "s": 25368, "text": "In this article, if memory allocation using new is failed in C++ then how it should be handled? When an object of a class is created dynamically using new operator, the object occupies memory in the heap. Below are the major thing that must be keep in mind:" }, { "code": null, "e": 25719, "s": 25626, "text": "What if sufficient memory is not available in the heap memory, and how it should be handled?" }, { "code": null, "e": 25783, "s": 25719, "text": "If memory is not allocated then how to avoid the project crash?" }, { "code": null, "e": 26025, "s": 25783, "text": "Below is the program that occupies a large amount of memory so that the problem will occur. Use memory allocation statements in the try and catch block and for preventing memory crash and throw the exception when memory allocation is failed." }, { "code": null, "e": 26036, "s": 26025, "text": "Program 1:" }, { "code": null, "e": 26040, "s": 26036, "text": "C++" }, { "code": "// C++ program to illustrate memory// failure when very large memory// is allocated#include <iostream>using namespace std; // Driver Codeint main(){ // Allocate huge amount of memory long MEMORY_SIZE = 0x7fffffff; // Put memory allocation statement // in the try catch block try { char* ptr = new char[MEMORY_SIZE]; // When memory allocation fails, // below line is not be executed // & control will go in catch block cout << \"Memory is allocated\" << \" Successfully\" << endl; } // Catch Block handle error catch (const bad_alloc& e) { cout << \"Memory Allocation\" << \" is failed: \" << e.what() << endl; } return 0;}", "e": 26780, "s": 26040, "text": null }, { "code": null, "e": 26824, "s": 26780, "text": "Memory Allocation is failed: std::bad_alloc" }, { "code": null, "e": 26970, "s": 26826, "text": "The above memory failure issue can be resolved without using the try-catch block. It can be fixed by using nothrow version of the new operator:" }, { "code": null, "e": 27164, "s": 26970, "text": "The nothrow constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure but return a null pointer instead." }, { "code": null, "e": 27315, "s": 27164, "text": "By default, when the new operator is used to attempt to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown." }, { "code": null, "e": 27403, "s": 27315, "text": "But when nothrow is used as an argument for new, and it returns a null pointer instead." }, { "code": null, "e": 27606, "s": 27403, "text": "This constant (nothrow) is just a value of type nothrow_t, with the only purpose of triggering an overloaded version of the function operator new (or operator new[]) that takes an argument of this type." }, { "code": null, "e": 27679, "s": 27606, "text": "Below is the implementation of memory allocation using nothrow operator:" }, { "code": null, "e": 27690, "s": 27679, "text": "Program 2:" }, { "code": null, "e": 27694, "s": 27690, "text": "C++" }, { "code": "// C++ program to handle memory failure// when very large memory is allocated#include <iostream>using namespace std; // Drive Codeint main(){ // Allocate huge amount of memory long MEMORY_SIZE = 0x7fffffff; // Allocate memory dynamically // using \"new\" with \"nothrow\" // version of new char* addr = new (std::nothrow) char[MEMORY_SIZE]; // Check if addr is having // proper address or not if (addr) { cout << \"Memory is allocated\" << \" Successfully\" << endl; } else { // This part will be executed if // large memory is allocated and // failure occurs cout << \"Memory allocation\" << \" fails\" << endl; } return 0;}", "e": 28412, "s": 27694, "text": null }, { "code": null, "e": 28437, "s": 28412, "text": "Memory allocation fails" }, { "code": null, "e": 28453, "s": 28439, "text": "manikarora059" }, { "code": null, "e": 28472, "s": 28453, "text": "C++-new and delete" }, { "code": null, "e": 28500, "s": 28472, "text": "C-Dynamic Memory Allocation" }, { "code": null, "e": 28518, "s": 28500, "text": "memory-management" }, { "code": null, "e": 28522, "s": 28518, "text": "C++" }, { "code": null, "e": 28526, "s": 28522, "text": "CPP" }, { "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": 28652, "s": 28624, "text": "Operator Overloading in C++" }, { "code": null, "e": 28672, "s": 28652, "text": "Polymorphism in C++" }, { "code": null, "e": 28696, "s": 28672, "text": "Sorting a vector in C++" }, { "code": null, "e": 28729, "s": 28696, "text": "Friend class and function in C++" }, { "code": null, "e": 28754, "s": 28729, "text": "std::string class in C++" }, { "code": null, "e": 28798, "s": 28754, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 28843, "s": 28798, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 28867, "s": 28843, "text": "Inline Functions in C++" }, { "code": null, "e": 28920, "s": 28867, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
How to Implement Generic LinkedList in Java? - GeeksforGeeks
28 Mar, 2022 Linked List is Linear Data Structures that store values in nodes. As we do know here each Node possesses two properties namely the value of the node and link to the next node if present so. Linked List can not only be of Integer data type but String, boolean, Float, Character, etc. We can implement such a “generic” Linked List Data Type that can store values of any data type. There are 6 primary member functions of a linked list: E add (data): It adds an element at the end of the linked list add (position, data): It adds an element to any valid position in the linked list remove(key): It removes node that contains key from the linked list clear() : it clears the entire linked list empty(): It checks if the linked list is empty or not length(): It returns the length of the linked list Note: Time complexity is of order N for adding and removing operations and of order 1 for other operations. Illustration: An Integer Linked List {100,200,300,400} is represented looks like Implementation: Example Java // Java Program to Implement Generic Linked List // Importing all input output classesimport java.io.*; // Class 1// Helper Class (Generic node class for LinkedList)class node<T> { // Data members // 1. Storing value of node T data; // 2. Storing address of next node node<T> next; // Parameterized constructor to assign value node(T data) { // This keyword refers to current object itself this.data = data; this.next = null; }} // Class 2// Helper class ( Generic LinkedList class)class list<T> { // Generic node instance node<T> head; // Data member to store length of list private int length = 0; // Default constructor list() { this.head = null; } // Method // To add node at the end of List void add(T data) { // Creating new node with given value node<T> temp = new node<>(data); // Checking if list is empty // and assigning new value to head node if (this.head == null) { head = temp; } // If list already exists else { // Temporary node for traversal node<T> X = head; // Iterating till end of the List while (X.next != null) { X = X.next; } // Adding new valued node at the end of the list X.next = temp; } // Increasing length after adding new node length++; } // Method // To add new node at any given position void add(int position, T data) { // Checking if position is valid if (position > length + 1) { // Display message only System.out.println( "Position Unavailable in LinkedList"); return; } // If new position is head then replace head node if (position == 1) { // Temporary node that stores previous head // value node<T> temp = head; // New valued node stored in head head = new node<T>(data); // New head node pointing to old head node head.next = temp; return; } // Temporary node for traversal node<T> temp = head; // Dummy node with null value that stores previous // node node<T> prev = new node<T>(null); // iterating to the given position while (position - 1 > 0) { // assigning previous node prev = temp; // incrementing next node temp = temp.next; // decreasing position counter position--; } // previous node now points to new value prev.next = new node<T>(data); // new value now points to former current node prev.next.next = temp; } // Method // To remove a node from list void remove(T key) { // NOTE // dummy node is used to represent the node before // the current node Since in a Singly Linked-List we // cannot go backwards from a node, we use a dummy // node to represent the previous node. In case of // head node, since there is no previous node, the // previous node is assigned to null. // Dummy node with null value node<T> prev = new node<>(null); // Dummy node pointing to head node prev.next = head; // Next node that points ahead of current node node<T> next = head.next; // Temporary node for traversal node<T> temp = head; // Boolean value that checks whether value to be // deleted exists or not boolean exists = false; // If head node needs to be deleted if (head.data == key) { head = head.next; // Node to be deleted exists exists = true; } // Iterating over LinkedList while (temp.next != null) { // We convert value to be compared into Strings // and then compare using // String1.equals(String2) method // Comparing value of key and current node if (String.valueOf(temp.data).equals( String.valueOf(key))) { // If node to be deleted is found previous // node now points to next node skipping the // current node prev.next = next; // node to be deleted exists exists = true; // As soon as we find the node to be deleted // we exit the loop break; } // Previous node now points to current node prev = temp; // Current node now points to next node temp = temp.next; // Next node points the node ahead of current // node next = temp.next; } // Comparing the last node with the given key value if (exists == false && String.valueOf(temp.data).equals( String.valueOf(key))) { // If found , last node is skipped over prev.next = null; // Node to be deleted exists exists = true; } // If node to be deleted exists if (exists) { // Length of LinkedList reduced length--; } // If node to be deleted does not exist else { // Print statement System.out.println( "Given Value is not present in linked list"); } } // Method // To clear the entire LinkedList void clear() { // Head now points to null head = null; // length is 0 again length = 0; } // Method // Returns whether List is empty or not boolean empty() { // Checking if head node points to null if (head == null) { return true; } return false; } // Method // Returning the length of LinkedList int length() { return this.length; } // Method // To display the LinkedList // @Override public String toString() { String S = "{ "; node<T> X = head; if (X == null) return S + " }"; while (X.next != null) { S += String.valueOf(X.data) + " -> "; X = X.next; } S += String.valueOf(X.data); return S + " }"; }} // Class 3// Main Classpublic class GFG { // main driver method public static void main(String[] args) { // Integer List // Creating new empty Integer linked list list<Integer> list1 = new list<>(); System.out.println( "Integer LinkedList created as list1 :"); // Adding elements to the above List object // Element 1 - 100 list1.add(100); // Element 2 - 200 list1.add(200); // Element 3 - 300 list1.add(300); // Display message only System.out.println( "list1 after adding 100,200 and 300 :"); // Print and display the above List elements System.out.println(list1); // Removing 200 from list1 list1.remove(200); // Display message only System.out.println("list1 after removing 200 :"); // Print and display again updated List elements System.out.println(list1); // String LinkedList // Creating new empty String linked list list<String> list2 = new list<>(); System.out.println( "\nString LinkedList created as list2"); // Adding elements to the above List object // Element 1 - hello list2.add("hello"); // Element 2 - world list2.add("world"); // Display message only System.out.println( "list2 after adding hello and world :"); // Print current elements only System.out.println(list2); // Now, adding element 3- "GFG" at position 2 list2.add(2, "GFG"); // Display message only System.out.println( "list2 after adding GFG at position 2 :"); // now print the updated List again // after inserting element at second position System.out.println(list2); // Float LinkedList // Creating new empty Float linked list list<Float> list3 = new list<>(); // Display message only System.out.println( "\nFloat LinkedList created as list3"); // Adding elements to the above List // Element 1 - 20.25 list3.add(20.25f); // Element 2 - 50.42 list3.add(50.42f); // Element 3 - 30.99 list3.add(30.99f); // Display message only System.out.println( "list3 after adding 20.25, 50.42 and 30.99 :"); // Print and display List elements System.out.println(list3); // Display message only System.out.println("Clearing list3 :"); // Now.clearing this list using clear() method list3.clear(); // Now, print and display the above list again System.out.println(list3); }} Output :- Integer LinkedList created as list1 : list1 after adding 100,200 and 300 : { 100 -&gt; 200 -&gt; 300 } list1 after removing 200 : { 100 -&gt; 300 } String LinkedList created as list2 list2 after adding hello and world : { hello -&gt; world } list2 after adding GFG at position 2 : { hello -&gt; GFG -&gt; world } Float LinkedList created as list3 list3 after adding 20.25, 50.42 and 30.99 : { 20.25 -&gt; 50.42 -&gt; 30.99 } Clearing list3 : { } sweetyty simranarora5sos gabaa406 anikakapoor simmytarika5 sumitgumber28 Java Java Programs Linked List Linked List Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25303, "s": 25275, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25682, "s": 25303, "text": "Linked List is Linear Data Structures that store values in nodes. As we do know here each Node possesses two properties namely the value of the node and link to the next node if present so. Linked List can not only be of Integer data type but String, boolean, Float, Character, etc. We can implement such a “generic” Linked List Data Type that can store values of any data type." }, { "code": null, "e": 25739, "s": 25682, "text": "There are 6 primary member functions of a linked list: E" }, { "code": null, "e": 25800, "s": 25739, "text": "add (data): It adds an element at the end of the linked list" }, { "code": null, "e": 25882, "s": 25800, "text": "add (position, data): It adds an element to any valid position in the linked list" }, { "code": null, "e": 25950, "s": 25882, "text": "remove(key): It removes node that contains key from the linked list" }, { "code": null, "e": 25993, "s": 25950, "text": "clear() : it clears the entire linked list" }, { "code": null, "e": 26047, "s": 25993, "text": "empty(): It checks if the linked list is empty or not" }, { "code": null, "e": 26098, "s": 26047, "text": "length(): It returns the length of the linked list" }, { "code": null, "e": 26206, "s": 26098, "text": "Note: Time complexity is of order N for adding and removing operations and of order 1 for other operations." }, { "code": null, "e": 26287, "s": 26206, "text": "Illustration: An Integer Linked List {100,200,300,400} is represented looks like" }, { "code": null, "e": 26303, "s": 26287, "text": "Implementation:" }, { "code": null, "e": 26311, "s": 26303, "text": "Example" }, { "code": null, "e": 26316, "s": 26311, "text": "Java" }, { "code": "// Java Program to Implement Generic Linked List // Importing all input output classesimport java.io.*; // Class 1// Helper Class (Generic node class for LinkedList)class node<T> { // Data members // 1. Storing value of node T data; // 2. Storing address of next node node<T> next; // Parameterized constructor to assign value node(T data) { // This keyword refers to current object itself this.data = data; this.next = null; }} // Class 2// Helper class ( Generic LinkedList class)class list<T> { // Generic node instance node<T> head; // Data member to store length of list private int length = 0; // Default constructor list() { this.head = null; } // Method // To add node at the end of List void add(T data) { // Creating new node with given value node<T> temp = new node<>(data); // Checking if list is empty // and assigning new value to head node if (this.head == null) { head = temp; } // If list already exists else { // Temporary node for traversal node<T> X = head; // Iterating till end of the List while (X.next != null) { X = X.next; } // Adding new valued node at the end of the list X.next = temp; } // Increasing length after adding new node length++; } // Method // To add new node at any given position void add(int position, T data) { // Checking if position is valid if (position > length + 1) { // Display message only System.out.println( \"Position Unavailable in LinkedList\"); return; } // If new position is head then replace head node if (position == 1) { // Temporary node that stores previous head // value node<T> temp = head; // New valued node stored in head head = new node<T>(data); // New head node pointing to old head node head.next = temp; return; } // Temporary node for traversal node<T> temp = head; // Dummy node with null value that stores previous // node node<T> prev = new node<T>(null); // iterating to the given position while (position - 1 > 0) { // assigning previous node prev = temp; // incrementing next node temp = temp.next; // decreasing position counter position--; } // previous node now points to new value prev.next = new node<T>(data); // new value now points to former current node prev.next.next = temp; } // Method // To remove a node from list void remove(T key) { // NOTE // dummy node is used to represent the node before // the current node Since in a Singly Linked-List we // cannot go backwards from a node, we use a dummy // node to represent the previous node. In case of // head node, since there is no previous node, the // previous node is assigned to null. // Dummy node with null value node<T> prev = new node<>(null); // Dummy node pointing to head node prev.next = head; // Next node that points ahead of current node node<T> next = head.next; // Temporary node for traversal node<T> temp = head; // Boolean value that checks whether value to be // deleted exists or not boolean exists = false; // If head node needs to be deleted if (head.data == key) { head = head.next; // Node to be deleted exists exists = true; } // Iterating over LinkedList while (temp.next != null) { // We convert value to be compared into Strings // and then compare using // String1.equals(String2) method // Comparing value of key and current node if (String.valueOf(temp.data).equals( String.valueOf(key))) { // If node to be deleted is found previous // node now points to next node skipping the // current node prev.next = next; // node to be deleted exists exists = true; // As soon as we find the node to be deleted // we exit the loop break; } // Previous node now points to current node prev = temp; // Current node now points to next node temp = temp.next; // Next node points the node ahead of current // node next = temp.next; } // Comparing the last node with the given key value if (exists == false && String.valueOf(temp.data).equals( String.valueOf(key))) { // If found , last node is skipped over prev.next = null; // Node to be deleted exists exists = true; } // If node to be deleted exists if (exists) { // Length of LinkedList reduced length--; } // If node to be deleted does not exist else { // Print statement System.out.println( \"Given Value is not present in linked list\"); } } // Method // To clear the entire LinkedList void clear() { // Head now points to null head = null; // length is 0 again length = 0; } // Method // Returns whether List is empty or not boolean empty() { // Checking if head node points to null if (head == null) { return true; } return false; } // Method // Returning the length of LinkedList int length() { return this.length; } // Method // To display the LinkedList // @Override public String toString() { String S = \"{ \"; node<T> X = head; if (X == null) return S + \" }\"; while (X.next != null) { S += String.valueOf(X.data) + \" -> \"; X = X.next; } S += String.valueOf(X.data); return S + \" }\"; }} // Class 3// Main Classpublic class GFG { // main driver method public static void main(String[] args) { // Integer List // Creating new empty Integer linked list list<Integer> list1 = new list<>(); System.out.println( \"Integer LinkedList created as list1 :\"); // Adding elements to the above List object // Element 1 - 100 list1.add(100); // Element 2 - 200 list1.add(200); // Element 3 - 300 list1.add(300); // Display message only System.out.println( \"list1 after adding 100,200 and 300 :\"); // Print and display the above List elements System.out.println(list1); // Removing 200 from list1 list1.remove(200); // Display message only System.out.println(\"list1 after removing 200 :\"); // Print and display again updated List elements System.out.println(list1); // String LinkedList // Creating new empty String linked list list<String> list2 = new list<>(); System.out.println( \"\\nString LinkedList created as list2\"); // Adding elements to the above List object // Element 1 - hello list2.add(\"hello\"); // Element 2 - world list2.add(\"world\"); // Display message only System.out.println( \"list2 after adding hello and world :\"); // Print current elements only System.out.println(list2); // Now, adding element 3- \"GFG\" at position 2 list2.add(2, \"GFG\"); // Display message only System.out.println( \"list2 after adding GFG at position 2 :\"); // now print the updated List again // after inserting element at second position System.out.println(list2); // Float LinkedList // Creating new empty Float linked list list<Float> list3 = new list<>(); // Display message only System.out.println( \"\\nFloat LinkedList created as list3\"); // Adding elements to the above List // Element 1 - 20.25 list3.add(20.25f); // Element 2 - 50.42 list3.add(50.42f); // Element 3 - 30.99 list3.add(30.99f); // Display message only System.out.println( \"list3 after adding 20.25, 50.42 and 30.99 :\"); // Print and display List elements System.out.println(list3); // Display message only System.out.println(\"Clearing list3 :\"); // Now.clearing this list using clear() method list3.clear(); // Now, print and display the above list again System.out.println(list3); }}", "e": 35400, "s": 26316, "text": null }, { "code": null, "e": 35411, "s": 35400, "text": " Output :-" }, { "code": null, "e": 35860, "s": 35411, "text": "Integer LinkedList created as list1 :\nlist1 after adding 100,200 and 300 :\n{ 100 -&gt; 200 -&gt; 300 }\nlist1 after removing 200 :\n{ 100 -&gt; 300 }\n\nString LinkedList created as list2\nlist2 after adding hello and world :\n{ hello -&gt; world }\nlist2 after adding GFG at position 2 :\n{ hello -&gt; GFG -&gt; world }\n\nFloat LinkedList created as list3\nlist3 after adding 20.25, 50.42 and 30.99 :\n{ 20.25 -&gt; 50.42 -&gt; 30.99 }\nClearing list3 :\n{ }" }, { "code": null, "e": 35871, "s": 35862, "text": "sweetyty" }, { "code": null, "e": 35887, "s": 35871, "text": "simranarora5sos" }, { "code": null, "e": 35896, "s": 35887, "text": "gabaa406" }, { "code": null, "e": 35908, "s": 35896, "text": "anikakapoor" }, { "code": null, "e": 35921, "s": 35908, "text": "simmytarika5" }, { "code": null, "e": 35935, "s": 35921, "text": "sumitgumber28" }, { "code": null, "e": 35940, "s": 35935, "text": "Java" }, { "code": null, "e": 35954, "s": 35940, "text": "Java Programs" }, { "code": null, "e": 35966, "s": 35954, "text": "Linked List" }, { "code": null, "e": 35978, "s": 35966, "text": "Linked List" }, { "code": null, "e": 35983, "s": 35978, "text": "Java" }, { "code": null, "e": 36081, "s": 35983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36096, "s": 36081, "text": "Stream In Java" }, { "code": null, "e": 36117, "s": 36096, "text": "Constructors in Java" }, { "code": null, "e": 36136, "s": 36117, "text": "Exceptions in Java" }, { "code": null, "e": 36166, "s": 36136, "text": "Functional Interfaces in Java" }, { "code": null, "e": 36212, "s": 36166, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 36238, "s": 36212, "text": "Java Programming Examples" }, { "code": null, "e": 36272, "s": 36238, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 36319, "s": 36272, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 36351, "s": 36319, "text": "How to Iterate HashMap in Java?" } ]
Array vs ArrayList in Java - GeeksforGeeks
11 May, 2022 Let us discuss the concept of the arrays and ArrayList briefly in the header to incorporate the understanding in java programs later landing onto the conclusive differences between them. As we all are aware of that arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework. Being a good programmer one is already aware of using ArrayList over arrays despite knowing the differences between these two. Now moving ahead even with ArrayList there comes a functionality to pass the type of datatype of elements that are supposed to be stored in the ArrayList be it an object, string, integer, double, float, etc. Note: As a side note, ArrayList in Java can be seen as similar to vector in C++. Methods of Creating Arrays In Java, the following are two different ways to create an array. Simple fixed-sized arraysDynamically sized arrays Simple fixed-sized arrays Dynamically sized arrays int arr[] = new int[10] Syntax: Declaring a static array It can be further defined by two types: Type 1: Declaring and initializing at the same time Type 2: Declaring than initializing elements later. Type 1 Type array_name [array_size] ; Type array_name = { Element1, Element2, Element3, Element4,...., ElementN } ; // It is preferable if we have very limited array elements Type 2 int arr [100] ; // This does means we are declaring a memory block named 'arr' // which is containing continuous 100 block associated in it Note: arr(0) returns the first element of the array so it does mean that if we try to print out arr(0) then we will get Element1. It is very important statement and is left unveiliable when it comes to deep understanding of memory storage in arrays. Now let us dwell on the next concept of ArrayList that is as follows Syntax: Declaring an Arraylist Arraylist<Type> al = new ArrayList<Type> ; // Here Type is the type of elements in ArrayList to be created Note: ArrayList in Java (equivalent to vector in C++) having dynamic size. It can be shrunk or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package. Now let us illustrate examples with the help of differences between Array and ArrayList Base 1: An array is a basic functionality provided by Java. ArrayList is part of the collection framework in Java. Therefore array members are accessed using [], while ArrayList has a set of methods to access elements and modify them. Example: Java // Java program to demonstrate differences between// Array and ArrayList // Importing required classesimport java.util.ArrayList;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input array int[] arr = new int[2]; arr[0] = 1; arr[1] = 2; // Printing first element of array System.out.println(arr[0]); // ArrayList // Creating an arrayList with initial capacity // say bi it 2 ArrayList<Integer> arrL = new ArrayList<Integer>(2); // Adding elements to ArrayList // using add() method arrL.add(1); arrL.add(2); // Printing alongside accessing // elements of ArrayList System.out.println(arrL.get(0)); }} 1 1 Base 2: The array is a fixed-size data structure while ArrayList is not. One need not mention the size of the ArrayList while creating its object. Even if we specify some initial capacity, we can add more elements. Example: Java // Java program to demonstrate differences between// Array and ArrayList // Importing required classesimport java.util.ArrayList;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Normal Array // Need to specify the size for array int[] arr = new int[3]; arr[0] = 1; arr[1] = 2; arr[2] = 3; // We cannot add more elements to array arr[] // ArrayList // Need not to specify size // Declaring an Arraylist of Integer type ArrayList<Integer> arrL = new ArrayList<Integer>(); // Adding elements to ArrayList object arrL.add(1); arrL.add(2); arrL.add(3); arrL.add(4); // We can add more elements to arrL // Print and display Arraylist elements System.out.println(arrL); // Print and display array elements System.out.println(Arrays.toString(arr)); }} [1, 2, 3, 4] [1, 2, 3] Base 3: An array can contain both primitive data types as well as objects of a class depending on the definition of the array. However, ArrayList only supports object entries, not the primitive data types. Note: When we do arraylist.add(1) than it converts the primitive int data type into an Integer object which is as illustrated in below example Example: Java import java.util.ArrayList;class Test{ public static void main(String args[]) { // allowed int[] array = new int[3]; // allowed, however, need to be initialized Test[] array1 = new Test[3]; // not allowed (Uncommenting below line causes // compiler error) // ArrayList<char> arrL = new ArrayList<char>(); // Allowed ArrayList<Integer> arrL1 = new ArrayList<>(); ArrayList<String> arrL2 = new ArrayList<>(); ArrayList<Object> arrL3 = new ArrayList<>(); System.out.println("Successfully compiled and executed"); }} Successfully compiled and executed Base 4: Since ArrayList can’t be created for primitive data types, members of ArrayList are always references to objects at different memory locations (See this for details). Therefore in ArrayList, the actual objects are never stored at contiguous locations. References of the actual objects are stored at contiguous locations. On the other hand, in the array, it depends whether the array is of primitive type or object type. In the case of primitive types, actual values are contiguous locations, but in the case of objects, allocation is similar to ArrayList. Java ArrayList supports many additional operations like indexOf(), remove(), etc. These functions are not supported by Arrays. We have implemented and seen the differences between them as perceived from outputs. Now let us wrap up the article by plotting conclusive differences in a tabular format a shown below as follows: This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above vivekranjan Akanksha_Rai solankimayank adnanirshad158 simranarora5sos sagartomar9927 Java - util package Java-Array-Programs Java-ArrayList Java-Arrays Java-Collections Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25733, "s": 25705, "text": "\n11 May, 2022" }, { "code": null, "e": 26473, "s": 25733, "text": "Let us discuss the concept of the arrays and ArrayList briefly in the header to incorporate the understanding in java programs later landing onto the conclusive differences between them. As we all are aware of that arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework. Being a good programmer one is already aware of using ArrayList over arrays despite knowing the differences between these two. Now moving ahead even with ArrayList there comes a functionality to pass the type of datatype of elements that are supposed to be stored in the ArrayList be it an object, string, integer, double, float, etc. " }, { "code": null, "e": 26555, "s": 26473, "text": "Note: As a side note, ArrayList in Java can be seen as similar to vector in C++. " }, { "code": null, "e": 26582, "s": 26555, "text": "Methods of Creating Arrays" }, { "code": null, "e": 26649, "s": 26582, "text": "In Java, the following are two different ways to create an array. " }, { "code": null, "e": 26699, "s": 26649, "text": "Simple fixed-sized arraysDynamically sized arrays" }, { "code": null, "e": 26725, "s": 26699, "text": "Simple fixed-sized arrays" }, { "code": null, "e": 26750, "s": 26725, "text": "Dynamically sized arrays" }, { "code": null, "e": 26777, "s": 26750, "text": "int arr[] = new int[10] " }, { "code": null, "e": 26811, "s": 26777, "text": "Syntax: Declaring a static array " }, { "code": null, "e": 26851, "s": 26811, "text": "It can be further defined by two types:" }, { "code": null, "e": 26903, "s": 26851, "text": "Type 1: Declaring and initializing at the same time" }, { "code": null, "e": 26955, "s": 26903, "text": "Type 2: Declaring than initializing elements later." }, { "code": null, "e": 26963, "s": 26955, "text": " Type 1" }, { "code": null, "e": 27132, "s": 26963, "text": "Type array_name [array_size] ;\nType array_name = { Element1, Element2, Element3, Element4,...., ElementN } ;\n// It is preferable if we have very limited array elements " }, { "code": null, "e": 27139, "s": 27132, "text": "Type 2" }, { "code": null, "e": 27280, "s": 27139, "text": "int arr [100] ;\n// This does means we are declaring a memory block named 'arr' \n// which is containing continuous 100 block associated in it" }, { "code": null, "e": 27530, "s": 27280, "text": "Note: arr(0) returns the first element of the array so it does mean that if we try to print out arr(0) then we will get Element1. It is very important statement and is left unveiliable when it comes to deep understanding of memory storage in arrays." }, { "code": null, "e": 27600, "s": 27530, "text": "Now let us dwell on the next concept of ArrayList that is as follows " }, { "code": null, "e": 27631, "s": 27600, "text": "Syntax: Declaring an Arraylist" }, { "code": null, "e": 27738, "s": 27631, "text": "Arraylist<Type> al = new ArrayList<Type> ;\n// Here Type is the type of elements in ArrayList to be created" }, { "code": null, "e": 27943, "s": 27738, "text": "Note: ArrayList in Java (equivalent to vector in C++) having dynamic size. It can be shrunk or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package. " }, { "code": null, "e": 28032, "s": 27943, "text": "Now let us illustrate examples with the help of differences between Array and ArrayList " }, { "code": null, "e": 28268, "s": 28032, "text": "Base 1: An array is a basic functionality provided by Java. ArrayList is part of the collection framework in Java. Therefore array members are accessed using [], while ArrayList has a set of methods to access elements and modify them. " }, { "code": null, "e": 28277, "s": 28268, "text": "Example:" }, { "code": null, "e": 28282, "s": 28277, "text": "Java" }, { "code": "// Java program to demonstrate differences between// Array and ArrayList // Importing required classesimport java.util.ArrayList;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input array int[] arr = new int[2]; arr[0] = 1; arr[1] = 2; // Printing first element of array System.out.println(arr[0]); // ArrayList // Creating an arrayList with initial capacity // say bi it 2 ArrayList<Integer> arrL = new ArrayList<Integer>(2); // Adding elements to ArrayList // using add() method arrL.add(1); arrL.add(2); // Printing alongside accessing // elements of ArrayList System.out.println(arrL.get(0)); }}", "e": 29089, "s": 28282, "text": null }, { "code": null, "e": 29093, "s": 29089, "text": "1\n1" }, { "code": null, "e": 29308, "s": 29093, "text": "Base 2: The array is a fixed-size data structure while ArrayList is not. One need not mention the size of the ArrayList while creating its object. Even if we specify some initial capacity, we can add more elements." }, { "code": null, "e": 29317, "s": 29308, "text": "Example:" }, { "code": null, "e": 29322, "s": 29317, "text": "Java" }, { "code": "// Java program to demonstrate differences between// Array and ArrayList // Importing required classesimport java.util.ArrayList;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Normal Array // Need to specify the size for array int[] arr = new int[3]; arr[0] = 1; arr[1] = 2; arr[2] = 3; // We cannot add more elements to array arr[] // ArrayList // Need not to specify size // Declaring an Arraylist of Integer type ArrayList<Integer> arrL = new ArrayList<Integer>(); // Adding elements to ArrayList object arrL.add(1); arrL.add(2); arrL.add(3); arrL.add(4); // We can add more elements to arrL // Print and display Arraylist elements System.out.println(arrL); // Print and display array elements System.out.println(Arrays.toString(arr)); }}", "e": 30298, "s": 29322, "text": null }, { "code": null, "e": 30321, "s": 30298, "text": "[1, 2, 3, 4]\n[1, 2, 3]" }, { "code": null, "e": 30528, "s": 30321, "text": "Base 3: An array can contain both primitive data types as well as objects of a class depending on the definition of the array. However, ArrayList only supports object entries, not the primitive data types. " }, { "code": null, "e": 30671, "s": 30528, "text": "Note: When we do arraylist.add(1) than it converts the primitive int data type into an Integer object which is as illustrated in below example" }, { "code": null, "e": 30680, "s": 30671, "text": "Example:" }, { "code": null, "e": 30685, "s": 30680, "text": "Java" }, { "code": "import java.util.ArrayList;class Test{ public static void main(String args[]) { // allowed int[] array = new int[3]; // allowed, however, need to be initialized Test[] array1 = new Test[3]; // not allowed (Uncommenting below line causes // compiler error) // ArrayList<char> arrL = new ArrayList<char>(); // Allowed ArrayList<Integer> arrL1 = new ArrayList<>(); ArrayList<String> arrL2 = new ArrayList<>(); ArrayList<Object> arrL3 = new ArrayList<>(); System.out.println(\"Successfully compiled and executed\"); }}", "e": 31300, "s": 30685, "text": null }, { "code": null, "e": 31335, "s": 31300, "text": "Successfully compiled and executed" }, { "code": null, "e": 31665, "s": 31335, "text": "Base 4: Since ArrayList can’t be created for primitive data types, members of ArrayList are always references to objects at different memory locations (See this for details). Therefore in ArrayList, the actual objects are never stored at contiguous locations. References of the actual objects are stored at contiguous locations. " }, { "code": null, "e": 32027, "s": 31665, "text": "On the other hand, in the array, it depends whether the array is of primitive type or object type. In the case of primitive types, actual values are contiguous locations, but in the case of objects, allocation is similar to ArrayList. Java ArrayList supports many additional operations like indexOf(), remove(), etc. These functions are not supported by Arrays." }, { "code": null, "e": 32224, "s": 32027, "text": "We have implemented and seen the differences between them as perceived from outputs. Now let us wrap up the article by plotting conclusive differences in a tabular format a shown below as follows:" }, { "code": null, "e": 32493, "s": 32224, "text": "This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 32617, "s": 32493, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 32629, "s": 32617, "text": "vivekranjan" }, { "code": null, "e": 32642, "s": 32629, "text": "Akanksha_Rai" }, { "code": null, "e": 32656, "s": 32642, "text": "solankimayank" }, { "code": null, "e": 32671, "s": 32656, "text": "adnanirshad158" }, { "code": null, "e": 32687, "s": 32671, "text": "simranarora5sos" }, { "code": null, "e": 32702, "s": 32687, "text": "sagartomar9927" }, { "code": null, "e": 32722, "s": 32702, "text": "Java - util package" }, { "code": null, "e": 32742, "s": 32722, "text": "Java-Array-Programs" }, { "code": null, "e": 32757, "s": 32742, "text": "Java-ArrayList" }, { "code": null, "e": 32769, "s": 32757, "text": "Java-Arrays" }, { "code": null, "e": 32786, "s": 32769, "text": "Java-Collections" }, { "code": null, "e": 32805, "s": 32786, "text": "Java-List-Programs" }, { "code": null, "e": 32810, "s": 32805, "text": "Java" }, { "code": null, "e": 32815, "s": 32810, "text": "Java" }, { "code": null, "e": 32832, "s": 32815, "text": "Java-Collections" }, { "code": null, "e": 32930, "s": 32832, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32981, "s": 32930, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33011, "s": 32981, "text": "HashMap in Java with Examples" }, { "code": null, "e": 33030, "s": 33011, "text": "Interfaces in Java" }, { "code": null, "e": 33045, "s": 33030, "text": "Stream In Java" }, { "code": null, "e": 33076, "s": 33045, "text": "How to iterate any Map in Java" }, { "code": null, "e": 33108, "s": 33076, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33128, "s": 33108, "text": "Stack Class in Java" }, { "code": null, "e": 33160, "s": 33128, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33184, "s": 33160, "text": "Singleton Class in Java" } ]
Python | Check if string repeats itself - GeeksforGeeks
25 Jun, 2019 While working with strings, many times, we can come across a use case in which we need to find if a string has in it the repeating substring, which repeats all over the string and thus making a multiple of the root substring. Let’s discuss certain ways in which we can get the root substring of string. Method #1 : Using List comprehension + Brute ForceWe can perform this task using selective slicing and brute force manner. This is the naive method to find the string in which we try to get the root string by repetitive division of string. # Python3 code to demonstrate working of# Check if string repeats itself# Using List comprehension + Brute Force # initializing string test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks" # printing original string print("The original string is : " + test_str) # using List comprehension + Brute Force# Check if string repeats itselfres = Nonefor i in range(1, len(test_str)//2 + 1): if (not len(test_str) % len(test_str[0:i]) and test_str[0:i] * (len(test_str)//len(test_str[0:i])) == test_str): res = test_str[0:i] # printing result print("The root substring of string : " + res) The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks The root substring of string : GeeksforGeeks Method #2 : Using list slicing + find() This problem can also be solved using the fact that we can search for root string after adding a string and checking the root string in this string except last and first character, represents the string is repeating itself.Doesn’t work for string length < 2. # Python3 code to demonstrate working of# Check if string repeats itself# Using list slicing + find() # initializing string test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks" # printing original string print("The original string is : " + test_str) # using list slicing + find()# Check if string repeats itselfres = Nonetemp = (test_str + test_str).find(test_str, 1, -1)if temp != -1: res = test_str[:temp] # printing result print("The root substring of string : " + res) The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks The root substring of string : GeeksforGeeks Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Defaultdict in Python How to Install PIP on Windows ? Deque in Python Bar Plot in Matplotlib Check if element exists in list in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python Program for Binary Search (Recursive and Iterative) Python | Convert a list into a tuple
[ { "code": null, "e": 25537, "s": 25509, "text": "\n25 Jun, 2019" }, { "code": null, "e": 25840, "s": 25537, "text": "While working with strings, many times, we can come across a use case in which we need to find if a string has in it the repeating substring, which repeats all over the string and thus making a multiple of the root substring. Let’s discuss certain ways in which we can get the root substring of string." }, { "code": null, "e": 26080, "s": 25840, "text": "Method #1 : Using List comprehension + Brute ForceWe can perform this task using selective slicing and brute force manner. This is the naive method to find the string in which we try to get the root string by repetitive division of string." }, { "code": "# Python3 code to demonstrate working of# Check if string repeats itself# Using List comprehension + Brute Force # initializing string test_str = \"GeeksforGeeksGeeksforGeeksGeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # using List comprehension + Brute Force# Check if string repeats itselfres = Nonefor i in range(1, len(test_str)//2 + 1): if (not len(test_str) % len(test_str[0:i]) and test_str[0:i] * (len(test_str)//len(test_str[0:i])) == test_str): res = test_str[0:i] # printing result print(\"The root substring of string : \" + res)", "e": 26686, "s": 26080, "text": null }, { "code": null, "e": 26797, "s": 26686, "text": "The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks\nThe root substring of string : GeeksforGeeks\n" }, { "code": null, "e": 26839, "s": 26799, "text": "Method #2 : Using list slicing + find()" }, { "code": null, "e": 27098, "s": 26839, "text": "This problem can also be solved using the fact that we can search for root string after adding a string and checking the root string in this string except last and first character, represents the string is repeating itself.Doesn’t work for string length < 2." }, { "code": "# Python3 code to demonstrate working of# Check if string repeats itself# Using list slicing + find() # initializing string test_str = \"GeeksforGeeksGeeksforGeeksGeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # using list slicing + find()# Check if string repeats itselfres = Nonetemp = (test_str + test_str).find(test_str, 1, -1)if temp != -1: res = test_str[:temp] # printing result print(\"The root substring of string : \" + res)", "e": 27578, "s": 27098, "text": null }, { "code": null, "e": 27689, "s": 27578, "text": "The original string is : GeeksforGeeksGeeksforGeeksGeeksforGeeks\nThe root substring of string : GeeksforGeeks\n" }, { "code": null, "e": 27712, "s": 27689, "text": "Python string-programs" }, { "code": null, "e": 27719, "s": 27712, "text": "Python" }, { "code": null, "e": 27735, "s": 27719, "text": "Python Programs" }, { "code": null, "e": 27833, "s": 27735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27855, "s": 27833, "text": "Defaultdict in Python" }, { "code": null, "e": 27887, "s": 27855, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27903, "s": 27887, "text": "Deque in Python" }, { "code": null, "e": 27926, "s": 27903, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27968, "s": 27926, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27990, "s": 27968, "text": "Defaultdict in Python" }, { "code": null, "e": 28029, "s": 27990, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28075, "s": 28029, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28134, "s": 28075, "text": "Python Program for Binary Search (Recursive and Iterative)" } ]
How to create a Collapsed Sidebar? - GeeksforGeeks
09 Jul, 2019 Bootstrap Sidebar is a component that is used for vertical navigation. It can be customized in various styles according to your requirement by using CSS and can be made responsive by using JavaScript. The .sidebar class is used to create simple Bootstrap sidebar. To make a collapsing sidebar, you need to have a bit of JavaScript Knowledge as well, as it would be used to open and close the sidebar, would make your sidebar responsive. Example: <html> <head> <style> /*Position and style for the sidebar*/ .sidebar { height: 100%; width: 0; position: fixed; /*Stays in place */ background-color: green; /*green*/ overflow-x: hidden; /*for Disabling horizontal scroll */ } /* Position and style for the sidebar links */ .sidebar a { padding: 10px 10px 10px; font-size: 25px; color: #111; display: block; transition: 0.3s; } /* the links change color when mouse hovers upon them*/ .sidebar a:hover { color: #FFFFFF; } /* Position and style the for cross button */ .sidebar .closebtn { position: absolute; top: 0; right: 25px; } /* Style for the sidebar button */ .openbtn { font-size: 32px; background-color: #008000; color: #111; padding: 10px 10px 10px; border: none; } /* the sidebar button changes color when mouse hovers upon it */.openbtn:hover { color: #FFFFFF;} /* pushes the page content to the right when you open the side navigation */ #main { transition: margin-left .5s; /* If you want a transition effect */ padding: 10px; } </style></head> <body> <div id="sidebar" class="sidebar"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"> × </a> <!--the cross button--> <a href="#">India</a> <a href="#">Nepal</a> <a href="#">Srilanka</a> <a href="#">Myanmar</a> </div> <div id="main"> <button class="openbtn" onclick="openNav()"> SIDEBAR </button> <!-- for the sidebar button--> </div></body><script> /* Sets the width of the sidebar to 250 and the left margin of the page content to 250 */ function openNav() { document.getElementById( "sidebar").style.width = "250px"; document.getElementById( "main").style.marginLeft = "250px"; } /* Set the width of the sidebar to 0 and the left margin of the page content to 0 */ function closeNav() { document.getElementById( "sidebar").style.width = "0"; document.getElementById( "main").style.marginLeft = "0"; }</script> </html> Output: By running these three codes you can make a simple collapsing sidebar. You can further add more CSS features to make it even better according to your requirement. Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 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": 25983, "s": 25955, "text": "\n09 Jul, 2019" }, { "code": null, "e": 26184, "s": 25983, "text": "Bootstrap Sidebar is a component that is used for vertical navigation. It can be customized in various styles according to your requirement by using CSS and can be made responsive by using JavaScript." }, { "code": null, "e": 26420, "s": 26184, "text": "The .sidebar class is used to create simple Bootstrap sidebar. To make a collapsing sidebar, you need to have a bit of JavaScript Knowledge as well, as it would be used to open and close the sidebar, would make your sidebar responsive." }, { "code": null, "e": 26429, "s": 26420, "text": "Example:" }, { "code": "<html> <head> <style> /*Position and style for the sidebar*/ .sidebar { height: 100%; width: 0; position: fixed; /*Stays in place */ background-color: green; /*green*/ overflow-x: hidden; /*for Disabling horizontal scroll */ } /* Position and style for the sidebar links */ .sidebar a { padding: 10px 10px 10px; font-size: 25px; color: #111; display: block; transition: 0.3s; } /* the links change color when mouse hovers upon them*/ .sidebar a:hover { color: #FFFFFF; } /* Position and style the for cross button */ .sidebar .closebtn { position: absolute; top: 0; right: 25px; } /* Style for the sidebar button */ .openbtn { font-size: 32px; background-color: #008000; color: #111; padding: 10px 10px 10px; border: none; } /* the sidebar button changes color when mouse hovers upon it */.openbtn:hover { color: #FFFFFF;} /* pushes the page content to the right when you open the side navigation */ #main { transition: margin-left .5s; /* If you want a transition effect */ padding: 10px; } </style></head> <body> <div id=\"sidebar\" class=\"sidebar\"> <a href=\"javascript:void(0)\" class=\"closebtn\" onclick=\"closeNav()\"> × </a> <!--the cross button--> <a href=\"#\">India</a> <a href=\"#\">Nepal</a> <a href=\"#\">Srilanka</a> <a href=\"#\">Myanmar</a> </div> <div id=\"main\"> <button class=\"openbtn\" onclick=\"openNav()\"> SIDEBAR </button> <!-- for the sidebar button--> </div></body><script> /* Sets the width of the sidebar to 250 and the left margin of the page content to 250 */ function openNav() { document.getElementById( \"sidebar\").style.width = \"250px\"; document.getElementById( \"main\").style.marginLeft = \"250px\"; } /* Set the width of the sidebar to 0 and the left margin of the page content to 0 */ function closeNav() { document.getElementById( \"sidebar\").style.width = \"0\"; document.getElementById( \"main\").style.marginLeft = \"0\"; }</script> </html>", "e": 29006, "s": 26429, "text": null }, { "code": null, "e": 29014, "s": 29006, "text": "Output:" }, { "code": null, "e": 29177, "s": 29014, "text": "By running these three codes you can make a simple collapsing sidebar. You can further add more CSS features to make it even better according to your requirement." }, { "code": null, "e": 29192, "s": 29177, "text": "Bootstrap-Misc" }, { "code": null, "e": 29199, "s": 29192, "text": "Picked" }, { "code": null, "e": 29209, "s": 29199, "text": "Bootstrap" }, { "code": null, "e": 29226, "s": 29209, "text": "Web Technologies" }, { "code": null, "e": 29324, "s": 29226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29365, "s": 29324, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 29406, "s": 29365, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 29469, "s": 29406, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 29502, "s": 29469, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 29549, "s": 29502, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 29589, "s": 29549, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29622, "s": 29589, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29667, "s": 29622, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29710, "s": 29667, "text": "How to fetch data from an API in ReactJS ?" } ]
Recursive Functions in R Programming - GeeksforGeeks
10 May, 2020 Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. Recursion is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again and this technique is known as recursion. Since the loops increase the memory we use the recursion. The recursive function uses the concept of recursion to perform iterative tasks they call themselves, again and again, which acts as a loop. These kinds of functions need a stopping condition so that they can stop looping continuously. Recursive functions call themselves. They break down the problem into smaller components. The function() calls itself within the original function() on each of the smaller components. After this, the results will be put together to solve the original problem. Example: Factorial using Recursion in R rec_fac <- function(x){ if(x==0 || x==1) { return(1) } else { return(x*rec_fac(x-1)) }} Output: [1] 120 Here, rec_fac(5) calls rec_fac(4), which then calls rec_fac(3), and so on until the input argument x, has reached 1. The function returns 1 and is destroyed. The return value is multiplied with argument value and returned. This process continues until the first function call returns its output, giving us the final result. Example: Sum of Series Using RecursionRecursion in R is most useful for finding the sum of self-repeating series. In this example, we will find the sum of squares of a given series of numbers. Sum = 12+22+...+N2 Example: sum_series <- function(vec){ if(length(vec)<=1) { return(vec^2) } else { return(vec[1]^2+sum_series(vec[-1])) }}series <- c(1:10)sum_series(series) Output: [1] 385 The use of recursion, often, makes the code shorter and it also looks clean. It is a simple solution for a few cases. It expresses in a function that calls itself. Recursive functions are used in many efficient programming techniques like dynamic programming language(DSL) or divide and conquer algorithms. In dynamic programming, for both top-down as well as bottom-up approaches, recursion is vital for performance. In divide and conquer algorithms, we divide a problem into smaller sub-problems that are easier to solve. The output is then built back up to the top. Recursion has a similar process, which is why it is used to implement such algorithms. In its essence, recursion is the process of breaking down a problem into many smaller problems, these smaller problems are further broken down until the problem left is trivial. The solution is then built back up piece by piece. Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30289, "s": 30261, "text": "\n10 May, 2020" }, { "code": null, "e": 30877, "s": 30289, "text": "Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. Recursion is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again and this technique is known as recursion. Since the loops increase the memory we use the recursion. The recursive function uses the concept of recursion to perform iterative tasks they call themselves, again and again, which acts as a loop. These kinds of functions need a stopping condition so that they can stop looping continuously." }, { "code": null, "e": 31137, "s": 30877, "text": "Recursive functions call themselves. They break down the problem into smaller components. The function() calls itself within the original function() on each of the smaller components. After this, the results will be put together to solve the original problem." }, { "code": null, "e": 31177, "s": 31137, "text": "Example: Factorial using Recursion in R" }, { "code": "rec_fac <- function(x){ if(x==0 || x==1) { return(1) } else { return(x*rec_fac(x-1)) }}", "e": 31300, "s": 31177, "text": null }, { "code": null, "e": 31308, "s": 31300, "text": "Output:" }, { "code": null, "e": 31317, "s": 31308, "text": "[1] 120\n" }, { "code": null, "e": 31641, "s": 31317, "text": "Here, rec_fac(5) calls rec_fac(4), which then calls rec_fac(3), and so on until the input argument x, has reached 1. The function returns 1 and is destroyed. The return value is multiplied with argument value and returned. This process continues until the first function call returns its output, giving us the final result." }, { "code": null, "e": 31834, "s": 31641, "text": "Example: Sum of Series Using RecursionRecursion in R is most useful for finding the sum of self-repeating series. In this example, we will find the sum of squares of a given series of numbers." }, { "code": null, "e": 31853, "s": 31834, "text": "Sum = 12+22+...+N2" }, { "code": null, "e": 31862, "s": 31853, "text": "Example:" }, { "code": "sum_series <- function(vec){ if(length(vec)<=1) { return(vec^2) } else { return(vec[1]^2+sum_series(vec[-1])) }}series <- c(1:10)sum_series(series)", "e": 32042, "s": 31862, "text": null }, { "code": null, "e": 32050, "s": 32042, "text": "Output:" }, { "code": null, "e": 32059, "s": 32050, "text": "[1] 385\n" }, { "code": null, "e": 32136, "s": 32059, "text": "The use of recursion, often, makes the code shorter and it also looks clean." }, { "code": null, "e": 32177, "s": 32136, "text": "It is a simple solution for a few cases." }, { "code": null, "e": 32223, "s": 32177, "text": "It expresses in a function that calls itself." }, { "code": null, "e": 32366, "s": 32223, "text": "Recursive functions are used in many efficient programming techniques like dynamic programming language(DSL) or divide and conquer algorithms." }, { "code": null, "e": 32477, "s": 32366, "text": "In dynamic programming, for both top-down as well as bottom-up approaches, recursion is vital for performance." }, { "code": null, "e": 32715, "s": 32477, "text": "In divide and conquer algorithms, we divide a problem into smaller sub-problems that are easier to solve. The output is then built back up to the top. Recursion has a similar process, which is why it is used to implement such algorithms." }, { "code": null, "e": 32944, "s": 32715, "text": "In its essence, recursion is the process of breaking down a problem into many smaller problems, these smaller problems are further broken down until the problem left is trivial. The solution is then built back up piece by piece." }, { "code": null, "e": 32951, "s": 32944, "text": "Picked" }, { "code": null, "e": 32962, "s": 32951, "text": "R Language" }, { "code": null, "e": 33060, "s": 32962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33105, "s": 33060, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 33163, "s": 33105, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 33215, "s": 33163, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 33247, "s": 33215, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 33310, "s": 33247, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 33354, "s": 33310, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 33406, "s": 33354, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 33471, "s": 33406, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 33506, "s": 33471, "text": "Group by function in R using Dplyr" } ]
Unbounded Knapsack (Repetition of items allowed) - GeeksforGeeks
20 May, 2021 Given a knapsack weight W and a set of n items with certain value vali and weight wti, we need to calculate the maximum amount that could make up this quantity exactly. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item.Examples: Input : W = 100 val[] = {1, 30} wt[] = {1, 50} Output : 100 There are many ways to fill knapsack. 1) 2 instances of 50 unit weight item. 2) 100 instances of 1 unit weight item. 3) 1 instance of 50 unit weight item and 50 instances of 1 unit weight items. We get maximum value with option 2. Input : W = 8 val[] = {10, 40, 50, 70} wt[] = {1, 3, 4, 5} Output : 110 We get maximum value with one unit of weight 5 and one unit of weight 3. Its an unbounded knapsack problem as we can use 1 or more instances of any resource. A simple 1D array, say dp[W+1] can be used such that dp[i] stores the maximum value which can achieved using all items and i capacity of knapsack. Note that we use 1D array here which is different from classical knapsack where we used 2D array. Here number of items never changes. We always have all items available.We can recursively compute dp[] using below formula dp[i] = 0 dp[i] = max(dp[i], dp[i-wt[j]] + val[j] where j varies from 0 to n-1 such that: wt[j] <= i result = d[W] Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to find maximum achievable value// with a knapsack of weight W and multiple// instances allowed.#include<bits/stdc++.h>using namespace std; // Returns the maximum value with knapsack of// W capacityint unboundedKnapsack(int W, int n, int val[], int wt[]){ // dp[i] is going to store maximum value // with knapsack capacity i. int dp[W+1]; memset(dp, 0, sizeof dp); // Fill dp[] using above recursive formula for (int i=0; i<=W; i++) for (int j=0; j<n; j++) if (wt[j] <= i) dp[i] = max(dp[i], dp[i-wt[j]] + val[j]); return dp[W];} // Driver programint main(){ int W = 100; int val[] = {10, 30, 20}; int wt[] = {5, 10, 15}; int n = sizeof(val)/sizeof(val[0]); cout << unboundedKnapsack(W, n, val, wt); return 0;} // Java program to find maximum achievable// value with a knapsack of weight W and// multiple instances allowed.public class UboundedKnapsack{ private static int max(int i, int j) { return (i > j) ? i : j; } // Returns the maximum value with knapsack // of W capacity private static int unboundedKnapsack(int W, int n, int[] val, int[] wt) { // dp[i] is going to store maximum value // with knapsack capacity i. int dp[] = new int[W + 1]; // Fill dp[] using above recursive formula for(int i = 0; i <= W; i++){ for(int j = 0; j < n; j++){ if(wt[j] <= i){ dp[i] = max(dp[i], dp[i - wt[j]] + val[j]); } } } return dp[W]; } // Driver program public static void main(String[] args) { int W = 100; int val[] = {10, 30, 20}; int wt[] = {5, 10, 15}; int n = val.length; System.out.println(unboundedKnapsack(W, n, val, wt)); }}// This code is contributed by Aditya Kumar # Python3 program to find maximum# achievable value with a knapsack# of weight W and multiple instances allowed. # Returns the maximum value# with knapsack of W capacitydef unboundedKnapsack(W, n, val, wt): # dp[i] is going to store maximum # value with knapsack capacity i. dp = [0 for i in range(W + 1)] ans = 0 # Fill dp[] using above recursive formula for i in range(W + 1): for j in range(n): if (wt[j] <= i): dp[i] = max(dp[i], dp[i - wt[j]] + val[j]) return dp[W] # Driver programW = 100val = [10, 30, 20]wt = [5, 10, 15]n = len(val) print(unboundedKnapsack(W, n, val, wt)) # This code is contributed by Anant Agarwal. // C# program to find maximum achievable// value with a knapsack of weight W and// multiple instances allowed.using System; class UboundedKnapsack { private static int max(int i, int j) { return (i > j) ? i : j; } // Returns the maximum value // with knapsack of W capacity private static int unboundedKnapsack(int W, int n, int []val, int []wt) { // dp[i] is going to store maximum value // with knapsack capacity i. int []dp = new int[W + 1]; // Fill dp[] using above recursive formula for(int i = 0; i <= W; i++){ for(int j = 0; j < n; j++){ if(wt[j] <= i){ dp[i] = Math.Max(dp[i], dp[i - wt[j]] + val[j]); } } } return dp[W]; } // Driver program public static void Main() { int W = 100; int []val = {10, 30, 20}; int []wt = {5, 10, 15}; int n = val.Length; Console.WriteLine(unboundedKnapsack(W, n, val, wt)); }} // This code is contributed by vt_m. <?php// PHP program to find maximum// achievable value with a// knapsack of weight W and// multiple instances allowed. // Returns the maximum value// with knapsack of W capacityfunction unboundedKnapsack($W, $n, $val, $wt){ // dp[i] is going to store // maximum value with // knapsack capacity i. for($i = 0; $i <= $W; $i++) $dp[$i] = 0; $ans = 0; // Fill dp[] using above // recursive formula for ($i = 0; $i <= $W; $i++) for ($j = 0; $j < $n; $j++) if ($wt[$j] <= $i) $dp[$i] = max($dp[$i], $dp[$i - $wt[$j]] + $val[$j]); return $dp[$W];} // Driver Code$W = 100;$val = array(10, 30, 20);$wt = array(5, 10, 15);$n = count($val); //sizeof($val)/sizeof($val[0]); echo unboundedKnapsack($W, $n, $val, $wt); // This code is contributed// by shiv_bhakt?> <script> // Javascript program to find maximum achievable // value with a knapsack of weight W and // multiple instances allowed. function max(i, j) { return (i > j) ? i : j; } // Returns the maximum value // with knapsack of W capacity function unboundedKnapsack(W, n, val, wt) { // dp[i] is going to store maximum value // with knapsack capacity i. let dp = new Array(W + 1); dp.fill(0); // Fill dp[] using above recursive formula for(let i = 0; i <= W; i++){ for(let j = 0; j < n; j++){ if(wt[j] <= i){ dp[i] = Math.max(dp[i], dp[i - wt[j]] + val[j]); } } } return dp[W]; } let W = 100; let val = [10, 30, 20]; let wt = [5, 10, 15]; let n = val.length; document.write(unboundedKnapsack(W, n, val, wt)); </script> Output: 300 This article is compiled using inputs from Shubham Gupta, Shubham Joshi and Ashish kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Vishal_Khoda dStudent s_madaan25 mishrakush1999 divyesh072019 Amazon Google knapsack Dynamic Programming Amazon Google Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1 Maximum size square sub-matrix with all 1s
[ { "code": null, "e": 25779, "s": 25751, "text": "\n20 May, 2021" }, { "code": null, "e": 26078, "s": 25779, "text": "Given a knapsack weight W and a set of n items with certain value vali and weight wti, we need to calculate the maximum amount that could make up this quantity exactly. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item.Examples: " }, { "code": null, "e": 26556, "s": 26078, "text": "Input : W = 100\n val[] = {1, 30}\n wt[] = {1, 50}\nOutput : 100\nThere are many ways to fill knapsack.\n1) 2 instances of 50 unit weight item.\n2) 100 instances of 1 unit weight item.\n3) 1 instance of 50 unit weight item and 50\n instances of 1 unit weight items.\nWe get maximum value with option 2.\n\nInput : W = 8\n val[] = {10, 40, 50, 70}\n wt[] = {1, 3, 4, 5} \nOutput : 110 \nWe get maximum value with one unit of\nweight 5 and one unit of weight 3." }, { "code": null, "e": 27009, "s": 26556, "text": "Its an unbounded knapsack problem as we can use 1 or more instances of any resource. A simple 1D array, say dp[W+1] can be used such that dp[i] stores the maximum value which can achieved using all items and i capacity of knapsack. Note that we use 1D array here which is different from classical knapsack where we used 2D array. Here number of items never changes. We always have all items available.We can recursively compute dp[] using below formula" }, { "code": null, "e": 27184, "s": 27009, "text": "dp[i] = 0\ndp[i] = max(dp[i], dp[i-wt[j]] + val[j] \n where j varies from 0 \n to n-1 such that:\n wt[j] <= i\n\nresult = d[W]" }, { "code": null, "e": 27228, "s": 27184, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 27232, "s": 27228, "text": "C++" }, { "code": null, "e": 27237, "s": 27232, "text": "Java" }, { "code": null, "e": 27245, "s": 27237, "text": "Python3" }, { "code": null, "e": 27248, "s": 27245, "text": "C#" }, { "code": null, "e": 27252, "s": 27248, "text": "PHP" }, { "code": null, "e": 27263, "s": 27252, "text": "Javascript" }, { "code": "// C++ program to find maximum achievable value// with a knapsack of weight W and multiple// instances allowed.#include<bits/stdc++.h>using namespace std; // Returns the maximum value with knapsack of// W capacityint unboundedKnapsack(int W, int n, int val[], int wt[]){ // dp[i] is going to store maximum value // with knapsack capacity i. int dp[W+1]; memset(dp, 0, sizeof dp); // Fill dp[] using above recursive formula for (int i=0; i<=W; i++) for (int j=0; j<n; j++) if (wt[j] <= i) dp[i] = max(dp[i], dp[i-wt[j]] + val[j]); return dp[W];} // Driver programint main(){ int W = 100; int val[] = {10, 30, 20}; int wt[] = {5, 10, 15}; int n = sizeof(val)/sizeof(val[0]); cout << unboundedKnapsack(W, n, val, wt); return 0;}", "e": 28078, "s": 27263, "text": null }, { "code": "// Java program to find maximum achievable// value with a knapsack of weight W and// multiple instances allowed.public class UboundedKnapsack{ private static int max(int i, int j) { return (i > j) ? i : j; } // Returns the maximum value with knapsack // of W capacity private static int unboundedKnapsack(int W, int n, int[] val, int[] wt) { // dp[i] is going to store maximum value // with knapsack capacity i. int dp[] = new int[W + 1]; // Fill dp[] using above recursive formula for(int i = 0; i <= W; i++){ for(int j = 0; j < n; j++){ if(wt[j] <= i){ dp[i] = max(dp[i], dp[i - wt[j]] + val[j]); } } } return dp[W]; } // Driver program public static void main(String[] args) { int W = 100; int val[] = {10, 30, 20}; int wt[] = {5, 10, 15}; int n = val.length; System.out.println(unboundedKnapsack(W, n, val, wt)); }}// This code is contributed by Aditya Kumar", "e": 29234, "s": 28078, "text": null }, { "code": "# Python3 program to find maximum# achievable value with a knapsack# of weight W and multiple instances allowed. # Returns the maximum value# with knapsack of W capacitydef unboundedKnapsack(W, n, val, wt): # dp[i] is going to store maximum # value with knapsack capacity i. dp = [0 for i in range(W + 1)] ans = 0 # Fill dp[] using above recursive formula for i in range(W + 1): for j in range(n): if (wt[j] <= i): dp[i] = max(dp[i], dp[i - wt[j]] + val[j]) return dp[W] # Driver programW = 100val = [10, 30, 20]wt = [5, 10, 15]n = len(val) print(unboundedKnapsack(W, n, val, wt)) # This code is contributed by Anant Agarwal.", "e": 29918, "s": 29234, "text": null }, { "code": "// C# program to find maximum achievable// value with a knapsack of weight W and// multiple instances allowed.using System; class UboundedKnapsack { private static int max(int i, int j) { return (i > j) ? i : j; } // Returns the maximum value // with knapsack of W capacity private static int unboundedKnapsack(int W, int n, int []val, int []wt) { // dp[i] is going to store maximum value // with knapsack capacity i. int []dp = new int[W + 1]; // Fill dp[] using above recursive formula for(int i = 0; i <= W; i++){ for(int j = 0; j < n; j++){ if(wt[j] <= i){ dp[i] = Math.Max(dp[i], dp[i - wt[j]] + val[j]); } } } return dp[W]; } // Driver program public static void Main() { int W = 100; int []val = {10, 30, 20}; int []wt = {5, 10, 15}; int n = val.Length; Console.WriteLine(unboundedKnapsack(W, n, val, wt)); }} // This code is contributed by vt_m.", "e": 31075, "s": 29918, "text": null }, { "code": "<?php// PHP program to find maximum// achievable value with a// knapsack of weight W and// multiple instances allowed. // Returns the maximum value// with knapsack of W capacityfunction unboundedKnapsack($W, $n, $val, $wt){ // dp[i] is going to store // maximum value with // knapsack capacity i. for($i = 0; $i <= $W; $i++) $dp[$i] = 0; $ans = 0; // Fill dp[] using above // recursive formula for ($i = 0; $i <= $W; $i++) for ($j = 0; $j < $n; $j++) if ($wt[$j] <= $i) $dp[$i] = max($dp[$i], $dp[$i - $wt[$j]] + $val[$j]); return $dp[$W];} // Driver Code$W = 100;$val = array(10, 30, 20);$wt = array(5, 10, 15);$n = count($val); //sizeof($val)/sizeof($val[0]); echo unboundedKnapsack($W, $n, $val, $wt); // This code is contributed// by shiv_bhakt?>", "e": 31995, "s": 31075, "text": null }, { "code": "<script> // Javascript program to find maximum achievable // value with a knapsack of weight W and // multiple instances allowed. function max(i, j) { return (i > j) ? i : j; } // Returns the maximum value // with knapsack of W capacity function unboundedKnapsack(W, n, val, wt) { // dp[i] is going to store maximum value // with knapsack capacity i. let dp = new Array(W + 1); dp.fill(0); // Fill dp[] using above recursive formula for(let i = 0; i <= W; i++){ for(let j = 0; j < n; j++){ if(wt[j] <= i){ dp[i] = Math.max(dp[i], dp[i - wt[j]] + val[j]); } } } return dp[W]; } let W = 100; let val = [10, 30, 20]; let wt = [5, 10, 15]; let n = val.length; document.write(unboundedKnapsack(W, n, val, wt)); </script>", "e": 32937, "s": 31995, "text": null }, { "code": null, "e": 32946, "s": 32937, "text": "Output: " }, { "code": null, "e": 32950, "s": 32946, "text": "300" }, { "code": null, "e": 33416, "s": 32950, "text": "This article is compiled using inputs from Shubham Gupta, Shubham Joshi and Ashish kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33421, "s": 33416, "text": "vt_m" }, { "code": null, "e": 33434, "s": 33421, "text": "Vishal_Khoda" }, { "code": null, "e": 33443, "s": 33434, "text": "dStudent" }, { "code": null, "e": 33454, "s": 33443, "text": "s_madaan25" }, { "code": null, "e": 33469, "s": 33454, "text": "mishrakush1999" }, { "code": null, "e": 33483, "s": 33469, "text": "divyesh072019" }, { "code": null, "e": 33490, "s": 33483, "text": "Amazon" }, { "code": null, "e": 33497, "s": 33490, "text": "Google" }, { "code": null, "e": 33506, "s": 33497, "text": "knapsack" }, { "code": null, "e": 33526, "s": 33506, "text": "Dynamic Programming" }, { "code": null, "e": 33533, "s": 33526, "text": "Amazon" }, { "code": null, "e": 33540, "s": 33533, "text": "Google" }, { "code": null, "e": 33560, "s": 33540, "text": "Dynamic Programming" }, { "code": null, "e": 33658, "s": 33560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33689, "s": 33658, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 33722, "s": 33689, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 33749, "s": 33722, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 33784, "s": 33749, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 33822, "s": 33784, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 33890, "s": 33822, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 33911, "s": 33890, "text": "Edit Distance | DP-5" }, { "code": null, "e": 33933, "s": 33911, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33996, "s": 33933, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
How to execute AngularJS controller function on page load ? - GeeksforGeeks
18 Nov, 2019 The task is to execute/call a JS function on page load using AngularJS. This function can be used to perform initialization. Calling a function or initializing a single value on page load in AngularJS is quite easy. AngularJS provides us with a dedicated directive for this specific task. It’s the ng-init directive.Syntax: <element ng-init="function()"> Contents... </element> Example 1: In this example we will call a function to initialize a variable on page load. <html ng-app="myApp"><head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body ng-controller="MyController"> <!-- calling the firstFunction to initialize gfg variable --> <center ng-init="firstFunction(this)"> <!-- gfg variable with no value initially --> <h1 style="color: green;">{{gfg}}</h1> </center></body> <script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { // Function to be called on page load $scope.firstFunction = function($scope) { // We need $scope argument as we are // altering the variables defined in // the $scope $scope.gfg = "GeeksForGeeks" } }]);</script></html> Output: The function is called on page load and the value of variable gfg is set to GeeksForGeeks. Example 2: In this example we will assign an object to the variable gfg and use it. <html ng-app="myApp"><head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body ng-controller="MyController"> <!-- Calling the firstFunction to initialize gfg variable --> <center ng-init="firstFunction(this)"> <!-- gfg variable as an object --> <h1 style="color: green;">{{gfg.name}}</h1> <h3 style="color: green;">{{gfg.location}}</h3> </center></body> <script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { // Function to be called on page load $scope.firstFunction = function($scope) { // We need $scope argument as we are // altering the variables defined in // the $scope // Assigning an object to the gfg variable $scope.gfg = { name: "GeeksForGeeks", location: "India" } } }]);</script> </html> Output: The variable “gfg” is initialized successfully. Example 3: In this example we will directly initialize a variable from ng-init directive. <html ng-app="myApp"><head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body ng-controller="MyController"> <!-- initializing the gfg variable to 'GeeksForGeeks' --> <center ng-init="gfg='GeeksForGeeks'"> <h1 style="color: green;">{{gfg}}</h1> </center></body> <script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { }]);</script> </html> Output: The variable gfg is assigned the value “GeeksForGeeks” on page load. AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component What is AOT and JIT Compiler in Angular ? How to bundle an Angular app for production? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25670, "s": 25642, "text": "\n18 Nov, 2019" }, { "code": null, "e": 25795, "s": 25670, "text": "The task is to execute/call a JS function on page load using AngularJS. This function can be used to perform initialization." }, { "code": null, "e": 25994, "s": 25795, "text": "Calling a function or initializing a single value on page load in AngularJS is quite easy. AngularJS provides us with a dedicated directive for this specific task. It’s the ng-init directive.Syntax:" }, { "code": null, "e": 26049, "s": 25994, "text": "<element ng-init=\"function()\"> Contents... </element>\n" }, { "code": null, "e": 26139, "s": 26049, "text": "Example 1: In this example we will call a function to initialize a variable on page load." }, { "code": "<html ng-app=\"myApp\"><head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <!-- calling the firstFunction to initialize gfg variable --> <center ng-init=\"firstFunction(this)\"> <!-- gfg variable with no value initially --> <h1 style=\"color: green;\">{{gfg}}</h1> </center></body> <script type=\"text/javascript\"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { // Function to be called on page load $scope.firstFunction = function($scope) { // We need $scope argument as we are // altering the variables defined in // the $scope $scope.gfg = \"GeeksForGeeks\" } }]);</script></html>", "e": 26985, "s": 26139, "text": null }, { "code": null, "e": 27084, "s": 26985, "text": "Output: The function is called on page load and the value of variable gfg is set to GeeksForGeeks." }, { "code": null, "e": 27168, "s": 27084, "text": "Example 2: In this example we will assign an object to the variable gfg and use it." }, { "code": "<html ng-app=\"myApp\"><head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <!-- Calling the firstFunction to initialize gfg variable --> <center ng-init=\"firstFunction(this)\"> <!-- gfg variable as an object --> <h1 style=\"color: green;\">{{gfg.name}}</h1> <h3 style=\"color: green;\">{{gfg.location}}</h3> </center></body> <script type=\"text/javascript\"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { // Function to be called on page load $scope.firstFunction = function($scope) { // We need $scope argument as we are // altering the variables defined in // the $scope // Assigning an object to the gfg variable $scope.gfg = { name: \"GeeksForGeeks\", location: \"India\" } } }]);</script> </html>", "e": 28191, "s": 27168, "text": null }, { "code": null, "e": 28247, "s": 28191, "text": "Output: The variable “gfg” is initialized successfully." }, { "code": null, "e": 28337, "s": 28247, "text": "Example 3: In this example we will directly initialize a variable from ng-init directive." }, { "code": "<html ng-app=\"myApp\"><head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body ng-controller=\"MyController\"> <!-- initializing the gfg variable to 'GeeksForGeeks' --> <center ng-init=\"gfg='GeeksForGeeks'\"> <h1 style=\"color: green;\">{{gfg}}</h1> </center></body> <script type=\"text/javascript\"> var myApp = angular.module('myApp', []); myApp.controller('MyController', ['$scope', function($scope) { }]);</script> </html>", "e": 28860, "s": 28337, "text": null }, { "code": null, "e": 28937, "s": 28860, "text": "Output: The variable gfg is assigned the value “GeeksForGeeks” on page load." }, { "code": null, "e": 28952, "s": 28937, "text": "AngularJS-Misc" }, { "code": null, "e": 28959, "s": 28952, "text": "Picked" }, { "code": null, "e": 28969, "s": 28959, "text": "AngularJS" }, { "code": null, "e": 28986, "s": 28969, "text": "Web Technologies" }, { "code": null, "e": 29084, "s": 28986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29119, "s": 29084, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29150, "s": 29119, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 29185, "s": 29150, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29227, "s": 29185, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 29272, "s": 29227, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 29312, "s": 29272, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29345, "s": 29312, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29390, "s": 29345, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29433, "s": 29390, "text": "How to fetch data from an API in ReactJS ?" } ]
Calculate Trace of a Matrix in R Programming – tr() Function
19 Jun, 2020 tr() function in R Language is used to calculate the trace of a matrix. Trace of a matrix is the sum of the values on the main diagonal(upper left to lower right) of the matrix. Syntax: tr(x) Parameters:x: Matrix Example 1: # R program to calculate# trace of a matrix # Loading librarylibrary(psych) # Creating a matrixA = matrix( c(6, 1, 1, 4, -2, 5, 2, 8, 7), nrow = 3, ncol = 3, byrow = TRUE ) A # Calling tr() functioncat("Trace of A:\n") tr(A) Output: [, 1] [, 2] [, 3] [1, ] 6 1 1 [2, ] 4 -2 5 [3, ] 2 8 7 Trace of A: [1] 11 Example 2: # R program to calculate# trace of a matrix # Loading librarylibrary(psych) # Creating a matrixA = matrix(c(1:9), 3, 3) A # Calling tr() functioncat("Trace of A:\n") tr(A) Output: [, 1] [, 2] [, 3] [1, ] 1 4 7 [2, ] 2 5 8 [3, ] 3 6 9 Trace of A: [1] 15 R Matrix-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jun, 2020" }, { "code": null, "e": 206, "s": 28, "text": "tr() function in R Language is used to calculate the trace of a matrix. Trace of a matrix is the sum of the values on the main diagonal(upper left to lower right) of the matrix." }, { "code": null, "e": 220, "s": 206, "text": "Syntax: tr(x)" }, { "code": null, "e": 241, "s": 220, "text": "Parameters:x: Matrix" }, { "code": null, "e": 252, "s": 241, "text": "Example 1:" }, { "code": "# R program to calculate# trace of a matrix # Loading librarylibrary(psych) # Creating a matrixA = matrix( c(6, 1, 1, 4, -2, 5, 2, 8, 7), nrow = 3, ncol = 3, byrow = TRUE ) A # Calling tr() functioncat(\"Trace of A:\\n\") tr(A)", "e": 527, "s": 252, "text": null }, { "code": null, "e": 535, "s": 527, "text": "Output:" }, { "code": null, "e": 641, "s": 535, "text": " [, 1] [, 2] [, 3]\n[1, ] 6 1 1\n[2, ] 4 -2 5\n[3, ] 2 8 7\nTrace of A:\n[1] 11\n" }, { "code": null, "e": 652, "s": 641, "text": "Example 2:" }, { "code": "# R program to calculate# trace of a matrix # Loading librarylibrary(psych) # Creating a matrixA = matrix(c(1:9), 3, 3) A # Calling tr() functioncat(\"Trace of A:\\n\") tr(A)", "e": 829, "s": 652, "text": null }, { "code": null, "e": 837, "s": 829, "text": "Output:" }, { "code": null, "e": 943, "s": 837, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\nTrace of A:\n[1] 15\n" }, { "code": null, "e": 961, "s": 943, "text": "R Matrix-Function" }, { "code": null, "e": 972, "s": 961, "text": "R Language" } ]
Python unittest – assertIn() function
29 Aug, 2020 assertIn() in Python is a unittest library function that is used in unit testing to check whether a string is contained in other or not. This function will take three string parameters as input and return a boolean value depending upon the assert condition. If the key is contained in container string it will return true else it returns false. Syntax: assertIn(key, container, message) Parameters: assertIn() accept three parameters which are listed below with explanation: key: a string whose presence is checked in the given container container: a string in which key string is searched message: a string sentence as a message which got displayed when the test case got failed. Listed below are two different examples illustrating the positive and negative test case for given assert function: Example 1: Negative Test case Python3 # test suiteimport unittest class TestStringMethods(unittest.TestCase): # test function to test whether key is present in container def test_negative(self): key = "gfg" container = "geeksforgeeks" # error message in case if test case got failed message = "key is not in container." # assertIn() to check if key is in container self.assertIn(key, container, message) if __name__ == '__main__': unittest.main() Output: F ====================================================================== FAIL: test_negative (__main__.TestStringMethods) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/e920f2cd9195a3fd72bd531f7f101754.py", line 12, in test_negative self.assertIn(key, container, message) AssertionError: 'gfg' not found in 'geeksforgeeks' : key is not in container. ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1) Example 2: Positive Test case Python3 # test suiteimport unittest class TestStringMethods(unittest.TestCase): # test function to test whether key is present in container def test_positive(self): key = "geeks" container = "geeksforgeeks" # error message in case if test case got failed message = "key is not in container." # assertIn() to check if key is in container self.assertIn(key, container, message) if __name__ == '__main__': unittest.main() Output: . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Reference: https://docs.python.org/3/library/unittest.html Python unittest-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 373, "s": 28, "text": "assertIn() in Python is a unittest library function that is used in unit testing to check whether a string is contained in other or not. This function will take three string parameters as input and return a boolean value depending upon the assert condition. If the key is contained in container string it will return true else it returns false." }, { "code": null, "e": 415, "s": 373, "text": "Syntax: assertIn(key, container, message)" }, { "code": null, "e": 503, "s": 415, "text": "Parameters: assertIn() accept three parameters which are listed below with explanation:" }, { "code": null, "e": 567, "s": 503, "text": "key: a string whose presence is checked in the given container" }, { "code": null, "e": 619, "s": 567, "text": "container: a string in which key string is searched" }, { "code": null, "e": 710, "s": 619, "text": "message: a string sentence as a message which got displayed when the test case got failed." }, { "code": null, "e": 826, "s": 710, "text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:" }, { "code": null, "e": 856, "s": 826, "text": "Example 1: Negative Test case" }, { "code": null, "e": 864, "s": 856, "text": "Python3" }, { "code": "# test suiteimport unittest class TestStringMethods(unittest.TestCase): # test function to test whether key is present in container def test_negative(self): key = \"gfg\" container = \"geeksforgeeks\" # error message in case if test case got failed message = \"key is not in container.\" # assertIn() to check if key is in container self.assertIn(key, container, message) if __name__ == '__main__': unittest.main()", "e": 1326, "s": 864, "text": null }, { "code": null, "e": 1334, "s": 1326, "text": "Output:" }, { "code": null, "e": 1876, "s": 1334, "text": "F\n======================================================================\nFAIL: test_negative (__main__.TestStringMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/home/e920f2cd9195a3fd72bd531f7f101754.py\", line 12, in test_negative\n self.assertIn(key, container, message)\nAssertionError: 'gfg' not found in 'geeksforgeeks' : key is not in container.\n\n----------------------------------------------------------------------\nRan 1 test in 0.001s\n\nFAILED (failures=1)\n" }, { "code": null, "e": 1906, "s": 1876, "text": "Example 2: Positive Test case" }, { "code": null, "e": 1914, "s": 1906, "text": "Python3" }, { "code": "# test suiteimport unittest class TestStringMethods(unittest.TestCase): # test function to test whether key is present in container def test_positive(self): key = \"geeks\" container = \"geeksforgeeks\" # error message in case if test case got failed message = \"key is not in container.\" # assertIn() to check if key is in container self.assertIn(key, container, message) if __name__ == '__main__': unittest.main()", "e": 2382, "s": 1914, "text": null }, { "code": null, "e": 2390, "s": 2382, "text": "Output:" }, { "code": null, "e": 2489, "s": 2390, "text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n" }, { "code": null, "e": 2548, "s": 2489, "text": "Reference: https://docs.python.org/3/library/unittest.html" }, { "code": null, "e": 2572, "s": 2548, "text": "Python unittest-library" }, { "code": null, "e": 2579, "s": 2572, "text": "Python" } ]
Implementation of Diffie-Hellman Algorithm
09 Jun, 2022 Background Elliptic Curve Cryptography (ECC) is an approach to public-key cryptography, based on the algebraic structure of elliptic curves over finite fields. ECC requires a smaller key as compared to non-ECC cryptography to provide equivalent security (a 256-bit ECC security has equivalent security attained by 3072-bit RSA cryptography). For a better understanding of Elliptic Curve Cryptography, it is very important to understand the basics of the Elliptic Curve. An elliptic curve is a planar algebraic curve defined by an equation of the form Where ‘a’ is the co-efficient of x and ‘b’ is the constant of the equation The curve is non-singular; that is, its graph has no cusps or self-intersections (when the characteristic of the Co-efficient field is equal to 2 or 3). In general, an elliptic curve looks like as shown below. Elliptic curves can intersect almost 3 points when a straight line is drawn intersecting the curve. As we can see, the elliptic curve is symmetric about the x-axis. This property plays a key role in the algorithm. Diffie-Hellman algorithm The Diffie-Hellman algorithm is being used to establish a shared secret that can be used for secret communications while exchanging data over a public network using the elliptic curve to generate points and get the secret key using the parameters. For the sake of simplicity and practical implementation of the algorithm, we will consider only 4 variables, one prime P and G (a primitive root of P) and two private values a and b. P and G are both publicly available numbers. Users (say Alice and Bob) pick private values a and b and they generate a key and exchange it publicly. The opposite person receives the key and that generates a secret key, after which they have the same secret key to encrypt. Step by Step Explanation Key generated = Key generated = Generated Secret Key = Generated Secret Key = Algebraically, it can be shown that Example: Step 1: Alice and Bob get public numbers P = 23, G = 9 Step 2: Alice selected a private key a = 4 and Bob selected a private key b = 3 Step 3: Alice and Bob compute public values Alice: x =(9^4 mod 23) = (6561 mod 23) = 6 Bob: y = (9^3 mod 23) = (729 mod 23) = 16 Step 4: Alice and Bob exchange public numbers Step 5: Alice receives public key y =16 and Bob receives public key x = 6 Step 6: Alice and Bob compute symmetric keys Alice: ka = y^a mod p = 65536 mod 23 = 9 Bob: kb = x^b mod p = 216 mod 23 = 9 Step 7: 9 is the shared secret. Implementation: C Java Python3 Javascript C++ /* This program calculates the Key for two personsusing the Diffie-Hellman Key exchange algorithm */#include<stdio.h>#include<math.h> // Power function to return value of a ^ b mod Plong long int power(long long int a, long long int b, long long int P){ if (b == 1) return a; else return (((long long int)pow(a, b)) % P);} //Driver programint main(){ long long int P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the // public keys G and P P = 23; // A prime number P is taken printf("The value of P : %lld\n", P); G = 9; // A primitive root for P, G is taken printf("The value of G : %lld\n\n", G); // Alice will choose the private key a a = 4; // a is the chosen private key printf("The private key a for Alice : %lld\n", a); x = power(G, a, P); // gets the generated key // Bob will choose the private key b b = 3; // b is the chosen private key printf("The private key b for Bob : %lld\n\n", b); y = power(G, b, P); // gets the generated key // Generating the secret key after the exchange // of keys ka = power(y, a, P); // Secret key for Alice kb = power(x, b, P); // Secret key for Bob printf("Secret key for the Alice is : %lld\n", ka); printf("Secret Key for the Bob is : %lld\n", kb); return 0;} // This program calculates the Key for two persons// using the Diffie-Hellman Key exchange algorithmclass GFG{ // Power function to return value of a ^ b mod Pprivate static long power(long a, long b, long p){ if (b == 1) return a; else return (((long)Math.pow(a, b)) % p);} // Driver codepublic static void main(String[] args){ long P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the // public keys G and P // A prime number P is taken P = 23; System.out.println("The value of P:" + P); // A primitive root for P, G is taken G = 9; System.out.println("The value of G:" + G); // Alice will choose the private key a // a is the chosen private key a = 4; System.out.println("The private key a for Alice:" + a); // Gets the generated key x = power(G, a, P); // Bob will choose the private key b // b is the chosen private key b = 3; System.out.println("The private key b for Bob:" + b); // Gets the generated key y = power(G, b, P); // Generating the secret key after the exchange // of keys ka = power(y, a, P); // Secret key for Alice kb = power(x, b, P); // Secret key for Bob System.out.println("Secret key for the Alice is:" + ka); System.out.println("Secret key for the Bob is:" + kb);}} // This code is contributed by raghav14 from random import randint if __name__ == '__main__': # Both the persons will be agreed upon the # public keys G and P # A prime number P is taken P = 23 # A primitive root for P, G is taken G = 9 print('The Value of P is :%d'%(P)) print('The Value of G is :%d'%(G)) # Alice will choose the private key a a = 4 print('The Private Key a for Alice is :%d'%(a)) # gets the generated key x = int(pow(G,a,P)) # Bob will choose the private key b b = 3 print('The Private Key b for Bob is :%d'%(b)) # gets the generated key y = int(pow(G,b,P)) # Secret key for Alice ka = int(pow(y,a,P)) # Secret key for Bob kb = int(pow(x,b,P)) print('Secret key for the Alice is : %d'%(ka)) print('Secret Key for the Bob is : %d'%(kb)) <script> // This program calculates the Key for two persons// using the Diffie-Hellman Key exchange algorithm // Power function to return value of a ^ b mod Pfunction power(a, b, p){ if (b == 1) return a; else return((Math.pow(a, b)) % p);} // Driver codevar P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the// public keys G and P // A prime number P is takenP = 23;document.write("The value of P:" + P + "<br>"); // A primitive root for P, G is takenG = 9;document.write("The value of G:" + G + "<br>"); // Alice will choose the private key a// a is the chosen private keya = 4;document.write("The private key a for Alice:" + a + "<br>"); // Gets the generated keyx = power(G, a, P); // Bob will choose the private key b// b is the chosen private key b = 3;document.write("The private key b for Bob:" + b + "<br>"); // Gets the generated keyy = power(G, b, P); // Generating the secret key after the exchange// of keyska = power(y, a, P); // Secret key for Alicekb = power(x, b, P); // Secret key for Bob document.write("Secret key for the Alice is:" + ka + "<br>");document.write("Secret key for the Bob is:" + kb + "<br>"); // This code is contributed by Ankita saini </script> /* This program calculates the Key for two personsusing the Diffie-Hellman Key exchange algorithm using C++ */#include <cmath>#include <iostream>using namespace std; // Power function to return value of a ^ b mod Plong long int power(long long int a, long long int b, long long int P){ if (b == 1) return a; else return (((long long int)pow(a, b)) % P);} // Driver programint main(){ long long int P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the // public keys G and P P = 23; // A prime number P is taken cout << "The value of P : " << P << endl; G = 9; // A primitive root for P, G is taken cout << "The value of G : " << G << endl; // Alice will choose the private key a a = 4; // a is the chosen private key cout << "The private key a for Alice : " << a << endl; x = power(G, a, P); // gets the generated key // Bob will choose the private key b b = 3; // b is the chosen private key cout << "The private key b for Bob : " << b << endl; y = power(G, b, P); // gets the generated key // Generating the secret key after the exchange // of keys ka = power(y, a, P); // Secret key for Alice kb = power(x, b, P); // Secret key for Bob cout << "Secret key for the Alice is : " << ka << endl; cout << "Secret key for the Alice is : " << kb << endl; return 0;}// This code is contributed by Pranay Arora Output: The value of P : 23 The value of G : 9 The private key a for Alice : 4 The private key b for Bob : 3 Secret key for the Alice is : 9 Secret Key for the Bob is : 9 This article is contributed by Souvik Nandi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.GeeksforGeeks.org or mail your article to contribute@GeeksforGeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nalasivam ShJos raghav14 ankita_saini sooda367 arorapranay Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 65, "s": 54, "text": "Background" }, { "code": null, "e": 396, "s": 65, "text": "Elliptic Curve Cryptography (ECC) is an approach to public-key cryptography, based on the algebraic structure of elliptic curves over finite fields. ECC requires a smaller key as compared to non-ECC cryptography to provide equivalent security (a 256-bit ECC security has equivalent security attained by 3072-bit RSA cryptography)." }, { "code": null, "e": 605, "s": 396, "text": "For a better understanding of Elliptic Curve Cryptography, it is very important to understand the basics of the Elliptic Curve. An elliptic curve is a planar algebraic curve defined by an equation of the form" }, { "code": null, "e": 684, "s": 607, "text": "Where ‘a’ is the co-efficient of x and ‘b’ is the constant of the equation " }, { "code": null, "e": 838, "s": 684, "text": "The curve is non-singular; that is, its graph has no cusps or self-intersections (when the characteristic of the Co-efficient field is equal to 2 or 3). " }, { "code": null, "e": 1109, "s": 838, "text": "In general, an elliptic curve looks like as shown below. Elliptic curves can intersect almost 3 points when a straight line is drawn intersecting the curve. As we can see, the elliptic curve is symmetric about the x-axis. This property plays a key role in the algorithm." }, { "code": null, "e": 1134, "s": 1109, "text": "Diffie-Hellman algorithm" }, { "code": null, "e": 1384, "s": 1134, "text": "The Diffie-Hellman algorithm is being used to establish a shared secret that can be used for secret communications while exchanging data over a public network using the elliptic curve to generate points and get the secret key using the parameters. " }, { "code": null, "e": 1567, "s": 1384, "text": "For the sake of simplicity and practical implementation of the algorithm, we will consider only 4 variables, one prime P and G (a primitive root of P) and two private values a and b." }, { "code": null, "e": 1840, "s": 1567, "text": "P and G are both publicly available numbers. Users (say Alice and Bob) pick private values a and b and they generate a key and exchange it publicly. The opposite person receives the key and that generates a secret key, after which they have the same secret key to encrypt." }, { "code": null, "e": 1866, "s": 1840, "text": "Step by Step Explanation " }, { "code": null, "e": 1883, "s": 1866, "text": "Key generated = " }, { "code": null, "e": 1900, "s": 1883, "text": "Key generated = " }, { "code": null, "e": 1924, "s": 1900, "text": "Generated Secret Key = " }, { "code": null, "e": 1948, "s": 1924, "text": "Generated Secret Key = " }, { "code": null, "e": 1985, "s": 1948, "text": "Algebraically, it can be shown that " }, { "code": null, "e": 1995, "s": 1985, "text": "Example: " }, { "code": null, "e": 2591, "s": 1995, "text": "Step 1: Alice and Bob get public numbers P = 23, G = 9\n\nStep 2: Alice selected a private key a = 4 and\n Bob selected a private key b = 3\n\nStep 3: Alice and Bob compute public values\nAlice: x =(9^4 mod 23) = (6561 mod 23) = 6\n Bob: y = (9^3 mod 23) = (729 mod 23) = 16\n\nStep 4: Alice and Bob exchange public numbers\n\nStep 5: Alice receives public key y =16 and\n Bob receives public key x = 6\n\nStep 6: Alice and Bob compute symmetric keys\n Alice: ka = y^a mod p = 65536 mod 23 = 9\n Bob: kb = x^b mod p = 216 mod 23 = 9\n\nStep 7: 9 is the shared secret." }, { "code": null, "e": 2609, "s": 2591, "text": "Implementation: " }, { "code": null, "e": 2611, "s": 2609, "text": "C" }, { "code": null, "e": 2616, "s": 2611, "text": "Java" }, { "code": null, "e": 2624, "s": 2616, "text": "Python3" }, { "code": null, "e": 2635, "s": 2624, "text": "Javascript" }, { "code": null, "e": 2639, "s": 2635, "text": "C++" }, { "code": "/* This program calculates the Key for two personsusing the Diffie-Hellman Key exchange algorithm */#include<stdio.h>#include<math.h> // Power function to return value of a ^ b mod Plong long int power(long long int a, long long int b, long long int P){ if (b == 1) return a; else return (((long long int)pow(a, b)) % P);} //Driver programint main(){ long long int P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the // public keys G and P P = 23; // A prime number P is taken printf(\"The value of P : %lld\\n\", P); G = 9; // A primitive root for P, G is taken printf(\"The value of G : %lld\\n\\n\", G); // Alice will choose the private key a a = 4; // a is the chosen private key printf(\"The private key a for Alice : %lld\\n\", a); x = power(G, a, P); // gets the generated key // Bob will choose the private key b b = 3; // b is the chosen private key printf(\"The private key b for Bob : %lld\\n\\n\", b); y = power(G, b, P); // gets the generated key // Generating the secret key after the exchange // of keys ka = power(y, a, P); // Secret key for Alice kb = power(x, b, P); // Secret key for Bob printf(\"Secret key for the Alice is : %lld\\n\", ka); printf(\"Secret Key for the Bob is : %lld\\n\", kb); return 0;}", "e": 4017, "s": 2639, "text": null }, { "code": "// This program calculates the Key for two persons// using the Diffie-Hellman Key exchange algorithmclass GFG{ // Power function to return value of a ^ b mod Pprivate static long power(long a, long b, long p){ if (b == 1) return a; else return (((long)Math.pow(a, b)) % p);} // Driver codepublic static void main(String[] args){ long P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the // public keys G and P // A prime number P is taken P = 23; System.out.println(\"The value of P:\" + P); // A primitive root for P, G is taken G = 9; System.out.println(\"The value of G:\" + G); // Alice will choose the private key a // a is the chosen private key a = 4; System.out.println(\"The private key a for Alice:\" + a); // Gets the generated key x = power(G, a, P); // Bob will choose the private key b // b is the chosen private key b = 3; System.out.println(\"The private key b for Bob:\" + b); // Gets the generated key y = power(G, b, P); // Generating the secret key after the exchange // of keys ka = power(y, a, P); // Secret key for Alice kb = power(x, b, P); // Secret key for Bob System.out.println(\"Secret key for the Alice is:\" + ka); System.out.println(\"Secret key for the Bob is:\" + kb);}} // This code is contributed by raghav14", "e": 5420, "s": 4017, "text": null }, { "code": "from random import randint if __name__ == '__main__': # Both the persons will be agreed upon the # public keys G and P # A prime number P is taken P = 23 # A primitive root for P, G is taken G = 9 print('The Value of P is :%d'%(P)) print('The Value of G is :%d'%(G)) # Alice will choose the private key a a = 4 print('The Private Key a for Alice is :%d'%(a)) # gets the generated key x = int(pow(G,a,P)) # Bob will choose the private key b b = 3 print('The Private Key b for Bob is :%d'%(b)) # gets the generated key y = int(pow(G,b,P)) # Secret key for Alice ka = int(pow(y,a,P)) # Secret key for Bob kb = int(pow(x,b,P)) print('Secret key for the Alice is : %d'%(ka)) print('Secret Key for the Bob is : %d'%(kb))", "e": 6265, "s": 5420, "text": null }, { "code": "<script> // This program calculates the Key for two persons// using the Diffie-Hellman Key exchange algorithm // Power function to return value of a ^ b mod Pfunction power(a, b, p){ if (b == 1) return a; else return((Math.pow(a, b)) % p);} // Driver codevar P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the// public keys G and P // A prime number P is takenP = 23;document.write(\"The value of P:\" + P + \"<br>\"); // A primitive root for P, G is takenG = 9;document.write(\"The value of G:\" + G + \"<br>\"); // Alice will choose the private key a// a is the chosen private keya = 4;document.write(\"The private key a for Alice:\" + a + \"<br>\"); // Gets the generated keyx = power(G, a, P); // Bob will choose the private key b// b is the chosen private key b = 3;document.write(\"The private key b for Bob:\" + b + \"<br>\"); // Gets the generated keyy = power(G, b, P); // Generating the secret key after the exchange// of keyska = power(y, a, P); // Secret key for Alicekb = power(x, b, P); // Secret key for Bob document.write(\"Secret key for the Alice is:\" + ka + \"<br>\");document.write(\"Secret key for the Bob is:\" + kb + \"<br>\"); // This code is contributed by Ankita saini </script>", "e": 7544, "s": 6265, "text": null }, { "code": "/* This program calculates the Key for two personsusing the Diffie-Hellman Key exchange algorithm using C++ */#include <cmath>#include <iostream>using namespace std; // Power function to return value of a ^ b mod Plong long int power(long long int a, long long int b, long long int P){ if (b == 1) return a; else return (((long long int)pow(a, b)) % P);} // Driver programint main(){ long long int P, G, x, a, y, b, ka, kb; // Both the persons will be agreed upon the // public keys G and P P = 23; // A prime number P is taken cout << \"The value of P : \" << P << endl; G = 9; // A primitive root for P, G is taken cout << \"The value of G : \" << G << endl; // Alice will choose the private key a a = 4; // a is the chosen private key cout << \"The private key a for Alice : \" << a << endl; x = power(G, a, P); // gets the generated key // Bob will choose the private key b b = 3; // b is the chosen private key cout << \"The private key b for Bob : \" << b << endl; y = power(G, b, P); // gets the generated key // Generating the secret key after the exchange // of keys ka = power(y, a, P); // Secret key for Alice kb = power(x, b, P); // Secret key for Bob cout << \"Secret key for the Alice is : \" << ka << endl; cout << \"Secret key for the Alice is : \" << kb << endl; return 0;}// This code is contributed by Pranay Arora", "e": 8981, "s": 7544, "text": null }, { "code": null, "e": 8989, "s": 8981, "text": "Output:" }, { "code": null, "e": 9154, "s": 8989, "text": "The value of P : 23\nThe value of G : 9\n\nThe private key a for Alice : 4\nThe private key b for Bob : 3\n\nSecret key for the Alice is : 9\nSecret Key for the Bob is : 9" }, { "code": null, "e": 9579, "s": 9154, "text": "This article is contributed by Souvik Nandi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.GeeksforGeeks.org or mail your article to contribute@GeeksforGeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9589, "s": 9579, "text": "nalasivam" }, { "code": null, "e": 9595, "s": 9589, "text": "ShJos" }, { "code": null, "e": 9604, "s": 9595, "text": "raghav14" }, { "code": null, "e": 9617, "s": 9604, "text": "ankita_saini" }, { "code": null, "e": 9626, "s": 9617, "text": "sooda367" }, { "code": null, "e": 9638, "s": 9626, "text": "arorapranay" }, { "code": null, "e": 9656, "s": 9638, "text": "Computer Networks" }, { "code": null, "e": 9674, "s": 9656, "text": "Computer Networks" } ]
Python – Run same function in parallel with different parameters
03 Mar, 2021 In this article, we will learn how to run the same function in parallel with different parameters. We can run the same function in parallel with different parameters using parallel processing. The number of tasks performed by the program can be increased by parallel processing, which decreases the total processing time. These assist in addressing large-scale issues. Using the standard multiprocessing module, by creating child processes, we can effectively parallelize simple tasks. This module provides an easy-to-use interface and includes a set of task submission and synchronization handling utilities. Approach: We may construct a process running independently by subclassing the multiprocessing process. We can initialize the resource by extending the __init_ method, and we can write the code for the subprocess by implementing the Process.run() method. We see how to construct a process in the code below, which prints the assigned id. We need to initialize our process object and invoke the Process.start() method in order to spawn the process. Here, Process.start() will create a new process and invoke a method called Process.run(). The code after p.start() is executed immediately before process p completes the mission. You may use Process.join to wait for task completion(). Let’s understand this with some examples. Example 1: Python3 import multiprocessingimport time # Process classclass Process(multiprocessing.Process): def __init__(self, id): super(Process, self).__init__() self.id = id def run(self): time.sleep(1) print("I'm the process with id: {}".format(self.id)) if __name__ == '__main__': p = Process(0) # Create a new process and invoke the # Process.run() method p.start() # Process.join() to wait for task completion. p.join() p = Process(1) p.start() p.join() Output: We can also run the same function in parallel with different parameters using the Pool class. For parallel mapping, We have to first initialize multiprocessing.Pool() object. The first argument is the number of workers; if not given, that number will be equal to the number of elements in the system. Example 2: Let see by an example. In this example, we will see how to pass a function that computes the square of a number. Using Pool.map() we can map the function to the list and passing the function and the list of inputs as arguments, as follows: Python3 import multiprocessingimport time # square functiondef square(x): return x * x if __name__ == '__main__': # multiprocessing pool object pool = multiprocessing.Pool() # pool object with number of element pool = multiprocessing.Pool(processes=4) # input list inputs = [0, 1, 2, 3, 4] # map the function to the list and pass # function and input list as arguments outputs = pool.map(square, inputs) # Print input list print("Input: {}".format(inputs)) # Print output list print("Output: {}".format(outputs)) Output: Example 3: Python3 from multiprocessing import Pool def print_range(range): # print range print('From {} to {}:'.format(range[0], range[1])) def run_parallel(): # list of ranges list_ranges = [[0, 10], [10, 20], [20, 30]] # pool object with number of elements in the list pool = Pool(processes=len(list_ranges)) # map the function to the list and pass # function and list_ranges as arguments pool.map(print_range, list_ranges) # Driver codeif __name__ == '__main__': run_parallel() Output: Picked Python-Functions Python-multithreading Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Mar, 2021" }, { "code": null, "e": 247, "s": 54, "text": "In this article, we will learn how to run the same function in parallel with different parameters. We can run the same function in parallel with different parameters using parallel processing." }, { "code": null, "e": 664, "s": 247, "text": "The number of tasks performed by the program can be increased by parallel processing, which decreases the total processing time. These assist in addressing large-scale issues. Using the standard multiprocessing module, by creating child processes, we can effectively parallelize simple tasks. This module provides an easy-to-use interface and includes a set of task submission and synchronization handling utilities." }, { "code": null, "e": 674, "s": 664, "text": "Approach:" }, { "code": null, "e": 1001, "s": 674, "text": "We may construct a process running independently by subclassing the multiprocessing process. We can initialize the resource by extending the __init_ method, and we can write the code for the subprocess by implementing the Process.run() method. We see how to construct a process in the code below, which prints the assigned id." }, { "code": null, "e": 1201, "s": 1001, "text": "We need to initialize our process object and invoke the Process.start() method in order to spawn the process. Here, Process.start() will create a new process and invoke a method called Process.run()." }, { "code": null, "e": 1346, "s": 1201, "text": "The code after p.start() is executed immediately before process p completes the mission. You may use Process.join to wait for task completion()." }, { "code": null, "e": 1388, "s": 1346, "text": "Let’s understand this with some examples." }, { "code": null, "e": 1400, "s": 1388, "text": "Example 1: " }, { "code": null, "e": 1408, "s": 1400, "text": "Python3" }, { "code": "import multiprocessingimport time # Process classclass Process(multiprocessing.Process): def __init__(self, id): super(Process, self).__init__() self.id = id def run(self): time.sleep(1) print(\"I'm the process with id: {}\".format(self.id)) if __name__ == '__main__': p = Process(0) # Create a new process and invoke the # Process.run() method p.start() # Process.join() to wait for task completion. p.join() p = Process(1) p.start() p.join()", "e": 1921, "s": 1408, "text": null }, { "code": null, "e": 1929, "s": 1921, "text": "Output:" }, { "code": null, "e": 2230, "s": 1929, "text": "We can also run the same function in parallel with different parameters using the Pool class. For parallel mapping, We have to first initialize multiprocessing.Pool() object. The first argument is the number of workers; if not given, that number will be equal to the number of elements in the system." }, { "code": null, "e": 2241, "s": 2230, "text": "Example 2:" }, { "code": null, "e": 2481, "s": 2241, "text": "Let see by an example. In this example, we will see how to pass a function that computes the square of a number. Using Pool.map() we can map the function to the list and passing the function and the list of inputs as arguments, as follows:" }, { "code": null, "e": 2489, "s": 2481, "text": "Python3" }, { "code": "import multiprocessingimport time # square functiondef square(x): return x * x if __name__ == '__main__': # multiprocessing pool object pool = multiprocessing.Pool() # pool object with number of element pool = multiprocessing.Pool(processes=4) # input list inputs = [0, 1, 2, 3, 4] # map the function to the list and pass # function and input list as arguments outputs = pool.map(square, inputs) # Print input list print(\"Input: {}\".format(inputs)) # Print output list print(\"Output: {}\".format(outputs))", "e": 3052, "s": 2489, "text": null }, { "code": null, "e": 3060, "s": 3052, "text": "Output:" }, { "code": null, "e": 3071, "s": 3060, "text": "Example 3:" }, { "code": null, "e": 3079, "s": 3071, "text": "Python3" }, { "code": "from multiprocessing import Pool def print_range(range): # print range print('From {} to {}:'.format(range[0], range[1])) def run_parallel(): # list of ranges list_ranges = [[0, 10], [10, 20], [20, 30]] # pool object with number of elements in the list pool = Pool(processes=len(list_ranges)) # map the function to the list and pass # function and list_ranges as arguments pool.map(print_range, list_ranges) # Driver codeif __name__ == '__main__': run_parallel()", "e": 3592, "s": 3079, "text": null }, { "code": null, "e": 3600, "s": 3592, "text": "Output:" }, { "code": null, "e": 3607, "s": 3600, "text": "Picked" }, { "code": null, "e": 3624, "s": 3607, "text": "Python-Functions" }, { "code": null, "e": 3646, "s": 3624, "text": "Python-multithreading" }, { "code": null, "e": 3653, "s": 3646, "text": "Python" } ]
Traversing directory in Java using BFS
24 Mar, 2018 Given a directory, print all files and folders present in directory tree rooted with given directory. We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from queue. If the popped item is a directory, get list of all files and directories present in it, add each directory to the queue. If the popped item is a file, we print its name. // Java program to print all files/directories// present in a directory.import java.io.File;import java.util.LinkedList;import java.util.Queue; class FileUtils { public static void printDirsFiles(String inputDir) { /* make a queue to store files and directories */ Queue<File> queue = new LinkedList<>(); queue.add(new File(inputDir)); /* loop until queue is empty -*/ while (!queue.isEmpty()) { /* get next file/directory from the queue */ File current = queue.poll(); File[] fileDirList = current.listFiles(); if (fileDirList != null) { /* Enqueue all directories and print all files. */ for (File fd : fileDirList) { if (fd.isDirectory()) queue.add(fd); else System.out.println(fd); } } } } /* Iterative function to traverse given directory in Java using BFS*/ public static void main(String[] args) { String inputDir = "C:\\Programs"; printDirsFiles(inputDir); }} This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. BFS java-file-handling java-LinkedList Java Java BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Mar, 2018" }, { "code": null, "e": 130, "s": 28, "text": "Given a directory, print all files and folders present in directory tree rooted with given directory." }, { "code": null, "e": 503, "s": 130, "text": "We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from queue. If the popped item is a directory, get list of all files and directories present in it, add each directory to the queue. If the popped item is a file, we print its name." }, { "code": "// Java program to print all files/directories// present in a directory.import java.io.File;import java.util.LinkedList;import java.util.Queue; class FileUtils { public static void printDirsFiles(String inputDir) { /* make a queue to store files and directories */ Queue<File> queue = new LinkedList<>(); queue.add(new File(inputDir)); /* loop until queue is empty -*/ while (!queue.isEmpty()) { /* get next file/directory from the queue */ File current = queue.poll(); File[] fileDirList = current.listFiles(); if (fileDirList != null) { /* Enqueue all directories and print all files. */ for (File fd : fileDirList) { if (fd.isDirectory()) queue.add(fd); else System.out.println(fd); } } } } /* Iterative function to traverse given directory in Java using BFS*/ public static void main(String[] args) { String inputDir = \"C:\\\\Programs\"; printDirsFiles(inputDir); }}", "e": 1697, "s": 503, "text": null }, { "code": null, "e": 1991, "s": 1697, "text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2116, "s": 1991, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2120, "s": 2116, "text": "BFS" }, { "code": null, "e": 2139, "s": 2120, "text": "java-file-handling" }, { "code": null, "e": 2155, "s": 2139, "text": "java-LinkedList" }, { "code": null, "e": 2160, "s": 2155, "text": "Java" }, { "code": null, "e": 2165, "s": 2160, "text": "Java" }, { "code": null, "e": 2169, "s": 2165, "text": "BFS" } ]
Matching strings for similar characters - JavaScript
We are required to write a JavaScript function that accepts two string and a number n. The function matches the two strings i.e., it checks if the two strings contains the same characters. The function returns true if both the strings contain the same character irrespective of their order or if they contain at most n different characters, else the function should return false. Following is the code − const str = 'some random text'; const str2 = 'some r@ndom text'; const deviationMatching = (first, second, num) => { let count = 0; for(let i = 0; i < first.length; i++){ if(!second.includes(first[i])){ count++; }; if(count > num){ return false; }; }; return true; }; console.log(deviationMatching(str, str2, 1)); This will produce the following output in console − true
[ { "code": null, "e": 1149, "s": 1062, "text": "We are required to write a JavaScript function that accepts two string and a number n." }, { "code": null, "e": 1251, "s": 1149, "text": "The function matches the two strings i.e., it checks if the two strings contains the same characters." }, { "code": null, "e": 1442, "s": 1251, "text": "The function returns true if both the strings contain the same character irrespective of their order or if they contain at most n different characters, else the function should return false." }, { "code": null, "e": 1466, "s": 1442, "text": "Following is the code −" }, { "code": null, "e": 1834, "s": 1466, "text": "const str = 'some random text';\nconst str2 = 'some r@ndom text';\nconst deviationMatching = (first, second, num) => {\n let count = 0;\n for(let i = 0; i < first.length; i++){\n if(!second.includes(first[i])){\n count++;\n };\n if(count > num){\n return false;\n };\n };\n return true;\n};\nconsole.log(deviationMatching(str, str2, 1));" }, { "code": null, "e": 1886, "s": 1834, "text": "This will produce the following output in console −" }, { "code": null, "e": 1891, "s": 1886, "text": "true" } ]
TestNG - Executing Tests
The test cases are executed using TestNG class. This class is the main entry point for running tests in the TestNG framework. Users can create their own TestNG object and invoke it in many different ways such as − On an existing testng.xml. On an existing testng.xml. On a synthetic testng.xml, created entirely from Java. On a synthetic testng.xml, created entirely from Java. By directly setting the test classes. By directly setting the test classes. You can also define which groups to include or exclude, assign parameters, etc. The command line parameters are − -d outputdir: specify the output directory. -d outputdir: specify the output directory. -testclass class_name: specifies one or several class names. -testclass class_name: specifies one or several class names. -testjar jar_name: specifies the jar containing the tests. -testjar jar_name: specifies the jar containing the tests. -sourcedir src1;src2: ; separated list of source directories (used only when javadoc annotations are used). -sourcedir src1;src2: ; separated list of source directories (used only when javadoc annotations are used). -target -target -groups -groups -testrunfactory -testrunfactory -listener -listener We will create the TestNG object an existing testng.xml in our example below. Create a java class to be tested, say, MessageUtil.java in /work/testng/src. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } } Create a java test class, say, SampleTest.java. Create a java test class, say, SampleTest.java. Add a test method testPrintMessage() to your test class. Add a test method testPrintMessage() to your test class. Add an Annotation @Test to method testPrintMessage(). Add an Annotation @Test to method testPrintMessage(). Implement the test condition and check the condition using assertEquals API of TestNG. Implement the test condition and check the condition using assertEquals API of TestNG. Create a java class file called SampleTest.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class SampleTest { String message = "Hello World"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { Assert.assertEquals(message, messageUtil.printMessage()); } } Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database). <?xml version = "1.0" encoding = "UTF-8"?> <suite name = "Sample test Suite"> <test name = "Sample test"> <classes> <class name = "SampleTest" /> </classes> </test> </suite> Compile the test case using javac. /work/testng/src$ javac MessageUtil.java SampleTest.java Now, run the testng.xml, which will run the test case defined in <test> tag. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Hello World =============================================== Sample test Suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== 38 Lectures 4.5 hours Lets Kode It 15 Lectures 1.5 hours Quaatso Learning 28 Lectures 3 hours Dezlearn Education Print Add Notes Bookmark this page
[ { "code": null, "e": 2274, "s": 2060, "text": "The test cases are executed using TestNG class. This class is the main entry point for running tests in the TestNG framework. Users can create their own TestNG object and invoke it in many different ways such as −" }, { "code": null, "e": 2301, "s": 2274, "text": "On an existing testng.xml." }, { "code": null, "e": 2328, "s": 2301, "text": "On an existing testng.xml." }, { "code": null, "e": 2383, "s": 2328, "text": "On a synthetic testng.xml, created entirely from Java." }, { "code": null, "e": 2438, "s": 2383, "text": "On a synthetic testng.xml, created entirely from Java." }, { "code": null, "e": 2476, "s": 2438, "text": "By directly setting the test classes." }, { "code": null, "e": 2514, "s": 2476, "text": "By directly setting the test classes." }, { "code": null, "e": 2628, "s": 2514, "text": "You can also define which groups to include or exclude, assign parameters, etc. The command line parameters are −" }, { "code": null, "e": 2672, "s": 2628, "text": "-d outputdir: specify the output directory." }, { "code": null, "e": 2716, "s": 2672, "text": "-d outputdir: specify the output directory." }, { "code": null, "e": 2777, "s": 2716, "text": "-testclass class_name: specifies one or several class names." }, { "code": null, "e": 2838, "s": 2777, "text": "-testclass class_name: specifies one or several class names." }, { "code": null, "e": 2897, "s": 2838, "text": "-testjar jar_name: specifies the jar containing the tests." }, { "code": null, "e": 2956, "s": 2897, "text": "-testjar jar_name: specifies the jar containing the tests." }, { "code": null, "e": 3064, "s": 2956, "text": "-sourcedir src1;src2: ; separated list of source directories (used only when javadoc annotations are used)." }, { "code": null, "e": 3172, "s": 3064, "text": "-sourcedir src1;src2: ; separated list of source directories (used only when javadoc annotations are used)." }, { "code": null, "e": 3180, "s": 3172, "text": "-target" }, { "code": null, "e": 3188, "s": 3180, "text": "-target" }, { "code": null, "e": 3196, "s": 3188, "text": "-groups" }, { "code": null, "e": 3204, "s": 3196, "text": "-groups" }, { "code": null, "e": 3220, "s": 3204, "text": "-testrunfactory" }, { "code": null, "e": 3236, "s": 3220, "text": "-testrunfactory" }, { "code": null, "e": 3246, "s": 3236, "text": "-listener" }, { "code": null, "e": 3256, "s": 3246, "text": "-listener" }, { "code": null, "e": 3334, "s": 3256, "text": "We will create the TestNG object an existing testng.xml in our example below." }, { "code": null, "e": 3411, "s": 3334, "text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src." }, { "code": null, "e": 3774, "s": 3411, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public String printMessage() {\n System.out.println(message);\n return message;\n }\n}" }, { "code": null, "e": 3822, "s": 3774, "text": "Create a java test class, say, SampleTest.java." }, { "code": null, "e": 3870, "s": 3822, "text": "Create a java test class, say, SampleTest.java." }, { "code": null, "e": 3927, "s": 3870, "text": "Add a test method testPrintMessage() to your test class." }, { "code": null, "e": 3984, "s": 3927, "text": "Add a test method testPrintMessage() to your test class." }, { "code": null, "e": 4038, "s": 3984, "text": "Add an Annotation @Test to method testPrintMessage()." }, { "code": null, "e": 4092, "s": 4038, "text": "Add an Annotation @Test to method testPrintMessage()." }, { "code": null, "e": 4179, "s": 4092, "text": "Implement the test condition and check the condition using assertEquals API of TestNG." }, { "code": null, "e": 4266, "s": 4179, "text": "Implement the test condition and check the condition using assertEquals API of TestNG." }, { "code": null, "e": 4335, "s": 4266, "text": "Create a java class file called SampleTest.java in /work/testng/src." }, { "code": null, "e": 4632, "s": 4335, "text": "import org.testng.Assert;\nimport org.testng.annotations.Test;\n\npublic class SampleTest {\n\n String message = \"Hello World\";\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\n Assert.assertEquals(message, messageUtil.printMessage());\n }\n}" }, { "code": null, "e": 5091, "s": 4632, "text": "Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database)." }, { "code": null, "e": 5293, "s": 5091, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<suite name = \"Sample test Suite\">\n <test name = \"Sample test\">\n <classes>\n <class name = \"SampleTest\" />\n </classes>\n </test>\n</suite>" }, { "code": null, "e": 5328, "s": 5293, "text": "Compile the test case using javac." }, { "code": null, "e": 5386, "s": 5328, "text": "/work/testng/src$ javac MessageUtil.java SampleTest.java\n" }, { "code": null, "e": 5463, "s": 5386, "text": "Now, run the testng.xml, which will run the test case defined in <test> tag." }, { "code": null, "e": 5516, "s": 5463, "text": "/work/testng/src$ java org.testng.TestNG testng.xml\n" }, { "code": null, "e": 5535, "s": 5516, "text": "Verify the output." }, { "code": null, "e": 5705, "s": 5535, "text": "Hello World\n\n===============================================\nSample test Suite\nTotal tests run: 1, Failures: 0, Skips: 0\n===============================================\n" }, { "code": null, "e": 5740, "s": 5705, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5754, "s": 5740, "text": " Lets Kode It" }, { "code": null, "e": 5789, "s": 5754, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5807, "s": 5789, "text": " Quaatso Learning" }, { "code": null, "e": 5840, "s": 5807, "text": "\n 28 Lectures \n 3 hours \n" }, { "code": null, "e": 5860, "s": 5840, "text": " Dezlearn Education" }, { "code": null, "e": 5867, "s": 5860, "text": " Print" }, { "code": null, "e": 5878, "s": 5867, "text": " Add Notes" } ]
Maven - Build & Test Project
What we learnt in Project Creation chapter is how to create a Java application using Maven. Now we'll see how to build and test the application. Go to C:/MVN directory where you've created your java application. Open consumerBanking folder. You will see the POM.xml file with the following contents. Update it to reflect the current java version. <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.projectgroup</groupId> <artifactId>project</artifactId> <version>1.0</version> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> </dependency> </dependencies> </project> Here you can see, Maven already added Junit as test framework. By default, Maven adds a source file App.java and a test file AppTest.java in its default directory structure, as discussed in the previous chapter. Let's open the command console, go the C:\MVN\consumerBanking directory and execute the following mvn command. C:\MVN\consumerBanking>mvn clean package Maven will start building the project. C:\MVN\consumerBanking>mvn clean package [INFO] Scanning for projects... [INFO] [INFO] ----------------< com.companyname.bank:consumerBanking >---------------- [INFO] Building consumerBanking 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking --- [INFO] Deleting C:\MVN\consumerBanking\target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking --- [INFO] Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.companyname.bank.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking --- [INFO] Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.663 s [INFO] Finished at: 2021-12-13T17:34:27+05:30 [INFO] ------------------------------------------------------------------------ C:\MVN\consumerBanking> You've built your project and created final jar file, following are the key learning concepts − We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package). We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package). Packaged jar is available in consumerBanking\target folder as consumerBanking-1.0-SNAPSHOT.jar. Packaged jar is available in consumerBanking\target folder as consumerBanking-1.0-SNAPSHOT.jar. Test reports are available in consumerBanking\target\surefire-reports folder. Test reports are available in consumerBanking\target\surefire-reports folder. Maven compiles the source code file(s) and then tests the source code file(s). Maven compiles the source code file(s) and then tests the source code file(s). Then Maven runs the test cases. Then Maven runs the test cases. Finally, Maven creates the package. Finally, Maven creates the package. Now open the command console, go the C:\MVN\consumerBanking\target\classes directory and execute the following java command. >java com.companyname.bank.App You will see the result as follows − Hello World! Let's see how we can add additional Java files in our project. Open C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, create Util class in it as Util.java. package com.companyname.bank; public class Util { public static void printMessage(String message){ System.out.println(message); } } Update the App class to use Util class. package com.companyname.bank; /** * Hello world! * */ public class App { public static void main( String[] args ){ Util.printMessage("Hello World!"); } } Now open the command console, go the C:\MVN\consumerBanking directory and execute the following mvn command. >mvn clean compile After Maven build is successful, go to the C:\MVN\consumerBanking\target\classes directory and execute the following java command. >java -cp com.companyname.bank.App You will see the result as follows − Hello World! 34 Lectures 4 hours Karthikeya T 14 Lectures 1.5 hours Quaatso Learning Print Add Notes Bookmark this page
[ { "code": null, "e": 2205, "s": 2060, "text": "What we learnt in Project Creation chapter is how to create a Java application using Maven. Now we'll see how to build and test the application." }, { "code": null, "e": 2407, "s": 2205, "text": "Go to C:/MVN directory where you've created your java application. Open consumerBanking folder. You will see the POM.xml file with the following contents. Update it to reflect the current java version." }, { "code": null, "e": 3118, "s": 2407, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.projectgroup</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <properties>\n <maven.compiler.source>11</maven.compiler.source>\n <maven.compiler.target>11</maven.compiler.target>\n </properties>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n </dependency>\n </dependencies> \n</project>" }, { "code": null, "e": 3330, "s": 3118, "text": "Here you can see, Maven already added Junit as test framework. By default, Maven adds a source file App.java and a test file AppTest.java in its default directory structure, as discussed in the previous chapter." }, { "code": null, "e": 3441, "s": 3330, "text": "Let's open the command console, go the C:\\MVN\\consumerBanking directory and execute the following mvn command." }, { "code": null, "e": 3483, "s": 3441, "text": "C:\\MVN\\consumerBanking>mvn clean package\n" }, { "code": null, "e": 3522, "s": 3483, "text": "Maven will start building the project." }, { "code": null, "e": 6186, "s": 3522, "text": "C:\\MVN\\consumerBanking>mvn clean package\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ----------------< com.companyname.bank:consumerBanking >----------------\n[INFO] Building consumerBanking 1.0-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ consumerBanking ---\n[INFO] Deleting C:\\MVN\\consumerBanking\\target\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ consumerBanking ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ consumerBanking ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 1 source file to C:\\MVN\\consumerBanking\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ consumerBanking ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MVN\\consumerBanking\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ consumerBanking ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 1 source file to C:\\MVN\\consumerBanking\\target\\test-classes\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ consumerBanking ---\n[INFO] Surefire report directory: C:\\MVN\\consumerBanking\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.companyname.bank.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO]\n[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ consumerBanking ---\n[INFO] Building jar: C:\\MVN\\consumerBanking\\target\\consumerBanking-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 4.663 s\n[INFO] Finished at: 2021-12-13T17:34:27+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN\\consumerBanking>\n" }, { "code": null, "e": 6282, "s": 6186, "text": "You've built your project and created final jar file, following are the key learning concepts −" }, { "code": null, "e": 6411, "s": 6282, "text": "We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package)." }, { "code": null, "e": 6540, "s": 6411, "text": "We give maven two goals, first to clean the target directory (clean) and then package the project build output as jar (package)." }, { "code": null, "e": 6636, "s": 6540, "text": "Packaged jar is available in consumerBanking\\target folder as consumerBanking-1.0-SNAPSHOT.jar." }, { "code": null, "e": 6732, "s": 6636, "text": "Packaged jar is available in consumerBanking\\target folder as consumerBanking-1.0-SNAPSHOT.jar." }, { "code": null, "e": 6810, "s": 6732, "text": "Test reports are available in consumerBanking\\target\\surefire-reports folder." }, { "code": null, "e": 6888, "s": 6810, "text": "Test reports are available in consumerBanking\\target\\surefire-reports folder." }, { "code": null, "e": 6967, "s": 6888, "text": "Maven compiles the source code file(s) and then tests the source code file(s)." }, { "code": null, "e": 7046, "s": 6967, "text": "Maven compiles the source code file(s) and then tests the source code file(s)." }, { "code": null, "e": 7078, "s": 7046, "text": "Then Maven runs the test cases." }, { "code": null, "e": 7110, "s": 7078, "text": "Then Maven runs the test cases." }, { "code": null, "e": 7146, "s": 7110, "text": "Finally, Maven creates the package." }, { "code": null, "e": 7182, "s": 7146, "text": "Finally, Maven creates the package." }, { "code": null, "e": 7307, "s": 7182, "text": "Now open the command console, go the C:\\MVN\\consumerBanking\\target\\classes directory and execute the following java command." }, { "code": null, "e": 7339, "s": 7307, "text": ">java com.companyname.bank.App\n" }, { "code": null, "e": 7376, "s": 7339, "text": "You will see the result as follows −" }, { "code": null, "e": 7390, "s": 7376, "text": "Hello World!\n" }, { "code": null, "e": 7562, "s": 7390, "text": "Let's see how we can add additional Java files in our project. Open C:\\MVN\\consumerBanking\\src\\main\\java\\com\\companyname\\bank folder, create Util class in it as Util.java." }, { "code": null, "e": 7707, "s": 7562, "text": "package com.companyname.bank;\n\npublic class Util {\n public static void printMessage(String message){\n System.out.println(message);\n }\n}" }, { "code": null, "e": 7747, "s": 7707, "text": "Update the App class to use Util class." }, { "code": null, "e": 7915, "s": 7747, "text": "package com.companyname.bank;\n\n/**\n* Hello world!\n*\n*/\n\npublic class App {\n public static void main( String[] args ){\n Util.printMessage(\"Hello World!\");\n }\n}" }, { "code": null, "e": 8024, "s": 7915, "text": "Now open the command console, go the C:\\MVN\\consumerBanking directory and execute the following mvn command." }, { "code": null, "e": 8044, "s": 8024, "text": ">mvn clean compile\n" }, { "code": null, "e": 8175, "s": 8044, "text": "After Maven build is successful, go to the C:\\MVN\\consumerBanking\\target\\classes directory and execute the following java command." }, { "code": null, "e": 8210, "s": 8175, "text": ">java -cp com.companyname.bank.App" }, { "code": null, "e": 8247, "s": 8210, "text": "You will see the result as follows −" }, { "code": null, "e": 8261, "s": 8247, "text": "Hello World!\n" }, { "code": null, "e": 8294, "s": 8261, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 8308, "s": 8294, "text": " Karthikeya T" }, { "code": null, "e": 8343, "s": 8308, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8361, "s": 8343, "text": " Quaatso Learning" }, { "code": null, "e": 8368, "s": 8361, "text": " Print" }, { "code": null, "e": 8379, "s": 8368, "text": " Add Notes" } ]
Model? Or do you mean Weight of Evidence (WoE) and Information Value (IV)? | by JT Quant | Towards Data Science
As a data scientist, I’m always interested to know how certain independent variables, such as occupation, influence the dependent variables, such as income. Specifically, when it comes to classification problems, WoE and IV can tell stories between an independent variable and a dependent variable. These concepts were developed mainly to answer credit scoring problems, where customers are labelled either ‘good’ or ‘bad’, which is based on them defaulting credit repayment. Their associated variables, such as age, are also recorded. Now, we are applying these concepts on the Titanic data set. using DataFrames, CSVdf = DataFrame(CSV.File("train.csv"))show(describe(df), allcols=true) The formula of WoE is as such:For each class i of an independent variable x, we want to find the ratio of the proportion/percentage of the population, whose dependent variable y belongs to a certain class, that has the class i, followed by natural log. Sound confusing? To put it in context, we can take x as “Sex” and y as “Survived”. “Sex” is divided into 2 classes: “Male” & “Female”. To calculate WoE, 1a. Count the number of perished males (“Sex” = “Male”, “Survived” = 0): 4681b. Divide the number by the total number of perished passengers (“Survived” = 0):468/549 = 0.852462a. Count the number of surviving males (“Sex” = “Male”, “Survived” = 1): 1092b. Divide the number by the total number of surviving passengers (“Survived” = 0):109/342 = 0.318713. Divide (1b) result by (2b) result, then take natural log to derive WoE: ln(0.85246/0.31871) = 0.98383 We perform the same steps for “Female” to derive WoE, which is -1.52988. The code is as follows: survived = by(df, :Survived, (count = :Survived => length))sex_df = unstack(by(df, [:Sex, :Survived], (count = :Sex => length)), :Sex, :count)male_event = sex_df[(sex_df.Survived .== 1), :male] / survived[(survived.Survived .== 1), :count]male_non_event = sex_df[(sex_df.Survived .== 0), :male] / survived[(survived.Survived .== 0), :count]woe_male = log(male_non_event/male_event)female_event = sex_df[(sex_df.Survived .== 1), :female] / survived[(survived.Survived .== 1), :count]female_non_event = sex_df[(sex_df.Survived .== 0), :female] / survived[(survived.Survived .== 0), :count]woe_female = log(female_non_event/female_event) Going back to the formula, WoE, through the sign (+/-), shed light on the proportion of male survivors vs the proportion of male victims during the fateful event. However, we are more interested to know the relationship between an independent variable (“Sex”) and a dependent variable (“Survived”). This will then be able to combine different WoEs for under the same independent variable together. The formula is as such: Continuing from our previous example, these are the steps to be taken:4a. Take the difference between (1b) result and (2b) result:0.85246 - 0.31871 = 0.533754b. Multiply (4a) result with (3) result, which is the WoE:0.53375 * 0.98383 = 0.52512 We perform the same steps for “Female” and derive 0.81656. Summing both values up, we obtain IV = 1.34168 for the independent variable “Sex”. The code is as follows: iv_male = (male_non_event - male_event) * woe_maleiv_female = (female_non_event - female_event) * woe_femaleiv = iv_male + iv_female Once we have the IV of the variable, we can check against this table to see the predictive power of the variable. As you can see, the table is saying the variable “Sex” is too good to be true! There are a few assumptions we are making here: firstly, the table serves as a guide when the methodology is created to address credit default problem statement. During that time, the researchers wanted to understand the variables that were likely to influence clients’ credit ratings. The researchers found that the table was very relevant to their problem statement. It was then served as a guide. Secondly, it has been shown that more females than males survived from the sinking of Titanic. The odds of females surviving is higher than that of males from the accident. Hence, it is no surprise that the variable “Sex” is indeed an exceptional strong predictive power. Apart from applying the concepts for research purposes, the main practical use of WoE is for encoding, where you can replace the classes with their associated values. For example, in our example, you can replace “Male” with 0.98383 and “Female” with -1.52988. The reason is obvious: Machine Learning algorithms are primarily taking numbers as inputs, so we have to turn strings to figures before training a model. Another positive outcome of using WoE is to reduce the number of columns of the input used for training a model. Imagine you have a categorical variable with 10 different classes and you perform a one-hot encoding, you will end up with 10 columns with mostly ‘0’ as values. Using WoE technique, the classes are replaced by their associated WoE values. As for IVs, they provide a basis for us to drill down further in our relationship analysis between independent and dependent variables. Furthermore, if the variable is a qualitative type, we can use binning method followed by WoE and IV concepts to engineer meaningful features. That’s all for the explanation for now. Do drop me comments if there is any way I can improve my Julia coding skill, as I recently picked this language up. Cheers!
[ { "code": null, "e": 470, "s": 171, "text": "As a data scientist, I’m always interested to know how certain independent variables, such as occupation, influence the dependent variables, such as income. Specifically, when it comes to classification problems, WoE and IV can tell stories between an independent variable and a dependent variable." }, { "code": null, "e": 707, "s": 470, "text": "These concepts were developed mainly to answer credit scoring problems, where customers are labelled either ‘good’ or ‘bad’, which is based on them defaulting credit repayment. Their associated variables, such as age, are also recorded." }, { "code": null, "e": 768, "s": 707, "text": "Now, we are applying these concepts on the Titanic data set." }, { "code": null, "e": 859, "s": 768, "text": "using DataFrames, CSVdf = DataFrame(CSV.File(\"train.csv\"))show(describe(df), allcols=true)" }, { "code": null, "e": 1112, "s": 859, "text": "The formula of WoE is as such:For each class i of an independent variable x, we want to find the ratio of the proportion/percentage of the population, whose dependent variable y belongs to a certain class, that has the class i, followed by natural log." }, { "code": null, "e": 1722, "s": 1112, "text": "Sound confusing? To put it in context, we can take x as “Sex” and y as “Survived”. “Sex” is divided into 2 classes: “Male” & “Female”. To calculate WoE, 1a. Count the number of perished males (“Sex” = “Male”, “Survived” = 0): 4681b. Divide the number by the total number of perished passengers (“Survived” = 0):468/549 = 0.852462a. Count the number of surviving males (“Sex” = “Male”, “Survived” = 1): 1092b. Divide the number by the total number of surviving passengers (“Survived” = 0):109/342 = 0.318713. Divide (1b) result by (2b) result, then take natural log to derive WoE: ln(0.85246/0.31871) = 0.98383" }, { "code": null, "e": 1819, "s": 1722, "text": "We perform the same steps for “Female” to derive WoE, which is -1.52988. The code is as follows:" }, { "code": null, "e": 2454, "s": 1819, "text": "survived = by(df, :Survived, (count = :Survived => length))sex_df = unstack(by(df, [:Sex, :Survived], (count = :Sex => length)), :Sex, :count)male_event = sex_df[(sex_df.Survived .== 1), :male] / survived[(survived.Survived .== 1), :count]male_non_event = sex_df[(sex_df.Survived .== 0), :male] / survived[(survived.Survived .== 0), :count]woe_male = log(male_non_event/male_event)female_event = sex_df[(sex_df.Survived .== 1), :female] / survived[(survived.Survived .== 1), :count]female_non_event = sex_df[(sex_df.Survived .== 0), :female] / survived[(survived.Survived .== 0), :count]woe_female = log(female_non_event/female_event)" }, { "code": null, "e": 2753, "s": 2454, "text": "Going back to the formula, WoE, through the sign (+/-), shed light on the proportion of male survivors vs the proportion of male victims during the fateful event. However, we are more interested to know the relationship between an independent variable (“Sex”) and a dependent variable (“Survived”)." }, { "code": null, "e": 2876, "s": 2753, "text": "This will then be able to combine different WoEs for under the same independent variable together. The formula is as such:" }, { "code": null, "e": 3120, "s": 2876, "text": "Continuing from our previous example, these are the steps to be taken:4a. Take the difference between (1b) result and (2b) result:0.85246 - 0.31871 = 0.533754b. Multiply (4a) result with (3) result, which is the WoE:0.53375 * 0.98383 = 0.52512" }, { "code": null, "e": 3286, "s": 3120, "text": "We perform the same steps for “Female” and derive 0.81656. Summing both values up, we obtain IV = 1.34168 for the independent variable “Sex”. The code is as follows:" }, { "code": null, "e": 3419, "s": 3286, "text": "iv_male = (male_non_event - male_event) * woe_maleiv_female = (female_non_event - female_event) * woe_femaleiv = iv_male + iv_female" }, { "code": null, "e": 3612, "s": 3419, "text": "Once we have the IV of the variable, we can check against this table to see the predictive power of the variable. As you can see, the table is saying the variable “Sex” is too good to be true!" }, { "code": null, "e": 4012, "s": 3612, "text": "There are a few assumptions we are making here: firstly, the table serves as a guide when the methodology is created to address credit default problem statement. During that time, the researchers wanted to understand the variables that were likely to influence clients’ credit ratings. The researchers found that the table was very relevant to their problem statement. It was then served as a guide." }, { "code": null, "e": 4284, "s": 4012, "text": "Secondly, it has been shown that more females than males survived from the sinking of Titanic. The odds of females surviving is higher than that of males from the accident. Hence, it is no surprise that the variable “Sex” is indeed an exceptional strong predictive power." }, { "code": null, "e": 4698, "s": 4284, "text": "Apart from applying the concepts for research purposes, the main practical use of WoE is for encoding, where you can replace the classes with their associated values. For example, in our example, you can replace “Male” with 0.98383 and “Female” with -1.52988. The reason is obvious: Machine Learning algorithms are primarily taking numbers as inputs, so we have to turn strings to figures before training a model." }, { "code": null, "e": 5050, "s": 4698, "text": "Another positive outcome of using WoE is to reduce the number of columns of the input used for training a model. Imagine you have a categorical variable with 10 different classes and you perform a one-hot encoding, you will end up with 10 columns with mostly ‘0’ as values. Using WoE technique, the classes are replaced by their associated WoE values." }, { "code": null, "e": 5329, "s": 5050, "text": "As for IVs, they provide a basis for us to drill down further in our relationship analysis between independent and dependent variables. Furthermore, if the variable is a qualitative type, we can use binning method followed by WoE and IV concepts to engineer meaningful features." } ]
Loading Image using Glide in Android
Before getting into Glide example, we should know what is glide, Glide is an image processing library developed by muyangmin. Using glide library we can show image, decode images,cache images, animated gifs and many more. This example demonstrate about how to integrate glide 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 in build.gradle(Module:app). apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.myapplication" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' implementation 'com.github.bumptech.glide:glide:4.8.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } Step 3 − Add the following code in build.gradle(Project:Myapplication). // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } Step 4 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout 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"> <LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:background = "#797979" android:gravity = "center" android:orientation = "vertical"> <ImageView android:id = "@+id/imageView" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> </android.support.constraint.ConstraintLayout> Step 5 − Add the following code to src/MainActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import com.bumptech.glide.Glide; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = findViewById(R.id.imageView); Glide.with(this) .load("https://www.tutorialspoint.com/images/tp-logo-diamond.png") .into(imageView); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen Click here to download the project code
[ { "code": null, "e": 1284, "s": 1062, "text": "Before getting into Glide example, we should know what is glide, Glide is an image processing library developed by muyangmin. Using glide library we can show image, decode images,cache images, animated gifs and many more." }, { "code": null, "e": 1350, "s": 1284, "text": "This example demonstrate about how to integrate glide in android." }, { "code": null, "e": 1479, "s": 1350, "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": 1540, "s": 1479, "text": "Step 2 − Add the following code in build.gradle(Module:app)." }, { "code": null, "e": 2564, "s": 1540, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n implementation 'com.github.bumptech.glide:glide:4.8.0'\n annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}" }, { "code": null, "e": 2636, "s": 2564, "text": "Step 3 − Add the following code in build.gradle(Project:Myapplication)." }, { "code": null, "e": 3143, "s": 2636, "text": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n repositories {\n google()\n jcenter()\n }\n dependencies {\n classpath 'com.android.tools.build:gradle:3.2.1'\n // NOTE: Do not place your application dependencies here; they belong\n // in the individual module build.gradle files\n }\n}\nallprojects {\n repositories {\n google()\n jcenter()\n }\n}\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}" }, { "code": null, "e": 3208, "s": 3143, "text": "Step 4 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3926, "s": 3208, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\" xmlns:tools = \"http://schemas.android.com/tools\" android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n <LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:background = \"#797979\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <ImageView\n android:id = \"@+id/imageView\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 3983, "s": 3926, "text": "Step 5 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4520, "s": 3983, "text": "import android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.ImageView;\nimport com.bumptech.glide.Glide;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ImageView imageView = findViewById(R.id.imageView);\n Glide.with(this)\n .load(\"https://www.tutorialspoint.com/images/tp-logo-diamond.png\")\n .into(imageView);\n }\n}" }, { "code": null, "e": 4866, "s": 4520, "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": 4906, "s": 4866, "text": "Click here to download the project code" } ]
How to fill the NA with last observation in the column of an R data frame?
There are multiple ways to fill missing values in data analysis and one of the ways is filling them with the previous value in the same column of the data frame. For example, if we have a column x in data frame df and this columns x contains some NA values then we can fill them with the values in the upper row. This can be done with the help of na.locf function of zoo package. Consider the below data frame − Live Demo set.seed(477) x<-sample(c(0,1,NA),20,replace=TRUE) y<-sample(c(0:2,NA),20,replace=TRUE) z<-sample(c(0:5,NA),20,replace=TRUE) a<-sample(c(7,11,13,NA),20,replace=TRUE) b<-sample(c(51,NA),20,replace=TRUE) c<-sample(c(rnorm(2,1,0.05),NA),20,replace=TRUE) df<-data.frame(x,y,z,a,b,c) df x y z a b c 1 1 1 3 13 51 1.011752 2 NA 1 1 NA NA 1.011752 3 0 0 2 11 NA 1.092852 4 NA 0 4 7 51 1.011752 5 NA 1 5 11 51 NA 6 1 NA 0 7 51 NA 7 0 1 5 11 51 1.092852 8 0 0 5 7 NA 1.011752 9 1 1 3 NA NA 1.092852 10 1 NA 2 7 51 1.011752 11 0 1 3 NA 51 1.011752 12 NA 1 4 11 51 NA 13 1 NA 3 NA NA 1.011752 14 NA 0 5 11 51 1.011752 15 0 NA 0 NA NA NA 16 NA 0 3 7 NA 1.092852 17 NA NA NA NA 51 NA 18 NA 1 3 11 51 1.011752 19 NA NA 0 11 51 NA 20 NA NA 0 11 NA NA Loading zoo package and replacing the NA values with last observation in the same column − library(zoo) na.locf(df) x y z a b c 2 1 1 4 7 51 1.031294 3 0 2 3 7 51 1.031294 4 0 2 2 13 51 1.031294 5 0 0 3 13 51 0.954332 6 0 0 2 13 51 1.031294 7 1 2 2 13 51 1.031294 8 1 1 5 13 51 0.954332 9 1 1 3 7 51 1.031294 10 1 1 3 7 51 0.954332 11 0 1 0 7 51 0.954332 12 0 1 2 13 51 0.954332 13 1 1 4 7 51 0.954332 14 0 2 4 7 51 0.954332 15 0 0 0 11 51 0.954332 16 0 0 1 13 51 0.954332 17 0 0 0 13 51 0.954332 18 0 2 2 11 51 1.031294 19 0 2 3 7 51 0.954332 20 1 2 3 7 51 0.954332 Let’s have a look at another example − Live Demo v1<-sample(c(rexp(5,1),NA),20,replace=TRUE) v2<-sample(c(runif(5,1,2),NA),20,replace=TRUE) v3<-sample(c(rnorm(4,0.95,0.04),NA),20,replace=TRUE) df_v<-data.frame(v1,v2,v3) df_v v1 v2 v3 1 0.3197994 1.664430 0.9608500 2 0.7260356 1.951135 0.9741401 3 0.2851354 1.951135 0.9741401 4 NA 1.354400 0.9155426 5 0.4840855 1.951135 0.9155426 6 0.7260356 1.927019 0.9155426 7 0.3197994 1.602498 0.9608500 8 0.3197994 1.602498 NA 9 0.7260356 1.951135 NA 10 0.4840855 1.354400 NA 11 NA 1.664430 NA 12 0.7260356 1.927019 NA 13 0.3197994 1.951135 0.9741401 14 0.2851354 1.354400 0.9155426 15 2.3741214 1.602498 0.9290660 16 0.3197994 1.354400 0.9290660 17 0.7260356 1.951135 0.9155426 18 0.3197994 1.354400 0.9608500 19 0.7260356 1.664430 0.9290660 20 NA 1.602498 NA Replacing the NA values with last observation in the same column − na.locf(df_v) v1 v2 v3 1 0.1109255 1.687216 0.9349647 2 0.1109255 1.687216 0.9611297 3 0.1862784 1.025610 0.9405675 4 0.1862784 1.278997 0.9517017 5 0.1109255 1.341934 0.9517017 6 0.1862784 1.687216 0.9517017 7 0.3978860 1.687216 0.9349647 8 0.1862784 1.025610 0.9517017 9 0.6972909 1.687216 0.9405675 10 0.1109255 1.199711 0.9405675 11 0.1109255 1.199711 0.9611297 12 0.6972909 1.199711 0.9349647 13 0.1862784 1.199711 0.9611297 14 0.3978860 1.025610 0.9349647 15 0.6972909 1.341934 0.9349647 16 0.3978860 1.025610 0.9405675 17 0.6972909 1.199711 0.9517017 18 0.1862784 1.687216 0.9517017 19 0.1862784 1.025610 0.9405675 20 0.6972909 1.025610 0.9611297
[ { "code": null, "e": 1442, "s": 1062, "text": "There are multiple ways to fill missing values in data analysis and one of the ways is filling them with the previous value in the same column of the data frame. For example, if we have a column x in data frame df and this columns x contains some NA values then we can fill them with the values in the upper row. This can be done with the help of na.locf function of zoo package." }, { "code": null, "e": 1474, "s": 1442, "text": "Consider the below data frame −" }, { "code": null, "e": 1485, "s": 1474, "text": " Live Demo" }, { "code": null, "e": 1767, "s": 1485, "text": "set.seed(477)\nx<-sample(c(0,1,NA),20,replace=TRUE)\ny<-sample(c(0:2,NA),20,replace=TRUE)\nz<-sample(c(0:5,NA),20,replace=TRUE)\na<-sample(c(7,11,13,NA),20,replace=TRUE)\nb<-sample(c(51,NA),20,replace=TRUE)\nc<-sample(c(rnorm(2,1,0.05),NA),20,replace=TRUE)\ndf<-data.frame(x,y,z,a,b,c)\ndf" }, { "code": null, "e": 2223, "s": 1767, "text": " x y z a b c\n1 1 1 3 13 51 1.011752\n2 NA 1 1 NA NA 1.011752\n3 0 0 2 11 NA 1.092852\n4 NA 0 4 7 51 1.011752\n5 NA 1 5 11 51 NA\n6 1 NA 0 7 51 NA\n7 0 1 5 11 51 1.092852\n8 0 0 5 7 NA 1.011752\n9 1 1 3 NA NA 1.092852\n10 1 NA 2 7 51 1.011752\n11 0 1 3 NA 51 1.011752\n12 NA 1 4 11 51 NA\n13 1 NA 3 NA NA 1.011752\n14 NA 0 5 11 51 1.011752\n15 0 NA 0 NA NA NA\n16 NA 0 3 7 NA 1.092852\n17 NA NA NA NA 51 NA\n18 NA 1 3 11 51 1.011752\n19 NA NA 0 11 51 NA\n20 NA NA 0 11 NA NA" }, { "code": null, "e": 2314, "s": 2223, "text": "Loading zoo package and replacing the NA values with last observation in the same column −" }, { "code": null, "e": 2339, "s": 2314, "text": "library(zoo)\nna.locf(df)" }, { "code": null, "e": 2856, "s": 2339, "text": " x y z a b c\n2 1 1 4 7 51 1.031294\n3 0 2 3 7 51 1.031294\n4 0 2 2 13 51 1.031294\n5 0 0 3 13 51 0.954332\n6 0 0 2 13 51 1.031294\n7 1 2 2 13 51 1.031294\n8 1 1 5 13 51 0.954332\n9 1 1 3 7 51 1.031294\n10 1 1 3 7 51 0.954332\n11 0 1 0 7 51 0.954332\n12 0 1 2 13 51 0.954332\n13 1 1 4 7 51 0.954332\n14 0 2 4 7 51 0.954332\n15 0 0 0 11 51 0.954332\n16 0 0 1 13 51 0.954332\n17 0 0 0 13 51 0.954332\n18 0 2 2 11 51 1.031294\n19 0 2 3 7 51 0.954332\n20 1 2 3 7 51 0.954332" }, { "code": null, "e": 2895, "s": 2856, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2906, "s": 2895, "text": " Live Demo" }, { "code": null, "e": 3082, "s": 2906, "text": "v1<-sample(c(rexp(5,1),NA),20,replace=TRUE)\nv2<-sample(c(runif(5,1,2),NA),20,replace=TRUE)\nv3<-sample(c(rnorm(4,0.95,0.04),NA),20,replace=TRUE)\ndf_v<-data.frame(v1,v2,v3)\ndf_v" }, { "code": null, "e": 3748, "s": 3082, "text": " v1 v2 v3\n1 0.3197994 1.664430 0.9608500\n2 0.7260356 1.951135 0.9741401\n3 0.2851354 1.951135 0.9741401\n4 NA 1.354400 0.9155426\n5 0.4840855 1.951135 0.9155426\n6 0.7260356 1.927019 0.9155426\n7 0.3197994 1.602498 0.9608500\n8 0.3197994 1.602498 NA\n9 0.7260356 1.951135 NA\n10 0.4840855 1.354400 NA\n11 NA 1.664430 NA\n12 0.7260356 1.927019 NA\n13 0.3197994 1.951135 0.9741401\n14 0.2851354 1.354400 0.9155426\n15 2.3741214 1.602498 0.9290660\n16 0.3197994 1.354400 0.9290660\n17 0.7260356 1.951135 0.9155426\n18 0.3197994 1.354400 0.9608500\n19 0.7260356 1.664430 0.9290660\n20 NA 1.602498 NA" }, { "code": null, "e": 3815, "s": 3748, "text": "Replacing the NA values with last observation in the same column −" }, { "code": null, "e": 3829, "s": 3815, "text": "na.locf(df_v)" }, { "code": null, "e": 4495, "s": 3829, "text": " v1 v2 v3\n1 0.1109255 1.687216 0.9349647\n2 0.1109255 1.687216 0.9611297\n3 0.1862784 1.025610 0.9405675\n4 0.1862784 1.278997 0.9517017\n5 0.1109255 1.341934 0.9517017\n6 0.1862784 1.687216 0.9517017\n7 0.3978860 1.687216 0.9349647\n8 0.1862784 1.025610 0.9517017\n9 0.6972909 1.687216 0.9405675\n10 0.1109255 1.199711 0.9405675\n11 0.1109255 1.199711 0.9611297\n12 0.6972909 1.199711 0.9349647\n13 0.1862784 1.199711 0.9611297\n14 0.3978860 1.025610 0.9349647\n15 0.6972909 1.341934 0.9349647\n16 0.3978860 1.025610 0.9405675\n17 0.6972909 1.199711 0.9517017\n18 0.1862784 1.687216 0.9517017\n19 0.1862784 1.025610 0.9405675\n20 0.6972909 1.025610 0.9611297" } ]
C# Program For Reading Data From Stream and Cast Data to Chars - GeeksforGeeks
01 Nov, 2021 Given data, now our task is to read data from the stream and cast data to chars in C#. So to do this task we use the following class and methods: FileStream: It is a class that is used to read and write files. So, to manipulate files using FileStream, you need to create an object of FileStream class. Syntax: Stream object = new FileStream(path, FileMode.Open) Where path is the location of your file – @”c:\A\data.txt” and FileMode is the mode of the file like reading and writing. ReadByte(): This method is used to read the data from the file Byte by Byte. This method will throw NotSupportException when the current stream did not support reading. If the current stream is closed then this method will throw ObjectDisposedException. Syntax: FileStream_object.ReadByte() Example: Let us consider a file named “file.txt” is present in the A folder of C drive like as shown in the below image: Now we read data from stream and cast data to chars. So to this follow the following approach. Approach Read the file named “file.txt” using FileStream with the help of specified path. Read the data in file byte by byte using ReadByte() method until it reaches end of file. while ((obj = s.ReadByte()) != -1) { // Convert the data into chars and display Console.Write("{0} ", (char)obj); } Display file data into chars using Casting to char. (char)obj C# // C# program to read the data from stream// and cast data to chars using System;using System.IO; public sealed class GFG{ public static void Main(){ // Read the file from the specified path using (Stream s = new FileStream(@"c:\A\file.txt", FileMode.Open)) { int obj; // Read the data in file byte by byte // Using ReadByte() method while ((obj = s.ReadByte()) != -1) { // Convert the data into chars and display Console.Write("{0} ", (char)obj); } Console.ReadLine(); }}} Output: T H I S I S F I L E D E M O CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Nov, 2021" }, { "code": null, "e": 24448, "s": 24302, "text": "Given data, now our task is to read data from the stream and cast data to chars in C#. So to do this task we use the following class and methods:" }, { "code": null, "e": 24605, "s": 24448, "text": "FileStream: It is a class that is used to read and write files. So, to manipulate files using FileStream, you need to create an object of FileStream class. " }, { "code": null, "e": 24613, "s": 24605, "text": "Syntax:" }, { "code": null, "e": 24665, "s": 24613, "text": "Stream object = new FileStream(path, FileMode.Open)" }, { "code": null, "e": 24787, "s": 24665, "text": "Where path is the location of your file – @”c:\\A\\data.txt” and FileMode is the mode of the file like reading and writing." }, { "code": null, "e": 25041, "s": 24787, "text": "ReadByte(): This method is used to read the data from the file Byte by Byte. This method will throw NotSupportException when the current stream did not support reading. If the current stream is closed then this method will throw ObjectDisposedException." }, { "code": null, "e": 25049, "s": 25041, "text": "Syntax:" }, { "code": null, "e": 25078, "s": 25049, "text": "FileStream_object.ReadByte()" }, { "code": null, "e": 25087, "s": 25078, "text": "Example:" }, { "code": null, "e": 25199, "s": 25087, "text": "Let us consider a file named “file.txt” is present in the A folder of C drive like as shown in the below image:" }, { "code": null, "e": 25294, "s": 25199, "text": "Now we read data from stream and cast data to chars. So to this follow the following approach." }, { "code": null, "e": 25303, "s": 25294, "text": "Approach" }, { "code": null, "e": 25384, "s": 25303, "text": "Read the file named “file.txt” using FileStream with the help of specified path." }, { "code": null, "e": 25473, "s": 25384, "text": "Read the data in file byte by byte using ReadByte() method until it reaches end of file." }, { "code": null, "e": 25598, "s": 25473, "text": "while ((obj = s.ReadByte()) != -1)\n{\n\n // Convert the data into chars and display\n Console.Write(\"{0} \", (char)obj);\n}" }, { "code": null, "e": 25650, "s": 25598, "text": "Display file data into chars using Casting to char." }, { "code": null, "e": 25660, "s": 25650, "text": "(char)obj" }, { "code": null, "e": 25663, "s": 25660, "text": "C#" }, { "code": "// C# program to read the data from stream// and cast data to chars using System;using System.IO; public sealed class GFG{ public static void Main(){ // Read the file from the specified path using (Stream s = new FileStream(@\"c:\\A\\file.txt\", FileMode.Open)) { int obj; // Read the data in file byte by byte // Using ReadByte() method while ((obj = s.ReadByte()) != -1) { // Convert the data into chars and display Console.Write(\"{0} \", (char)obj); } Console.ReadLine(); }}}", "e": 26256, "s": 25663, "text": null }, { "code": null, "e": 26264, "s": 26256, "text": "Output:" }, { "code": null, "e": 26295, "s": 26264, "text": "T H I S I S F I L E D E M O" }, { "code": null, "e": 26311, "s": 26295, "text": "CSharp-programs" }, { "code": null, "e": 26318, "s": 26311, "text": "Picked" }, { "code": null, "e": 26321, "s": 26318, "text": "C#" }, { "code": null, "e": 26419, "s": 26321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26437, "s": 26419, "text": "Destructors in C#" }, { "code": null, "e": 26460, "s": 26437, "text": "Extension Method in C#" }, { "code": null, "e": 26488, "s": 26460, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26528, "s": 26488, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26571, "s": 26528, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26593, "s": 26571, "text": "Partial Classes in C#" }, { "code": null, "e": 26610, "s": 26593, "text": "C# | Inheritance" }, { "code": null, "e": 26626, "s": 26610, "text": "C# | List Class" }, { "code": null, "e": 26676, "s": 26626, "text": "Difference between Hashtable and Dictionary in C#" } ]
How to create a plot in R with a different plot window size using plot function?
We can create plots in R with having different plot window sizes. This will be helpful when we want to express X-axis or Y-axis differently. Also, the change in the size of the plot window will help us to paste the plot in places that are short or large. For example, if we want to present the plot in a business meeting then we can increase its size and if we want to publish it in a paper then its size can be decreased. Consider the below vectors x and y − > x<-1:20 > y<-20:1 Plotting with default − > plot(x,y) Plotting with 10-inch-wide and 5 inch in height − > dev.new(width=10, height=5, unit="in") > plot(x,y) Plotting with 10-cm-wide and 5-cm in height − > dev.new(width=5, height=5, unit="cm") > plot(x,y) Plotting with 100x50 pixel − > dev.new(width=100, height=50, unit="px") > plot(x,y)
[ { "code": null, "e": 1485, "s": 1062, "text": "We can create plots in R with having different plot window sizes. This will be helpful when we want to express X-axis or Y-axis differently. Also, the change in the size of the plot window will help us to paste the plot in places that are short or large. For example, if we want to present the plot in a business meeting then we can increase its size and if we want to publish it in a paper then its size can be decreased." }, { "code": null, "e": 1522, "s": 1485, "text": "Consider the below vectors x and y −" }, { "code": null, "e": 1542, "s": 1522, "text": "> x<-1:20\n> y<-20:1" }, { "code": null, "e": 1566, "s": 1542, "text": "Plotting with default −" }, { "code": null, "e": 1578, "s": 1566, "text": "> plot(x,y)" }, { "code": null, "e": 1628, "s": 1578, "text": "Plotting with 10-inch-wide and 5 inch in height −" }, { "code": null, "e": 1681, "s": 1628, "text": "> dev.new(width=10, height=5, unit=\"in\")\n> plot(x,y)" }, { "code": null, "e": 1727, "s": 1681, "text": "Plotting with 10-cm-wide and 5-cm in height −" }, { "code": null, "e": 1779, "s": 1727, "text": "> dev.new(width=5, height=5, unit=\"cm\")\n> plot(x,y)" }, { "code": null, "e": 1808, "s": 1779, "text": "Plotting with 100x50 pixel −" }, { "code": null, "e": 1863, "s": 1808, "text": "> dev.new(width=100, height=50, unit=\"px\")\n> plot(x,y)" } ]
C++ Program to Implement Network_Flow Problem
This is a C++ Program to implement Network_Flow problem using Ford Fulkerson algorithm. Begin function bfs() returns true if there is path from source s to sink t in the residual graph which indicates additional possible flow in the graph. End Begin function fordfulkarson() return maximum flow in given graph: A) initiate flow as 0. B) If there is an augmenting path from source to sink, add the path to flow. C) Return flow. End #include <iostream> #include <climits> #include <cstring> #include <queue> #define n 7 using namespace std; bool bfs(int g[n][n], int s, int t, int par[]) { bool visit[n]; memset(visit, 0, sizeof(visit)); queue <int> q; q.push(s); visit[s] = true; par[s] = -1; while (!q.empty()) { int u = q.front(); q.pop(); for (int v=0; v<n; v++) { if (visit[v]==false && g[u][v] > 0) { q.push(v); par[v] = u; visit[v] = true; } } } return (visit[t] == true); } int fordFulkerson(int G[n][n], int s, int t) { int u, v; int g[n][n]; for (u = 0; u < n; u++) { for (v = 0; v < n; v++) g[u][v] = G[u][v]; } int par[n]; int max_flow = 0; while (bfs(g, s, t,par)) { int path_flow = INT_MAX; for (v=t; v!=s; v=par[v]) { u = par[v]; path_flow = min(path_flow, g[u][v]); } for (v = t; v != s; v = par[v]) { u = par[v]; g[u][v] -= path_flow; g[v][u] += path_flow; } max_flow += path_flow; } return max_flow; } int main() { int g[n][n] = {{0, 6, 7, 1}, {0, 0, 4, 2}, {0, 5, 0, 0}, {0, 0, 19, 12}, {0, 0, 0, 17}, {0, 0, 0, 0}}; cout << "The maximum possible flow is " << fordFulkerson(g, 0, 3); return 0; } The maximum possible flow is 3
[ { "code": null, "e": 1150, "s": 1062, "text": "This is a C++ Program to implement Network_Flow problem using Ford Fulkerson algorithm." }, { "code": null, "e": 1511, "s": 1150, "text": "Begin\n function bfs() returns true if there is path from source s to sink t in\n the residual graph which indicates additional possible flow in the graph.\nEnd\nBegin\n function fordfulkarson() return maximum flow in given graph:\n A) initiate flow as 0.\n B) If there is an augmenting path from source to sink, add the path to flow.\n C) Return flow.\nEnd" }, { "code": null, "e": 2899, "s": 1511, "text": "#include <iostream>\n#include <climits>\n#include <cstring>\n#include <queue>\n#define n 7\nusing namespace std;\nbool bfs(int g[n][n], int s, int t, int par[])\n{\n bool visit[n];\n memset(visit, 0, sizeof(visit));\n queue <int> q;\n q.push(s);\n visit[s] = true;\n par[s] = -1;\n while (!q.empty())\n {\n int u = q.front();\n q.pop();\n for (int v=0; v<n; v++)\n {\n if (visit[v]==false && g[u][v] > 0)\n {\n q.push(v);\n par[v] = u;\n visit[v] = true;\n }\n }\n }\n return (visit[t] == true);\n}\nint fordFulkerson(int G[n][n], int s, int t)\n{\n int u, v;\n int g[n][n];\n for (u = 0; u < n; u++)\n {\n for (v = 0; v < n; v++)\n g[u][v] = G[u][v];\n }\n int par[n];\n int max_flow = 0;\n while (bfs(g, s, t,par))\n {\n int path_flow = INT_MAX;\n for (v=t; v!=s; v=par[v])\n {\n u = par[v];\n path_flow = min(path_flow, g[u][v]);\n }\n for (v = t; v != s; v = par[v])\n {\n u = par[v]; \n g[u][v] -= path_flow;\n g[v][u] += path_flow;\n }\n max_flow += path_flow;\n }\n return max_flow;\n}\nint main()\n{\n int g[n][n] = {{0, 6, 7, 1},\n {0, 0, 4, 2},\n {0, 5, 0, 0},\n {0, 0, 19, 12},\n {0, 0, 0, 17},\n {0, 0, 0, 0}};\n cout << \"The maximum possible flow is \" << fordFulkerson(g, 0, 3);\n return 0;\n}" }, { "code": null, "e": 2930, "s": 2899, "text": "The maximum possible flow is 3" } ]
Cosets in Mathematics - GeeksforGeeks
07 Sep, 2020 Coset is subset of mathematical group consisting of all the products obtained by multiplying fixed element of group by each of elements of given subgroup, either on right or on left.mCosets are basic tool in study of groups Suppose if A is group, and B is subgroup of A, and is an element of A, then aB = {ab : b an element of B } is left coset of B in A, The left coset of B in A is subset of A of form aB for some a(element of A). In aB(left coset), a is representative of coset. and Ba = {ba : b an element of B } is right coset of B in A. The right coset of B in A is subset of A of form Ba for some a(element of A). In right coset Ba, element a is referred to as representative of coset. The map aB -> (aB)' = Ba' map defines bijection between left cosets and B‘s right cosets, so total of left cosets is equivalent to total of right cosets. The common value is called index of B in A. Left cosets and right cosets are always the same in case of abelian groupings. Notation used switches to a+B or B+a if group operation is written additively. Definition using Equivalence Classes :Some authors define the left cosets of B in A as equivalence classes given by x ~ y under equivalence relationship on A if and only if x'y subset of B is given. Relation can also be described by x ~ y if and only if xb = y is described in B for certain b. It can be seen that given relation is simply an equivalence relationship and that two concepts are identical. Consequently, two left B-in-A cosets are either equivalent or disjoint. So, every element of A belongs to single left coset and so left cosets form partition of A. Similar claims for right cosets are also valid. Double Cosets :If A is group, B and C are subgroups of A, then in A double coset of B and C are sets of BaC = {bac: b an element of B, c an element of B }. These are left cosets of C and right cosets of B, respectively, if B=1 and C=1. Notation :Suppose A is group and B and C.are subgroups of A. denotes set of left cosetsof B in A. denotes set of right cosets of B in A. denotes set of double cosets of B and C in A. Applications : In computational group theory, cosets are essential.Cosets play key role in the theorem for Lagrange.The Thistlethwaite’s algorithm used to solve Rubik’s Cube is highly based on cosets.linear error-correction in obtained decoded data is done using cosets.They are used to construct Vitali sets, kind of non-measurable package. In computational group theory, cosets are essential. Cosets play key role in the theorem for Lagrange. The Thistlethwaite’s algorithm used to solve Rubik’s Cube is highly based on cosets. linear error-correction in obtained decoded data is done using cosets. They are used to construct Vitali sets, kind of non-measurable package. Picked Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Propositional Logic and Predicate Logic Activation Functions Proof that vertex cover is NP complete Logic Notations in LaTeX Brackets in Latex Layers of OSI Model ACID Properties in DBMS TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems
[ { "code": null, "e": 24916, "s": 24888, "text": "\n07 Sep, 2020" }, { "code": null, "e": 25140, "s": 24916, "text": "Coset is subset of mathematical group consisting of all the products obtained by multiplying fixed element of group by each of elements of given subgroup, either on right or on left.mCosets are basic tool in study of groups" }, { "code": null, "e": 25216, "s": 25140, "text": "Suppose if A is group, and B is subgroup of A, and is an element of A, then" }, { "code": null, "e": 25273, "s": 25216, "text": "aB = {ab : b an element of B } is left coset of B in A,\n" }, { "code": null, "e": 25399, "s": 25273, "text": "The left coset of B in A is subset of A of form aB for some a(element of A). In aB(left coset), a is representative of coset." }, { "code": null, "e": 25403, "s": 25399, "text": "and" }, { "code": null, "e": 25461, "s": 25403, "text": "Ba = {ba : b an element of B } is right coset of B in A.\n" }, { "code": null, "e": 25611, "s": 25461, "text": "The right coset of B in A is subset of A of form Ba for some a(element of A). In right coset Ba, element a is referred to as representative of coset." }, { "code": null, "e": 25809, "s": 25611, "text": "The map aB -> (aB)' = Ba' map defines bijection between left cosets and B‘s right cosets, so total of left cosets is equivalent to total of right cosets. The common value is called index of B in A." }, { "code": null, "e": 25967, "s": 25809, "text": "Left cosets and right cosets are always the same in case of abelian groupings. Notation used switches to a+B or B+a if group operation is written additively." }, { "code": null, "e": 26583, "s": 25967, "text": "Definition using Equivalence Classes :Some authors define the left cosets of B in A as equivalence classes given by x ~ y under equivalence relationship on A if and only if x'y subset of B is given. Relation can also be described by x ~ y if and only if xb = y is described in B for certain b. It can be seen that given relation is simply an equivalence relationship and that two concepts are identical. Consequently, two left B-in-A cosets are either equivalent or disjoint. So, every element of A belongs to single left coset and so left cosets form partition of A. Similar claims for right cosets are also valid." }, { "code": null, "e": 26819, "s": 26583, "text": "Double Cosets :If A is group, B and C are subgroups of A, then in A double coset of B and C are sets of BaC = {bac: b an element of B, c an element of B }. These are left cosets of C and right cosets of B, respectively, if B=1 and C=1." }, { "code": null, "e": 26880, "s": 26819, "text": "Notation :Suppose A is group and B and C.are subgroups of A." }, { "code": null, "e": 26919, "s": 26880, "text": " denotes set of left cosetsof B in A." }, { "code": null, "e": 26960, "s": 26919, "text": " denotes set of right cosets of B in A." }, { "code": null, "e": 27008, "s": 26960, "text": " denotes set of double cosets of B and C in A." }, { "code": null, "e": 27023, "s": 27008, "text": "Applications :" }, { "code": null, "e": 27350, "s": 27023, "text": "In computational group theory, cosets are essential.Cosets play key role in the theorem for Lagrange.The Thistlethwaite’s algorithm used to solve Rubik’s Cube is highly based on cosets.linear error-correction in obtained decoded data is done using cosets.They are used to construct Vitali sets, kind of non-measurable package." }, { "code": null, "e": 27403, "s": 27350, "text": "In computational group theory, cosets are essential." }, { "code": null, "e": 27453, "s": 27403, "text": "Cosets play key role in the theorem for Lagrange." }, { "code": null, "e": 27538, "s": 27453, "text": "The Thistlethwaite’s algorithm used to solve Rubik’s Cube is highly based on cosets." }, { "code": null, "e": 27609, "s": 27538, "text": "linear error-correction in obtained decoded data is done using cosets." }, { "code": null, "e": 27681, "s": 27609, "text": "They are used to construct Vitali sets, kind of non-measurable package." }, { "code": null, "e": 27688, "s": 27681, "text": "Picked" }, { "code": null, "e": 27712, "s": 27688, "text": "Engineering Mathematics" }, { "code": null, "e": 27720, "s": 27712, "text": "GATE CS" }, { "code": null, "e": 27818, "s": 27720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27877, "s": 27818, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 27898, "s": 27877, "text": "Activation Functions" }, { "code": null, "e": 27937, "s": 27898, "text": "Proof that vertex cover is NP complete" }, { "code": null, "e": 27962, "s": 27937, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 27980, "s": 27962, "text": "Brackets in Latex" }, { "code": null, "e": 28000, "s": 27980, "text": "Layers of OSI Model" }, { "code": null, "e": 28024, "s": 28000, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28037, "s": 28024, "text": "TCP/IP Model" }, { "code": null, "e": 28086, "s": 28037, "text": "Page Replacement Algorithms in Operating Systems" } ]
How to Plot Complex Numbers in Python?
You can plot complex numbers on a polar plot. If you have an array of complex numbers, you can plot it using: import matplotlib.pyplot as plt import numpy as np cnums = np.arange(5) + 1j * np.arange(6,11) X = [x.real for x in cnums] Y = [x.imag for x in cnums] plt.scatter(X,Y, color='red') plt.show() This will plot a graph of the numbers in a complex plane.
[ { "code": null, "e": 1172, "s": 1062, "text": "You can plot complex numbers on a polar plot. If you have an array of complex numbers, you can plot it using:" }, { "code": null, "e": 1365, "s": 1172, "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\ncnums = np.arange(5) + 1j * np.arange(6,11)\nX = [x.real for x in cnums]\nY = [x.imag for x in cnums]\nplt.scatter(X,Y, color='red')\nplt.show()" }, { "code": null, "e": 1423, "s": 1365, "text": "This will plot a graph of the numbers in a complex plane." } ]
Running Jupyter Notebook on Google Cloud Platform in 15 min | by Amulya Aankul | Towards Data Science
Recently, while I was doing my research project on Computer Vision using Convolutional Neural Network, I found out that my 8GB RAM laptop is useless. It took me an hour to learn from just 1 epoch. Therefore, rather than spending 1500$ on a new GPU based laptop, I did it for free on Google Cloud. (Google Cloud gives 300$ credit, and I have 3 gmail accounts and 3 credit cards :D) So lets not waste anymore time and move straight to running jupyter notebook in GCP. For this step, you will have to put your payment information and verify your account. It’s the most simple step. If you fail this step, close your laptop and think where you are going in life. Click on the three dots shown in the image below and then click on the + sign to create a new project. Click on the three lines on the upper left corner, then on the compute option, click on ‘Compute Engine’ Now click on ‘Create new instance’. Name your instance, select zone as ‘ us-west1-b’. Choose your ‘machine type’. (I chose 8v CPUs). Select your boot disk as ‘Ubuntu 16.04 LTS’. Under the firewall options tick both ‘http’ and ‘https’ (very important). Then, choose the disk tab and untick ‘ Delete boot disk when instance is deleted’. If you click on ‘customize’, you will be able to find options for using GPUs. You can choose between 2 NVIDIA GPUs. Some firewall settings:- Now click on ‘Create’ and your instance is ready! Your new VM instance should look something like this. Note down the External IP. IMPORTANT : DON’T FORGET TO STOP YOUR GPU INSTANCE AFTER YOU ARE DONE BY CLICKING ON THE THREE DOTS ON THE IMAGE ABOVE AND SELECTING STOP. OTHERWISE GCP WILL KEEP CHARGING YOU ON AN HOURLY BASIS. By default, the external IP address is dynamic and we need to make it static to make our life easier. Click on the three horizontal lines on top left and then under networking, click on VPC network and then External IP addresses. Change the type from Ephemeral to Static. Now, click on the ‘Firewall rules’ setting under Networking. Click on ‘Create Firewall Rules’ and refer the below image: Under protocols and ports you can choose any port. I have chosen tcp:5000 as my port number. Now click on the save button. Now start your VM instance. When you see the green tick click on SSH. This will open a command window and now you are inside the VM. In your SSH terminal, enter: wget http://repo.continuum.io/archive/Anaconda3-4.0.0-Linux-x86_64.shbash Anaconda3-4.0.0-Linux-x86_64.sh and follow the on-screen instructions. The defaults usually work fine, but answer yes to the last question about prepending the install location to PATH: Do you wish the installer to prepend the Anaconda3 install location to PATH in your /home/haroldsoh/.bashrc ? [yes|no][no] >>> yes To make use of Anaconda right away, source your bashrc: source ~/.bashrc Now, install other softwares : pip install tensorflowpip install keras Open up a SSH session to your VM. Check if you have a Jupyter configuration file: ls ~/.jupyter/jupyter_notebook_config.py If it doesn’t exist, create one: jupyter notebook --generate-config We’re going to add a few lines to your Jupyter configuration file; the file is plain text so, you can do this via your favorite editor (e.g., vim, emacs). Make sure you replace the port number with the one you allowed firewall access to in step 5. c = get_config()c.NotebookApp.ip = '*'c.NotebookApp.open_browser = Falsec.NotebookApp.port = <Port Number> It should look something like this : To run the jupyter notebook, just type the following command in the ssh window you are in : jupyter-notebook --no-browser --port=<PORT-NUMBER> Once you run the command, it should show something like this: Now to launch your jupyter notebook, just type the following in your browser: http://<External Static IP Address>:<Port Number> where, external ip address is the ip address which we made static and port number is the one which we allowed firewall access to. Congratulations! You successfully installed jupyter notebook on GCP! Lets connect : https://www.linkedin.com/in/aankul Follow me on medium: https://medium.com/@aankul.a Edit :All those facing ‘ERR_CONNECTION_TIMED_OUT’ error. Please try Bastardized Eloquence’s solution in the comments. Some rights reserved
[ { "code": null, "e": 552, "s": 171, "text": "Recently, while I was doing my research project on Computer Vision using Convolutional Neural Network, I found out that my 8GB RAM laptop is useless. It took me an hour to learn from just 1 epoch. Therefore, rather than spending 1500$ on a new GPU based laptop, I did it for free on Google Cloud. (Google Cloud gives 300$ credit, and I have 3 gmail accounts and 3 credit cards :D)" }, { "code": null, "e": 637, "s": 552, "text": "So lets not waste anymore time and move straight to running jupyter notebook in GCP." }, { "code": null, "e": 830, "s": 637, "text": "For this step, you will have to put your payment information and verify your account. It’s the most simple step. If you fail this step, close your laptop and think where you are going in life." }, { "code": null, "e": 933, "s": 830, "text": "Click on the three dots shown in the image below and then click on the + sign to create a new project." }, { "code": null, "e": 1038, "s": 933, "text": "Click on the three lines on the upper left corner, then on the compute option, click on ‘Compute Engine’" }, { "code": null, "e": 1171, "s": 1038, "text": "Now click on ‘Create new instance’. Name your instance, select zone as ‘ us-west1-b’. Choose your ‘machine type’. (I chose 8v CPUs)." }, { "code": null, "e": 1373, "s": 1171, "text": "Select your boot disk as ‘Ubuntu 16.04 LTS’. Under the firewall options tick both ‘http’ and ‘https’ (very important). Then, choose the disk tab and untick ‘ Delete boot disk when instance is deleted’." }, { "code": null, "e": 1489, "s": 1373, "text": "If you click on ‘customize’, you will be able to find options for using GPUs. You can choose between 2 NVIDIA GPUs." }, { "code": null, "e": 1514, "s": 1489, "text": "Some firewall settings:-" }, { "code": null, "e": 1564, "s": 1514, "text": "Now click on ‘Create’ and your instance is ready!" }, { "code": null, "e": 1645, "s": 1564, "text": "Your new VM instance should look something like this. Note down the External IP." }, { "code": null, "e": 1841, "s": 1645, "text": "IMPORTANT : DON’T FORGET TO STOP YOUR GPU INSTANCE AFTER YOU ARE DONE BY CLICKING ON THE THREE DOTS ON THE IMAGE ABOVE AND SELECTING STOP. OTHERWISE GCP WILL KEEP CHARGING YOU ON AN HOURLY BASIS." }, { "code": null, "e": 2071, "s": 1841, "text": "By default, the external IP address is dynamic and we need to make it static to make our life easier. Click on the three horizontal lines on top left and then under networking, click on VPC network and then External IP addresses." }, { "code": null, "e": 2113, "s": 2071, "text": "Change the type from Ephemeral to Static." }, { "code": null, "e": 2174, "s": 2113, "text": "Now, click on the ‘Firewall rules’ setting under Networking." }, { "code": null, "e": 2234, "s": 2174, "text": "Click on ‘Create Firewall Rules’ and refer the below image:" }, { "code": null, "e": 2357, "s": 2234, "text": "Under protocols and ports you can choose any port. I have chosen tcp:5000 as my port number. Now click on the save button." }, { "code": null, "e": 2490, "s": 2357, "text": "Now start your VM instance. When you see the green tick click on SSH. This will open a command window and now you are inside the VM." }, { "code": null, "e": 2519, "s": 2490, "text": "In your SSH terminal, enter:" }, { "code": null, "e": 2625, "s": 2519, "text": "wget http://repo.continuum.io/archive/Anaconda3-4.0.0-Linux-x86_64.shbash Anaconda3-4.0.0-Linux-x86_64.sh" }, { "code": null, "e": 2779, "s": 2625, "text": "and follow the on-screen instructions. The defaults usually work fine, but answer yes to the last question about prepending the install location to PATH:" }, { "code": null, "e": 2910, "s": 2779, "text": "Do you wish the installer to prepend the Anaconda3 install location to PATH in your /home/haroldsoh/.bashrc ? [yes|no][no] >>> yes" }, { "code": null, "e": 2966, "s": 2910, "text": "To make use of Anaconda right away, source your bashrc:" }, { "code": null, "e": 2983, "s": 2966, "text": "source ~/.bashrc" }, { "code": null, "e": 3014, "s": 2983, "text": "Now, install other softwares :" }, { "code": null, "e": 3054, "s": 3014, "text": "pip install tensorflowpip install keras" }, { "code": null, "e": 3136, "s": 3054, "text": "Open up a SSH session to your VM. Check if you have a Jupyter configuration file:" }, { "code": null, "e": 3177, "s": 3136, "text": "ls ~/.jupyter/jupyter_notebook_config.py" }, { "code": null, "e": 3210, "s": 3177, "text": "If it doesn’t exist, create one:" }, { "code": null, "e": 3245, "s": 3210, "text": "jupyter notebook --generate-config" }, { "code": null, "e": 3493, "s": 3245, "text": "We’re going to add a few lines to your Jupyter configuration file; the file is plain text so, you can do this via your favorite editor (e.g., vim, emacs). Make sure you replace the port number with the one you allowed firewall access to in step 5." }, { "code": null, "e": 3600, "s": 3493, "text": "c = get_config()c.NotebookApp.ip = '*'c.NotebookApp.open_browser = Falsec.NotebookApp.port = <Port Number>" }, { "code": null, "e": 3637, "s": 3600, "text": "It should look something like this :" }, { "code": null, "e": 3729, "s": 3637, "text": "To run the jupyter notebook, just type the following command in the ssh window you are in :" }, { "code": null, "e": 3780, "s": 3729, "text": "jupyter-notebook --no-browser --port=<PORT-NUMBER>" }, { "code": null, "e": 3842, "s": 3780, "text": "Once you run the command, it should show something like this:" }, { "code": null, "e": 3920, "s": 3842, "text": "Now to launch your jupyter notebook, just type the following in your browser:" }, { "code": null, "e": 3970, "s": 3920, "text": "http://<External Static IP Address>:<Port Number>" }, { "code": null, "e": 4100, "s": 3970, "text": "where, external ip address is the ip address which we made static and port number is the one which we allowed firewall access to." }, { "code": null, "e": 4169, "s": 4100, "text": "Congratulations! You successfully installed jupyter notebook on GCP!" }, { "code": null, "e": 4219, "s": 4169, "text": "Lets connect : https://www.linkedin.com/in/aankul" }, { "code": null, "e": 4269, "s": 4219, "text": "Follow me on medium: https://medium.com/@aankul.a" }, { "code": null, "e": 4387, "s": 4269, "text": "Edit :All those facing ‘ERR_CONNECTION_TIMED_OUT’ error. Please try Bastardized Eloquence’s solution in the comments." } ]
C# Program for Anagram Substring Search (Or Search for all permutations) - GeeksforGeeks
07 Jul, 2021 Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m.Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found at Index 6 2) Input: txt[] = "AAABABAA" pat[] = "AABA" Output: Found at Index 0 Found at Index 1 Found at Index 4 A simple idea is to modify Rabin Karp Algorithm. For example we can keep the hash value as sum of ASCII values of all characters under modulo of a big prime number. For every character of text, we can add the current character to hash value and subtract the first character of previous window. This solution looks good, but like standard Rabin Karp, the worst case time complexity of this solution is O(mn). The worst case occurs when all hash values match and we one by one match all characters.We can achieve O(n) time complexity under the assumption that alphabet size is fixed which is typically true as we have maximum 256 possible characters in ASCII. The idea is to use two count arrays: 1) The first count array store frequencies of characters in pattern.2) The second count array stores frequencies of characters in current window of text. The important thing to note is, time complexity to compare two count arrays is O(1) as the number of elements in them are fixed (independent of pattern and text sizes). Following are steps of this algorithm.1) Store counts of frequencies of pattern in first count array countP[]. Also store counts of frequencies of characters in first window of text in array countTW[]. 2) Now run a loop from i = M to N-1. Do following in loop......a) If the two count arrays are identical, we found an occurrence......b) Increment count of current character of text in countTW[].....c) Decrement count of first character in previous window in countWT[] 3) The last window is not checked by above loop, so explicitly check it. C# // C# program to search all anagrams// of a pattern in a textusing System; class GFG { public const int MAX = 256; // This function returns true if // contents of arr1[] and arr2[] // are same, otherwise false. public static bool compare(char[] arr1, char[] arr2) { for (int i = 0; i < MAX; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } // This function search for all // permutations of pat[] in txt[] public static void search(string pat, string txt) { int M = pat.Length; int N = txt.Length; // countP[]: Store count of all // characters of pattern // countTW[]: Store count of current // window of text char[] countP = new char[MAX]; char[] countTW = new char[MAX]; for (int i = 0; i < M; i++) { (countP[pat[i]])++; (countTW[txt[i]])++; } // Traverse through remaining // characters of pattern for (int i = M; i < N; i++) { // Compare counts of current window // of text with counts of pattern[] if (compare(countP, countTW)) { Console.WriteLine("Found at Index " + (i - M)); } // Add current character to // current window (countTW[txt[i]])++; // Remove the first character of // previous window countTW[txt[i - M]]--; } // Check for the last window in text if (compare(countP, countTW)) { Console.WriteLine("Found at Index " + (N - M)); } } // Driver Code public static void Main(string[] args) { string txt = "BACDGABCDA"; string pat = "ABCD"; search(pat, txt); }} // This code is contributed// by Shrikant1 Found at Index 0 Found at Index 5 Found at Index 6 Please refer complete article on Anagram Substring Search (Or Search for all permutations) for more details! C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Remove Duplicate Values From an Array in C#? C# Program to Convert a Binary String to an Integer How to Convert ASCII Char to Byte in C#? C# Program to Demonstrate the IList Interface Different Ways to Take Input and Print a Float Value in C# Hash Function for String data in C# C# Program to Check a Specified Type is an Enum or Not C# Program to Read and Write a Byte Array to File using FileStream Class How to Calculate the Code Execution Time in C#? C# Program to Sort a List of Integers Using the LINQ OrderBy() Method
[ { "code": null, "e": 25334, "s": 25306, "text": "\n07 Jul, 2021" }, { "code": null, "e": 25575, "s": 25334, "text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m.Expected time complexity is O(n)" }, { "code": null, "e": 25585, "s": 25575, "text": "Examples:" }, { "code": null, "e": 25858, "s": 25585, "text": "1) Input: txt[] = \"BACDGABCDA\" pat[] = \"ABCD\"\n Output: Found at Index 0\n Found at Index 5\n Found at Index 6\n2) Input: txt[] = \"AAABABAA\" pat[] = \"AABA\"\n Output: Found at Index 0\n Found at Index 1\n Found at Index 4" }, { "code": null, "e": 26553, "s": 25858, "text": "A simple idea is to modify Rabin Karp Algorithm. For example we can keep the hash value as sum of ASCII values of all characters under modulo of a big prime number. For every character of text, we can add the current character to hash value and subtract the first character of previous window. This solution looks good, but like standard Rabin Karp, the worst case time complexity of this solution is O(mn). The worst case occurs when all hash values match and we one by one match all characters.We can achieve O(n) time complexity under the assumption that alphabet size is fixed which is typically true as we have maximum 256 possible characters in ASCII. The idea is to use two count arrays:" }, { "code": null, "e": 26707, "s": 26553, "text": "1) The first count array store frequencies of characters in pattern.2) The second count array stores frequencies of characters in current window of text." }, { "code": null, "e": 27078, "s": 26707, "text": "The important thing to note is, time complexity to compare two count arrays is O(1) as the number of elements in them are fixed (independent of pattern and text sizes). Following are steps of this algorithm.1) Store counts of frequencies of pattern in first count array countP[]. Also store counts of frequencies of characters in first window of text in array countTW[]." }, { "code": null, "e": 27346, "s": 27078, "text": "2) Now run a loop from i = M to N-1. Do following in loop......a) If the two count arrays are identical, we found an occurrence......b) Increment count of current character of text in countTW[].....c) Decrement count of first character in previous window in countWT[]" }, { "code": null, "e": 27419, "s": 27346, "text": "3) The last window is not checked by above loop, so explicitly check it." }, { "code": null, "e": 27422, "s": 27419, "text": "C#" }, { "code": "// C# program to search all anagrams// of a pattern in a textusing System; class GFG { public const int MAX = 256; // This function returns true if // contents of arr1[] and arr2[] // are same, otherwise false. public static bool compare(char[] arr1, char[] arr2) { for (int i = 0; i < MAX; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } // This function search for all // permutations of pat[] in txt[] public static void search(string pat, string txt) { int M = pat.Length; int N = txt.Length; // countP[]: Store count of all // characters of pattern // countTW[]: Store count of current // window of text char[] countP = new char[MAX]; char[] countTW = new char[MAX]; for (int i = 0; i < M; i++) { (countP[pat[i]])++; (countTW[txt[i]])++; } // Traverse through remaining // characters of pattern for (int i = M; i < N; i++) { // Compare counts of current window // of text with counts of pattern[] if (compare(countP, countTW)) { Console.WriteLine(\"Found at Index \" + (i - M)); } // Add current character to // current window (countTW[txt[i]])++; // Remove the first character of // previous window countTW[txt[i - M]]--; } // Check for the last window in text if (compare(countP, countTW)) { Console.WriteLine(\"Found at Index \" + (N - M)); } } // Driver Code public static void Main(string[] args) { string txt = \"BACDGABCDA\"; string pat = \"ABCD\"; search(pat, txt); }} // This code is contributed// by Shrikant1", "e": 29338, "s": 27422, "text": null }, { "code": null, "e": 29390, "s": 29338, "text": "Found at Index 0\nFound at Index 5\nFound at Index 6\n" }, { "code": null, "e": 29499, "s": 29390, "text": "Please refer complete article on Anagram Substring Search (Or Search for all permutations) for more details!" }, { "code": null, "e": 29511, "s": 29499, "text": "C# Programs" }, { "code": null, "e": 29609, "s": 29511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29661, "s": 29609, "text": "How to Remove Duplicate Values From an Array in C#?" }, { "code": null, "e": 29713, "s": 29661, "text": "C# Program to Convert a Binary String to an Integer" }, { "code": null, "e": 29754, "s": 29713, "text": "How to Convert ASCII Char to Byte in C#?" }, { "code": null, "e": 29800, "s": 29754, "text": "C# Program to Demonstrate the IList Interface" }, { "code": null, "e": 29859, "s": 29800, "text": "Different Ways to Take Input and Print a Float Value in C#" }, { "code": null, "e": 29895, "s": 29859, "text": "Hash Function for String data in C#" }, { "code": null, "e": 29950, "s": 29895, "text": "C# Program to Check a Specified Type is an Enum or Not" }, { "code": null, "e": 30023, "s": 29950, "text": "C# Program to Read and Write a Byte Array to File using FileStream Class" }, { "code": null, "e": 30071, "s": 30023, "text": "How to Calculate the Code Execution Time in C#?" } ]
Deep Learning with Python: Neural Networks (complete tutorial) | by Mauro Di Pietro | Towards Data Science
In this article, I will show how to build Neural Networks with Python and how to explain Deep Learning to the Business using visualization and creating an explainer for model predictions. Deep Learning is a type of machine learning that imitates the way humans gain certain types of knowledge, and it got more popular over the years compared to standard models. While traditional algorithms are linear, Deep Learning models, generally Neural Networks, are stacked in a hierarchy of increasing complexity and abstraction (therefore the “deep” in Deep Learning). Neural Networks are based on a collection of connected units (neurons), which, just like the synapses in a brain, can transmit a signal to other neurons, so that, acting like interconnected brain cells, they can learn and make decisions in a more human-like manner. Today, Deep Learning is so popular that many companies want to use it even though they don’t fully understand it. Often data scientists, first have to simplify these complex algorithms for the Business, and then explain and justify the results of the models, which is not always simple with Neural Networks. I think the best way to do it is through visualization. I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate the examples. In particular, I will go through: Environment Setup, tensorflow vs pytorch. Artificial Neural Networks breakdown, input, output, hidden layers, activation functions. Deep Learning with deep neural networks. Model design with tensorflow/keras. Visualization of Neural Networks with python. Model training & testing. Explainability with shap. There are two main libraries for building Neural Networks: TensorFlow (developed by Google) and PyTorch (developed by Facebook). They can perform similar tasks, but the former is more production-ready while the latter is good for building rapid prototypes because it is easier to learn. Those two libraries are favored by the community and businesses because they can leverage the power of the NVIDIA GPUs. That is very useful, and sometimes necessary, for processing big datasets like a corpus of text or a gallery of images. For this tutorial, I’m going to use TensorFlow and Keras, a higher-level module way more user-friendly than pure TensorFlow and PyTorch, although a bit slower. The first step is to install TensorFlow through the terminal: pip install tensorflow If you want to enable GPU support, you can read the official documentation or follow this guide. After setting it up, your Python instructions will be translated into CUDA by your machine and processed by the GPUs, so your models shall run incredibly faster. Now we can import on our notebook the main modules from TensorFlow Keras and start coding: from tensorflow.keras import models, layers, utils, backend as Kimport matplotlib.pyplot as pltimport shap ANN are made of layers with an input and an output dimension. The latter is determined by the number of neurons (also called “nodes”), a computational unit that connects the weighted inputs through an activation function (which helps the neuron to switch on/off). The weights, like in most of the machine learning algorithms, are randomly initialized and optimized during the training to minimize a loss function. The layers can be grouped as: Input layer has the job to pass the input vector to the Neural Network. If we have a matrix of 3 features (shape N x 3), this layer takes 3 numbers as the input and passes the same 3 numbers to the next layer. Hidden layers represent the intermediary nodes, they apply several transformations to the numbers in order to improve the accuracy of the final result, and the output is defined by the number of neurons. Output layer that returns the final output of the Neural Network. If we are doing a simple binary classification or regression, the output layer shall have only 1 neuron (so that it returns only 1 number). In the case of a multiclass classification with 5 different classes, the output layer shall have 5 neurons. The simplest form of ANN is the Perceptron, a model with one layer only, very similar to the linear regression model. Asking what happens inside a Perceptron is equivalent to asking what happens inside a single node of a multi-layer Neural Network... let’s break it down. Let’s say we have a dataset of N rows, 3 features and 1 target variable (i.e. binary 1/0): Just like in every other machine learning use case, we are going to train a model to predict the target using the features row by row. Let’s start with the first row: What does “training a model” mean? Searching for the best parameters in a mathematical formula that minimize the error of your predictions. In the regression models (i.e. linear regression) you have to find the best weights, in the tree-based models (i.e. random forest) it’s about finding the best splitting points... Usually, the weights are randomly initialized then adjusted as the learning proceeds. Here I’ll just set them all as 1: So far we haven't done anything different from a linear regression (which is pretty straightforward for the business to understand). Now, here’s the upgrade from a linear model Σ(xi*wi)=Y to a non-linear one f(Σ(xi*wi))=Y ... enter the activation function. The activation function defines the output of that node. There are many and one can even create some custom functions, you can find the details in the official documentation and have a look at this cheat sheet. If we would set a simple linear function in our example, then we would have no difference from a linear regression model. I shall use a binary step activation function that returns 1 or 0 only: We have the output of our Perceptron, a single-layer Neural Network that takes some inputs and returns 1 output. Now the training of the model would continue by comparing the output with the target, calculating the error and optimizing the weights, reiterating the whole process again and again. And here’s the common representation of a neuron: One could say that all the Deep Learning models are Neural Networks but not all the Neural Networks are Deep Learning models. Generally speaking, “Deep” Learning applies when the algorithm has at least 2 hidden layers (so 4 layers in total including input and output). Imagine replicating the neuron process 3 times simultaneously: since each node (weighted sum & activation function) returns a value, we would have the first hidden layer with 3 outputs. Now let’s do it again using those 3 outputs as the inputs for the second hidden layer, which returns 3 new numbers. Finally, we shall add an output layer (1 node only) to get the final prediction of our model. Remember that the layers can have a different number of neurons and a different activation function, and in each node, weights are trained to optimize the final result. That’s why the more layers you add, the bigger the number of trainable parameters gets. Now you can review the full picture of a Neural Network: Please note that, in order to keep it as simple as possible, I haven’t mentioned certain details that might not be of interest to the Business, but a data scientist should definitely be aware of. In particular: Bias: inside each neuron, the linear combination of inputs and weights includes also a bias, similar to the constant in a linear equation, therefore the full formula of a neuron is f( Σ(Xi * Wi ) + bias ) Backpropagation: during training, the model learns by propagating the error back into the nodes and updating the parameters (weights and biases) to minimize the loss. Gradient Descent: the optimization algorithm used to train Neural Networks which finds the local minimum of the loss function by taking repeated steps in the direction of steepest descent. The easiest way to build a Neural Network with TensorFlow is with the Sequential class of Keras. Let’s use it to make the Perceptron from our previous example, so a model with only one Dense layer. It is the most basic layer as it feeds all its inputs to all the neurons, each neuron providing one output. model = models.Sequential(name="Perceptron", layers=[ layers.Dense( #a fully connected layer name="dense", input_dim=3, #with 3 features as the input units=1, #and 1 node because we want 1 output activation='linear' #f(x)=x )])model.summary() The summary function provides a snapshot of the structure and the size (in terms of parameters to train). In this case, we have just 4 (3 weights and 1 bias), so it’s pretty lite. If you want to use an activation function that is not already included in Keras, like the binary step function that I showed in the visual example, you gotta get your hands dirty with raw TensorFlow: # define the functionimport tensorflow as tfdef binary_step_activation(x): ##return 1 if x>0 else 0 return K.switch(x>0, tf.math.divide(x,x), tf.math.multiply(x,0))# build the modelmodel = models.Sequential(name="Perceptron", layers=[ layers.Dense( name="dense", input_dim=3, units=1, activation=binary_step_activation )]) Now let’s try to move from the Perceptron to a Deep Neural Network. Probably you are gonna ask yourself some questions: How many layers? The right answer is “try different variants and see what works”. I usually work with 2 Dense hidden layers with Dropout, a technique that reduces overfitting by randomly setting inputs to 0. Hidden layers are useful to overcome the non-linearity of data, so if you don’t need non-linearity then you can avoid hidden layers. Too many hidden layers will lead to overfitting. How many layers? The right answer is “try different variants and see what works”. I usually work with 2 Dense hidden layers with Dropout, a technique that reduces overfitting by randomly setting inputs to 0. Hidden layers are useful to overcome the non-linearity of data, so if you don’t need non-linearity then you can avoid hidden layers. Too many hidden layers will lead to overfitting. How many neurons? The number of hidden neurons should be between the size of the input layer and the size of the output layer. My rule of thumb is (number of inputs + 1 output)/2.What activation function? There are many and we can’t say that one is absolutely better. Anyway, the most used one is ReLU, a piecewise linear function that returns the output only if it’s positive, and it is mainly used for hidden layers. Besides, the output layer must have an activation compatible with the expected output. For example, the linear function is suited for regression problems while the Sigmoid is frequently used for classification. How many neurons? The number of hidden neurons should be between the size of the input layer and the size of the output layer. My rule of thumb is (number of inputs + 1 output)/2. What activation function? There are many and we can’t say that one is absolutely better. Anyway, the most used one is ReLU, a piecewise linear function that returns the output only if it’s positive, and it is mainly used for hidden layers. Besides, the output layer must have an activation compatible with the expected output. For example, the linear function is suited for regression problems while the Sigmoid is frequently used for classification. I’m going to assume an input dataset of N features and 1 binary target variable (most likely a classification use case). n_features = 10model = models.Sequential(name="DeepNN", layers=[ ### hidden layer 1 layers.Dense(name="h1", input_dim=n_features, units=int(round((n_features+1)/2)), activation='relu'), layers.Dropout(name="drop1", rate=0.2), ### hidden layer 2 layers.Dense(name="h2", units=int(round((n_features+1)/4)), activation='relu'), layers.Dropout(name="drop2", rate=0.2), ### layer output layers.Dense(name="output", units=1, activation='sigmoid')])model.summary() Please note that the Sequential class isn’t the only way to build a Neural Network with Keras. The Model class gives more flexibility and control over the layers, and it can be used to build more complex models with multiple inputs/outputs. There are two major differences: The Input layer needs to be specified while in the Sequential class it’s implied in the input dimension of the first Dense layer. The layers are saved like objects and can be applied to the outputs of other layers like: output = layer(...)(input) This is how you can use the Model class to build our Perceptron and DeepNN: # Perceptroninputs = layers.Input(name="input", shape=(3,))outputs = layers.Dense(name="output", units=1, activation='linear')(inputs)model = models.Model(inputs=inputs, outputs=outputs, name="Perceptron")# DeepNN### layer inputinputs = layers.Input(name="input", shape=(n_features,))### hidden layer 1h1 = layers.Dense(name="h1", units=int(round((n_features+1)/2)), activation='relu')(inputs)h1 = layers.Dropout(name="drop1", rate=0.2)(h1)### hidden layer 2h2 = layers.Dense(name="h2", units=int(round((n_features+1)/4)), activation='relu')(h1)h2 = layers.Dropout(name="drop2", rate=0.2)(h2)### layer outputoutputs = layers.Dense(name="output", units=1, activation='sigmoid')(h2)model = models.Model(inputs=inputs, outputs=outputs, name="DeepNN") One can always check if the number of parameters in the model summary is the same as the one from Sequential. Remember, we are telling a story to the business and visualization is our best ally. I prepared a function to plot the structure of an Artificial Neural Network from its TensorFlow model, here’s the full code: Let’s try it out on our 2 models, first the Perceptron: visualize_nn(model, description=True, figsize=(10,8)) then the Deep Neural Network: TensorFlow provides a tool for plotting the model structure as well, you might want to use it for more complex Neural Networks with more complicated layers (CNN, RNN, ...). Sometimes it’s a bit tricky to set up, if you have issues this post might help. utils.plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True) That saves this image on your laptop, so if you just want to plot it out on your notebook, you can just run the following to delete the file: import osos.remove('model.png') Finally, it’s time to train our Deep Learning model. In order for it to run, we must “compile”, or to put it in another way, we need to define the Optimizer, the Loss function, and the Metrics. I usually use the Adam optimizer, a replacement optimization algorithm for gradient descent (the best among the adaptive optimizers). The other arguments depend on the use case. In (binary) classification problems, you should use a (binary) Cross-Entropy loss which compares each of the predicted probabilities to the actual class output. As for the metrics, I like to monitor both the Accuracy and the F1-score, a metric that combines Precision and Recall (the latter must be implemented as it is not already included in TensorFlow). # define metricsdef Recall(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recalldef Precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precisiondef F1(y_true, y_pred): precision = Precision(y_true, y_pred) recall = Recall(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon()))# compile the neural networkmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy',F1]) On the other hand, in regression problems, I usually set the MAE as the loss and the R-squared as the metric. # define metricsdef R2(y, y_hat): ss_res = K.sum(K.square(y - y_hat)) ss_tot = K.sum(K.square(y - K.mean(y))) return ( 1 - ss_res/(ss_tot + K.epsilon()) )# compile the neural networkmodel.compile(optimizer='adam', loss='mean_absolute_error', metrics=[R2]) Before starting the training, we also need to decide the Epochs and Batches: since the dataset might be too large to be processed all at once, it is split into batches (the higher the batch size, the more memory space you need). The backpropagation and the consequent parameters update happen every batch. An epoch is one pass over the full training set. So, if you have 100 observations and the batch size is 20, it will take 5 batches to complete 1 epoch. The batch size should be a multiple of 2 (common: 32, 64, 128, 256) because computers usually organize the memory in power of 2. I tend to start with 100 epochs with a batch size of 32. During the training, we would expect to see the metrics improving and the loss decreasing epoch by epoch. Moreover, it’s good practice to keep a portion of the data (20%-30%) for validation. In other words, the model will set apart this fraction of data to evaluate the loss and metrics at the end of each epoch, outside the training. Assuming you got your data ready into some X and y arrays (if not you can simply generate random data like import numpy as npX = np.random.rand(1000,10)y = np.random.choice([1,0], size=1000) ), you can launch and visualize the training as follows: # train/validationtraining = model.fit(x=X, y=y, batch_size=32, epochs=100, shuffle=True, verbose=0, validation_split=0.3)# plotmetrics = [k for k in training.history.keys() if ("loss" not in k) and ("val" not in k)] fig, ax = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(15,3)) ## training ax[0].set(title="Training") ax11 = ax[0].twinx() ax[0].plot(training.history['loss'], color='black') ax[0].set_xlabel('Epochs') ax[0].set_ylabel('Loss', color='black') for metric in metrics: ax11.plot(training.history[metric], label=metric) ax11.set_ylabel("Score", color='steelblue') ax11.legend() ## validation ax[1].set(title="Validation") ax22 = ax[1].twinx() ax[1].plot(training.history['val_loss'], color='black') ax[1].set_xlabel('Epochs') ax[1].set_ylabel('Loss', color='black') for metric in metrics: ax22.plot(training.history['val_'+metric], label=metric) ax22.set_ylabel("Score", color="steelblue") plt.show() Those plots are taken from two actual use cases which compare standard machine learning algorithms with Neural Networks (links under each image). We trained and tested our model, but we still haven’t convinced the Business about the results... what can we do? Easy, we build an explainer to show that our Deep Learning model is not a black box. I find Shap working very well with Neural Networks: for every prediction, it’s able to estimate the contribution of each feature to the value predicted by the model. Basically, it answers the question “why the model says this is a 1 and not a 0?”. You can use the following code: Please note that you can use this function on other Machine Learning models as well (i.e. Linear Regression, Random Forest), not just Neural Networks. As you can read from the code, if the X_train argument is kept as None, my function assumes it’s not Deep Learning. Let’s test it out on the classification and regression examples: i = 1explainer_shap(model, X_names=list_feature_names, X_instance=X[i], X_train=X, task="classification", #task="regression" top=10) This article has been a tutorial to demonstrate how to design and build Artificial Neural Networks, deep and not. I broke down step by step what happens inside a single neuron and more generally inside the layers. I kept the story as simple as if we are explaining Deep Learning to the Business, using tons of visualization. In the second part of the tutorial, we used TensorFlow to create some Neural Networks, from the Perceptron to a more complex one. Then, we trained the Deep Learning model and assessed its explainability for both classification and regression use cases. I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects. 👉 Let’s Connect 👈 This article is part of the series Machine Learning with Python, see also:
[ { "code": null, "e": 360, "s": 172, "text": "In this article, I will show how to build Neural Networks with Python and how to explain Deep Learning to the Business using visualization and creating an explainer for model predictions." }, { "code": null, "e": 733, "s": 360, "text": "Deep Learning is a type of machine learning that imitates the way humans gain certain types of knowledge, and it got more popular over the years compared to standard models. While traditional algorithms are linear, Deep Learning models, generally Neural Networks, are stacked in a hierarchy of increasing complexity and abstraction (therefore the “deep” in Deep Learning)." }, { "code": null, "e": 999, "s": 733, "text": "Neural Networks are based on a collection of connected units (neurons), which, just like the synapses in a brain, can transmit a signal to other neurons, so that, acting like interconnected brain cells, they can learn and make decisions in a more human-like manner." }, { "code": null, "e": 1363, "s": 999, "text": "Today, Deep Learning is so popular that many companies want to use it even though they don’t fully understand it. Often data scientists, first have to simplify these complex algorithms for the Business, and then explain and justify the results of the models, which is not always simple with Neural Networks. I think the best way to do it is through visualization." }, { "code": null, "e": 1566, "s": 1363, "text": "I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate the examples." }, { "code": null, "e": 1600, "s": 1566, "text": "In particular, I will go through:" }, { "code": null, "e": 1642, "s": 1600, "text": "Environment Setup, tensorflow vs pytorch." }, { "code": null, "e": 1732, "s": 1642, "text": "Artificial Neural Networks breakdown, input, output, hidden layers, activation functions." }, { "code": null, "e": 1773, "s": 1732, "text": "Deep Learning with deep neural networks." }, { "code": null, "e": 1809, "s": 1773, "text": "Model design with tensorflow/keras." }, { "code": null, "e": 1855, "s": 1809, "text": "Visualization of Neural Networks with python." }, { "code": null, "e": 1881, "s": 1855, "text": "Model training & testing." }, { "code": null, "e": 1907, "s": 1881, "text": "Explainability with shap." }, { "code": null, "e": 2194, "s": 1907, "text": "There are two main libraries for building Neural Networks: TensorFlow (developed by Google) and PyTorch (developed by Facebook). They can perform similar tasks, but the former is more production-ready while the latter is good for building rapid prototypes because it is easier to learn." }, { "code": null, "e": 2434, "s": 2194, "text": "Those two libraries are favored by the community and businesses because they can leverage the power of the NVIDIA GPUs. That is very useful, and sometimes necessary, for processing big datasets like a corpus of text or a gallery of images." }, { "code": null, "e": 2594, "s": 2434, "text": "For this tutorial, I’m going to use TensorFlow and Keras, a higher-level module way more user-friendly than pure TensorFlow and PyTorch, although a bit slower." }, { "code": null, "e": 2656, "s": 2594, "text": "The first step is to install TensorFlow through the terminal:" }, { "code": null, "e": 2679, "s": 2656, "text": "pip install tensorflow" }, { "code": null, "e": 2938, "s": 2679, "text": "If you want to enable GPU support, you can read the official documentation or follow this guide. After setting it up, your Python instructions will be translated into CUDA by your machine and processed by the GPUs, so your models shall run incredibly faster." }, { "code": null, "e": 3029, "s": 2938, "text": "Now we can import on our notebook the main modules from TensorFlow Keras and start coding:" }, { "code": null, "e": 3136, "s": 3029, "text": "from tensorflow.keras import models, layers, utils, backend as Kimport matplotlib.pyplot as pltimport shap" }, { "code": null, "e": 3550, "s": 3136, "text": "ANN are made of layers with an input and an output dimension. The latter is determined by the number of neurons (also called “nodes”), a computational unit that connects the weighted inputs through an activation function (which helps the neuron to switch on/off). The weights, like in most of the machine learning algorithms, are randomly initialized and optimized during the training to minimize a loss function." }, { "code": null, "e": 3580, "s": 3550, "text": "The layers can be grouped as:" }, { "code": null, "e": 3790, "s": 3580, "text": "Input layer has the job to pass the input vector to the Neural Network. If we have a matrix of 3 features (shape N x 3), this layer takes 3 numbers as the input and passes the same 3 numbers to the next layer." }, { "code": null, "e": 3994, "s": 3790, "text": "Hidden layers represent the intermediary nodes, they apply several transformations to the numbers in order to improve the accuracy of the final result, and the output is defined by the number of neurons." }, { "code": null, "e": 4308, "s": 3994, "text": "Output layer that returns the final output of the Neural Network. If we are doing a simple binary classification or regression, the output layer shall have only 1 neuron (so that it returns only 1 number). In the case of a multiclass classification with 5 different classes, the output layer shall have 5 neurons." }, { "code": null, "e": 4580, "s": 4308, "text": "The simplest form of ANN is the Perceptron, a model with one layer only, very similar to the linear regression model. Asking what happens inside a Perceptron is equivalent to asking what happens inside a single node of a multi-layer Neural Network... let’s break it down." }, { "code": null, "e": 4671, "s": 4580, "text": "Let’s say we have a dataset of N rows, 3 features and 1 target variable (i.e. binary 1/0):" }, { "code": null, "e": 4838, "s": 4671, "text": "Just like in every other machine learning use case, we are going to train a model to predict the target using the features row by row. Let’s start with the first row:" }, { "code": null, "e": 5157, "s": 4838, "text": "What does “training a model” mean? Searching for the best parameters in a mathematical formula that minimize the error of your predictions. In the regression models (i.e. linear regression) you have to find the best weights, in the tree-based models (i.e. random forest) it’s about finding the best splitting points..." }, { "code": null, "e": 5277, "s": 5157, "text": "Usually, the weights are randomly initialized then adjusted as the learning proceeds. Here I’ll just set them all as 1:" }, { "code": null, "e": 5534, "s": 5277, "text": "So far we haven't done anything different from a linear regression (which is pretty straightforward for the business to understand). Now, here’s the upgrade from a linear model Σ(xi*wi)=Y to a non-linear one f(Σ(xi*wi))=Y ... enter the activation function." }, { "code": null, "e": 5867, "s": 5534, "text": "The activation function defines the output of that node. There are many and one can even create some custom functions, you can find the details in the official documentation and have a look at this cheat sheet. If we would set a simple linear function in our example, then we would have no difference from a linear regression model." }, { "code": null, "e": 5939, "s": 5867, "text": "I shall use a binary step activation function that returns 1 or 0 only:" }, { "code": null, "e": 6235, "s": 5939, "text": "We have the output of our Perceptron, a single-layer Neural Network that takes some inputs and returns 1 output. Now the training of the model would continue by comparing the output with the target, calculating the error and optimizing the weights, reiterating the whole process again and again." }, { "code": null, "e": 6285, "s": 6235, "text": "And here’s the common representation of a neuron:" }, { "code": null, "e": 6554, "s": 6285, "text": "One could say that all the Deep Learning models are Neural Networks but not all the Neural Networks are Deep Learning models. Generally speaking, “Deep” Learning applies when the algorithm has at least 2 hidden layers (so 4 layers in total including input and output)." }, { "code": null, "e": 6740, "s": 6554, "text": "Imagine replicating the neuron process 3 times simultaneously: since each node (weighted sum & activation function) returns a value, we would have the first hidden layer with 3 outputs." }, { "code": null, "e": 6950, "s": 6740, "text": "Now let’s do it again using those 3 outputs as the inputs for the second hidden layer, which returns 3 new numbers. Finally, we shall add an output layer (1 node only) to get the final prediction of our model." }, { "code": null, "e": 7207, "s": 6950, "text": "Remember that the layers can have a different number of neurons and a different activation function, and in each node, weights are trained to optimize the final result. That’s why the more layers you add, the bigger the number of trainable parameters gets." }, { "code": null, "e": 7264, "s": 7207, "text": "Now you can review the full picture of a Neural Network:" }, { "code": null, "e": 7475, "s": 7264, "text": "Please note that, in order to keep it as simple as possible, I haven’t mentioned certain details that might not be of interest to the Business, but a data scientist should definitely be aware of. In particular:" }, { "code": null, "e": 7656, "s": 7475, "text": "Bias: inside each neuron, the linear combination of inputs and weights includes also a bias, similar to the constant in a linear equation, therefore the full formula of a neuron is" }, { "code": null, "e": 7680, "s": 7656, "text": "f( Σ(Xi * Wi ) + bias )" }, { "code": null, "e": 7847, "s": 7680, "text": "Backpropagation: during training, the model learns by propagating the error back into the nodes and updating the parameters (weights and biases) to minimize the loss." }, { "code": null, "e": 8036, "s": 7847, "text": "Gradient Descent: the optimization algorithm used to train Neural Networks which finds the local minimum of the loss function by taking repeated steps in the direction of steepest descent." }, { "code": null, "e": 8342, "s": 8036, "text": "The easiest way to build a Neural Network with TensorFlow is with the Sequential class of Keras. Let’s use it to make the Perceptron from our previous example, so a model with only one Dense layer. It is the most basic layer as it feeds all its inputs to all the neurons, each neuron providing one output." }, { "code": null, "e": 8657, "s": 8342, "text": "model = models.Sequential(name=\"Perceptron\", layers=[ layers.Dense( #a fully connected layer name=\"dense\", input_dim=3, #with 3 features as the input units=1, #and 1 node because we want 1 output activation='linear' #f(x)=x )])model.summary()" }, { "code": null, "e": 8837, "s": 8657, "text": "The summary function provides a snapshot of the structure and the size (in terms of parameters to train). In this case, we have just 4 (3 weights and 1 bias), so it’s pretty lite." }, { "code": null, "e": 9037, "s": 8837, "text": "If you want to use an activation function that is not already included in Keras, like the binary step function that I showed in the visual example, you gotta get your hands dirty with raw TensorFlow:" }, { "code": null, "e": 9446, "s": 9037, "text": "# define the functionimport tensorflow as tfdef binary_step_activation(x): ##return 1 if x>0 else 0 return K.switch(x>0, tf.math.divide(x,x), tf.math.multiply(x,0))# build the modelmodel = models.Sequential(name=\"Perceptron\", layers=[ layers.Dense( name=\"dense\", input_dim=3, units=1, activation=binary_step_activation )])" }, { "code": null, "e": 9566, "s": 9446, "text": "Now let’s try to move from the Perceptron to a Deep Neural Network. Probably you are gonna ask yourself some questions:" }, { "code": null, "e": 9956, "s": 9566, "text": "How many layers? The right answer is “try different variants and see what works”. I usually work with 2 Dense hidden layers with Dropout, a technique that reduces overfitting by randomly setting inputs to 0. Hidden layers are useful to overcome the non-linearity of data, so if you don’t need non-linearity then you can avoid hidden layers. Too many hidden layers will lead to overfitting." }, { "code": null, "e": 10346, "s": 9956, "text": "How many layers? The right answer is “try different variants and see what works”. I usually work with 2 Dense hidden layers with Dropout, a technique that reduces overfitting by randomly setting inputs to 0. Hidden layers are useful to overcome the non-linearity of data, so if you don’t need non-linearity then you can avoid hidden layers. Too many hidden layers will lead to overfitting." }, { "code": null, "e": 10976, "s": 10346, "text": "How many neurons? The number of hidden neurons should be between the size of the input layer and the size of the output layer. My rule of thumb is (number of inputs + 1 output)/2.What activation function? There are many and we can’t say that one is absolutely better. Anyway, the most used one is ReLU, a piecewise linear function that returns the output only if it’s positive, and it is mainly used for hidden layers. Besides, the output layer must have an activation compatible with the expected output. For example, the linear function is suited for regression problems while the Sigmoid is frequently used for classification." }, { "code": null, "e": 11156, "s": 10976, "text": "How many neurons? The number of hidden neurons should be between the size of the input layer and the size of the output layer. My rule of thumb is (number of inputs + 1 output)/2." }, { "code": null, "e": 11607, "s": 11156, "text": "What activation function? There are many and we can’t say that one is absolutely better. Anyway, the most used one is ReLU, a piecewise linear function that returns the output only if it’s positive, and it is mainly used for hidden layers. Besides, the output layer must have an activation compatible with the expected output. For example, the linear function is suited for regression problems while the Sigmoid is frequently used for classification." }, { "code": null, "e": 11728, "s": 11607, "text": "I’m going to assume an input dataset of N features and 1 binary target variable (most likely a classification use case)." }, { "code": null, "e": 12268, "s": 11728, "text": "n_features = 10model = models.Sequential(name=\"DeepNN\", layers=[ ### hidden layer 1 layers.Dense(name=\"h1\", input_dim=n_features, units=int(round((n_features+1)/2)), activation='relu'), layers.Dropout(name=\"drop1\", rate=0.2), ### hidden layer 2 layers.Dense(name=\"h2\", units=int(round((n_features+1)/4)), activation='relu'), layers.Dropout(name=\"drop2\", rate=0.2), ### layer output layers.Dense(name=\"output\", units=1, activation='sigmoid')])model.summary()" }, { "code": null, "e": 12542, "s": 12268, "text": "Please note that the Sequential class isn’t the only way to build a Neural Network with Keras. The Model class gives more flexibility and control over the layers, and it can be used to build more complex models with multiple inputs/outputs. There are two major differences:" }, { "code": null, "e": 12672, "s": 12542, "text": "The Input layer needs to be specified while in the Sequential class it’s implied in the input dimension of the first Dense layer." }, { "code": null, "e": 12789, "s": 12672, "text": "The layers are saved like objects and can be applied to the outputs of other layers like: output = layer(...)(input)" }, { "code": null, "e": 12865, "s": 12789, "text": "This is how you can use the Model class to build our Perceptron and DeepNN:" }, { "code": null, "e": 13657, "s": 12865, "text": "# Perceptroninputs = layers.Input(name=\"input\", shape=(3,))outputs = layers.Dense(name=\"output\", units=1, activation='linear')(inputs)model = models.Model(inputs=inputs, outputs=outputs, name=\"Perceptron\")# DeepNN### layer inputinputs = layers.Input(name=\"input\", shape=(n_features,))### hidden layer 1h1 = layers.Dense(name=\"h1\", units=int(round((n_features+1)/2)), activation='relu')(inputs)h1 = layers.Dropout(name=\"drop1\", rate=0.2)(h1)### hidden layer 2h2 = layers.Dense(name=\"h2\", units=int(round((n_features+1)/4)), activation='relu')(h1)h2 = layers.Dropout(name=\"drop2\", rate=0.2)(h2)### layer outputoutputs = layers.Dense(name=\"output\", units=1, activation='sigmoid')(h2)model = models.Model(inputs=inputs, outputs=outputs, name=\"DeepNN\")" }, { "code": null, "e": 13767, "s": 13657, "text": "One can always check if the number of parameters in the model summary is the same as the one from Sequential." }, { "code": null, "e": 13977, "s": 13767, "text": "Remember, we are telling a story to the business and visualization is our best ally. I prepared a function to plot the structure of an Artificial Neural Network from its TensorFlow model, here’s the full code:" }, { "code": null, "e": 14033, "s": 13977, "text": "Let’s try it out on our 2 models, first the Perceptron:" }, { "code": null, "e": 14087, "s": 14033, "text": "visualize_nn(model, description=True, figsize=(10,8))" }, { "code": null, "e": 14117, "s": 14087, "text": "then the Deep Neural Network:" }, { "code": null, "e": 14370, "s": 14117, "text": "TensorFlow provides a tool for plotting the model structure as well, you might want to use it for more complex Neural Networks with more complicated layers (CNN, RNN, ...). Sometimes it’s a bit tricky to set up, if you have issues this post might help." }, { "code": null, "e": 14456, "s": 14370, "text": "utils.plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)" }, { "code": null, "e": 14598, "s": 14456, "text": "That saves this image on your laptop, so if you just want to plot it out on your notebook, you can just run the following to delete the file:" }, { "code": null, "e": 14630, "s": 14598, "text": "import osos.remove('model.png')" }, { "code": null, "e": 15002, "s": 14630, "text": "Finally, it’s time to train our Deep Learning model. In order for it to run, we must “compile”, or to put it in another way, we need to define the Optimizer, the Loss function, and the Metrics. I usually use the Adam optimizer, a replacement optimization algorithm for gradient descent (the best among the adaptive optimizers). The other arguments depend on the use case." }, { "code": null, "e": 15359, "s": 15002, "text": "In (binary) classification problems, you should use a (binary) Cross-Entropy loss which compares each of the predicted probabilities to the actual class output. As for the metrics, I like to monitor both the Accuracy and the F1-score, a metric that combines Precision and Recall (the latter must be implemented as it is not already included in TensorFlow)." }, { "code": null, "e": 16146, "s": 15359, "text": "# define metricsdef Recall(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recalldef Precision(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precisiondef F1(y_true, y_pred): precision = Precision(y_true, y_pred) recall = Recall(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon()))# compile the neural networkmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy',F1])" }, { "code": null, "e": 16256, "s": 16146, "text": "On the other hand, in regression problems, I usually set the MAE as the loss and the R-squared as the metric." }, { "code": null, "e": 16538, "s": 16256, "text": "# define metricsdef R2(y, y_hat): ss_res = K.sum(K.square(y - y_hat)) ss_tot = K.sum(K.square(y - K.mean(y))) return ( 1 - ss_res/(ss_tot + K.epsilon()) )# compile the neural networkmodel.compile(optimizer='adam', loss='mean_absolute_error', metrics=[R2])" }, { "code": null, "e": 17182, "s": 16538, "text": "Before starting the training, we also need to decide the Epochs and Batches: since the dataset might be too large to be processed all at once, it is split into batches (the higher the batch size, the more memory space you need). The backpropagation and the consequent parameters update happen every batch. An epoch is one pass over the full training set. So, if you have 100 observations and the batch size is 20, it will take 5 batches to complete 1 epoch. The batch size should be a multiple of 2 (common: 32, 64, 128, 256) because computers usually organize the memory in power of 2. I tend to start with 100 epochs with a batch size of 32." }, { "code": null, "e": 17517, "s": 17182, "text": "During the training, we would expect to see the metrics improving and the loss decreasing epoch by epoch. Moreover, it’s good practice to keep a portion of the data (20%-30%) for validation. In other words, the model will set apart this fraction of data to evaluate the loss and metrics at the end of each epoch, outside the training." }, { "code": null, "e": 17624, "s": 17517, "text": "Assuming you got your data ready into some X and y arrays (if not you can simply generate random data like" }, { "code": null, "e": 17708, "s": 17624, "text": "import numpy as npX = np.random.rand(1000,10)y = np.random.choice([1,0], size=1000)" }, { "code": null, "e": 17765, "s": 17708, "text": "), you can launch and visualize the training as follows:" }, { "code": null, "e": 18774, "s": 17765, "text": "# train/validationtraining = model.fit(x=X, y=y, batch_size=32, epochs=100, shuffle=True, verbose=0, validation_split=0.3)# plotmetrics = [k for k in training.history.keys() if (\"loss\" not in k) and (\"val\" not in k)] fig, ax = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(15,3)) ## training ax[0].set(title=\"Training\") ax11 = ax[0].twinx() ax[0].plot(training.history['loss'], color='black') ax[0].set_xlabel('Epochs') ax[0].set_ylabel('Loss', color='black') for metric in metrics: ax11.plot(training.history[metric], label=metric) ax11.set_ylabel(\"Score\", color='steelblue') ax11.legend() ## validation ax[1].set(title=\"Validation\") ax22 = ax[1].twinx() ax[1].plot(training.history['val_loss'], color='black') ax[1].set_xlabel('Epochs') ax[1].set_ylabel('Loss', color='black') for metric in metrics: ax22.plot(training.history['val_'+metric], label=metric) ax22.set_ylabel(\"Score\", color=\"steelblue\") plt.show()" }, { "code": null, "e": 18920, "s": 18774, "text": "Those plots are taken from two actual use cases which compare standard machine learning algorithms with Neural Networks (links under each image)." }, { "code": null, "e": 19119, "s": 18920, "text": "We trained and tested our model, but we still haven’t convinced the Business about the results... what can we do? Easy, we build an explainer to show that our Deep Learning model is not a black box." }, { "code": null, "e": 19367, "s": 19119, "text": "I find Shap working very well with Neural Networks: for every prediction, it’s able to estimate the contribution of each feature to the value predicted by the model. Basically, it answers the question “why the model says this is a 1 and not a 0?”." }, { "code": null, "e": 19399, "s": 19367, "text": "You can use the following code:" }, { "code": null, "e": 19666, "s": 19399, "text": "Please note that you can use this function on other Machine Learning models as well (i.e. Linear Regression, Random Forest), not just Neural Networks. As you can read from the code, if the X_train argument is kept as None, my function assumes it’s not Deep Learning." }, { "code": null, "e": 19731, "s": 19666, "text": "Let’s test it out on the classification and regression examples:" }, { "code": null, "e": 19938, "s": 19731, "text": "i = 1explainer_shap(model, X_names=list_feature_names, X_instance=X[i], X_train=X, task=\"classification\", #task=\"regression\" top=10)" }, { "code": null, "e": 20263, "s": 19938, "text": "This article has been a tutorial to demonstrate how to design and build Artificial Neural Networks, deep and not. I broke down step by step what happens inside a single neuron and more generally inside the layers. I kept the story as simple as if we are explaining Deep Learning to the Business, using tons of visualization." }, { "code": null, "e": 20516, "s": 20263, "text": "In the second part of the tutorial, we used TensorFlow to create some Neural Networks, from the Perceptron to a more complex one. Then, we trained the Deep Learning model and assessed its explainability for both classification and regression use cases." }, { "code": null, "e": 20634, "s": 20516, "text": "I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects." }, { "code": null, "e": 20652, "s": 20634, "text": "👉 Let’s Connect 👈" } ]
How to insert a document into a MongoDB collection using Java?
You can insert a document into an existing collection in MongoDB using the insert() method. db.coll.insert(doc) Where, db is the database. db is the database. coll is the collection (name) in which you want to insert the document coll is the collection (name) in which you want to insert the document doc is the document you want to insert. doc is the document you want to insert. > use myDatabase() switched to db myDatabase() > db.createCollection(sample) { "ok" : 1 } > db.sample.insert({name:"Ram", age:26, city:"Hyderabad"}) WriteResult({ "nInserted" : 1 }) In Java, you can insert a document into a collection using the insertOne() method of the com.mongodb.client.MongoCollection interface. This method accepts a document (object) representing the document you want to insert as a parameter. Therefore to create a collection in MongoDB using Java program − Make sure you have installed MongoDB in your system Make sure you have installed MongoDB in your system Add the following dependency to its pom.xml file of your Java project. Add the following dependency to its pom.xml file of your Java project. <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency> Create a MongoDB client by instantiating the MongoClient class. Create a MongoDB client by instantiating the MongoClient class. Connect to a database using the getDatabase() method. Connect to a database using the getDatabase() method. Prepare the document to be inserted. Prepare the document to be inserted. Get the object of the collection into which you want to insert the document, using the getCollection() method. Get the object of the collection into which you want to insert the document, using the getCollection() method. Invoke the insertOne() method by passing the document (created above) as a parameter. Invoke the insertOne() method by passing the document (created above) as a parameter. import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.MongoClient; public class InsertingDocument { public static void main( String args[] ) { //Creating a MongoDB client MongoClient mongo = new MongoClient( "localhost" , 27017 ); //Connecting to the database MongoDatabase database = mongo.getDatabase("myDatabase"); //Creating a collection database.createCollection("students"); //Preparing a document Document document = new Document(); document.append("name", "Ram"); document.append("age", 26); document.append("city", "Hyderabad"); //Inserting the document into the collection database.getCollection("students").insertOne(document); System.out.println("Document inserted successfully"); } } Document inserted successfully
[ { "code": null, "e": 1154, "s": 1062, "text": "You can insert a document into an existing collection in MongoDB using the insert() method." }, { "code": null, "e": 1174, "s": 1154, "text": "db.coll.insert(doc)" }, { "code": null, "e": 1181, "s": 1174, "text": "Where," }, { "code": null, "e": 1201, "s": 1181, "text": "db is the database." }, { "code": null, "e": 1221, "s": 1201, "text": "db is the database." }, { "code": null, "e": 1292, "s": 1221, "text": "coll is the collection (name) in which you want to insert the document" }, { "code": null, "e": 1363, "s": 1292, "text": "coll is the collection (name) in which you want to insert the document" }, { "code": null, "e": 1403, "s": 1363, "text": "doc is the document you want to insert." }, { "code": null, "e": 1443, "s": 1403, "text": "doc is the document you want to insert." }, { "code": null, "e": 1625, "s": 1443, "text": "> use myDatabase()\nswitched to db myDatabase()\n> db.createCollection(sample)\n{ \"ok\" : 1 }\n> db.sample.insert({name:\"Ram\", age:26, city:\"Hyderabad\"})\nWriteResult({ \"nInserted\" : 1 })" }, { "code": null, "e": 1861, "s": 1625, "text": "In Java, you can insert a document into a collection using the insertOne() method of the com.mongodb.client.MongoCollection interface. This method accepts a document (object) representing the document you want to insert as a parameter." }, { "code": null, "e": 1926, "s": 1861, "text": "Therefore to create a collection in MongoDB using Java program −" }, { "code": null, "e": 1978, "s": 1926, "text": "Make sure you have installed MongoDB in your system" }, { "code": null, "e": 2030, "s": 1978, "text": "Make sure you have installed MongoDB in your system" }, { "code": null, "e": 2101, "s": 2030, "text": "Add the following dependency to its pom.xml file of your Java project." }, { "code": null, "e": 2172, "s": 2101, "text": "Add the following dependency to its pom.xml file of your Java project." }, { "code": null, "e": 2308, "s": 2172, "text": "<dependency>\n <groupId>org.mongodb</groupId>\n <artifactId>mongo-java-driver</artifactId>\n <version>3.12.2</version>\n</dependency>" }, { "code": null, "e": 2372, "s": 2308, "text": "Create a MongoDB client by instantiating the MongoClient class." }, { "code": null, "e": 2436, "s": 2372, "text": "Create a MongoDB client by instantiating the MongoClient class." }, { "code": null, "e": 2490, "s": 2436, "text": "Connect to a database using the getDatabase() method." }, { "code": null, "e": 2544, "s": 2490, "text": "Connect to a database using the getDatabase() method." }, { "code": null, "e": 2581, "s": 2544, "text": "Prepare the document to be inserted." }, { "code": null, "e": 2618, "s": 2581, "text": "Prepare the document to be inserted." }, { "code": null, "e": 2729, "s": 2618, "text": "Get the object of the collection into which you want to insert the document, using the getCollection() method." }, { "code": null, "e": 2840, "s": 2729, "text": "Get the object of the collection into which you want to insert the document, using the getCollection() method." }, { "code": null, "e": 2926, "s": 2840, "text": "Invoke the insertOne() method by passing the document (created above) as a parameter." }, { "code": null, "e": 3012, "s": 2926, "text": "Invoke the insertOne() method by passing the document (created above) as a parameter." }, { "code": null, "e": 3831, "s": 3012, "text": "import com.mongodb.client.MongoDatabase;\nimport org.bson.Document;\nimport com.mongodb.MongoClient;\npublic class InsertingDocument {\n public static void main( String args[] ) {\n //Creating a MongoDB client\n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n //Connecting to the database\n MongoDatabase database = mongo.getDatabase(\"myDatabase\");\n //Creating a collection\n database.createCollection(\"students\");\n //Preparing a document\n Document document = new Document();\n document.append(\"name\", \"Ram\");\n document.append(\"age\", 26);\n document.append(\"city\", \"Hyderabad\");\n //Inserting the document into the collection\n database.getCollection(\"students\").insertOne(document);\n System.out.println(\"Document inserted successfully\");\n }\n}" }, { "code": null, "e": 3862, "s": 3831, "text": "Document inserted successfully" } ]
How do I use Window Manager (wm) attributes in Tkinter?
The Window Manager is a toolkit available in Tcl/Tk that can be accessed with the command 'wm'. The 'wm' command allows you to set the appearance and geometry of the Tkinter window. We can control the title, color, size, and other attributes with this command. The 'wm' command has numerous keywords that can be used to modify its property. # Import the required library from tkinter import * from tkinter import ttk from tkinter import messagebox # Create an instance of tkinter frame win=Tk() # Set the geometry win.geometry("700x350") Label(win, text="This window is disabled.", font=("Calibri, 24")).pack() # Makes the window topmost win.wm_attributes('-topmost', True) # Makes the window transparent win.wm_attributes('-alpha', 0.9) # Disable the window win.wm_attributes('-disabled', True) # Set the geometry of the window win.wm_geometry('700x350') win.mainloop() If you run the above code, it will display a topmost transparent window that you cannot interact with, as the window is disabled using the wm attribute "-disabled".
[ { "code": null, "e": 1403, "s": 1062, "text": "The Window Manager is a toolkit available in Tcl/Tk that can be accessed with the command 'wm'. The 'wm' command allows you to set the appearance and geometry of the Tkinter window. We can control the title, color, size, and other attributes with this command. The 'wm' command has numerous keywords that can be used to modify its property." }, { "code": null, "e": 1944, "s": 1403, "text": "# Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n# Create an instance of tkinter frame\nwin=Tk()\n\n# Set the geometry\nwin.geometry(\"700x350\")\n\nLabel(win, text=\"This window is disabled.\",\n font=(\"Calibri, 24\")).pack()\n\n# Makes the window topmost\nwin.wm_attributes('-topmost', True)\n\n# Makes the window transparent\nwin.wm_attributes('-alpha', 0.9)\n\n# Disable the window\nwin.wm_attributes('-disabled', True)\n\n# Set the geometry of the window\nwin.wm_geometry('700x350')\n\nwin.mainloop()" }, { "code": null, "e": 2109, "s": 1944, "text": "If you run the above code, it will display a topmost transparent window that you cannot interact with, as the window is disabled using the wm attribute \"-disabled\"." } ]
env command in Linux with Examples - GeeksforGeeks
15 May, 2019 env is used to either print environment variables. It is also used to run a utility or command in a custom environment. In practice, env has another common use. It is often used by shell scripts to launch the correct interpreter. In this usage, the environment is typically not changed. Syntax : env [OPTION]... [-][NAME=VALUE]... [COMMAND [ARG]...] Options of env command 1. Without any argument : print out a list of all environment variables. EXAMPLE : 2. -i or –ignore-environment or only – : runs a command with an empty environment SYNTAX : $ env -i your_command Note: This completely clear out the environment, but it does not prevent your_command setting new variables. EXAMPLE : To clear the environment (creating a new environment without any existing environment variables) for a new shell In this, it clears all the environment variable and then new shell sets the environment variable PWD. Thus in this new shell when we execute env, we only see one environment variable PWD. 3. -u or –unset: remove variable from the environment SYNTAX : $ env -u variable_name EXAMPLE : Removing XDG_VTNR environment variable which you can see in the image above in the output of just env. 4. -0 or –null: End each output line with NULL, not newline SYNTAX : $ env -0 EXAMPLE : 5. –version: Display version information and exit. SYNTAX : $ env --version EXAMPLE : 6. –help: Display a help message and exit. SYNTAX : $ env --help EXAMPLE : linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization
[ { "code": null, "e": 24146, "s": 24118, "text": "\n15 May, 2019" }, { "code": null, "e": 24433, "s": 24146, "text": "env is used to either print environment variables. It is also used to run a utility or command in a custom environment. In practice, env has another common use. It is often used by shell scripts to launch the correct interpreter. In this usage, the environment is typically not changed." }, { "code": null, "e": 24442, "s": 24433, "text": "Syntax :" }, { "code": null, "e": 24497, "s": 24442, "text": "env [OPTION]... [-][NAME=VALUE]... [COMMAND [ARG]...]\n" }, { "code": null, "e": 24520, "s": 24497, "text": "Options of env command" }, { "code": null, "e": 24593, "s": 24520, "text": "1. Without any argument : print out a list of all environment variables." }, { "code": null, "e": 24603, "s": 24593, "text": "EXAMPLE :" }, { "code": null, "e": 24685, "s": 24603, "text": "2. -i or –ignore-environment or only – : runs a command with an empty environment" }, { "code": null, "e": 24694, "s": 24685, "text": "SYNTAX :" }, { "code": null, "e": 24717, "s": 24694, "text": "$ env -i your_command\n" }, { "code": null, "e": 24826, "s": 24717, "text": "Note: This completely clear out the environment, but it does not prevent your_command setting new variables." }, { "code": null, "e": 24949, "s": 24826, "text": "EXAMPLE : To clear the environment (creating a new environment without any existing environment variables) for a new shell" }, { "code": null, "e": 25137, "s": 24949, "text": "In this, it clears all the environment variable and then new shell sets the environment variable PWD. Thus in this new shell when we execute env, we only see one environment variable PWD." }, { "code": null, "e": 25191, "s": 25137, "text": "3. -u or –unset: remove variable from the environment" }, { "code": null, "e": 25200, "s": 25191, "text": "SYNTAX :" }, { "code": null, "e": 25224, "s": 25200, "text": "$ env -u variable_name\n" }, { "code": null, "e": 25337, "s": 25224, "text": "EXAMPLE : Removing XDG_VTNR environment variable which you can see in the image above in the output of just env." }, { "code": null, "e": 25397, "s": 25337, "text": "4. -0 or –null: End each output line with NULL, not newline" }, { "code": null, "e": 25406, "s": 25397, "text": "SYNTAX :" }, { "code": null, "e": 25416, "s": 25406, "text": "$ env -0\n" }, { "code": null, "e": 25426, "s": 25416, "text": "EXAMPLE :" }, { "code": null, "e": 25477, "s": 25426, "text": "5. –version: Display version information and exit." }, { "code": null, "e": 25486, "s": 25477, "text": "SYNTAX :" }, { "code": null, "e": 25503, "s": 25486, "text": "$ env --version\n" }, { "code": null, "e": 25513, "s": 25503, "text": "EXAMPLE :" }, { "code": null, "e": 25556, "s": 25513, "text": "6. –help: Display a help message and exit." }, { "code": null, "e": 25565, "s": 25556, "text": "SYNTAX :" }, { "code": null, "e": 25579, "s": 25565, "text": "$ env --help\n" }, { "code": null, "e": 25589, "s": 25579, "text": "EXAMPLE :" }, { "code": null, "e": 25603, "s": 25589, "text": "linux-command" }, { "code": null, "e": 25623, "s": 25603, "text": "Linux-misc-commands" }, { "code": null, "e": 25630, "s": 25623, "text": "Picked" }, { "code": null, "e": 25641, "s": 25630, "text": "Linux-Unix" }, { "code": null, "e": 25739, "s": 25641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25777, "s": 25739, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25812, "s": 25777, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 25847, "s": 25812, "text": "tar command in Linux with examples" }, { "code": null, "e": 25883, "s": 25847, "text": "curl command in Linux with Examples" }, { "code": null, "e": 25921, "s": 25883, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 25959, "s": 25921, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 25994, "s": 25959, "text": "Cat command in Linux with examples" }, { "code": null, "e": 26030, "s": 25994, "text": "Tail command in Linux with examples" }, { "code": null, "e": 26067, "s": 26030, "text": "touch command in Linux with Examples" } ]
Plot a Line Graph for Pandas Dataframe with Matplotlib?
We will plot a line grapg for Pandas DataFrame using the plot(). At first, import the required libraries − import pandas as pd import matplotlib.pyplot as plt Create a DataFrame − dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Reg_Price": [2000, 2500, 2800, 3000, 3200, 3500],"Units": [100, 120, 150, 170, 180, 200] } ) Plot a line graph with both the columns − plt.plot(dataFrame["Reg_Price"], dataFrame["Units"]) Following is the code − import pandas as pd import matplotlib.pyplot as plt # creating a DataFrame with 2 columns dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Reg_Price": [2000, 2500, 2800, 3000, 3200, 3500],"Units": [100, 120, 150, 170, 180, 200] } ) # plot a line graph plt.plot(dataFrame["Reg_Price"], dataFrame["Units"]) plt.show() This will produce the following output −
[ { "code": null, "e": 1169, "s": 1062, "text": "We will plot a line grapg for Pandas DataFrame using the plot(). At first, import the required libraries −" }, { "code": null, "e": 1221, "s": 1169, "text": "import pandas as pd\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 1242, "s": 1221, "text": "Create a DataFrame −" }, { "code": null, "e": 1440, "s": 1242, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\"Reg_Price\": [2000, 2500, 2800, 3000, 3200, 3500],\"Units\": [100, 120, 150, 170, 180, 200]\n }\n)" }, { "code": null, "e": 1482, "s": 1440, "text": "Plot a line graph with both the columns −" }, { "code": null, "e": 1535, "s": 1482, "text": "plt.plot(dataFrame[\"Reg_Price\"], dataFrame[\"Units\"])" }, { "code": null, "e": 1559, "s": 1535, "text": "Following is the code −" }, { "code": null, "e": 1933, "s": 1559, "text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\n# creating a DataFrame with 2 columns\ndataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\"Reg_Price\": [2000, 2500, 2800, 3000, 3200, 3500],\"Units\": [100, 120, 150, 170, 180, 200]\n }\n)\n\n# plot a line graph\nplt.plot(dataFrame[\"Reg_Price\"], dataFrame[\"Units\"])\nplt.show()" }, { "code": null, "e": 1974, "s": 1933, "text": "This will produce the following output −" } ]
How to bind multiple versions of a DB2 program into a package?
Packages are DB2 database objects which hold the executable forms of SQLs which are used in COBOL-DB2 programs. The packages are stored in a catalog table and contain the strategy/tables/columns/predicate associated with the SQL statements. If there is a DB2 table ORDERS_TEST in test environment and ORDERS_PROD in production environment, then we need two versions of COBOL-DB2 program (which will access these tables) — one for test and the other for production. Although both programs will be carbon copy of each other, the only difference lies in the SQL statements. The test version of the program will use table ORDERS_TEST in SQL statements and the production version of program will use ORDERS_PROD table in SQL statement. In order to achieve this versioning, we need to bifurcate the packages of the program. To keep the multiple versions of the package, we have to use the VERSION option in the pre-compilation step. Therefore, we can give the VERSION(TEST) for the test version of the package and VERSION(PROD) for the production version of the package. Following is an example: //BIND EXEC PGM=IKJEFT01 //STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR //SYSOUT DD SYSOUT=* //SYSTSIN DD * DSN SYSTEM(TB3) BIND PLAN(PLANA) - PKLIST(PACKA) - VERSION(PROD) - ACQUIRE(ALLOCATE) - ISOLATION (RS) /*
[ { "code": null, "e": 1303, "s": 1062, "text": "Packages are DB2 database objects which hold the executable forms of SQLs which are used in COBOL-DB2 programs. The packages are stored in a catalog table and contain the strategy/tables/columns/predicate associated with the SQL statements." }, { "code": null, "e": 1527, "s": 1303, "text": "If there is a DB2 table ORDERS_TEST in test environment and ORDERS_PROD in production environment, then we need two versions of COBOL-DB2 program (which will access these tables) — one for test and the other for production." }, { "code": null, "e": 1880, "s": 1527, "text": "Although both programs will be carbon copy of each other, the only difference lies in the SQL statements. The test version of the program will use table ORDERS_TEST in SQL statements and the production version of program will use ORDERS_PROD table in SQL statement. In order to achieve this versioning, we need to bifurcate the packages of the program." }, { "code": null, "e": 2127, "s": 1880, "text": "To keep the multiple versions of the package, we have to use the VERSION option in the pre-compilation step. Therefore, we can give the VERSION(TEST) for the test version of the package and VERSION(PROD) for the production version of the package." }, { "code": null, "e": 2152, "s": 2127, "text": "Following is an example:" }, { "code": null, "e": 2361, "s": 2152, "text": "//BIND EXEC PGM=IKJEFT01\n//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR\n//SYSOUT DD SYSOUT=*\n//SYSTSIN DD *\nDSN SYSTEM(TB3)\nBIND PLAN(PLANA) -\nPKLIST(PACKA) -\nVERSION(PROD) -\nACQUIRE(ALLOCATE) -\nISOLATION (RS)\n/*" } ]
Pattern pattern() method in Java with examples
The java.util.regex package of java provides various classes to find particular patterns in character sequences. The pattern class of this package is a compiled representation of a regular expression. The pattern() method of the Pattern class fetches and returns the regular expression in the string format, using which the current pattern was compiled. import java.util.regex.Pattern; public class PatternExample { public static void main(String[] args) { String date = "12/09/2019"; String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); if(pattern.matcher(date).matches()) { System.out.println("Date is valid"); } else { System.out.println("Date is not valid"); } //Retrieving the regular expression of the current pattern String regularExpression = pattern.pattern(); System.out.println("Regular expression: "+regularExpression); } } Date is valid Regular expression: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$ public class PatternExample { public static void main(String[] args) { String input = "Hi my id is 056E1563"; //Regular expression using groups String regex = "(.*)?(\\d+)"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); if(pattern.matcher(input).matches()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } //Retrieving the regular expression of the current pattern String regularExpression = pattern.pattern(); System.out.println("Regular expression: "+regularExpression); } } Match found Regular expression: (.*)?(\d+)
[ { "code": null, "e": 1263, "s": 1062, "text": "The java.util.regex package of java provides various classes to find particular patterns in character sequences. The pattern class of this package is a compiled representation of a regular expression." }, { "code": null, "e": 1416, "s": 1263, "text": "The pattern() method of the Pattern class fetches and returns the regular expression in the string format, using which the current pattern was compiled." }, { "code": null, "e": 2069, "s": 1416, "text": "import java.util.regex.Pattern;\npublic class PatternExample {\n public static void main(String[] args) {\n String date = \"12/09/2019\";\n String regex = \"^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n if(pattern.matcher(date).matches()) {\n System.out.println(\"Date is valid\");\n } else {\n System.out.println(\"Date is not valid\");\n }\n //Retrieving the regular expression of the current pattern\n String regularExpression = pattern.pattern();\n System.out.println(\"Regular expression: \"+regularExpression);\n }\n}" }, { "code": null, "e": 2155, "s": 2069, "text": "Date is valid\nRegular expression: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$" }, { "code": null, "e": 2784, "s": 2155, "text": "public class PatternExample {\n public static void main(String[] args) {\n String input = \"Hi my id is 056E1563\";\n //Regular expression using groups\n String regex = \"(.*)?(\\\\d+)\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n if(pattern.matcher(input).matches()) {\n System.out.println(\"Match found\");\n } else {\n System.out.println(\"Match not found\");\n }\n //Retrieving the regular expression of the current pattern\n String regularExpression = pattern.pattern();\n System.out.println(\"Regular expression: \"+regularExpression);\n }\n}" }, { "code": null, "e": 2827, "s": 2784, "text": "Match found\nRegular expression: (.*)?(\\d+)" } ]
wxPython - Change font of Radio Button - GeeksforGeeks
06 Jan, 2022 In this article we are going to learn that how can we change the font of the label text present on the radio button present in the frame. We need to follow some steps as follows: Step 1: Create a wx.Font object. Step 2: Add different attributes of font in parameters like: family, style etc. Step 3: Create a Radio Button. Step 3: Set font by using SetFont() function. Syntax: wx.RadioButton.SetFont(self, font)Parameters: Code Example: Python3 import wx APP_EXIT = 1 class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): # create parent panel for radio buttons self.pnl = wx.Panel(self) # create radio buttons self.rb1 = wx.RadioButton(self.pnl, label ='Btn1', pos =(30, 10), size =(100, 20)) self.rb2 = wx.RadioButton(self.pnl, label ='Btn2', pos =(30, 30), size =(100, 20)) self.rb3 = wx.RadioButton(self.pnl, label ='Btn3', pos =(30, 50), size =(100, 20)) # declare font for radio buttons font = wx.Font(12, wx.FONTFAMILY_MODERN, 0, 90, underline = False, faceName ="") # set font for all radio buttons self.rb1.SetFont(font) self.rb2.SetFont(font) self.rb3.SetFont(font) def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output Window: gulshankumarar231 Python wxPython-Button Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n06 Jan, 2022" }, { "code": null, "e": 24472, "s": 24292, "text": "In this article we are going to learn that how can we change the font of the label text present on the radio button present in the frame. We need to follow some steps as follows: " }, { "code": null, "e": 24663, "s": 24472, "text": "Step 1: Create a wx.Font object. Step 2: Add different attributes of font in parameters like: family, style etc. Step 3: Create a Radio Button. Step 3: Set font by using SetFont() function. " }, { "code": null, "e": 24720, "s": 24665, "text": "Syntax: wx.RadioButton.SetFont(self, font)Parameters: " }, { "code": null, "e": 24740, "s": 24724, "text": "Code Example: " }, { "code": null, "e": 24748, "s": 24740, "text": "Python3" }, { "code": "import wx APP_EXIT = 1 class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): # create parent panel for radio buttons self.pnl = wx.Panel(self) # create radio buttons self.rb1 = wx.RadioButton(self.pnl, label ='Btn1', pos =(30, 10), size =(100, 20)) self.rb2 = wx.RadioButton(self.pnl, label ='Btn2', pos =(30, 30), size =(100, 20)) self.rb3 = wx.RadioButton(self.pnl, label ='Btn3', pos =(30, 50), size =(100, 20)) # declare font for radio buttons font = wx.Font(12, wx.FONTFAMILY_MODERN, 0, 90, underline = False, faceName =\"\") # set font for all radio buttons self.rb1.SetFont(font) self.rb2.SetFont(font) self.rb3.SetFont(font) def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 25730, "s": 24748, "text": null }, { "code": null, "e": 25747, "s": 25730, "text": "Output Window: " }, { "code": null, "e": 25767, "s": 25749, "text": "gulshankumarar231" }, { "code": null, "e": 25790, "s": 25767, "text": "Python wxPython-Button" }, { "code": null, "e": 25801, "s": 25790, "text": "Python-gui" }, { "code": null, "e": 25817, "s": 25801, "text": "Python-wxPython" }, { "code": null, "e": 25824, "s": 25817, "text": "Python" }, { "code": null, "e": 25922, "s": 25824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25931, "s": 25922, "text": "Comments" }, { "code": null, "e": 25944, "s": 25931, "text": "Old Comments" }, { "code": null, "e": 25976, "s": 25944, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26018, "s": 25976, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26073, "s": 26018, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26129, "s": 26073, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26171, "s": 26129, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26193, "s": 26171, "text": "Defaultdict in Python" }, { "code": null, "e": 26232, "s": 26193, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26263, "s": 26232, "text": "Python | os.path.join() method" }, { "code": null, "e": 26292, "s": 26263, "text": "Create a directory in Python" } ]
How To Change the Nginx Web Document Location on Ubuntu 16.04
In this article, we will learn about how to move or change the location of the Nginx Web server documents folder. By default Nginx Web server default location is at /usr/share/nginx/html which is located on the default file system of the Linux. Generally, this is done, based on the website requirement or client requirements. To complete our setup we need the below requirements. Ubuntu 16.04 installed with a used with sudo permission on the machine. Nginx web server installed A mounted drive or the new document located for where we wanted to change the default document location. As the Nginx default document root is at /usr/share/nginx/html, if you have an Nginx installed and existing servers are configured we needed to check the sites-enabled folder which is located on the /etc/nginx/sites-enabled, if the location is changed on the existing servers we can search for the sites-enabled folder with the below command $ grep “root” –R /etc/nginx/sites-enabled /etc/nginx/sites-enabled/default: root /usr/share/nginx/html; /etc/nginx/sites-enabled/default: # deny access to .htaccess files, if Apache's document root /etc/nginx/sites-enabled/default:# root /var/www/demosite; Assuming that we are moving the default site files /var/www/demosite to the newly created volume, which is located at /mnt/newdatavolume. $ sudo rsync –av /usr/share/nginx/html /mnt/newdatavolume Nginx allow us to change the configuration for the site globally or site specific, in this demo we are using the existing site to be changed from the default location to the new location we have to find the location using the grep command and change the configuration files. $ sudo vi /etc/nginx/sites-enabled/000-default We needed to look for the line ‘root’ and update the new location comment that line and add the new line root /mnt/newdatavolume Below is the sample file of the default nginx configuration. ## # You should look at the following URL's in order to grasp a solid understanding # of Nginx configuration files in order to fully unleash the power of Nginx. # http://wiki.nginx.org/Pitfalls # http://wiki.nginx.org/QuickStart # http://wiki.nginx.org/Configuration # # Generally, you will want to move this file somewhere, and start with a clean # file but keep this around for reference. Or just disable in sites-enabled. # # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples. ## server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; #root /usr/share/nginx/html; root /mnt/newdatavolume index index.html index.htm; # Make site accessible from http://localhost/ server_name localhost; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; # Uncomment to enable naxsi on this location # include /etc/nginx/naxsi.rules } # Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests #location /RequestDenied { # proxy_pass http://127.0.0.1:8080; #} #error_page 404 /404.html; # redirect server error pages to the static page /50x.html Once the configuration is changed, then accordingly we needed to restart the Nginx Web server to apply the changes. First, we will check the configuration files and restart the Niginx Web server. $ sudo nginx –t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful $ sudo systemctl restart nginx In the above article and setup we have learned to change the Nginx default document root folder location to the new location mounted on the other volume, where we wanted to manage the sites and bulk site date on a single server.
[ { "code": null, "e": 1389, "s": 1062, "text": "In this article, we will learn about how to move or change the location of the Nginx Web server documents folder. By default Nginx Web server default location is at /usr/share/nginx/html which is located on the default file system of the Linux. Generally, this is done, based on the website requirement or client requirements." }, { "code": null, "e": 1443, "s": 1389, "text": "To complete our setup we need the below requirements." }, { "code": null, "e": 1515, "s": 1443, "text": "Ubuntu 16.04 installed with a used with sudo permission on the machine." }, { "code": null, "e": 1542, "s": 1515, "text": "Nginx web server installed" }, { "code": null, "e": 1647, "s": 1542, "text": "A mounted drive or the new document located for where we wanted to change the default document location." }, { "code": null, "e": 1989, "s": 1647, "text": "As the Nginx default document root is at /usr/share/nginx/html, if you have an Nginx installed and existing servers are configured we needed to check the sites-enabled folder which is located on the /etc/nginx/sites-enabled, if the location is changed on the existing servers we can search for the sites-enabled folder with the below command" }, { "code": null, "e": 2246, "s": 1989, "text": "$ grep “root” –R /etc/nginx/sites-enabled\n/etc/nginx/sites-enabled/default: root /usr/share/nginx/html;\n/etc/nginx/sites-enabled/default: # deny access to .htaccess files, if Apache's document root\n/etc/nginx/sites-enabled/default:# root /var/www/demosite;" }, { "code": null, "e": 2384, "s": 2246, "text": "Assuming that we are moving the default site files /var/www/demosite to the newly created volume, which is located at /mnt/newdatavolume." }, { "code": null, "e": 2442, "s": 2384, "text": "$ sudo rsync –av /usr/share/nginx/html /mnt/newdatavolume" }, { "code": null, "e": 2717, "s": 2442, "text": "Nginx allow us to change the configuration for the site globally or site specific, in this demo we are using the existing site to be changed from the default location to the new location we have to find the location using the grep command and change the configuration files." }, { "code": null, "e": 2764, "s": 2717, "text": "$ sudo vi /etc/nginx/sites-enabled/000-default" }, { "code": null, "e": 2869, "s": 2764, "text": "We needed to look for the line ‘root’ and update the new location comment that line and add the new line" }, { "code": null, "e": 2893, "s": 2869, "text": "root /mnt/newdatavolume" }, { "code": null, "e": 2954, "s": 2893, "text": "Below is the sample file of the default nginx configuration." }, { "code": null, "e": 4133, "s": 2954, "text": "##\n# You should look at the following URL's in order to grasp a solid understanding\n# of Nginx configuration files in order to fully unleash the power of Nginx.\n# http://wiki.nginx.org/Pitfalls\n# http://wiki.nginx.org/QuickStart\n# http://wiki.nginx.org/Configuration\n#\n# Generally, you will want to move this file somewhere, and start with a clean\n# file but keep this around for reference. Or just disable in sites-enabled.\n#\n# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.\n##\nserver {\nlisten 80 default_server;\nlisten [::]:80 default_server ipv6only=on;\n#root /usr/share/nginx/html;\nroot /mnt/newdatavolume\nindex index.html index.htm;\n# Make site accessible from http://localhost/\nserver_name localhost;\nlocation / {\n# First attempt to serve request as file, then\n# as directory, then fall back to displaying a 404.\ntry_files $uri $uri/ =404;\n# Uncomment to enable naxsi on this location\n# include /etc/nginx/naxsi.rules\n}\n# Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests\n#location /RequestDenied {\n# proxy_pass http://127.0.0.1:8080;\n#}\n#error_page 404 /404.html;\n# redirect server error pages to the static page /50x.html" }, { "code": null, "e": 4329, "s": 4133, "text": "Once the configuration is changed, then accordingly we needed to restart the Nginx Web server to apply the changes. First, we will check the configuration files and restart the Niginx Web server." }, { "code": null, "e": 4509, "s": 4329, "text": "$ sudo nginx –t\nnginx: the configuration file /etc/nginx/nginx.conf syntax is ok\nnginx: configuration file /etc/nginx/nginx.conf test is successful\n\n$ sudo systemctl restart nginx" }, { "code": null, "e": 4738, "s": 4509, "text": "In the above article and setup we have learned to change the Nginx default document root folder location to the new location mounted on the other volume, where we wanted to manage the sites and bulk site date on a single server." } ]
ASP.NET Core - Razor View Import
In this chapter, we will discuss the Razor View Import. In addition to the ViewStart file, there is also a ViewImports file that the MVC framework will look for when rendering any view. Like the ViewStart file, we can drop ViewImports.cshtml into a folder, and the ViewImports file can influence all the views in the folder hierarchy This view is new for this version of MVC, in the previous versions of MVC, we could use an XML configuration file to configure certain aspects of the Razor view engine. This view is new for this version of MVC, in the previous versions of MVC, we could use an XML configuration file to configure certain aspects of the Razor view engine. Those XML files are gone now and we use code instead. Those XML files are gone now and we use code instead. The ViewImports file is a place where we can write code and place common directives to pull in namespaces that our views need. The ViewImports file is a place where we can write code and place common directives to pull in namespaces that our views need. If there are namespaces that we commonly use in our views, we can have using directives appear once in our ViewImports file instead of having using directives in every view or typing out the full namespace of a class. If there are namespaces that we commonly use in our views, we can have using directives appear once in our ViewImports file instead of having using directives in every view or typing out the full namespace of a class. Let us take a simple example to see how to move our using directives into ViewImports. Inside the Index view, we have a using directive to bring in the namespace FirstAppDemo.Controllers as shown in the following program. @using FirstAppDemo.Controllers @model HomePageViewModel @{ ViewBag.Title = "Home"; } <h1>Welcome!</h1> <table> @foreach (var employee in Model.Employees) { <tr> <td> @Html.ActionLink(employee.Id.ToString(), "Details", new { id = employee.Id }) </td> <td>@employee.Name</td> </tr> } </table> Using directives will allow the code that is generated from the Razor view to compile correctly. Without using directives, the C# compiler won't be able to find this Employee type. To see the employee type, let us remove the using directive from the Index.cshtml file. @model HomePageViewModel @{ ViewBag.Title = "Home"; } <h1>Welcome!</h1> <table> @foreach (var employee in Model.Employees) { <tr> <td> @Html.ActionLink(employee.Id.ToString(), "Details", new { id = employee.Id }) </td> <td>@employee.Name</td> </tr> } </table> Now, run the application. You will see one of the errors that states that the type or namespace HomePageViewModel could not be found. It might be because several of your views need that same using directive. So, instead of placing that inside each view, let us create a View import in the Views folder. This will add using statements to every view with just a right-click on the Views folder and selecting Add → New Item. In the middle pane, select the MVC View Imports Page. By default, the name is _ViewImports.cshtml. Just like ViewStart, we cannot use this file to render HTML, so let us click on the Add button. Now add the using directive in this into _ViewImports.cshtml file as shown below. @using FirstAppDemo.Controllers Now, all the views that appear in this folder or any subfolder will be able to use types from FirstAppDemo.Controllers without specifying that exact using statement. Let us run your application again and you can see that the view is working now. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2647, "s": 2461, "text": "In this chapter, we will discuss the Razor View Import. In addition to the ViewStart file, there is also a ViewImports file that the MVC framework will look for when rendering any view." }, { "code": null, "e": 2795, "s": 2647, "text": "Like the ViewStart file, we can drop ViewImports.cshtml into a folder, and the ViewImports file can influence all the views in the folder hierarchy" }, { "code": null, "e": 2964, "s": 2795, "text": "This view is new for this version of MVC, in the previous versions of MVC, we could use an XML configuration file to configure certain aspects of the Razor view engine." }, { "code": null, "e": 3133, "s": 2964, "text": "This view is new for this version of MVC, in the previous versions of MVC, we could use an XML configuration file to configure certain aspects of the Razor view engine." }, { "code": null, "e": 3187, "s": 3133, "text": "Those XML files are gone now and we use code instead." }, { "code": null, "e": 3241, "s": 3187, "text": "Those XML files are gone now and we use code instead." }, { "code": null, "e": 3368, "s": 3241, "text": "The ViewImports file is a place where we can write code and place common directives to pull in namespaces that our views need." }, { "code": null, "e": 3495, "s": 3368, "text": "The ViewImports file is a place where we can write code and place common directives to pull in namespaces that our views need." }, { "code": null, "e": 3713, "s": 3495, "text": "If there are namespaces that we commonly use in our views, we can have using directives appear once in our ViewImports file instead of having using directives in every view or typing out the full namespace of a class." }, { "code": null, "e": 3931, "s": 3713, "text": "If there are namespaces that we commonly use in our views, we can have using directives appear once in our ViewImports file instead of having using directives in every view or typing out the full namespace of a class." }, { "code": null, "e": 4153, "s": 3931, "text": "Let us take a simple example to see how to move our using directives into ViewImports. Inside the Index view, we have a using directive to bring in the namespace FirstAppDemo.Controllers as shown in the following program." }, { "code": null, "e": 4522, "s": 4153, "text": "@using FirstAppDemo.Controllers \n@model HomePageViewModel \n@{ \n ViewBag.Title = \"Home\"; \n} \n<h1>Welcome!</h1> \n\n<table> \n @foreach (var employee in Model.Employees) { \n <tr> \n <td> \n @Html.ActionLink(employee.Id.ToString(), \"Details\", new { id = employee.Id })\n </td> \n <td>@employee.Name</td> \n </tr> \n } \n</table>" }, { "code": null, "e": 4791, "s": 4522, "text": "Using directives will allow the code that is generated from the Razor view to compile correctly. Without using directives, the C# compiler won't be able to find this Employee type. To see the employee type, let us remove the using directive from the Index.cshtml file." }, { "code": null, "e": 5126, "s": 4791, "text": "@model HomePageViewModel \n@{ \n ViewBag.Title = \"Home\"; \n} \n<h1>Welcome!</h1> \n\n<table> \n @foreach (var employee in Model.Employees) { \n <tr>\n <td>\n @Html.ActionLink(employee.Id.ToString(), \"Details\", new { id = employee.Id })\n </td> \n <td>@employee.Name</td> \n </tr> \n } \n</table> " }, { "code": null, "e": 5152, "s": 5126, "text": "Now, run the application." }, { "code": null, "e": 5548, "s": 5152, "text": "You will see one of the errors that states that the type or namespace HomePageViewModel could not be found. It might be because several of your views need that same using directive. So, instead of placing that inside each view, let us create a View import in the Views folder. This will add using statements to every view with just a right-click on the Views folder and selecting Add → New Item." }, { "code": null, "e": 5743, "s": 5548, "text": "In the middle pane, select the MVC View Imports Page. By default, the name is _ViewImports.cshtml. Just like ViewStart, we cannot use this file to render HTML, so let us click on the Add button." }, { "code": null, "e": 5825, "s": 5743, "text": "Now add the using directive in this into _ViewImports.cshtml file as shown below." }, { "code": null, "e": 5858, "s": 5825, "text": "@using FirstAppDemo.Controllers\n" }, { "code": null, "e": 6104, "s": 5858, "text": "Now, all the views that appear in this folder or any subfolder will be able to use types from FirstAppDemo.Controllers without specifying that exact using statement. Let us run your application again and you can see that the view is working now." }, { "code": null, "e": 6139, "s": 6104, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6153, "s": 6139, "text": " Anadi Sharma" }, { "code": null, "e": 6188, "s": 6153, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6211, "s": 6188, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6245, "s": 6211, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 6265, "s": 6245, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6300, "s": 6265, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6317, "s": 6300, "text": " University Code" }, { "code": null, "e": 6352, "s": 6317, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6369, "s": 6352, "text": " University Code" }, { "code": null, "e": 6403, "s": 6369, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 6418, "s": 6403, "text": " Bhrugen Patel" }, { "code": null, "e": 6425, "s": 6418, "text": " Print" }, { "code": null, "e": 6436, "s": 6425, "text": " Add Notes" } ]
How to install DSC resources using PowerShell?
To install the DSC resource using PowerShell, we can use the same command to install modules in PowerShell (Install-Module). The Find-DscResource command would get all the available DSC resources. To search the specific DSC resource, you can provide the -Name parameter in the Find-DscReource command. For example, we need to search for the FilesAndFolder DSC resource Find-DSCResource -Name filesandfolders Name Version ModuleName Repository ---- ------- ---------- ---------- FilesAndFolders 0.3.212 CommonTasks PSGallery To install this module, we can pipeline the Install-Module command. Find-DSCResource -Name filesandfolders | Install-Module -Force -Verbose Once the module is installed, we can use the Get-DSCResource command to check if the module is installed properly. Get-DscResource -Name FilesAndFolders To check the properties of the installed module, we can use the below command. Get-DscResource -Name FilesAndFolders | Select -ExpandProperty Properties Name PropertyType IsMandatory Values ---- ------------ ----------- ------ DependsOn [String[]] False {} PsDscRunAsCredential [PSCredential] False {} Items [Hashtable[]] True {}
[ { "code": null, "e": 1187, "s": 1062, "text": "To install the DSC resource using PowerShell, we can use the same command to install modules in PowerShell (Install-Module)." }, { "code": null, "e": 1431, "s": 1187, "text": "The Find-DscResource command would get all the available DSC resources. To search the specific DSC resource, you can provide the -Name parameter in the Find-DscReource command. For example, we need to search for the FilesAndFolder DSC resource" }, { "code": null, "e": 1470, "s": 1431, "text": "Find-DSCResource -Name filesandfolders" }, { "code": null, "e": 1610, "s": 1470, "text": "Name Version ModuleName Repository\n---- ------- ---------- ----------\nFilesAndFolders 0.3.212 CommonTasks PSGallery" }, { "code": null, "e": 1678, "s": 1610, "text": "To install this module, we can pipeline the Install-Module command." }, { "code": null, "e": 1750, "s": 1678, "text": "Find-DSCResource -Name filesandfolders | Install-Module -Force -Verbose" }, { "code": null, "e": 1865, "s": 1750, "text": "Once the module is installed, we can use the Get-DSCResource command to check if the module is installed properly." }, { "code": null, "e": 1903, "s": 1865, "text": "Get-DscResource -Name FilesAndFolders" }, { "code": null, "e": 1982, "s": 1903, "text": "To check the properties of the installed module, we can use the below command." }, { "code": null, "e": 2056, "s": 1982, "text": "Get-DscResource -Name FilesAndFolders | Select -ExpandProperty Properties" }, { "code": null, "e": 2318, "s": 2056, "text": "Name PropertyType IsMandatory Values\n---- ------------ ----------- ------\nDependsOn [String[]] False {}\nPsDscRunAsCredential [PSCredential] False {}\nItems [Hashtable[]] True {}" } ]
Exp() and Count() Function in MS Access
01 Sep, 2020 1. Exp() function :In MS Access, the Exp() function returns e( 2.718281) power raised to a number. In this function, a number will be pass as a parameter and it will return e raised to the power of a specified number.e is a constant which value is equal to 2.718281. It is the base of natural logarithms. Syntax : Exp(number) Example-1 : SELECT Exp(6) AS ExpNum; Output – Example-2 : SELECT Exp(1) AS ExpNum; Output – 2. Count() function :In MS Access, The Count() function returns the total number of eligible records of a query. When a query expression is performed with the help of count function then it will count total records and return that total count number. Note –Null values will not be included in the count. Syntax : Count(expression) Consider an example for Demo Database given below. Table name : Stu_Details. Example-1 : SELECT Count(*) AS TOTAL FROM Stu_Details; Output – Example-2 : SELECT Count(*) AS TOTAL FROM Stu_Details Where MARKS>50; Output – DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL Window functions in SQL SQL | GROUP BY Difference between DELETE and TRUNCATE MySQL | Group_CONCAT() Function Difference between DDL and DML in DBMS SQL Correlated Subqueries
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2020" }, { "code": null, "e": 333, "s": 28, "text": "1. Exp() function :In MS Access, the Exp() function returns e( 2.718281) power raised to a number. In this function, a number will be pass as a parameter and it will return e raised to the power of a specified number.e is a constant which value is equal to 2.718281. It is the base of natural logarithms." }, { "code": null, "e": 342, "s": 333, "text": "Syntax :" }, { "code": null, "e": 355, "s": 342, "text": "Exp(number)\n" }, { "code": null, "e": 367, "s": 355, "text": "Example-1 :" }, { "code": null, "e": 393, "s": 367, "text": "SELECT Exp(6) AS ExpNum;\n" }, { "code": null, "e": 402, "s": 393, "text": "Output –" }, { "code": null, "e": 414, "s": 402, "text": "Example-2 :" }, { "code": null, "e": 440, "s": 414, "text": "SELECT Exp(1) AS ExpNum;\n" }, { "code": null, "e": 449, "s": 440, "text": "Output –" }, { "code": null, "e": 700, "s": 449, "text": "2. Count() function :In MS Access, The Count() function returns the total number of eligible records of a query. When a query expression is performed with the help of count function then it will count total records and return that total count number." }, { "code": null, "e": 753, "s": 700, "text": "Note –Null values will not be included in the count." }, { "code": null, "e": 762, "s": 753, "text": "Syntax :" }, { "code": null, "e": 781, "s": 762, "text": "Count(expression)\n" }, { "code": null, "e": 832, "s": 781, "text": "Consider an example for Demo Database given below." }, { "code": null, "e": 858, "s": 832, "text": "Table name : Stu_Details." }, { "code": null, "e": 870, "s": 858, "text": "Example-1 :" }, { "code": null, "e": 914, "s": 870, "text": "SELECT Count(*) AS TOTAL FROM Stu_Details;\n" }, { "code": null, "e": 923, "s": 914, "text": "Output –" }, { "code": null, "e": 935, "s": 923, "text": "Example-2 :" }, { "code": null, "e": 994, "s": 935, "text": "SELECT Count(*) AS TOTAL FROM Stu_Details\nWhere MARKS>50;\n" }, { "code": null, "e": 1003, "s": 994, "text": "Output –" }, { "code": null, "e": 1012, "s": 1003, "text": "DBMS-SQL" }, { "code": null, "e": 1016, "s": 1012, "text": "SQL" }, { "code": null, "e": 1020, "s": 1016, "text": "SQL" }, { "code": null, "e": 1118, "s": 1020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1142, "s": 1118, "text": "SQL Interview Questions" }, { "code": null, "e": 1208, "s": 1142, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1253, "s": 1208, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1286, "s": 1253, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1310, "s": 1286, "text": "Window functions in SQL" }, { "code": null, "e": 1325, "s": 1310, "text": "SQL | GROUP BY" }, { "code": null, "e": 1364, "s": 1325, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 1396, "s": 1364, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1435, "s": 1396, "text": "Difference between DDL and DML in DBMS" } ]
Python Pandas - Swap levels of a MultiIndex
To swap levels of a MultiIndex, use the swaplevel() method in Pandas. The levels to be swapped should be mentioned as arguments. At first, import the required libraries − import pandas as pd MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays − arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]] The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex − multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points')) Swap levels of MultiIndex using swaplevel(). The 1st parameter is the first level of index to be swapped. The 2nd parameter is the second level of index to be swapped − print("\nSwap levels in MultiIndex...\n",multiIndex.swaplevel(0,2)) Following is the code − import pandas as pd # MultiIndex is a multi-level, or hierarchical, index object for pandas objects # Create arrays arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]] # The "names" parameter sets the names for each of the index levels # The from_arrays() is used to create a MultiIndex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points')) # display the MultiIndex print("The MultiIndex...\n",multiIndex) # get the levels in MultiIndex print("\nThe levels in MultiIndex...\n",multiIndex.levels) # swap levels of MultiIndex using swaplevel() # The 1st parameter is the first level of index to be swapped # The 2nd parameter is the second level of index to be swapped print("\nSwap levels in MultiIndex...\n",multiIndex.swaplevel(0,2)) This will produce the following output − The MultiIndex... MultiIndex([(2, 'Peter', 50), (4, 'Chris', 30), (3, 'Andy', 40), (1, 'Jacob', 70)], names=['rank', 'student', 'points']) The levels in MultiIndex... [[1, 2, 3, 4], ['Andy', 'Chris', 'Jacob', 'Peter'], [30, 40, 50, 70]] Swap levels in MultiIndex... MultiIndex([(50, 'Peter', 2), (30, 'Chris', 4), (40, 'Andy', 3), (70, 'Jacob', 1)], names=['points', 'student', 'rank'])
[ { "code": null, "e": 1316, "s": 1187, "text": "To swap levels of a MultiIndex, use the swaplevel() method in Pandas. The levels to be swapped should be mentioned as arguments." }, { "code": null, "e": 1358, "s": 1316, "text": "At first, import the required libraries −" }, { "code": null, "e": 1378, "s": 1358, "text": "import pandas as pd" }, { "code": null, "e": 1473, "s": 1378, "text": "MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −" }, { "code": null, "e": 1553, "s": 1473, "text": "arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]]\n" }, { "code": null, "e": 1671, "s": 1553, "text": "The \"names\" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −" }, { "code": null, "e": 1755, "s": 1671, "text": "multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points'))" }, { "code": null, "e": 1924, "s": 1755, "text": "Swap levels of MultiIndex using swaplevel(). The 1st parameter is the first level of index to be swapped. The 2nd parameter is the second level of index to be swapped −" }, { "code": null, "e": 1993, "s": 1924, "text": "print(\"\\nSwap levels in MultiIndex...\\n\",multiIndex.swaplevel(0,2))\n" }, { "code": null, "e": 2017, "s": 1993, "text": "Following is the code −" }, { "code": null, "e": 2814, "s": 2017, "text": "import pandas as pd\n\n# MultiIndex is a multi-level, or hierarchical, index object for pandas objects\n# Create arrays\narrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]]\n\n# The \"names\" parameter sets the names for each of the index levels\n# The from_arrays() is used to create a MultiIndex\nmultiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points'))\n\n# display the MultiIndex\nprint(\"The MultiIndex...\\n\",multiIndex)\n\n# get the levels in MultiIndex\nprint(\"\\nThe levels in MultiIndex...\\n\",multiIndex.levels)\n\n# swap levels of MultiIndex using swaplevel()\n# The 1st parameter is the first level of index to be swapped\n# The 2nd parameter is the second level of index to be swapped\nprint(\"\\nSwap levels in MultiIndex...\\n\",multiIndex.swaplevel(0,2))" }, { "code": null, "e": 2855, "s": 2814, "text": "This will produce the following output −" }, { "code": null, "e": 3344, "s": 2855, "text": "The MultiIndex...\nMultiIndex([(2, 'Peter', 50),\n (4, 'Chris', 30),\n (3, 'Andy', 40),\n (1, 'Jacob', 70)],\n names=['rank', 'student', 'points'])\n\nThe levels in MultiIndex...\n [[1, 2, 3, 4], ['Andy', 'Chris', 'Jacob', 'Peter'], [30, 40, 50, 70]]\n\nSwap levels in MultiIndex...\nMultiIndex([(50, 'Peter', 2),\n (30, 'Chris', 4),\n (40, 'Andy', 3),\n (70, 'Jacob', 1)],\n names=['points', 'student', 'rank'])" } ]
How to use files in public folder in ReactJS ?
19 Aug, 2021 The public folder contains static files such as index.html, javascript library files, images, and other assets, etc. which you don’t want to be processed by webpack. Files in this folder are copied and pasted as they are directly into the build folder. Only files inside the `public` folder can be referenced from the HTML. Creating React Application: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Now create an assets folder and put any sample image into it, like here we have kept the gfg.png file. Also, we have kept the gfgPublic.png file in the public folder. Simple react app folder structure App.js import Intro from './components/Intro';import './App.css'; function App() { return ( <div className="App"> <Intro /> </div> );} export default App; For the above file structure, in order to display the src/assets/gfg.png in Intro component, it can be simply imported and shown like this: import gfgLogo from "../assets/gfg.png"; ... <img src={gfgLogo} /> For showing image inside the public folder, ‘public/gfgPublic.png’. The URL for the src attribute will be process.env.PUBLIC_URL + “/gfgPublic.png”. Here, the PUBLIC_URL will be replaced with the URL of the `public` folder during the build. <img src={process.env.PUBLIC_URL + "/gfgPublic.png"} /> Intro.js import gfgLogo from "../assets/gfg.png"; const Intro = () => { return ( <div className="App"> Image at src/assets/gfg.png : <br /> <img src={gfgLogo} /> <br /> Image at public/gfgPublic.png: <br /> <img src={process.env.PUBLIC_URL + "/gfgPublic.png"} /> <br /> </div> );}; export default Intro; 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: For including any js files from the Public folder in the HTML file, add the following line. The %PUBLIC_URL% will be replaced with the URL of the `public` folder during the build. <script src="%PUBLIC_URL%/customScript.js" ></script> customScript.js console.log("Your public/customScript.js is loaded !!"); Output: React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Aug, 2021" }, { "code": null, "e": 376, "s": 52, "text": "The public folder contains static files such as index.html, javascript library files, images, and other assets, etc. which you don’t want to be processed by webpack. Files in this folder are copied and pasted as they are directly into the build folder. Only files inside the `public` folder can be referenced from the HTML." }, { "code": null, "e": 404, "s": 376, "text": "Creating React Application:" }, { "code": null, "e": 499, "s": 404, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 563, "s": 499, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 595, "s": 563, "text": "npx create-react-app foldername" }, { "code": null, "e": 708, "s": 595, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 808, "s": 708, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 822, "s": 808, "text": "cd foldername" }, { "code": null, "e": 1041, "s": 822, "text": "Project Structure: It will look like the following. Now create an assets folder and put any sample image into it, like here we have kept the gfg.png file. Also, we have kept the gfgPublic.png file in the public folder." }, { "code": null, "e": 1075, "s": 1041, "text": "Simple react app folder structure" }, { "code": null, "e": 1082, "s": 1075, "text": "App.js" }, { "code": "import Intro from './components/Intro';import './App.css'; function App() { return ( <div className=\"App\"> <Intro /> </div> );} export default App;", "e": 1245, "s": 1082, "text": null }, { "code": null, "e": 1386, "s": 1245, "text": "For the above file structure, in order to display the src/assets/gfg.png in Intro component, it can be simply imported and shown like this: " }, { "code": null, "e": 1453, "s": 1386, "text": "import gfgLogo from \"../assets/gfg.png\";\n...\n<img src={gfgLogo} />" }, { "code": null, "e": 1694, "s": 1453, "text": "For showing image inside the public folder, ‘public/gfgPublic.png’. The URL for the src attribute will be process.env.PUBLIC_URL + “/gfgPublic.png”. Here, the PUBLIC_URL will be replaced with the URL of the `public` folder during the build." }, { "code": null, "e": 1750, "s": 1694, "text": "<img src={process.env.PUBLIC_URL + \"/gfgPublic.png\"} />" }, { "code": null, "e": 1759, "s": 1750, "text": "Intro.js" }, { "code": "import gfgLogo from \"../assets/gfg.png\"; const Intro = () => { return ( <div className=\"App\"> Image at src/assets/gfg.png : <br /> <img src={gfgLogo} /> <br /> Image at public/gfgPublic.png: <br /> <img src={process.env.PUBLIC_URL + \"/gfgPublic.png\"} /> <br /> </div> );}; export default Intro;", "e": 2100, "s": 1759, "text": null }, { "code": null, "e": 2213, "s": 2100, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2223, "s": 2213, "text": "npm start" }, { "code": null, "e": 2322, "s": 2223, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2502, "s": 2322, "text": "For including any js files from the Public folder in the HTML file, add the following line. The %PUBLIC_URL% will be replaced with the URL of the `public` folder during the build." }, { "code": null, "e": 2556, "s": 2502, "text": "<script src=\"%PUBLIC_URL%/customScript.js\" ></script>" }, { "code": null, "e": 2572, "s": 2556, "text": "customScript.js" }, { "code": "console.log(\"Your public/customScript.js is loaded !!\");", "e": 2629, "s": 2572, "text": null }, { "code": null, "e": 2637, "s": 2629, "text": "Output:" }, { "code": null, "e": 2653, "s": 2637, "text": "React-Questions" }, { "code": null, "e": 2664, "s": 2653, "text": "JavaScript" }, { "code": null, "e": 2672, "s": 2664, "text": "ReactJS" }, { "code": null, "e": 2689, "s": 2672, "text": "Web Technologies" }, { "code": null, "e": 2787, "s": 2689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2848, "s": 2787, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2920, "s": 2848, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2960, "s": 2920, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3001, "s": 2960, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3047, "s": 3001, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 3090, "s": 3047, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3135, "s": 3090, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 3173, "s": 3135, "text": "Axios in React: A Guide for Beginners" } ]
Minimum swaps and K together | Practice | GeeksforGeeks
Given an array arr of n positive integers and a number k. One can apply a swap operation on the array any number of times, i.e choose any two index i and j (i < j) and swap arr[i] , arr[j] . Find the minimum number of swaps required to bring all the numbers less than or equal to k together, i.e. make them a contiguous subarray. Example 1: Input : arr[ ] = {2, 1, 5, 6, 3} K = 3 Output : 1 Explanation: To bring elements 2, 1, 3 together, swap index 2 with 4 (0-based indexing), i.e. element arr[2] = 5 with arr[4] = 3 such that final array will be- arr[] = {2, 1, 3, 6, 5} Example 2: Input : arr[ ] = {2, 7, 9, 5, 8, 7, 4} K = 6 Output : 2 Explanation: To bring elements 2, 5, 4 together, swap index 0 with 2 (0-based indexing) and index 4 with 6 (0-based indexing) such that final array will be- arr[] = {9, 7, 2, 5, 4, 7, 8} Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwap() that takes an array (arr), sizeOfArray (n), an integer K, and return the minimum swaps required. The driver code takes care of the printing. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 ≤ N ≤ 105 1 ≤ Arri, K ≤107 0 hr06in 8 hours class Solution { public: int minSwap(int arr[], int n, int k) { // Complete the function int less = 0; // to keep track of elements less than / = K for(int i = 0; i<n; i++) { if(arr[i] <= k) { less++; } } // now check for windows of size less; int ans = INT_MAX; // for updating to find out the minimum no of swaps int not_req = 0; // first process for the first window for(int i = 0; i<less; i++) { if(arr[i] > k) { not_req++; } } // ans for the first less size window ans = min(ans,not_req); // now process for the rest of the windows using Sliding window Algo for(int i = 0,j = less;j<n;j++,i++) { // first removal if(arr[i] > k) { not_req--; } // then addition if(arr[j] > k) { not_req++; } // now update the ans ans = min(ans,not_req); } return ans; } }; 0 mayankyadav252 weeks ago c++ Solution class Solution{public: int minSwap(int arr[], int n, int k) { // Complet the function int good=0,bad=0; for(int i=0;i<n;i++){ if(arr[i]<=k) good++; } for(int i=0;i<good;i++){ if(arr[i]>k) bad++; } int ans=bad; for(int i=0,j=good;j<n;i++,j++){ if(arr[i]>k) bad--; if(arr[j]>k) bad++; ans=min(ans,bad);} return ans; }}; +1 nanawatiritik083 weeks ago int count=0,countk=0,ans=INT_MAX; for(int i=0;i<n;i++){ if(arr[i]<=k){ count++; } } for(int i=0;i<count;i++){ if(arr[i]>k){ countk++; } } ans=min(ans,countk); int j=0; for(int i=count;i<n;i++){ if(arr[j]>k){ countk--; } if(arr[i]>k){ countk++; } ans=min(ans,countk); j++; } return ans; +2 gardnerchris3 weeks ago Total Time Taken: 0.4/2.2 int minSwap(int a[], int n, int k) { int count=0; for(int i=0; i<n; i++) { if(a[i]<=k) count++; } if(count<2) return 0; int bad=0,curr=0,si=0; for(int i=0; i<count; i++) { if(a[i]>k) bad++; } curr=bad; for(int i=count; i<n; i++) { if(a[si]<=k&&a[i]>k) curr++; else if(a[si]>k&&a[i]<=k) curr--; bad=min(bad,curr); si++; } return bad; } 0 kushwaharajshree233 weeks ago Sliding Window Technique in O(n) time and O(1) space. int minSwap(int arr[], int n, int k) { // Complet the function int count = 0; for(int i=0;i<n;i++) { if(arr[i]<=k) count++; } int bad=0; for(int i=0;i<count;i++) { if(arr[i]>k) bad++; } int ans= bad; for(int i=0, j=count;j<n;i++,j++) { if(arr[i]>k) bad--; if(arr[j]>k) bad++; ans= min(ans, bad); } return ans; } -2 charansaisadla1 month ago def minSwap (arr, n, k) : #Complete the function count=0 for i in range(n): if(arr[i]<=k): count+=1 max1=count bad=0 for i in range(count): if(arr[i]>k): bad=bad+1 ans=bad limit=count for i in range(n-k): bad=0 for j in range(i+1,limit): if(arr[j]>k): bad+=1 ans=min(ans,bad) limit+=1 return ans THE CODE PRODUCES NO OUTPUT 0 charansaisadla This comment was deleted. +1 shivamray1 month ago class Solution{public: int minSwap(int arr[], int n, int k) { int legal=0,count=0,maxcount=0; for(int i=0;i<n;i++) { if(arr[i]<=k) legal++; } for(int i=0;i<legal;i++) { if(arr[i]<=k) count++; } maxcount=count; for(int j=legal;j<n;j++) { if(arr[j]<=k) count++; if(arr[j-legal]<=k) count--; maxcount=max(maxcount,count); } return legal-maxcount; }}; 0 noob_7232 months ago Time Complexity : O(N) Space Complexity : O(1) Using Sliding Window Technique First count all the elements which are in the range Then create a window of count each in the array and find where minimum number of swaps are required. int minSwap(int v[], int n, int k) { int count = 0; for(int i = 0; i < n; i++) { if(v[i] <= k) count++; } if(count == 0) return 0; int i, j, bad, cc; i = 0; j = 0; cc = 0; bad = INT_MAX; while(j < n) { if(v[j] > k) cc++; // If window not reached if(j - i + 1 != count) { j++; } else { bad = min(bad, cc); if(v[i] > k) cc--; i++; j++; } } return bad; } +1 aloksinghbais022 months ago C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- Execution Time :- 0.4 / 2.2 sec int minSwap(int arr[], int n, int k) { // using sliding window technique int fav = 0; for(int i = 0; i < n; i++){ if(arr[i] <= k) fav++; } int nfav = 0; for(int i = 0; i < fav; i++){ if(arr[i] > k) nfav++; } int st = 0,en = fav-1; int minSwaps = INT_MAX; while(en < n){ minSwaps = min(minSwaps,nfav); en++; if(en < n && arr[en] > k) nfav++; if(arr[st] > k) nfav--; st++; } return minSwaps == INT_MAX ? 0 : minSwaps; } 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": 568, "s": 238, "text": "Given an array arr of n positive integers and a number k. One can apply a swap operation on the array any number of times, i.e choose any two index i and j (i < j) and swap arr[i] , arr[j] . Find the minimum number of swaps required to bring all the numbers less than or equal to k together, i.e. make them a contiguous subarray." }, { "code": null, "e": 579, "s": 568, "text": "Example 1:" }, { "code": null, "e": 818, "s": 579, "text": "Input : \narr[ ] = {2, 1, 5, 6, 3} \nK = 3\nOutput : \n1\nExplanation:\nTo bring elements 2, 1, 3 together,\nswap index 2 with 4 (0-based indexing),\ni.e. element arr[2] = 5 with arr[4] = 3\nsuch that final array will be- \narr[] = {2, 1, 3, 6, 5}\n" }, { "code": null, "e": 830, "s": 818, "text": "\nExample 2:" }, { "code": null, "e": 1083, "s": 830, "text": "Input : \narr[ ] = {2, 7, 9, 5, 8, 7, 4} \nK = 6 \nOutput : \n2 \nExplanation: \nTo bring elements 2, 5, 4 together, \nswap index 0 with 2 (0-based indexing)\nand index 4 with 6 (0-based indexing)\nsuch that final array will be- \narr[] = {9, 7, 2, 5, 4, 7, 8}\n" }, { "code": null, "e": 1369, "s": 1085, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwap() that takes an array (arr), sizeOfArray (n), an integer K, and return the minimum swaps required. The driver code takes care of the printing." }, { "code": null, "e": 1433, "s": 1369, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1476, "s": 1433, "text": "\nConstraints:\n1 ≤ N ≤ 105\n1 ≤ Arri, K ≤107" }, { "code": null, "e": 1478, "s": 1476, "text": "0" }, { "code": null, "e": 1493, "s": 1478, "text": "hr06in 8 hours" }, { "code": null, "e": 2746, "s": 1493, "text": "class Solution\n{\n public:\n int minSwap(int arr[], int n, int k) {\n // Complete the function\n int less = 0; // to keep track of elements less than / = K\n \n for(int i = 0; i<n; i++)\n {\n if(arr[i] <= k)\n {\n less++;\n }\n }\n \n // now check for windows of size less;\n \n int ans = INT_MAX; // for updating to find out the minimum no of swaps\n \n int not_req = 0;\n \n // first process for the first window\n for(int i = 0; i<less; i++)\n {\n if(arr[i] > k)\n {\n not_req++;\n }\n }\n \n // ans for the first less size window\n ans = min(ans,not_req);\n \n \n // now process for the rest of the windows using Sliding window Algo\n for(int i = 0,j = less;j<n;j++,i++)\n { \n // first removal \n if(arr[i] > k)\n {\n not_req--;\n }\n \n // then addition\n if(arr[j] > k)\n {\n not_req++;\n }\n \n // now update the ans\n ans = min(ans,not_req);\n }\n \n return ans;\n \n }\n};" }, { "code": null, "e": 2748, "s": 2746, "text": "0" }, { "code": null, "e": 2773, "s": 2748, "text": "mayankyadav252 weeks ago" }, { "code": null, "e": 2786, "s": 2773, "text": "c++ Solution" }, { "code": null, "e": 3242, "s": 2786, "text": "class Solution{public: int minSwap(int arr[], int n, int k) { // Complet the function int good=0,bad=0; for(int i=0;i<n;i++){ if(arr[i]<=k) good++; } for(int i=0;i<good;i++){ if(arr[i]>k) bad++; } int ans=bad; for(int i=0,j=good;j<n;i++,j++){ if(arr[i]>k) bad--; if(arr[j]>k) bad++; ans=min(ans,bad);} return ans; }};" }, { "code": null, "e": 3245, "s": 3242, "text": "+1" }, { "code": null, "e": 3272, "s": 3245, "text": "nanawatiritik083 weeks ago" }, { "code": null, "e": 3790, "s": 3272, "text": "int count=0,countk=0,ans=INT_MAX; for(int i=0;i<n;i++){ if(arr[i]<=k){ count++; } } for(int i=0;i<count;i++){ if(arr[i]>k){ countk++; } } ans=min(ans,countk); int j=0; for(int i=count;i<n;i++){ if(arr[j]>k){ countk--; } if(arr[i]>k){ countk++; } ans=min(ans,countk); j++; } return ans;" }, { "code": null, "e": 3793, "s": 3790, "text": "+2" }, { "code": null, "e": 3817, "s": 3793, "text": "gardnerchris3 weeks ago" }, { "code": null, "e": 3843, "s": 3817, "text": "Total Time Taken: 0.4/2.2" }, { "code": null, "e": 4342, "s": 3843, "text": "int minSwap(int a[], int n, int k) {\n int count=0;\n for(int i=0; i<n; i++) {\n if(a[i]<=k) count++;\n }\n if(count<2) return 0;\n int bad=0,curr=0,si=0;\n for(int i=0; i<count; i++) {\n if(a[i]>k) bad++;\n }\n curr=bad;\n for(int i=count; i<n; i++) {\n if(a[si]<=k&&a[i]>k) curr++;\n else if(a[si]>k&&a[i]<=k) curr--;\n bad=min(bad,curr);\n si++;\n }\n return bad;\n }" }, { "code": null, "e": 4344, "s": 4342, "text": "0" }, { "code": null, "e": 4374, "s": 4344, "text": "kushwaharajshree233 weeks ago" }, { "code": null, "e": 4428, "s": 4374, "text": "Sliding Window Technique in O(n) time and O(1) space." }, { "code": null, "e": 4977, "s": 4428, "text": "int minSwap(int arr[], int n, int k) {\n // Complet the function\n int count = 0;\n for(int i=0;i<n;i++)\n {\n if(arr[i]<=k)\n count++;\n }\n int bad=0;\n for(int i=0;i<count;i++)\n {\n if(arr[i]>k)\n bad++;\n }\n int ans= bad;\n for(int i=0, j=count;j<n;i++,j++)\n {\n if(arr[i]>k)\n bad--;\n \n if(arr[j]>k)\n bad++;\n ans= min(ans, bad);\n }\n return ans;\n }" }, { "code": null, "e": 4980, "s": 4977, "text": "-2" }, { "code": null, "e": 5006, "s": 4980, "text": "charansaisadla1 month ago" }, { "code": null, "e": 5403, "s": 5006, "text": "def minSwap (arr, n, k) : #Complete the function count=0 for i in range(n): if(arr[i]<=k): count+=1 max1=count bad=0 for i in range(count): if(arr[i]>k): bad=bad+1 ans=bad limit=count for i in range(n-k): bad=0 for j in range(i+1,limit): if(arr[j]>k): bad+=1 ans=min(ans,bad) limit+=1 return ans" }, { "code": null, "e": 5431, "s": 5403, "text": "THE CODE PRODUCES NO OUTPUT" }, { "code": null, "e": 5433, "s": 5431, "text": "0" }, { "code": null, "e": 5448, "s": 5433, "text": "charansaisadla" }, { "code": null, "e": 5474, "s": 5448, "text": "This comment was deleted." }, { "code": null, "e": 5477, "s": 5474, "text": "+1" }, { "code": null, "e": 5498, "s": 5477, "text": "shivamray1 month ago" }, { "code": null, "e": 6025, "s": 5498, "text": "class Solution{public: int minSwap(int arr[], int n, int k) { int legal=0,count=0,maxcount=0; for(int i=0;i<n;i++) { if(arr[i]<=k) legal++; } for(int i=0;i<legal;i++) { if(arr[i]<=k) count++; } maxcount=count; for(int j=legal;j<n;j++) { if(arr[j]<=k) count++; if(arr[j-legal]<=k) count--; maxcount=max(maxcount,count); } return legal-maxcount; }};" }, { "code": null, "e": 6027, "s": 6025, "text": "0" }, { "code": null, "e": 6048, "s": 6027, "text": "noob_7232 months ago" }, { "code": null, "e": 6072, "s": 6048, "text": "Time Complexity : O(N) " }, { "code": null, "e": 6096, "s": 6072, "text": "Space Complexity : O(1)" }, { "code": null, "e": 6130, "s": 6098, "text": "Using Sliding Window Technique " }, { "code": null, "e": 6182, "s": 6130, "text": "First count all the elements which are in the range" }, { "code": null, "e": 6283, "s": 6182, "text": "Then create a window of count each in the array and find where minimum number of swaps are required." }, { "code": null, "e": 6798, "s": 6283, "text": "int minSwap(int v[], int n, int k) {\n \tint count = 0;\n \tfor(int i = 0; i < n; i++) {\n \t\tif(v[i] <= k) count++;\n \t}\n \n \tif(count == 0) return 0;\n \n \tint i, j, bad, cc;\n \ti = 0; \n \tj = 0;\n \tcc = 0;\n \tbad = INT_MAX;\n \n \twhile(j < n) {\n \t\tif(v[j] > k) cc++;\n \t\t// If window not reached \n \t\tif(j - i + 1 != count) {\n \t\t\tj++;\n \t\t}\n \t\telse {\n \t\t\tbad = min(bad, cc);\n \t\t\tif(v[i] > k) cc--;\n \t\t\ti++;\n \t\t\tj++;\n \t\t}\n \t}\n \n \treturn bad;\n }" }, { "code": null, "e": 6805, "s": 6802, "text": "+1" }, { "code": null, "e": 6833, "s": 6805, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 6924, "s": 6833, "text": "C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- " }, { "code": null, "e": 6958, "s": 6926, "text": "Execution Time :- 0.4 / 2.2 sec" }, { "code": null, "e": 7543, "s": 6960, "text": "int minSwap(int arr[], int n, int k) { // using sliding window technique int fav = 0; for(int i = 0; i < n; i++){ if(arr[i] <= k) fav++; } int nfav = 0; for(int i = 0; i < fav; i++){ if(arr[i] > k) nfav++; } int st = 0,en = fav-1; int minSwaps = INT_MAX; while(en < n){ minSwaps = min(minSwaps,nfav); en++; if(en < n && arr[en] > k) nfav++; if(arr[st] > k) nfav--; st++; } return minSwaps == INT_MAX ? 0 : minSwaps; }" }, { "code": null, "e": 7689, "s": 7543, "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": 7725, "s": 7689, "text": " Login to access your submissions. " }, { "code": null, "e": 7735, "s": 7725, "text": "\nProblem\n" }, { "code": null, "e": 7745, "s": 7735, "text": "\nContest\n" }, { "code": null, "e": 7808, "s": 7745, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7956, "s": 7808, "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": 8164, "s": 7956, "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": 8270, "s": 8164, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Build a DIY Mini Radar Using Arduino, Python and Streamlit | by M Khorasani | Towards Data Science
For those of us in the business of robotics, specifically the competitive type the likes of sumo-wrestling and RoboCup bots, we know that detecting objects for avoidance or for collision rather cannot possibly be overstated. While more often than not you would inundate your robot with a slew of IR sensors to detect objects all around, it is in fact possible to build your own mini radar to achieve the same effect with far fewer resources. Here I will show you how to use an IR distance measuring sensor coupled with a servo motor to create a DIY mini radar and also how to visualize the results in real-time with a dazzling dashboard. To begin with, we will use an Arduino Uno board to read distance values from the Sharp distance measuring sensor. Subsequently, we will mount the sensor onto the arm of a servo motor using double-sided tape and connect the wiring as shown below. Once you have connected the sensor and servo, proceed with uploading the following program to the Arduino. Please note that depending on which sensor you use and your supply voltage, you may need to recalibrate the sensor. The current sensor can read values between 20–150cm, if necessary recalibrate the motor experimentally by reading the sensor measurements for known distances and using that to derive a new equation. To verify that the Arduino and sensor are working as expected, open the serial monitor (Tools > Serial monitor) to ensure that values are being recorded and sent over the serial port as shown below. Now that the Arduino, sensor, and servo are working and sending values to the serial port, we need to acquire the readings in Python to produce our radar dashboard. To interface our Python script with the Arduino through a serial USB connection, we will need to download and install Pyserial. Go ahead and fire up Anaconda or any other Python IDE of your choice and type the following command: pip install pyserial To produce a graphical user interface where we can visualize and interact with our dashboard we will use Streamlit. This highly versatile web framework allows you to quickly develop and deploy applications to a web server or alternatively run them locally on your browser. And to display a radar plot of the sensor readings we will use Plotly. This is a Python binding for JavaScript’s highly interactive data visualization framework that allows you to render dazzling visuals at your fingertips. Proceed by saving the following source code in your local directory: The above code will initiate a connection to the Arduino and then will continuously read radar position and sensor values from the serial port until prompted to stop. It will also continuously render and update the radar plot. To run the above script type the following commands in Anaconda prompt: cd C:/Users/.../local_directorystreamlit run python_radar.py And there you have it, a DIY mini radar in action! If you want to learn more about data visualization and Python, then feel free to check out the following (affiliate linked) courses:
[ { "code": null, "e": 809, "s": 171, "text": "For those of us in the business of robotics, specifically the competitive type the likes of sumo-wrestling and RoboCup bots, we know that detecting objects for avoidance or for collision rather cannot possibly be overstated. While more often than not you would inundate your robot with a slew of IR sensors to detect objects all around, it is in fact possible to build your own mini radar to achieve the same effect with far fewer resources. Here I will show you how to use an IR distance measuring sensor coupled with a servo motor to create a DIY mini radar and also how to visualize the results in real-time with a dazzling dashboard." }, { "code": null, "e": 1055, "s": 809, "text": "To begin with, we will use an Arduino Uno board to read distance values from the Sharp distance measuring sensor. Subsequently, we will mount the sensor onto the arm of a servo motor using double-sided tape and connect the wiring as shown below." }, { "code": null, "e": 1162, "s": 1055, "text": "Once you have connected the sensor and servo, proceed with uploading the following program to the Arduino." }, { "code": null, "e": 1477, "s": 1162, "text": "Please note that depending on which sensor you use and your supply voltage, you may need to recalibrate the sensor. The current sensor can read values between 20–150cm, if necessary recalibrate the motor experimentally by reading the sensor measurements for known distances and using that to derive a new equation." }, { "code": null, "e": 1676, "s": 1477, "text": "To verify that the Arduino and sensor are working as expected, open the serial monitor (Tools > Serial monitor) to ensure that values are being recorded and sent over the serial port as shown below." }, { "code": null, "e": 2070, "s": 1676, "text": "Now that the Arduino, sensor, and servo are working and sending values to the serial port, we need to acquire the readings in Python to produce our radar dashboard. To interface our Python script with the Arduino through a serial USB connection, we will need to download and install Pyserial. Go ahead and fire up Anaconda or any other Python IDE of your choice and type the following command:" }, { "code": null, "e": 2091, "s": 2070, "text": "pip install pyserial" }, { "code": null, "e": 2588, "s": 2091, "text": "To produce a graphical user interface where we can visualize and interact with our dashboard we will use Streamlit. This highly versatile web framework allows you to quickly develop and deploy applications to a web server or alternatively run them locally on your browser. And to display a radar plot of the sensor readings we will use Plotly. This is a Python binding for JavaScript’s highly interactive data visualization framework that allows you to render dazzling visuals at your fingertips." }, { "code": null, "e": 2657, "s": 2588, "text": "Proceed by saving the following source code in your local directory:" }, { "code": null, "e": 2884, "s": 2657, "text": "The above code will initiate a connection to the Arduino and then will continuously read radar position and sensor values from the serial port until prompted to stop. It will also continuously render and update the radar plot." }, { "code": null, "e": 2956, "s": 2884, "text": "To run the above script type the following commands in Anaconda prompt:" }, { "code": null, "e": 3017, "s": 2956, "text": "cd C:/Users/.../local_directorystreamlit run python_radar.py" }, { "code": null, "e": 3068, "s": 3017, "text": "And there you have it, a DIY mini radar in action!" } ]
BreakIterator getText() method in Java with Examples - GeeksforGeeks
27 Jun, 2021 The getText() method of java.text.BreakIterator class is used to get the text previously set by the setText() method in breakiterator.Syntax: public abstract CharacterIterator getText() Parameter: This method does not accept any parameter.Return Value: This method provides the text scanned previously.Below are the examples to illustrate the getText() method:Example 1: Java // Java program to demonstrate getText() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { // creating and initializing BreakIterator BreakIterator wb = BreakIterator.getWordInstance(); // setting text for BreakIterator wb.setText("Code Geeks"); // getting the text being scanned by // using getText() method StringCharacterIterator text = (StringCharacterIterator)wb.getText(); // display the result System.out.print("Retrieved text is : " + text.first()); for (int i = text.getBeginIndex() - 1; i < text.getEndIndex() - 2; i++) System.out.print(text.next()); }} Retrieved text is : Code Geeks Example 2: Java // Java program to demonstrate getText() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { // creating and initializing BreakIterator BreakIterator wb = BreakIterator.getWordInstance(); // setting text for BreakIterator wb.setText("Geeks For GEeks"); // getting the text being scanned by // using getText() method StringCharacterIterator text = (StringCharacterIterator)wb.getText(); // display the result System.out.print("Retrieved text is : " + text.first()); for (int i = text.getBeginIndex() - 1; i < text.getEndIndex() - 2; i++) System.out.print(text.next()); }} Retrieved text is : Geeks For GEeks Reference: https://docs.oracle.com/javase/9/docs/api/java/text/BreakIterator.html#getText– akshaysingh98088 Java-BreakIterator Java-Functions Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Internal Working of HashMap in Java Checked vs Unchecked Exceptions in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23868, "s": 23840, "text": "\n27 Jun, 2021" }, { "code": null, "e": 24012, "s": 23868, "text": "The getText() method of java.text.BreakIterator class is used to get the text previously set by the setText() method in breakiterator.Syntax: " }, { "code": null, "e": 24056, "s": 24012, "text": "public abstract CharacterIterator getText()" }, { "code": null, "e": 24243, "s": 24056, "text": "Parameter: This method does not accept any parameter.Return Value: This method provides the text scanned previously.Below are the examples to illustrate the getText() method:Example 1: " }, { "code": null, "e": 24248, "s": 24243, "text": "Java" }, { "code": "// Java program to demonstrate getText() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { // creating and initializing BreakIterator BreakIterator wb = BreakIterator.getWordInstance(); // setting text for BreakIterator wb.setText(\"Code Geeks\"); // getting the text being scanned by // using getText() method StringCharacterIterator text = (StringCharacterIterator)wb.getText(); // display the result System.out.print(\"Retrieved text is : \" + text.first()); for (int i = text.getBeginIndex() - 1; i < text.getEndIndex() - 2; i++) System.out.print(text.next()); }}", "e": 25048, "s": 24248, "text": null }, { "code": null, "e": 25079, "s": 25048, "text": "Retrieved text is : Code Geeks" }, { "code": null, "e": 25092, "s": 25079, "text": "Example 2: " }, { "code": null, "e": 25097, "s": 25092, "text": "Java" }, { "code": "// Java program to demonstrate getText() method import java.text.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { // creating and initializing BreakIterator BreakIterator wb = BreakIterator.getWordInstance(); // setting text for BreakIterator wb.setText(\"Geeks For GEeks\"); // getting the text being scanned by // using getText() method StringCharacterIterator text = (StringCharacterIterator)wb.getText(); // display the result System.out.print(\"Retrieved text is : \" + text.first()); for (int i = text.getBeginIndex() - 1; i < text.getEndIndex() - 2; i++) System.out.print(text.next()); }}", "e": 25902, "s": 25097, "text": null }, { "code": null, "e": 25938, "s": 25902, "text": "Retrieved text is : Geeks For GEeks" }, { "code": null, "e": 26030, "s": 25938, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/text/BreakIterator.html#getText– " }, { "code": null, "e": 26047, "s": 26030, "text": "akshaysingh98088" }, { "code": null, "e": 26066, "s": 26047, "text": "Java-BreakIterator" }, { "code": null, "e": 26081, "s": 26066, "text": "Java-Functions" }, { "code": null, "e": 26099, "s": 26081, "text": "Java-text package" }, { "code": null, "e": 26104, "s": 26099, "text": "Java" }, { "code": null, "e": 26109, "s": 26104, "text": "Java" }, { "code": null, "e": 26207, "s": 26109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26216, "s": 26207, "text": "Comments" }, { "code": null, "e": 26229, "s": 26216, "text": "Old Comments" }, { "code": null, "e": 26250, "s": 26229, "text": "Constructors in Java" }, { "code": null, "e": 26265, "s": 26250, "text": "Stream In Java" }, { "code": null, "e": 26284, "s": 26265, "text": "Exceptions in Java" }, { "code": null, "e": 26314, "s": 26284, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26360, "s": 26314, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26386, "s": 26360, "text": "Java Programming Examples" }, { "code": null, "e": 26422, "s": 26386, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 26462, "s": 26422, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 26478, "s": 26462, "text": "Strings in Java" } ]
Check if string follows order of characters defined by a pattern or not | Set 1 - GeeksforGeeks
08 Jun, 2021 Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern.Examples: Input: string = "engineers rock" pattern = "er"; Output: true Explanation: All 'e' in the input string are before all 'r'. Input: string = "engineers rock" pattern = "egr"; Output: false Explanation: There are two 'e' after 'g' in the input string. Input: string = "engineers rock" pattern = "gsr"; Output: false Explanation: There are one 'r' before 's' in the input string. The idea is very simple. For every pair (x, y) of consecutive characters in the pattern string, we find the last occurrence of x and first occurrence of y in the input string. If last occurrence of character x is after first occurrence of character y for any pair, we return false. Checking for every pair of consecutive characters in the pattern string will suffice. For example, if we consider three consecutive characters in the pattern say x, y and z, if (x, y) and (y, z) returns true, that implies (x, z) is also true. Below is the implementation of above idea – C++ Java Python3 C# Javascript // C++ program check if characters in the input string// follows the same order as determined by characters// present in the given pattern#include <iostream>using namespace std; // Function to check if characters in the input string// follows the same order as determined by characters// present in the given patternbool checkPattern(string str, string pattern){ // len stores length of the given pattern int len = pattern.length(); // if length of pattern is more than length of // input string, return false; if (str.length() < len) return false; for (int i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern char x = pattern[i]; char y = pattern[i + 1]; // find index of last occurrence of character x // in the input string size_t last = str.find_last_of(x); // find index of first occurrence of character y // in the input string size_t first = str.find_first_of(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last == string::npos || first == string::npos || last > first) return false; } // return true if string matches the pattern return true;} // Driver codeint main(){ string str = "engineers rock"; string pattern = "gsr"; cout << boolalpha << checkPattern(str, pattern); return 0;} // Java program check if characters in the input string// follows the same order as determined by characters// present in the given pattern class GFG{ // Function to check if characters in the input string // follows the same order as determined by characters // present in the given pattern static boolean checkPattern(String str, String pattern) { // len stores length of the given pattern int len = pattern.length(); // if length of pattern is more than length of // input string, return false; if (str.length() < len) { return false; } for (int i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern char x = pattern.charAt(i); char y = pattern.charAt(i + 1); // find index of last occurrence of character x // in the input string int last = str.lastIndexOf(x); // find index of first occurrence of character y // in the input string int first = str.indexOf(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last == -1 || first == -1 || last > first) { return false; } } // return true if string matches the pattern return true; } // Driver code public static void main(String[] args) { String str = "engineers rock"; String pattern = "gsr"; System.out.println(checkPattern(str, pattern)); }} // This code contributed by Rajput-Ji # Python3 program check if characters in# the input string follows the same order# as determined by characters present in# the given pattern # Function to check if characters in the# input string follows the same order as# determined by characters present# in the given patterndef checkPattern(string, pattern): # len stores length of the given pattern l = len(pattern) # if length of pattern is more than length # of input string, return false; if len(string) < l: return False for i in range(l - 1): # x, y are two adjacent characters in pattern x = pattern[i] y = pattern[i + 1] # find index of last occurrence of # character x in the input string last = string.rindex(x) # find index of first occurrence of # character y in the input string first = string.index(y) # return false if x or y are not present # in the input string OR last occurrence of # x is after the first occurrence of y # in the input string if last == -1 or first == -1 or last > first: return False # return true if # string matches the pattern return True # Driver Codeif __name__ == "__main__": string = "engineers rock" pattern = "gsr" print(checkPattern(string, pattern)) # This code is contributed by# sanjeev2552 // C# program check if characters in the input string// follows the same order as determined by characters// present in the given patternusing System; class GFG{ // Function to check if characters in the input string // follows the same order as determined by characters // present in the given pattern static Boolean checkPattern(String str, String pattern) { // len stores length of the given pattern int len = pattern.Length; // if length of pattern is more than length of // input string, return false; if (str.Length < len) { return false; } for (int i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern char x = pattern[i]; char y = pattern[i+1]; // find index of last occurrence of character x // in the input string int last = str.LastIndexOf(x); // find index of first occurrence of character y // in the input string int first = str.IndexOf(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last == -1 || first == -1 || last > first) { return false; } } // return true if string matches the pattern return true; } // Driver code public static void Main(String[] args) { String str = "engineers rock"; String pattern = "gsr"; Console.WriteLine(checkPattern(str, pattern)); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program check if characters in the input string // follows the same order as determined by characters // present in the given pattern // Function to check if characters in the input string // follows the same order as determined by characters // present in the given pattern function checkPattern(str, pattern) { // len stores length of the given pattern var len = pattern.length; // if length of pattern is more than length of // input string, return false; if (str.length < len) { return false; } for (var i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern var x = pattern[i]; var y = pattern[i + 1]; // find index of last occurrence of character x // in the input string var last = str.lastIndexOf(x); // find index of first occurrence of character y // in the input string var first = str.indexOf(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last === -1 || first === -1 || last > first) { return false; } } // return true if string matches the pattern return true; } // Driver code var str = "engineers rock"; var pattern = "gsr"; document.write(checkPattern(str, pattern)); // This code is contributed by rdtank. </script> Output: false We have discussed two more approaches to solve this problem. Check if string follows order of characters defined by a pattern or not | Set 2 Check if string follows order of characters defined by a pattern or not | Set 3This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji princiraj1992 sanjeev2552 rdtank Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Python program to check if a string is palindrome or not Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography stringstream in C++ and its applications How to Append a Character to a String in C Convert character array to string in C++ Comparing two strings in C++ How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 25027, "s": 24999, "text": "\n08 Jun, 2021" }, { "code": null, "e": 25253, "s": 25027, "text": "Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern.Examples: " }, { "code": null, "e": 25637, "s": 25253, "text": "Input: \nstring = \"engineers rock\"\npattern = \"er\";\nOutput: true\nExplanation: \nAll 'e' in the input string are before all 'r'.\n\nInput: \nstring = \"engineers rock\"\npattern = \"egr\";\nOutput: false\nExplanation: \nThere are two 'e' after 'g' in the input string.\n\nInput: \nstring = \"engineers rock\"\npattern = \"gsr\";\nOutput: false\nExplanation: \nThere are one 'r' before 's' in the input string." }, { "code": null, "e": 26210, "s": 25639, "text": "The idea is very simple. For every pair (x, y) of consecutive characters in the pattern string, we find the last occurrence of x and first occurrence of y in the input string. If last occurrence of character x is after first occurrence of character y for any pair, we return false. Checking for every pair of consecutive characters in the pattern string will suffice. For example, if we consider three consecutive characters in the pattern say x, y and z, if (x, y) and (y, z) returns true, that implies (x, z) is also true. Below is the implementation of above idea – " }, { "code": null, "e": 26214, "s": 26210, "text": "C++" }, { "code": null, "e": 26219, "s": 26214, "text": "Java" }, { "code": null, "e": 26227, "s": 26219, "text": "Python3" }, { "code": null, "e": 26230, "s": 26227, "text": "C#" }, { "code": null, "e": 26241, "s": 26230, "text": "Javascript" }, { "code": "// C++ program check if characters in the input string// follows the same order as determined by characters// present in the given pattern#include <iostream>using namespace std; // Function to check if characters in the input string// follows the same order as determined by characters// present in the given patternbool checkPattern(string str, string pattern){ // len stores length of the given pattern int len = pattern.length(); // if length of pattern is more than length of // input string, return false; if (str.length() < len) return false; for (int i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern char x = pattern[i]; char y = pattern[i + 1]; // find index of last occurrence of character x // in the input string size_t last = str.find_last_of(x); // find index of first occurrence of character y // in the input string size_t first = str.find_first_of(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last == string::npos || first == string::npos || last > first) return false; } // return true if string matches the pattern return true;} // Driver codeint main(){ string str = \"engineers rock\"; string pattern = \"gsr\"; cout << boolalpha << checkPattern(str, pattern); return 0;}", "e": 27778, "s": 26241, "text": null }, { "code": "// Java program check if characters in the input string// follows the same order as determined by characters// present in the given pattern class GFG{ // Function to check if characters in the input string // follows the same order as determined by characters // present in the given pattern static boolean checkPattern(String str, String pattern) { // len stores length of the given pattern int len = pattern.length(); // if length of pattern is more than length of // input string, return false; if (str.length() < len) { return false; } for (int i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern char x = pattern.charAt(i); char y = pattern.charAt(i + 1); // find index of last occurrence of character x // in the input string int last = str.lastIndexOf(x); // find index of first occurrence of character y // in the input string int first = str.indexOf(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last == -1 || first == -1 || last > first) { return false; } } // return true if string matches the pattern return true; } // Driver code public static void main(String[] args) { String str = \"engineers rock\"; String pattern = \"gsr\"; System.out.println(checkPattern(str, pattern)); }} // This code contributed by Rajput-Ji", "e": 29491, "s": 27778, "text": null }, { "code": "# Python3 program check if characters in# the input string follows the same order# as determined by characters present in# the given pattern # Function to check if characters in the# input string follows the same order as# determined by characters present# in the given patterndef checkPattern(string, pattern): # len stores length of the given pattern l = len(pattern) # if length of pattern is more than length # of input string, return false; if len(string) < l: return False for i in range(l - 1): # x, y are two adjacent characters in pattern x = pattern[i] y = pattern[i + 1] # find index of last occurrence of # character x in the input string last = string.rindex(x) # find index of first occurrence of # character y in the input string first = string.index(y) # return false if x or y are not present # in the input string OR last occurrence of # x is after the first occurrence of y # in the input string if last == -1 or first == -1 or last > first: return False # return true if # string matches the pattern return True # Driver Codeif __name__ == \"__main__\": string = \"engineers rock\" pattern = \"gsr\" print(checkPattern(string, pattern)) # This code is contributed by# sanjeev2552", "e": 30845, "s": 29491, "text": null }, { "code": "// C# program check if characters in the input string// follows the same order as determined by characters// present in the given patternusing System; class GFG{ // Function to check if characters in the input string // follows the same order as determined by characters // present in the given pattern static Boolean checkPattern(String str, String pattern) { // len stores length of the given pattern int len = pattern.Length; // if length of pattern is more than length of // input string, return false; if (str.Length < len) { return false; } for (int i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern char x = pattern[i]; char y = pattern[i+1]; // find index of last occurrence of character x // in the input string int last = str.LastIndexOf(x); // find index of first occurrence of character y // in the input string int first = str.IndexOf(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last == -1 || first == -1 || last > first) { return false; } } // return true if string matches the pattern return true; } // Driver code public static void Main(String[] args) { String str = \"engineers rock\"; String pattern = \"gsr\"; Console.WriteLine(checkPattern(str, pattern)); }} /* This code contributed by PrinciRaj1992 */", "e": 32559, "s": 30845, "text": null }, { "code": "<script> // JavaScript program check if characters in the input string // follows the same order as determined by characters // present in the given pattern // Function to check if characters in the input string // follows the same order as determined by characters // present in the given pattern function checkPattern(str, pattern) { // len stores length of the given pattern var len = pattern.length; // if length of pattern is more than length of // input string, return false; if (str.length < len) { return false; } for (var i = 0; i < len - 1; i++) { // x, y are two adjacent characters in pattern var x = pattern[i]; var y = pattern[i + 1]; // find index of last occurrence of character x // in the input string var last = str.lastIndexOf(x); // find index of first occurrence of character y // in the input string var first = str.indexOf(y); // return false if x or y are not present in the // input string OR last occurrence of x is after // the first occurrence of y in the input string if (last === -1 || first === -1 || last > first) { return false; } } // return true if string matches the pattern return true; } // Driver code var str = \"engineers rock\"; var pattern = \"gsr\"; document.write(checkPattern(str, pattern)); // This code is contributed by rdtank. </script>", "e": 34142, "s": 32559, "text": null }, { "code": null, "e": 34152, "s": 34142, "text": "Output: " }, { "code": null, "e": 34158, "s": 34152, "text": "false" }, { "code": null, "e": 34798, "s": 34158, "text": "We have discussed two more approaches to solve this problem. Check if string follows order of characters defined by a pattern or not | Set 2 Check if string follows order of characters defined by a pattern or not | Set 3This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34808, "s": 34798, "text": "Rajput-Ji" }, { "code": null, "e": 34822, "s": 34808, "text": "princiraj1992" }, { "code": null, "e": 34834, "s": 34822, "text": "sanjeev2552" }, { "code": null, "e": 34841, "s": 34834, "text": "rdtank" }, { "code": null, "e": 34849, "s": 34841, "text": "Strings" }, { "code": null, "e": 34857, "s": 34849, "text": "Strings" }, { "code": null, "e": 34955, "s": 34857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34964, "s": 34955, "text": "Comments" }, { "code": null, "e": 34977, "s": 34964, "text": "Old Comments" }, { "code": null, "e": 35030, "s": 34977, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 35066, "s": 35030, "text": "Convert string to char array in C++" }, { "code": null, "e": 35123, "s": 35066, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 35161, "s": 35123, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 35191, "s": 35161, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 35232, "s": 35191, "text": "stringstream in C++ and its applications" }, { "code": null, "e": 35275, "s": 35232, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 35316, "s": 35275, "text": "Convert character array to string in C++" }, { "code": null, "e": 35345, "s": 35316, "text": "Comparing two strings in C++" } ]
How to permanently hide the Navigation Bar in an Android activity using Kotlin?
This example demonstrates how to permanently hide the Navigation Bar in an Android activity using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Hello World!" android:textColor="@android:color/holo_blue_dark" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Build import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity @Suppress("DEPRECATED_IDENTITY_EQUALS", "DEPRECATION") class MainActivity : AppCompatActivity() { private var currentApiVersion: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" currentApiVersion = Build.VERSION.SDK_INT val flags: Int = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY if (currentApiVersion >= Build.VERSION_CODES.KITKAT) { window.decorView.systemUiVisibility = flags val decorView: View = window.decorView decorView.setOnSystemUiVisibilityChangeListener { visibility -> if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0) { decorView.systemUiVisibility = flags } } } } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus) { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1168, "s": 1062, "text": "This example demonstrates how to permanently hide the Navigation Bar in an Android activity using Kotlin." }, { "code": null, "e": 1297, "s": 1168, "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": 1362, "s": 1297, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2360, "s": 1362, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Hello World!\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2415, "s": 2360, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 4049, "s": 2415, "text": "import android.os.Build\nimport android.os.Bundle\nimport android.view.View\nimport androidx.appcompat.app.AppCompatActivity\n@Suppress(\"DEPRECATED_IDENTITY_EQUALS\", \"DEPRECATION\")\nclass MainActivity : AppCompatActivity() {\n private var currentApiVersion: Int = 0\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n currentApiVersion = Build.VERSION.SDK_INT\n val flags: Int = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or\n View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or\n View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or\n View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY\n if (currentApiVersion >= Build.VERSION_CODES.KITKAT) {\n window.decorView.systemUiVisibility = flags\n val decorView: View = window.decorView\n decorView.setOnSystemUiVisibilityChangeListener { visibility ->\n if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0) {\n decorView.systemUiVisibility = flags\n }\n }\n }\n }\n override fun onWindowFocusChanged(hasFocus: Boolean) {\n super.onWindowFocusChanged(hasFocus)\n if (currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus) {\n window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or\n View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or\n View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or\n View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY\n }\n }\n}" }, { "code": null, "e": 4104, "s": 4049, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4778, "s": 4104, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5127, "s": 4778, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Tryit Editor v3.7
CSS Attr Selectors Tryit: The [attribute|="value"] selector
[ { "code": null, "e": 28, "s": 9, "text": "CSS Attr Selectors" } ]
How to create a Dialog in JavaFX?
A Dialog is a graphical element, a window that shows information to the window and receives a response. You can create a dialog by instantiating the javafx.scene.control.Dialog class. The following Example demonstrates the creation of a Dialog. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.layout.HBox; import javafx.stage.Stage; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class DialogExample extends Application { @Override public void start(Stage stage) { //Creating a dialog Dialog<String> dialog = new Dialog<String>(); //Setting the title dialog.setTitle("Dialog"); ButtonType type = new ButtonType("Ok", ButtonData.OK_DONE); //Setting the content of the dialog dialog.setContentText("This is a sample dialog"); //Adding buttons to the dialog pane dialog.getDialogPane().getButtonTypes().add(type); //Setting the label Text txt = new Text("Click the button to show the dialog"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); txt.setFont(font); //Creating a button Button button = new Button("Show Dialog"); //Showing the dialog on clicking the button button.setOnAction(e -> { dialog.showAndWait(); }); //Creating a vbox to hold the button and the label HBox pane = new HBox(15); //Setting the space between the nodes of a HBox pane pane.setPadding(new Insets(50, 150, 50, 60)); pane.getChildren().addAll(txt, button); //Creating a scene object Scene scene = new Scene(new Group(pane), 595, 250, Color.BEIGE); stage.setTitle("Dialog"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1246, "s": 1062, "text": "A Dialog is a graphical element, a window that shows information to the window and receives a response. You can create a dialog by instantiating the javafx.scene.control.Dialog class." }, { "code": null, "e": 1307, "s": 1246, "text": "The following Example demonstrates the creation of a Dialog." }, { "code": null, "e": 3223, "s": 1307, "text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ButtonBar.ButtonData;\nimport javafx.scene.control.ButtonType;\nimport javafx.scene.control.Dialog;\nimport javafx.scene.layout.HBox;\nimport javafx.stage.Stage;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.scene.text.Text;\npublic class DialogExample extends Application {\n @Override\n public void start(Stage stage) {\n //Creating a dialog\n Dialog<String> dialog = new Dialog<String>();\n //Setting the title\n dialog.setTitle(\"Dialog\");\n ButtonType type = new ButtonType(\"Ok\", ButtonData.OK_DONE);\n //Setting the content of the dialog\n dialog.setContentText(\"This is a sample dialog\");\n //Adding buttons to the dialog pane\n dialog.getDialogPane().getButtonTypes().add(type);\n //Setting the label\n Text txt = new Text(\"Click the button to show the dialog\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n txt.setFont(font);\n //Creating a button\n Button button = new Button(\"Show Dialog\");\n //Showing the dialog on clicking the button\n button.setOnAction(e -> {\n dialog.showAndWait();\n });\n //Creating a vbox to hold the button and the label\n HBox pane = new HBox(15);\n //Setting the space between the nodes of a HBox pane\n pane.setPadding(new Insets(50, 150, 50, 60));\n pane.getChildren().addAll(txt, button);\n //Creating a scene object\n Scene scene = new Scene(new Group(pane), 595, 250, Color.BEIGE);\n stage.setTitle(\"Dialog\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Java - String equals() Method
This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. Here is the syntax of this method − public boolean equals(Object anObject) Here is the detail of parameters − anObject − the object to compare this String against. anObject − the object to compare this String against. This method returns true if the String are equal; false otherwise. public class Test { public static void main(String args[]) { String Str1 = new String("This is really not immutable!!"); String Str2 = Str1; String Str3 = new String("This is really not immutable!!"); boolean retVal; retVal = Str1.equals( Str2 ); System.out.println("Returned Value = " + retVal ); retVal = Str1.equals( Str3 ); System.out.println("Returned Value = " + retVal ); } } This will produce the following result − Returned Value = true Returned Value = true 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2581, "s": 2377, "text": "This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object." }, { "code": null, "e": 2617, "s": 2581, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2657, "s": 2617, "text": "public boolean equals(Object anObject)\n" }, { "code": null, "e": 2692, "s": 2657, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2746, "s": 2692, "text": "anObject − the object to compare this String against." }, { "code": null, "e": 2800, "s": 2746, "text": "anObject − the object to compare this String against." }, { "code": null, "e": 2867, "s": 2800, "text": "This method returns true if the String are equal; false otherwise." }, { "code": null, "e": 3307, "s": 2867, "text": "public class Test {\n\n public static void main(String args[]) {\n String Str1 = new String(\"This is really not immutable!!\");\n String Str2 = Str1;\n String Str3 = new String(\"This is really not immutable!!\");\n boolean retVal;\n\n retVal = Str1.equals( Str2 );\n System.out.println(\"Returned Value = \" + retVal );\n\n retVal = Str1.equals( Str3 );\n System.out.println(\"Returned Value = \" + retVal );\n }\n}" }, { "code": null, "e": 3348, "s": 3307, "text": "This will produce the following result −" }, { "code": null, "e": 3393, "s": 3348, "text": "Returned Value = true\nReturned Value = true\n" }, { "code": null, "e": 3426, "s": 3393, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3442, "s": 3426, "text": " Malhar Lathkar" }, { "code": null, "e": 3475, "s": 3442, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3491, "s": 3475, "text": " Malhar Lathkar" }, { "code": null, "e": 3526, "s": 3491, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3540, "s": 3526, "text": " Anadi Sharma" }, { "code": null, "e": 3574, "s": 3540, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3588, "s": 3574, "text": " Tushar Kale" }, { "code": null, "e": 3625, "s": 3588, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3640, "s": 3625, "text": " Monica Mittal" }, { "code": null, "e": 3673, "s": 3640, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3692, "s": 3673, "text": " Arnab Chakraborty" }, { "code": null, "e": 3699, "s": 3692, "text": " Print" }, { "code": null, "e": 3710, "s": 3699, "text": " Add Notes" } ]
Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript - GeeksforGeeks
31 Dec, 2019 The tree view elements are kind of dropdown menu however well organized. This kind of view gives your web site an organized look, to create a tree view architecture of a drop down we can use HTML, CSS, and JavaScript. We will divide the whole procedure into two sections Creating structure and Designing structure. Below both sections are elaborated. Creating Structure: In this section, we will create a basic structure of a Table of Content in Tree View Architecture of elements. HTML code:<!DOCTYPE html><html> <head> <title> Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript </title></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <ul id="tuitorial"> <li><span class="gfg">Tutorials</span> <ol class="cover" type="i"> <li><span class="gfg">Algorithms</span> <ol class="cover" type="a"> <li> <span class="gfg"> Analysis of Algorithms </span> <ol class="cover"> <li>Asymptotic Analysis</li> <li>Worst, Average and Best Cases</li> <li>Asymptotic Notations</li> <li>Little o and little omega notations</li> <li>Lower and Upper Bound Theory</li> <li>Analysis of Loops</li> <li>Solving Recurrences</li> <li>Amortized Analysis</li> <li>What does ‘Space Complexity’ mean?</li> <li>Pseudo-polynomial Algorithms</li> <li>Polynomial Time Approximation Scheme</li> <li>A Time Complexity Question</li> </ol> </li> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <li>Graph Algorithms</li> <li>Pattern Searching</li> <li>Geometric Algorithms</li> <li>Mathematical</li> <li>Randomized Algorithms</li> <li>Greedy Algorithms</li> <li>Dynamic Programming</li> <li>Divide and Conquer</li> <li>Backtracking</li> <li>Branch and Bound</li> <li>All Algorithms</li> </ol> </li> <li> <spna class="gfg"> Data Structures </span> <ol class="cover" type="a"> <li>Arrays</li> <li>Linked List</li> <li>Stack</li> <li>Queue</li> <li>Binary Tree</li> <li>Binary Search Tree</li> <li>Heap</li> <li>Hashing</li> <li>Graph</li> <li>Advanced Data Structure</li> <li>Matrix</li> <li>Strings</li> <li>All Data Structures</li> </ol> </li> <li> <spna class="gfg">Languages</span> <ol class="cover" type="a"> <li>C</li> <li>C++</li> <li>Java</li> <li>Python</li> <li>C#</li> <li>Javascript</li> <li>JQuery</li> <li>SQL</li> <li>PHP</li> <li>Scala</li> <li>Perl</li> <li>Go Language</li> <li>HTML</li> <li>CSS</li> <li>Kotlin</li> </ol> </li> <li> <span class="gfg">Interview Corner</span> <ol class="cover" type="a"> <li>Company Preparation</li> <li>Top Topics</li> <li>Practice Company Questions</li> <li>Interview Experiences</li> <li>Experienced Interviews</li> <li>Internship Interviews</li> <li>Competitive Programming</li> <li>Design Patterns</li> <li>Multiple Choice Quizzes</li> </ol> <li> <spna class="gfg">GATE</span> </li> <li> <spna class="gfg">ISRO CS</span> </li> <li> <spna class="gfg">UGC NET CS</span> </li> <li> <spna class="gfg">CS Subjects</span> </li> <li> < class="gfg">Web Technologies</span> </li> </li> </ol> </li> </ul></body> </html> <!DOCTYPE html><html> <head> <title> Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript </title></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <ul id="tuitorial"> <li><span class="gfg">Tutorials</span> <ol class="cover" type="i"> <li><span class="gfg">Algorithms</span> <ol class="cover" type="a"> <li> <span class="gfg"> Analysis of Algorithms </span> <ol class="cover"> <li>Asymptotic Analysis</li> <li>Worst, Average and Best Cases</li> <li>Asymptotic Notations</li> <li>Little o and little omega notations</li> <li>Lower and Upper Bound Theory</li> <li>Analysis of Loops</li> <li>Solving Recurrences</li> <li>Amortized Analysis</li> <li>What does ‘Space Complexity’ mean?</li> <li>Pseudo-polynomial Algorithms</li> <li>Polynomial Time Approximation Scheme</li> <li>A Time Complexity Question</li> </ol> </li> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <li>Graph Algorithms</li> <li>Pattern Searching</li> <li>Geometric Algorithms</li> <li>Mathematical</li> <li>Randomized Algorithms</li> <li>Greedy Algorithms</li> <li>Dynamic Programming</li> <li>Divide and Conquer</li> <li>Backtracking</li> <li>Branch and Bound</li> <li>All Algorithms</li> </ol> </li> <li> <spna class="gfg"> Data Structures </span> <ol class="cover" type="a"> <li>Arrays</li> <li>Linked List</li> <li>Stack</li> <li>Queue</li> <li>Binary Tree</li> <li>Binary Search Tree</li> <li>Heap</li> <li>Hashing</li> <li>Graph</li> <li>Advanced Data Structure</li> <li>Matrix</li> <li>Strings</li> <li>All Data Structures</li> </ol> </li> <li> <spna class="gfg">Languages</span> <ol class="cover" type="a"> <li>C</li> <li>C++</li> <li>Java</li> <li>Python</li> <li>C#</li> <li>Javascript</li> <li>JQuery</li> <li>SQL</li> <li>PHP</li> <li>Scala</li> <li>Perl</li> <li>Go Language</li> <li>HTML</li> <li>CSS</li> <li>Kotlin</li> </ol> </li> <li> <span class="gfg">Interview Corner</span> <ol class="cover" type="a"> <li>Company Preparation</li> <li>Top Topics</li> <li>Practice Company Questions</li> <li>Interview Experiences</li> <li>Experienced Interviews</li> <li>Internship Interviews</li> <li>Competitive Programming</li> <li>Design Patterns</li> <li>Multiple Choice Quizzes</li> </ol> <li> <spna class="gfg">GATE</span> </li> <li> <spna class="gfg">ISRO CS</span> </li> <li> <spna class="gfg">UGC NET CS</span> </li> <li> <spna class="gfg">CS Subjects</span> </li> <li> < class="gfg">Web Technologies</span> </li> </li> </ol> </li> </ul></body> </html> Designing Structure: In the previous section, we have created the structure of the basic tree view elements. In this section, we will design the structure for the tree view. CSS code:<style> h1 { color: green; } .gfg { cursor: pointer; } .gfg::before { content: "\25B6"; color: black; display: inline-block; margin-right: 8px; } .cover { display: none; } .active { display: block; } ol [type=a] { background-color: yellow; color: purple; }</style> <style> h1 { color: green; } .gfg { cursor: pointer; } .gfg::before { content: "\25B6"; color: black; display: inline-block; margin-right: 8px; } .cover { display: none; } .active { display: block; } ol [type=a] { background-color: yellow; color: purple; }</style> JavaScript code:<script> var toggler = document.getElementsByClassName("gfg"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener("click", function() { this.parentElement.querySelector(".cover") .classList.toggle("active"); this.classList.toggle("gfg-down"); } ); }</script> <script> var toggler = document.getElementsByClassName("gfg"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener("click", function() { this.parentElement.querySelector(".cover") .classList.toggle("active"); this.classList.toggle("gfg-down"); } ); }</script> Combine the HTML, CSS, and JavaScript code: This is the final code after combining the above sections. It will display the Table of Content in Tree View Architecture. <!DOCTYPE html><html> <head> <title> Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript </title> <style> h1 { color: green; } .gfg { cursor: pointer; } .gfg::before { content: "\25B6"; color: black; display: inline-block; margin-right: 8px; } .cover { display: none; } .active { display: block; } ol [type=a] { background-color: yellow; color: purple; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <ul id="tuitorial"> <li><span class="gfg">Tutorials</span> <ol class="cover" type="i"> <li><span class="gfg">Algorithms</span> <ol class="cover" type="a"> <li> <span class="gfg">Analysis of Algorithms</span> <ol class="cover"> <li>Asymptotic Analysis</li> <li>Worst, Average and Best Cases</li> <li>Asymptotic Notations</li> <li>Little o and little omega notations</li> <li>Lower and Upper Bound Theory</li> <li>Analysis of Loops</li> <li>Solving Recurrences</li> <li>Amortized Analysis</li> <li>What does ‘Space Complexity’ mean?</li> <li>Pseudo-polynomial Algorithms</li> <li>Polynomial Time Approximation Scheme</li> <li>A Time Complexity Question</li> </ol> </li> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <li>Graph Algorithms</li> <li>Pattern Searching</li> <li>Geometric Algorithms</li> <li>Mathematical</li> <li>Randomized Algorithms</li> <li>Greedy Algorithms</li> <li>Dynamic Programming</li> <li>Divide and Conquer</li> <li>Backtracking</li> <li>Branch and Bound</li> <li>All Algorithms</li> </ol> </li> <li> <spna class="gfg">Data Structures</span> <ol class="cover" type="a"> <li>Arrays</li> <li>Linked List</li> <li>Stack</li> <li>Queue</li> <li>Binary Tree</li> <li>Binary Search Tree</li> <li>Heap</li> <li>Hashing</li> <li>Graph</li> <li>Advanced Data Structure</li> <li>Matrix</li> <li>Strings</li> <li>All Data Structures</li> </ol> </li> <li> <spna class="gfg">Languages</span> <ol class="cover" type="a"> <li>C</li> <li>C++</li> <li>Java</li> <li>Python</li> <li>C#</li> <li>Javascript</li> <li>JQuery</li> <li>SQL</li> <li>PHP</li> <li>Scala</li> <li>Perl</li> <li>Go Language</li> <li>HTML</li> <li>CSS</li> <li>Kotlin</li> </ol> </li> <li> <span class="gfg">Interview Corner</span> <ol class="cover" type="a"> <li>Company Preparation</li> <li>Top Topics</li> <li>Practice Company Questions</li> <li>Interview Experiences</li> <li>Experienced Interviews</li> <li>Internship Interviews</li> <li>Competitive Programming</li> <li>Design Patterns</li> <li>Multiple Choice Quizzes</li> </ol> <li><spna class="gfg">GATE</span></li> <li><spna class="gfg">ISRO CS</span></li> <li><spna class="gfg">UGC NET CS</span></li> <li><spna class="gfg">CS Subjects</span></li> <li><spna class="gfg">Web Technologies</span></li> </li> </ol> </li> </ul> <script> var toggler = document.getElementsByClassName("gfg"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener("click", function() { this.parentElement.querySelector(".cover") .classList.toggle("active"); this.classList.toggle("gfg-down"); } ); } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS CSS | :not(:last-child):after Selector Making a div vertically scrollable using CSS How to set fixed width for <td> in a table ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25321, "s": 25293, "text": "\n31 Dec, 2019" }, { "code": null, "e": 25672, "s": 25321, "text": "The tree view elements are kind of dropdown menu however well organized. This kind of view gives your web site an organized look, to create a tree view architecture of a drop down we can use HTML, CSS, and JavaScript. We will divide the whole procedure into two sections Creating structure and Designing structure. Below both sections are elaborated." }, { "code": null, "e": 25803, "s": 25672, "text": "Creating Structure: In this section, we will create a basic structure of a Table of Content in Tree View Architecture of elements." }, { "code": null, "e": 30759, "s": 25803, "text": "HTML code:<!DOCTYPE html><html> <head> <title> Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript </title></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <ul id=\"tuitorial\"> <li><span class=\"gfg\">Tutorials</span> <ol class=\"cover\" type=\"i\"> <li><span class=\"gfg\">Algorithms</span> <ol class=\"cover\" type=\"a\"> <li> <span class=\"gfg\"> Analysis of Algorithms </span> <ol class=\"cover\"> <li>Asymptotic Analysis</li> <li>Worst, Average and Best Cases</li> <li>Asymptotic Notations</li> <li>Little o and little omega notations</li> <li>Lower and Upper Bound Theory</li> <li>Analysis of Loops</li> <li>Solving Recurrences</li> <li>Amortized Analysis</li> <li>What does ‘Space Complexity’ mean?</li> <li>Pseudo-polynomial Algorithms</li> <li>Polynomial Time Approximation Scheme</li> <li>A Time Complexity Question</li> </ol> </li> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <li>Graph Algorithms</li> <li>Pattern Searching</li> <li>Geometric Algorithms</li> <li>Mathematical</li> <li>Randomized Algorithms</li> <li>Greedy Algorithms</li> <li>Dynamic Programming</li> <li>Divide and Conquer</li> <li>Backtracking</li> <li>Branch and Bound</li> <li>All Algorithms</li> </ol> </li> <li> <spna class=\"gfg\"> Data Structures </span> <ol class=\"cover\" type=\"a\"> <li>Arrays</li> <li>Linked List</li> <li>Stack</li> <li>Queue</li> <li>Binary Tree</li> <li>Binary Search Tree</li> <li>Heap</li> <li>Hashing</li> <li>Graph</li> <li>Advanced Data Structure</li> <li>Matrix</li> <li>Strings</li> <li>All Data Structures</li> </ol> </li> <li> <spna class=\"gfg\">Languages</span> <ol class=\"cover\" type=\"a\"> <li>C</li> <li>C++</li> <li>Java</li> <li>Python</li> <li>C#</li> <li>Javascript</li> <li>JQuery</li> <li>SQL</li> <li>PHP</li> <li>Scala</li> <li>Perl</li> <li>Go Language</li> <li>HTML</li> <li>CSS</li> <li>Kotlin</li> </ol> </li> <li> <span class=\"gfg\">Interview Corner</span> <ol class=\"cover\" type=\"a\"> <li>Company Preparation</li> <li>Top Topics</li> <li>Practice Company Questions</li> <li>Interview Experiences</li> <li>Experienced Interviews</li> <li>Internship Interviews</li> <li>Competitive Programming</li> <li>Design Patterns</li> <li>Multiple Choice Quizzes</li> </ol> <li> <spna class=\"gfg\">GATE</span> </li> <li> <spna class=\"gfg\">ISRO CS</span> </li> <li> <spna class=\"gfg\">UGC NET CS</span> </li> <li> <spna class=\"gfg\">CS Subjects</span> </li> <li> < class=\"gfg\">Web Technologies</span> </li> </li> </ol> </li> </ul></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript </title></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <ul id=\"tuitorial\"> <li><span class=\"gfg\">Tutorials</span> <ol class=\"cover\" type=\"i\"> <li><span class=\"gfg\">Algorithms</span> <ol class=\"cover\" type=\"a\"> <li> <span class=\"gfg\"> Analysis of Algorithms </span> <ol class=\"cover\"> <li>Asymptotic Analysis</li> <li>Worst, Average and Best Cases</li> <li>Asymptotic Notations</li> <li>Little o and little omega notations</li> <li>Lower and Upper Bound Theory</li> <li>Analysis of Loops</li> <li>Solving Recurrences</li> <li>Amortized Analysis</li> <li>What does ‘Space Complexity’ mean?</li> <li>Pseudo-polynomial Algorithms</li> <li>Polynomial Time Approximation Scheme</li> <li>A Time Complexity Question</li> </ol> </li> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <li>Graph Algorithms</li> <li>Pattern Searching</li> <li>Geometric Algorithms</li> <li>Mathematical</li> <li>Randomized Algorithms</li> <li>Greedy Algorithms</li> <li>Dynamic Programming</li> <li>Divide and Conquer</li> <li>Backtracking</li> <li>Branch and Bound</li> <li>All Algorithms</li> </ol> </li> <li> <spna class=\"gfg\"> Data Structures </span> <ol class=\"cover\" type=\"a\"> <li>Arrays</li> <li>Linked List</li> <li>Stack</li> <li>Queue</li> <li>Binary Tree</li> <li>Binary Search Tree</li> <li>Heap</li> <li>Hashing</li> <li>Graph</li> <li>Advanced Data Structure</li> <li>Matrix</li> <li>Strings</li> <li>All Data Structures</li> </ol> </li> <li> <spna class=\"gfg\">Languages</span> <ol class=\"cover\" type=\"a\"> <li>C</li> <li>C++</li> <li>Java</li> <li>Python</li> <li>C#</li> <li>Javascript</li> <li>JQuery</li> <li>SQL</li> <li>PHP</li> <li>Scala</li> <li>Perl</li> <li>Go Language</li> <li>HTML</li> <li>CSS</li> <li>Kotlin</li> </ol> </li> <li> <span class=\"gfg\">Interview Corner</span> <ol class=\"cover\" type=\"a\"> <li>Company Preparation</li> <li>Top Topics</li> <li>Practice Company Questions</li> <li>Interview Experiences</li> <li>Experienced Interviews</li> <li>Internship Interviews</li> <li>Competitive Programming</li> <li>Design Patterns</li> <li>Multiple Choice Quizzes</li> </ol> <li> <spna class=\"gfg\">GATE</span> </li> <li> <spna class=\"gfg\">ISRO CS</span> </li> <li> <spna class=\"gfg\">UGC NET CS</span> </li> <li> <spna class=\"gfg\">CS Subjects</span> </li> <li> < class=\"gfg\">Web Technologies</span> </li> </li> </ol> </li> </ul></body> </html>", "e": 35705, "s": 30759, "text": null }, { "code": null, "e": 35879, "s": 35705, "text": "Designing Structure: In the previous section, we have created the structure of the basic tree view elements. In this section, we will design the structure for the tree view." }, { "code": null, "e": 36294, "s": 35879, "text": "CSS code:<style> h1 { color: green; } .gfg { cursor: pointer; } .gfg::before { content: \"\\25B6\"; color: black; display: inline-block; margin-right: 8px; } .cover { display: none; } .active { display: block; } ol [type=a] { background-color: yellow; color: purple; }</style>" }, { "code": "<style> h1 { color: green; } .gfg { cursor: pointer; } .gfg::before { content: \"\\25B6\"; color: black; display: inline-block; margin-right: 8px; } .cover { display: none; } .active { display: block; } ol [type=a] { background-color: yellow; color: purple; }</style>", "e": 36700, "s": 36294, "text": null }, { "code": null, "e": 37098, "s": 36700, "text": "JavaScript code:<script> var toggler = document.getElementsByClassName(\"gfg\"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener(\"click\", function() { this.parentElement.querySelector(\".cover\") .classList.toggle(\"active\"); this.classList.toggle(\"gfg-down\"); } ); }</script>" }, { "code": "<script> var toggler = document.getElementsByClassName(\"gfg\"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener(\"click\", function() { this.parentElement.querySelector(\".cover\") .classList.toggle(\"active\"); this.classList.toggle(\"gfg-down\"); } ); }</script>", "e": 37480, "s": 37098, "text": null }, { "code": null, "e": 37647, "s": 37480, "text": "Combine the HTML, CSS, and JavaScript code: This is the final code after combining the above sections. It will display the Table of Content in Tree View Architecture." }, { "code": "<!DOCTYPE html><html> <head> <title> Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript </title> <style> h1 { color: green; } .gfg { cursor: pointer; } .gfg::before { content: \"\\25B6\"; color: black; display: inline-block; margin-right: 8px; } .cover { display: none; } .active { display: block; } ol [type=a] { background-color: yellow; color: purple; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> <br> <ul id=\"tuitorial\"> <li><span class=\"gfg\">Tutorials</span> <ol class=\"cover\" type=\"i\"> <li><span class=\"gfg\">Algorithms</span> <ol class=\"cover\" type=\"a\"> <li> <span class=\"gfg\">Analysis of Algorithms</span> <ol class=\"cover\"> <li>Asymptotic Analysis</li> <li>Worst, Average and Best Cases</li> <li>Asymptotic Notations</li> <li>Little o and little omega notations</li> <li>Lower and Upper Bound Theory</li> <li>Analysis of Loops</li> <li>Solving Recurrences</li> <li>Amortized Analysis</li> <li>What does ‘Space Complexity’ mean?</li> <li>Pseudo-polynomial Algorithms</li> <li>Polynomial Time Approximation Scheme</li> <li>A Time Complexity Question</li> </ol> </li> <li>Searching Algorithms</li> <li>Sorting Algorithms</li> <li>Graph Algorithms</li> <li>Pattern Searching</li> <li>Geometric Algorithms</li> <li>Mathematical</li> <li>Randomized Algorithms</li> <li>Greedy Algorithms</li> <li>Dynamic Programming</li> <li>Divide and Conquer</li> <li>Backtracking</li> <li>Branch and Bound</li> <li>All Algorithms</li> </ol> </li> <li> <spna class=\"gfg\">Data Structures</span> <ol class=\"cover\" type=\"a\"> <li>Arrays</li> <li>Linked List</li> <li>Stack</li> <li>Queue</li> <li>Binary Tree</li> <li>Binary Search Tree</li> <li>Heap</li> <li>Hashing</li> <li>Graph</li> <li>Advanced Data Structure</li> <li>Matrix</li> <li>Strings</li> <li>All Data Structures</li> </ol> </li> <li> <spna class=\"gfg\">Languages</span> <ol class=\"cover\" type=\"a\"> <li>C</li> <li>C++</li> <li>Java</li> <li>Python</li> <li>C#</li> <li>Javascript</li> <li>JQuery</li> <li>SQL</li> <li>PHP</li> <li>Scala</li> <li>Perl</li> <li>Go Language</li> <li>HTML</li> <li>CSS</li> <li>Kotlin</li> </ol> </li> <li> <span class=\"gfg\">Interview Corner</span> <ol class=\"cover\" type=\"a\"> <li>Company Preparation</li> <li>Top Topics</li> <li>Practice Company Questions</li> <li>Interview Experiences</li> <li>Experienced Interviews</li> <li>Internship Interviews</li> <li>Competitive Programming</li> <li>Design Patterns</li> <li>Multiple Choice Quizzes</li> </ol> <li><spna class=\"gfg\">GATE</span></li> <li><spna class=\"gfg\">ISRO CS</span></li> <li><spna class=\"gfg\">UGC NET CS</span></li> <li><spna class=\"gfg\">CS Subjects</span></li> <li><spna class=\"gfg\">Web Technologies</span></li> </li> </ol> </li> </ul> <script> var toggler = document.getElementsByClassName(\"gfg\"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener(\"click\", function() { this.parentElement.querySelector(\".cover\") .classList.toggle(\"active\"); this.classList.toggle(\"gfg-down\"); } ); } </script></body> </html>", "e": 43268, "s": 37647, "text": null }, { "code": null, "e": 43276, "s": 43268, "text": "Output:" }, { "code": null, "e": 43285, "s": 43276, "text": "CSS-Misc" }, { "code": null, "e": 43295, "s": 43285, "text": "HTML-Misc" }, { "code": null, "e": 43311, "s": 43295, "text": "JavaScript-Misc" }, { "code": null, "e": 43315, "s": 43311, "text": "CSS" }, { "code": null, "e": 43320, "s": 43315, "text": "HTML" }, { "code": null, "e": 43331, "s": 43320, "text": "JavaScript" }, { "code": null, "e": 43348, "s": 43331, "text": "Web Technologies" }, { "code": null, "e": 43375, "s": 43348, "text": "Web technologies Questions" }, { "code": null, "e": 43380, "s": 43375, "text": "HTML" }, { "code": null, "e": 43478, "s": 43380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43487, "s": 43478, "text": "Comments" }, { "code": null, "e": 43500, "s": 43487, "text": "Old Comments" }, { "code": null, "e": 43541, "s": 43500, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 43578, "s": 43541, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 43617, "s": 43578, "text": "CSS | :not(:last-child):after Selector" }, { "code": null, "e": 43662, "s": 43617, "text": "Making a div vertically scrollable using CSS" }, { "code": null, "e": 43707, "s": 43662, "text": "How to set fixed width for <td> in a table ?" }, { "code": null, "e": 43767, "s": 43707, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 43828, "s": 43767, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 43881, "s": 43828, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 43931, "s": 43881, "text": "How to Insert Form Data into Database using PHP ?" } ]
Check if a number ends with another number or not - GeeksforGeeks
22 Nov, 2021 Given two numbers A and B where (A > B), the task is to check if B is a suffix of A or not. Print “Yes” if it is a suffix Else print “No”.Examples: Input: A = 12345, B = 45 Output: YesInput: A = 12345, B = 123 Output: No Method 1: Convert the given numbers A and B to strings str1 and str2 respectively.Traverse both the strings from the end of the strings.While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”.Else print “Yes”. Convert the given numbers A and B to strings str1 and str2 respectively. Traverse both the strings from the end of the strings. While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”. Else print “Yes”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Function to check if B is a// suffix of A or notbool checkSuffix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); // Find the lengths of strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base Case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for (int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]) { return false; } } // Return true return true;} // Driver Codeint main(){ // Given numbers int A = 12345, B = 45; // Function Call bool result = checkSuffix(A, B); // If B is a suffix of A, then // print "Yes" if (result) { cout << "Yes"; } else { cout << "No"; } return 0;} // Java program for the above approachclass GFG{ // Function to check if B // is a suffix of A or notpublic static boolean checkSuffix(int A, int B){ // Convert numbers into strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); // Find the lengths of strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1.charAt(n1 - i - 1) != s2.charAt(n2 - i - 1)) { return false; } } // Return true return true;} // Driver codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 45; // Function Call boolean result = checkSuffix(A, B); // If B is a suffix of A, // then print "Yes" if (result) { System.out.print("Yes"); } else { System.out.println("No"); }}} // This code is contributed by divyeshrabadiya07 # Python3 program for the above approach # Function to check if B is a# suffix of A or notdef checkSuffix(A, B): # Convert numbers into strings s1 = str(A); s2 = str(B); # Find the lengths of strings # s1 and s2 n1 = len(s1) n2 = len(s2) # Base Case if (n1 < n2): return False; # Traverse the strings s1 & s2 for i in range(n2): # If at any index characters # are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]): return False; # Return true return True; # Driver Code # Given numbersA = 12345B = 45; # Function Callresult = checkSuffix(A, B); # If B is a suffix of A, then# print "Yes"if (result): print("Yes")else: print("No") # This code is contributed by grand_master // C# program for the above approachusing System;class GFG{ // Function to check if B// is a suffix of A or notpublic static bool checkSuffix(int A, int B){ // Convert numbers into strings string s1 = A.ToString(); string s2 = B.ToString(); // Find the lengths of strings // s1 and s2 int n1 = s1.Length; int n2 = s2.Length; // Base case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]) { return false; } } // Return true return true;} // Driver codepublic static void Main(string[] args){ // Given numbers int A = 12345, B = 45; // Function Call bool result = checkSuffix(A, B); // If B is a suffix of A, // then print "Yes" if (result) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by rutvik_56 <script> // javascript program for the above approach // Function to check if B// is a suffix of A or not function checkSuffix( A, B){ // Convert numbers into strings var s1 = A.toString(); var s2 = B.toString(); // Find the lengths of strings // s1 and s2 var n1 = s1.length; var n2 = s2.length; // Base case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for(var i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]) { return false; } } // Return true return true;} // Driver code // Given numbers var A = 12345, B = 45; // Function Call var result = checkSuffix(A, B); // If B is a suffix of A, // then print "Yes" if (result) { document.write("Yes"); } else { document.write("No"); } </script> Yes Method 2: Using inbuilt function std::boost::algorithm::ends_with() which is included in Boost Library of C++ which is used to check whether any string contains suffix of another string or not.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function to check if B is a// suffix of A or notvoid checkSuffix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); bool result; // Check if s2 is a suffix of s1 // or not using ends_with() function result = boost::algorithm::ends_with(s1, s2); // If result is true, print "Yes" if (result) { cout << "Yes"; } else { cout << "No"; }} // Driver Codeint main(){ // Given numbers int A = 12345, B = 45; // Function Call checkSuffix(A, B); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to check if B is a// suffix of A or notstatic void checkSuffix(int A, int B){ // Convert numbers into Strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); boolean result; // Check if s2 is a suffix of s1 // or not result = s1.endsWith(s2); // If result is true, print "Yes" if (result) { System.out.print("Yes"); } else { System.out.print("No"); }} // Driver Codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 45; // Function Call checkSuffix(A, B);}} // This code is contributed by 29AjayKumar # Python3 program for the above approach # Function to check if B is# a suffix of A or notdef checkSuffix(A, B): # Convert numbers into strings s1 = str(A) s2 = str(B) # Check if s2 is a suffix of s1 # or not result = s1.endswith(s2) # If result is true print "Yes" if (result): print("Yes") else: print("No") # Driver codeif __name__ == '__main__': # Given numbers A = 12345 B = 45 # Function call checkSuffix(A, B) # This code is contributed by himanshu77 // C# program for the above approachusing System; class GFG{ // Function to check if B is a// suffix of A or notstatic void checkSuffix(int A, int B){ // Convert numbers into Strings String s1 = String.Join("", A); String s2 = String.Join("", B); bool result; // Check if s2 is a suffix of s1 // or not result = s1.EndsWith(s2); // If result is true, print "Yes" if (result) { Console.Write("Yes"); } else { Console.Write("No"); }} // Driver Codepublic static void Main(String[] args){ // Given numbers int A = 12345, B = 45; // Function Call checkSuffix(A, B);}} // This code is contributed by 29AjayKumar <script> // JavaScript program for the above approach // Function to check if B is a// suffix of A or notfunction checkSuffix( A, B){ // Convert numbers into Strings let s1 = A.toString(); let s2 = B.toString(); let result; // Check if s2 is a suffix of s1 // or not result = s1.endsWith(s2); // If result is true, print "Yes" if (result) { document.write("Yes"); } else { document.write("No"); }} // Driver Code // Given numbers let A = 12345, B = 45; // Function Call checkSuffix(A, B); </script> Yes Method 3: Subtract B from A.Find the number of digits in B(say X) by using the Method 3 discussed in this article.Check whether A ends with atleast X number zeros or not. If yes then print “Yes”.Else print “No”. Subtract B from A. Find the number of digits in B(say X) by using the Method 3 discussed in this article. Check whether A ends with atleast X number zeros or not. If yes then print “Yes”. Else print “No”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function to check if B is a// suffix of A or notbool checkSuffix(int A, int B){ // Find the number of digit in B int digit_B = log10(B) + 1; // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % int(pow(10, digit_B)));} // Driver Codeint main(){ // Given numbers int A = 12345, B = 45; // Function Call bool result = checkSuffix(A, B); // If B is a suffix of A, then // print "Yes" if (!result) { cout << "Yes"; } else { cout << "No"; } return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to check if B// is a suffix of A or notstatic boolean checkSuffix(int A, int B){ // Find the number of digit in B int digit_B = (int) (Math.log10(B) + 1); // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % (int)(Math.pow(10, digit_B)) > 0);} // Driver codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 45; // Function call boolean result = checkSuffix(A, B); // If B is a suffix of A, // then print "Yes" if (!result) { System.out.print("Yes"); } else { System.out.print("No"); }}} // This code is contributed by 29AjayKumar # Python3 program for the above approachimport math # Function to check if B is a# suffix of A or notdef checkSuffix(A, B): # Find the number of digit in B digit_B = int(math.log10(B)) + 1; # Subtract B from A A -= B; # Returns true, # if B is a suffix of A return (A % int(math.pow(10, digit_B))); # Driver Code # Given numbersA = 12345; B = 45; # Function Callresult = checkSuffix(A, B); # If B is a suffix of A, then# print "Yes"if (result == 0): print("Yes"); else: print("No"); # This code is contributed by Nidhi_biet // C# program for the above approachusing System;class GFG{ // Function to check if B// is a suffix of A or notstatic bool checkSuffix(int A, int B){ // Find the number of digit in B int digit_B = (int)(Math.Log10(B) + 1); // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % (int)(Math.Pow(10, digit_B)) > 0);} // Driver codepublic static void Main(){ // Given numbers int A = 12345, B = 45; // Function call bool result = checkSuffix(A, B); // If B is a suffix of A, // then print "Yes" if (!result) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by Code_Mech <script> // JavaScript program for the above approach // Function to check if B // is a suffix of A or not function checkSuffix(A, B) { // Find the number of digit in B let digit_B = parseInt(Math.log10(B) + 1, 10); // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % (Math.pow(10, digit_B)) > 0); } // Given numbers let A = 12345, B = 45; // Function call let result = checkSuffix(A, B); // If B is a suffix of A, // then print "Yes" if (!result) { document.write("Yes"); } else { document.write("No"); } </script> Yes Time Complexity: O(1)Auxiliary Space: O(1) divyeshrabadiya07 rutvik_56 29AjayKumar Code_Mech nidhi_biet grand_master Akanksha_Rai himanshu77 bunnyram19 susmitakundugoaldanga mukesh07 subham348 Kirti_Mangal number-digits Numbers Mathematical Strings Strings Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find GCD or HCF of two numbers Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Python program to check if a string is palindrome or not Different methods to reverse a string in C/C++
[ { "code": null, "e": 25094, "s": 25066, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25244, "s": 25094, "text": "Given two numbers A and B where (A > B), the task is to check if B is a suffix of A or not. Print “Yes” if it is a suffix Else print “No”.Examples: " }, { "code": null, "e": 25319, "s": 25244, "text": "Input: A = 12345, B = 45 Output: YesInput: A = 12345, B = 123 Output: No " }, { "code": null, "e": 25333, "s": 25321, "text": "Method 1: " }, { "code": null, "e": 25581, "s": 25333, "text": "Convert the given numbers A and B to strings str1 and str2 respectively.Traverse both the strings from the end of the strings.While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”.Else print “Yes”." }, { "code": null, "e": 25654, "s": 25581, "text": "Convert the given numbers A and B to strings str1 and str2 respectively." }, { "code": null, "e": 25709, "s": 25654, "text": "Traverse both the strings from the end of the strings." }, { "code": null, "e": 25814, "s": 25709, "text": "While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”." }, { "code": null, "e": 25832, "s": 25814, "text": "Else print “Yes”." }, { "code": null, "e": 25884, "s": 25832, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25888, "s": 25884, "text": "C++" }, { "code": null, "e": 25893, "s": 25888, "text": "Java" }, { "code": null, "e": 25901, "s": 25893, "text": "Python3" }, { "code": null, "e": 25904, "s": 25901, "text": "C#" }, { "code": null, "e": 25915, "s": 25904, "text": "Javascript" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Function to check if B is a// suffix of A or notbool checkSuffix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); // Find the lengths of strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base Case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for (int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]) { return false; } } // Return true return true;} // Driver Codeint main(){ // Given numbers int A = 12345, B = 45; // Function Call bool result = checkSuffix(A, B); // If B is a suffix of A, then // print \"Yes\" if (result) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}", "e": 26894, "s": 25915, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to check if B // is a suffix of A or notpublic static boolean checkSuffix(int A, int B){ // Convert numbers into strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); // Find the lengths of strings // s1 and s2 int n1 = s1.length(); int n2 = s2.length(); // Base case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1.charAt(n1 - i - 1) != s2.charAt(n2 - i - 1)) { return false; } } // Return true return true;} // Driver codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 45; // Function Call boolean result = checkSuffix(A, B); // If B is a suffix of A, // then print \"Yes\" if (result) { System.out.print(\"Yes\"); } else { System.out.println(\"No\"); }}} // This code is contributed by divyeshrabadiya07", "e": 28067, "s": 26894, "text": null }, { "code": "# Python3 program for the above approach # Function to check if B is a# suffix of A or notdef checkSuffix(A, B): # Convert numbers into strings s1 = str(A); s2 = str(B); # Find the lengths of strings # s1 and s2 n1 = len(s1) n2 = len(s2) # Base Case if (n1 < n2): return False; # Traverse the strings s1 & s2 for i in range(n2): # If at any index characters # are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]): return False; # Return true return True; # Driver Code # Given numbersA = 12345B = 45; # Function Callresult = checkSuffix(A, B); # If B is a suffix of A, then# print \"Yes\"if (result): print(\"Yes\")else: print(\"No\") # This code is contributed by grand_master ", "e": 28868, "s": 28067, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to check if B// is a suffix of A or notpublic static bool checkSuffix(int A, int B){ // Convert numbers into strings string s1 = A.ToString(); string s2 = B.ToString(); // Find the lengths of strings // s1 and s2 int n1 = s1.Length; int n2 = s2.Length; // Base case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for(int i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]) { return false; } } // Return true return true;} // Driver codepublic static void Main(string[] args){ // Given numbers int A = 12345, B = 45; // Function Call bool result = checkSuffix(A, B); // If B is a suffix of A, // then print \"Yes\" if (result) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by rutvik_56", "e": 29993, "s": 28868, "text": null }, { "code": "<script> // javascript program for the above approach // Function to check if B// is a suffix of A or not function checkSuffix( A, B){ // Convert numbers into strings var s1 = A.toString(); var s2 = B.toString(); // Find the lengths of strings // s1 and s2 var n1 = s1.length; var n2 = s2.length; // Base case if (n1 < n2) { return false; } // Traverse the strings s1 & s2 for(var i = 0; i < n2; i++) { // If at any index characters // are unequals then return false if (s1[n1 - i - 1] != s2[n2 - i - 1]) { return false; } } // Return true return true;} // Driver code // Given numbers var A = 12345, B = 45; // Function Call var result = checkSuffix(A, B); // If B is a suffix of A, // then print \"Yes\" if (result) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script> ", "e": 31030, "s": 29993, "text": null }, { "code": null, "e": 31034, "s": 31030, "text": "Yes" }, { "code": null, "e": 31281, "s": 31036, "text": "Method 2: Using inbuilt function std::boost::algorithm::ends_with() which is included in Boost Library of C++ which is used to check whether any string contains suffix of another string or not.Below is the implementation of the above approach: " }, { "code": null, "e": 31285, "s": 31281, "text": "C++" }, { "code": null, "e": 31290, "s": 31285, "text": "Java" }, { "code": null, "e": 31298, "s": 31290, "text": "Python3" }, { "code": null, "e": 31301, "s": 31298, "text": "C#" }, { "code": null, "e": 31312, "s": 31301, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function to check if B is a// suffix of A or notvoid checkSuffix(int A, int B){ // Convert numbers into strings string s1 = to_string(A); string s2 = to_string(B); bool result; // Check if s2 is a suffix of s1 // or not using ends_with() function result = boost::algorithm::ends_with(s1, s2); // If result is true, print \"Yes\" if (result) { cout << \"Yes\"; } else { cout << \"No\"; }} // Driver Codeint main(){ // Given numbers int A = 12345, B = 45; // Function Call checkSuffix(A, B); return 0;}", "e": 32039, "s": 31312, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to check if B is a// suffix of A or notstatic void checkSuffix(int A, int B){ // Convert numbers into Strings String s1 = String.valueOf(A); String s2 = String.valueOf(B); boolean result; // Check if s2 is a suffix of s1 // or not result = s1.endsWith(s2); // If result is true, print \"Yes\" if (result) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }} // Driver Codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 45; // Function Call checkSuffix(A, B);}} // This code is contributed by 29AjayKumar", "e": 32734, "s": 32039, "text": null }, { "code": "# Python3 program for the above approach # Function to check if B is# a suffix of A or notdef checkSuffix(A, B): # Convert numbers into strings s1 = str(A) s2 = str(B) # Check if s2 is a suffix of s1 # or not result = s1.endswith(s2) # If result is true print \"Yes\" if (result): print(\"Yes\") else: print(\"No\") # Driver codeif __name__ == '__main__': # Given numbers A = 12345 B = 45 # Function call checkSuffix(A, B) # This code is contributed by himanshu77", "e": 33253, "s": 32734, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to check if B is a// suffix of A or notstatic void checkSuffix(int A, int B){ // Convert numbers into Strings String s1 = String.Join(\"\", A); String s2 = String.Join(\"\", B); bool result; // Check if s2 is a suffix of s1 // or not result = s1.EndsWith(s2); // If result is true, print \"Yes\" if (result) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }} // Driver Codepublic static void Main(String[] args){ // Given numbers int A = 12345, B = 45; // Function Call checkSuffix(A, B);}} // This code is contributed by 29AjayKumar", "e": 33933, "s": 33253, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to check if B is a// suffix of A or notfunction checkSuffix( A, B){ // Convert numbers into Strings let s1 = A.toString(); let s2 = B.toString(); let result; // Check if s2 is a suffix of s1 // or not result = s1.endsWith(s2); // If result is true, print \"Yes\" if (result) { document.write(\"Yes\"); } else { document.write(\"No\"); }} // Driver Code // Given numbers let A = 12345, B = 45; // Function Call checkSuffix(A, B); </script>", "e": 34518, "s": 33933, "text": null }, { "code": null, "e": 34522, "s": 34518, "text": "Yes" }, { "code": null, "e": 34536, "s": 34524, "text": "Method 3: " }, { "code": null, "e": 34738, "s": 34536, "text": "Subtract B from A.Find the number of digits in B(say X) by using the Method 3 discussed in this article.Check whether A ends with atleast X number zeros or not. If yes then print “Yes”.Else print “No”." }, { "code": null, "e": 34757, "s": 34738, "text": "Subtract B from A." }, { "code": null, "e": 34844, "s": 34757, "text": "Find the number of digits in B(say X) by using the Method 3 discussed in this article." }, { "code": null, "e": 34926, "s": 34844, "text": "Check whether A ends with atleast X number zeros or not. If yes then print “Yes”." }, { "code": null, "e": 34943, "s": 34926, "text": "Else print “No”." }, { "code": null, "e": 34995, "s": 34943, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 34999, "s": 34995, "text": "C++" }, { "code": null, "e": 35004, "s": 34999, "text": "Java" }, { "code": null, "e": 35012, "s": 35004, "text": "Python3" }, { "code": null, "e": 35015, "s": 35012, "text": "C#" }, { "code": null, "e": 35026, "s": 35015, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function to check if B is a// suffix of A or notbool checkSuffix(int A, int B){ // Find the number of digit in B int digit_B = log10(B) + 1; // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % int(pow(10, digit_B)));} // Driver Codeint main(){ // Given numbers int A = 12345, B = 45; // Function Call bool result = checkSuffix(A, B); // If B is a suffix of A, then // print \"Yes\" if (!result) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}", "e": 35698, "s": 35026, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to check if B// is a suffix of A or notstatic boolean checkSuffix(int A, int B){ // Find the number of digit in B int digit_B = (int) (Math.log10(B) + 1); // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % (int)(Math.pow(10, digit_B)) > 0);} // Driver codepublic static void main(String[] args){ // Given numbers int A = 12345, B = 45; // Function call boolean result = checkSuffix(A, B); // If B is a suffix of A, // then print \"Yes\" if (!result) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }}} // This code is contributed by 29AjayKumar", "e": 36443, "s": 35698, "text": null }, { "code": "# Python3 program for the above approachimport math # Function to check if B is a# suffix of A or notdef checkSuffix(A, B): # Find the number of digit in B digit_B = int(math.log10(B)) + 1; # Subtract B from A A -= B; # Returns true, # if B is a suffix of A return (A % int(math.pow(10, digit_B))); # Driver Code # Given numbersA = 12345; B = 45; # Function Callresult = checkSuffix(A, B); # If B is a suffix of A, then# print \"Yes\"if (result == 0): print(\"Yes\"); else: print(\"No\"); # This code is contributed by Nidhi_biet", "e": 36997, "s": 36443, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to check if B// is a suffix of A or notstatic bool checkSuffix(int A, int B){ // Find the number of digit in B int digit_B = (int)(Math.Log10(B) + 1); // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % (int)(Math.Pow(10, digit_B)) > 0);} // Driver codepublic static void Main(){ // Given numbers int A = 12345, B = 45; // Function call bool result = checkSuffix(A, B); // If B is a suffix of A, // then print \"Yes\" if (!result) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by Code_Mech", "e": 37705, "s": 36997, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to check if B // is a suffix of A or not function checkSuffix(A, B) { // Find the number of digit in B let digit_B = parseInt(Math.log10(B) + 1, 10); // Subtract B from A A -= B; // Returns true, // if B is a suffix of A return (A % (Math.pow(10, digit_B)) > 0); } // Given numbers let A = 12345, B = 45; // Function call let result = checkSuffix(A, B); // If B is a suffix of A, // then print \"Yes\" if (!result) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>", "e": 38391, "s": 37705, "text": null }, { "code": null, "e": 38395, "s": 38391, "text": "Yes" }, { "code": null, "e": 38440, "s": 38397, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 38458, "s": 38440, "text": "divyeshrabadiya07" }, { "code": null, "e": 38468, "s": 38458, "text": "rutvik_56" }, { "code": null, "e": 38480, "s": 38468, "text": "29AjayKumar" }, { "code": null, "e": 38490, "s": 38480, "text": "Code_Mech" }, { "code": null, "e": 38501, "s": 38490, "text": "nidhi_biet" }, { "code": null, "e": 38514, "s": 38501, "text": "grand_master" }, { "code": null, "e": 38527, "s": 38514, "text": "Akanksha_Rai" }, { "code": null, "e": 38538, "s": 38527, "text": "himanshu77" }, { "code": null, "e": 38549, "s": 38538, "text": "bunnyram19" }, { "code": null, "e": 38571, "s": 38549, "text": "susmitakundugoaldanga" }, { "code": null, "e": 38580, "s": 38571, "text": "mukesh07" }, { "code": null, "e": 38590, "s": 38580, "text": "subham348" }, { "code": null, "e": 38603, "s": 38590, "text": "Kirti_Mangal" }, { "code": null, "e": 38617, "s": 38603, "text": "number-digits" }, { "code": null, "e": 38625, "s": 38617, "text": "Numbers" }, { "code": null, "e": 38638, "s": 38625, "text": "Mathematical" }, { "code": null, "e": 38646, "s": 38638, "text": "Strings" }, { "code": null, "e": 38654, "s": 38646, "text": "Strings" }, { "code": null, "e": 38667, "s": 38654, "text": "Mathematical" }, { "code": null, "e": 38675, "s": 38667, "text": "Numbers" }, { "code": null, "e": 38773, "s": 38675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38782, "s": 38773, "text": "Comments" }, { "code": null, "e": 38795, "s": 38782, "text": "Old Comments" }, { "code": null, "e": 38837, "s": 38795, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 38861, "s": 38837, "text": "Merge two sorted arrays" }, { "code": null, "e": 38904, "s": 38861, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38918, "s": 38904, "text": "Prime Numbers" }, { "code": null, "e": 38967, "s": 38918, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 38992, "s": 38967, "text": "Reverse a string in Java" }, { "code": null, "e": 39038, "s": 38992, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 39072, "s": 39038, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 39129, "s": 39072, "text": "Python program to check if a string is palindrome or not" } ]
How to force Matplotlib to show the values on X-axis as integers?
To force matplotlib to show the values on X-axis as integers, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create two lists, x and y, of data points. Plot x and y using plot() method. Make a new list for only integers tick on X-axis. Use math.floor() and math.ceil() to remove the decimals and include only integers in the list. Set x and y labels. Set the title of the figure. To display the figure, use show() method. import math from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True y = [0.17, 1.17, 2.98, 3.15, 4.11, 5.151] x = [1.0, 1.75, 2.90, 3.15, 4.50, 5.50] plt.plot(x, y) new_list = range(math.floor(min(x)), math.ceil(max(x))+1) plt.xticks(new_list) plt.xlabel("X-axis ") plt.ylabel("Y-axis ") plt.title("Only Integers on the X-axis") plt.show()
[ { "code": null, "e": 1158, "s": 1062, "text": "To force matplotlib to show the values on X-axis as integers, we can take the following steps −" }, { "code": null, "e": 1234, "s": 1158, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1277, "s": 1234, "text": "Create two lists, x and y, of data points." }, { "code": null, "e": 1311, "s": 1277, "text": "Plot x and y using plot() method." }, { "code": null, "e": 1456, "s": 1311, "text": "Make a new list for only integers tick on X-axis. Use math.floor() and math.ceil() to remove the decimals and include only integers in the list." }, { "code": null, "e": 1476, "s": 1456, "text": "Set x and y labels." }, { "code": null, "e": 1505, "s": 1476, "text": "Set the title of the figure." }, { "code": null, "e": 1547, "s": 1505, "text": "To display the figure, use show() method." }, { "code": null, "e": 1962, "s": 1547, "text": "import math\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ny = [0.17, 1.17, 2.98, 3.15, 4.11, 5.151]\nx = [1.0, 1.75, 2.90, 3.15, 4.50, 5.50]\n\nplt.plot(x, y)\n\nnew_list = range(math.floor(min(x)), math.ceil(max(x))+1)\nplt.xticks(new_list)\n\nplt.xlabel(\"X-axis \")\nplt.ylabel(\"Y-axis \")\n\nplt.title(\"Only Integers on the X-axis\")\n\nplt.show()" } ]
Using Machine Learning To Detect Fraud | by Kurtis Pykes | Towards Data Science
Introduction The Fraud detection problem The Data Building the Framework Machine Learning is a subset of Artificial Intelligence (AI) that provides systems with the ability to automatically learn and improve from experience without being explicitly programmed. In saying that, it has been made possible for us (humans) to supply a large set of data to a computer for the computer to learn patterns so that it may learn how to make a decision when faced with a new instance or instances — When I discovered this insight I instantly knew the world is about to change. It reveals that fraud is costing the global economy £3.89 trillion, with losses rising by 56% in the past decade. — Crowe UK Having been a victim of fraud, coming up with ideas to prevent it from ever happening to me (and anyone else for that matter) again essentially contributed to me wondering into a totally different field from what I was accustomed to. In Machine Learning terminology, problems such as the Fraud Detection problem may be framed as a classification problem, of which the goal is to predict the discrete label 0 or 1 where 0 generally suggest that a transaction is non-fraudulent and 1 suggest that the transaction seems to be fraudulent. Hence, this problem requires practitioners to build models that are intelligent enough to be capable of accurately detecting fraudulent and non-fraudulent transactions given various users transaction data — which is often anonymous to protect users privacy. Since depending exclusively on rule-based systems is not the most effective strategy, Machine learning has been the approach many financial institutes are taking to combat the problem. What makes this problem (fraud detection) so challenging is that when we model it in the real world, the majority of transactions that occur are genuine transactions and only a very small portion account for fraudulent behavior. This means we deal with the problem of imbalanced data — My post on Oversampling and Undersampling is one approach to dealing with this problem. However, for this post our main focus will be on beginning our machine learning framework to detect fraud — If you are unfamiliar with building your own framework you may want to read through Structuring Machine Learning Projects before completing this post. towardsdatascience.com towardsdatascience.com The data was put together by researchers from IEEE Computational Intelligence Society (IEEE-CIS) for the task of predicting the probability that an online transaction is fraudulent, as denoted by the binary target isFraud. Note: The data section is copied from Kaggle Data section for this competition. The data is broken into two files identity and transaction, which are joined by TransactionID. Not all transactions have corresponding identity information. Categorical Features — Transaction ProductCD card1 - card6 addr1, addr2 P_emaildomain R_emaildomain M1 - M9 Categorical Features — Identity DeviceType DeviceInfo id_12 - id_38 The TransactionDT feature is a timedelta from a given reference datetime (not an actual timestamp). You can read more about the data from this post by the competition host. Files train_{transaction, identity}.csv — the training set test_{transaction, identity}.csv — the test set (you must predict the isFraud value for these observations) sample_submission.csv — a sample submission file in the correct format The first step of when working on any machine learning task is to build a reliable Cross Validation strategy. towardsdatascience.com Note: The general idea behind the framework was taken from no other than Abhishek Thakur — Github A general approach to take when facing a imbalanced data problem is to use StratifiedKFold which splits the data randomly in such a way that we maintain the same class distribution. I implemented out create folds as part of preprocessing.py. This code merges the identity and transaction data from the train and test set then renames the columns names in the merged_test data since the id columns use “-” instead of “_” — which will cause problems later when we check to ensure we have the exact same column names in our test. Next, we add a column name called kfold to our training data and set the index in accordance with the fold it is in then save to a csv file. You may of noticed that we import config and use it as a path to various things. All config is, is variables in another script so that we don’t have to repeatedly call those variables in different scripts. It is very important to build your pipeline fast and in a manner that allows for fast iterations when working on a machine learning problem, so the next script we will build is our model_dispatcher.py of which we call our classifiers and train.py where we train our model. Let’s start with model_dispatcher.py Here, we have simply imported a Logistic Regression and Random Forest that and created a dictionary so we can call the algorithms into our train script by doing models["logistic_regression"] which will run the Logistic Regression model. The train script is as follows... Hopefully you can read code but if you can not, to sum up what is going on, we set training data as the values in the column kfold that and the values that are equal to the fold we passed is the test set. Then we do Label encoding to the categorical variables, and fill all missing values with 0 before training our data on a logistic regression model. We get predictions on the current fold and print the ROC_AUC. towardsdatascience.com Note: As things stand, the code is does not run itself, so we’d have to pass the values for fold and model when we run each fold. Let’s see the outputs of our Logistic Regression Model. ### Logistic Regression # Fold 0 ROC_AUC_SCORE: 0.7446056326560758# Fold 1ROC_AUC_SCORE: 0.7476247589462117# Fold 2ROC_AUC_SCORE: 0.7395710927094167# Fold 3ROC_AUC_SCORE: 0.7365641912867861# Fold 4ROC_AUC_SCORE: 0.7115696956435416 Those are pretty decent results to start with, but let’s use the more powerful random forest model and see if we can improve. ### Random Forest# Fold 0 ROC_AUC_SCORE: 0.9280242455299264# Fold 1ROC_AUC_SCORE: 0.9281600723876517# Fold 2ROC_AUC_SCORE: 0.9265254015330469# Fold 3ROC_AUC_SCORE: 0.9224746067992484# Fold 4ROC_AUC_SCORE: 0.9196977372298685 It’s pretty clear the random forest model is yielding much better results. Let’s do a late submission on to Kaggle and see where we rank on the leaderboards. This is of the most important parts — To do this we must run inference.py. Note: The process of submitting to Kaggle is beyond the scope of this discussion so I will the score model gets and how that does on the Leaderboard. Given this score translated to Kaggle’s private leaderboard (since it is the score on the public leaderboard), we would of ranked 3875/6351 (Top 61%) on Kaggle’s private leaderboard. Although, It doesn’t look so good from a Kaggle perspective, in a real world scenario we’d probably settle with this score depending on the task. However, the goal of this project is not to come up with the best model, it is to create our own API which we will come back to in later post. For building a quick pipeline for fast iteration, the code we have is okay but if we want to deploy this model we’d have to do plenty of clean up work so that we follow the Software Engineering Best Practices. towardsdatascience.com Detecting Fraud is a very common and challenging problem in the real world and increasing the accuracy is very important to prevent the embarrassment of customers cards being declined when making a genuine transaction at a store. We’ve have built a very simple approach using label encoding for categorical variables, filling all missing values with 0, and a random forest without any tuning or methods to handle the imbalance in data but our model still scores pretty highly. To improve the model, we may want to first look at the important features from the Random Forest model and drop less important features, or we can use other more powerful models like Light Gradient Boosting Machine and Neural Networks Note: At the time of writing this script, the modules aren’t the best but it is in a format that would allow me to quickly iterate. In future work, I plan on deploying this model as an API on a cloud server. Let’s continue the conversation on LinkedIn...
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 213, "s": 185, "text": "The Fraud detection problem" }, { "code": null, "e": 222, "s": 213, "text": "The Data" }, { "code": null, "e": 245, "s": 222, "text": "Building the Framework" }, { "code": null, "e": 738, "s": 245, "text": "Machine Learning is a subset of Artificial Intelligence (AI) that provides systems with the ability to automatically learn and improve from experience without being explicitly programmed. In saying that, it has been made possible for us (humans) to supply a large set of data to a computer for the computer to learn patterns so that it may learn how to make a decision when faced with a new instance or instances — When I discovered this insight I instantly knew the world is about to change." }, { "code": null, "e": 863, "s": 738, "text": "It reveals that fraud is costing the global economy £3.89 trillion, with losses rising by 56% in the past decade. — Crowe UK" }, { "code": null, "e": 1097, "s": 863, "text": "Having been a victim of fraud, coming up with ideas to prevent it from ever happening to me (and anyone else for that matter) again essentially contributed to me wondering into a totally different field from what I was accustomed to." }, { "code": null, "e": 1398, "s": 1097, "text": "In Machine Learning terminology, problems such as the Fraud Detection problem may be framed as a classification problem, of which the goal is to predict the discrete label 0 or 1 where 0 generally suggest that a transaction is non-fraudulent and 1 suggest that the transaction seems to be fraudulent." }, { "code": null, "e": 1656, "s": 1398, "text": "Hence, this problem requires practitioners to build models that are intelligent enough to be capable of accurately detecting fraudulent and non-fraudulent transactions given various users transaction data — which is often anonymous to protect users privacy." }, { "code": null, "e": 1841, "s": 1656, "text": "Since depending exclusively on rule-based systems is not the most effective strategy, Machine learning has been the approach many financial institutes are taking to combat the problem." }, { "code": null, "e": 2474, "s": 1841, "text": "What makes this problem (fraud detection) so challenging is that when we model it in the real world, the majority of transactions that occur are genuine transactions and only a very small portion account for fraudulent behavior. This means we deal with the problem of imbalanced data — My post on Oversampling and Undersampling is one approach to dealing with this problem. However, for this post our main focus will be on beginning our machine learning framework to detect fraud — If you are unfamiliar with building your own framework you may want to read through Structuring Machine Learning Projects before completing this post." }, { "code": null, "e": 2497, "s": 2474, "text": "towardsdatascience.com" }, { "code": null, "e": 2520, "s": 2497, "text": "towardsdatascience.com" }, { "code": null, "e": 2743, "s": 2520, "text": "The data was put together by researchers from IEEE Computational Intelligence Society (IEEE-CIS) for the task of predicting the probability that an online transaction is fraudulent, as denoted by the binary target isFraud." }, { "code": null, "e": 2823, "s": 2743, "text": "Note: The data section is copied from Kaggle Data section for this competition." }, { "code": null, "e": 2980, "s": 2823, "text": "The data is broken into two files identity and transaction, which are joined by TransactionID. Not all transactions have corresponding identity information." }, { "code": null, "e": 3015, "s": 2980, "text": "Categorical Features — Transaction" }, { "code": null, "e": 3025, "s": 3015, "text": "ProductCD" }, { "code": null, "e": 3039, "s": 3025, "text": "card1 - card6" }, { "code": null, "e": 3052, "s": 3039, "text": "addr1, addr2" }, { "code": null, "e": 3066, "s": 3052, "text": "P_emaildomain" }, { "code": null, "e": 3080, "s": 3066, "text": "R_emaildomain" }, { "code": null, "e": 3088, "s": 3080, "text": "M1 - M9" }, { "code": null, "e": 3120, "s": 3088, "text": "Categorical Features — Identity" }, { "code": null, "e": 3131, "s": 3120, "text": "DeviceType" }, { "code": null, "e": 3142, "s": 3131, "text": "DeviceInfo" }, { "code": null, "e": 3156, "s": 3142, "text": "id_12 - id_38" }, { "code": null, "e": 3256, "s": 3156, "text": "The TransactionDT feature is a timedelta from a given reference datetime (not an actual timestamp)." }, { "code": null, "e": 3329, "s": 3256, "text": "You can read more about the data from this post by the competition host." }, { "code": null, "e": 3335, "s": 3329, "text": "Files" }, { "code": null, "e": 3388, "s": 3335, "text": "train_{transaction, identity}.csv — the training set" }, { "code": null, "e": 3496, "s": 3388, "text": "test_{transaction, identity}.csv — the test set (you must predict the isFraud value for these observations)" }, { "code": null, "e": 3567, "s": 3496, "text": "sample_submission.csv — a sample submission file in the correct format" }, { "code": null, "e": 3677, "s": 3567, "text": "The first step of when working on any machine learning task is to build a reliable Cross Validation strategy." }, { "code": null, "e": 3700, "s": 3677, "text": "towardsdatascience.com" }, { "code": null, "e": 3798, "s": 3700, "text": "Note: The general idea behind the framework was taken from no other than Abhishek Thakur — Github" }, { "code": null, "e": 3980, "s": 3798, "text": "A general approach to take when facing a imbalanced data problem is to use StratifiedKFold which splits the data randomly in such a way that we maintain the same class distribution." }, { "code": null, "e": 4040, "s": 3980, "text": "I implemented out create folds as part of preprocessing.py." }, { "code": null, "e": 4466, "s": 4040, "text": "This code merges the identity and transaction data from the train and test set then renames the columns names in the merged_test data since the id columns use “-” instead of “_” — which will cause problems later when we check to ensure we have the exact same column names in our test. Next, we add a column name called kfold to our training data and set the index in accordance with the fold it is in then save to a csv file." }, { "code": null, "e": 4672, "s": 4466, "text": "You may of noticed that we import config and use it as a path to various things. All config is, is variables in another script so that we don’t have to repeatedly call those variables in different scripts." }, { "code": null, "e": 4945, "s": 4672, "text": "It is very important to build your pipeline fast and in a manner that allows for fast iterations when working on a machine learning problem, so the next script we will build is our model_dispatcher.py of which we call our classifiers and train.py where we train our model." }, { "code": null, "e": 4982, "s": 4945, "text": "Let’s start with model_dispatcher.py" }, { "code": null, "e": 5219, "s": 4982, "text": "Here, we have simply imported a Logistic Regression and Random Forest that and created a dictionary so we can call the algorithms into our train script by doing models[\"logistic_regression\"] which will run the Logistic Regression model." }, { "code": null, "e": 5253, "s": 5219, "text": "The train script is as follows..." }, { "code": null, "e": 5606, "s": 5253, "text": "Hopefully you can read code but if you can not, to sum up what is going on, we set training data as the values in the column kfold that and the values that are equal to the fold we passed is the test set. Then we do Label encoding to the categorical variables, and fill all missing values with 0 before training our data on a logistic regression model." }, { "code": null, "e": 5668, "s": 5606, "text": "We get predictions on the current fold and print the ROC_AUC." }, { "code": null, "e": 5691, "s": 5668, "text": "towardsdatascience.com" }, { "code": null, "e": 5821, "s": 5691, "text": "Note: As things stand, the code is does not run itself, so we’d have to pass the values for fold and model when we run each fold." }, { "code": null, "e": 5877, "s": 5821, "text": "Let’s see the outputs of our Logistic Regression Model." }, { "code": null, "e": 6108, "s": 5877, "text": "### Logistic Regression # Fold 0 ROC_AUC_SCORE: 0.7446056326560758# Fold 1ROC_AUC_SCORE: 0.7476247589462117# Fold 2ROC_AUC_SCORE: 0.7395710927094167# Fold 3ROC_AUC_SCORE: 0.7365641912867861# Fold 4ROC_AUC_SCORE: 0.7115696956435416" }, { "code": null, "e": 6234, "s": 6108, "text": "Those are pretty decent results to start with, but let’s use the more powerful random forest model and see if we can improve." }, { "code": null, "e": 6458, "s": 6234, "text": "### Random Forest# Fold 0 ROC_AUC_SCORE: 0.9280242455299264# Fold 1ROC_AUC_SCORE: 0.9281600723876517# Fold 2ROC_AUC_SCORE: 0.9265254015330469# Fold 3ROC_AUC_SCORE: 0.9224746067992484# Fold 4ROC_AUC_SCORE: 0.9196977372298685" }, { "code": null, "e": 6691, "s": 6458, "text": "It’s pretty clear the random forest model is yielding much better results. Let’s do a late submission on to Kaggle and see where we rank on the leaderboards. This is of the most important parts — To do this we must run inference.py." }, { "code": null, "e": 6841, "s": 6691, "text": "Note: The process of submitting to Kaggle is beyond the scope of this discussion so I will the score model gets and how that does on the Leaderboard." }, { "code": null, "e": 7170, "s": 6841, "text": "Given this score translated to Kaggle’s private leaderboard (since it is the score on the public leaderboard), we would of ranked 3875/6351 (Top 61%) on Kaggle’s private leaderboard. Although, It doesn’t look so good from a Kaggle perspective, in a real world scenario we’d probably settle with this score depending on the task." }, { "code": null, "e": 7313, "s": 7170, "text": "However, the goal of this project is not to come up with the best model, it is to create our own API which we will come back to in later post." }, { "code": null, "e": 7523, "s": 7313, "text": "For building a quick pipeline for fast iteration, the code we have is okay but if we want to deploy this model we’d have to do plenty of clean up work so that we follow the Software Engineering Best Practices." }, { "code": null, "e": 7546, "s": 7523, "text": "towardsdatascience.com" }, { "code": null, "e": 8258, "s": 7546, "text": "Detecting Fraud is a very common and challenging problem in the real world and increasing the accuracy is very important to prevent the embarrassment of customers cards being declined when making a genuine transaction at a store. We’ve have built a very simple approach using label encoding for categorical variables, filling all missing values with 0, and a random forest without any tuning or methods to handle the imbalance in data but our model still scores pretty highly. To improve the model, we may want to first look at the important features from the Random Forest model and drop less important features, or we can use other more powerful models like Light Gradient Boosting Machine and Neural Networks" }, { "code": null, "e": 8466, "s": 8258, "text": "Note: At the time of writing this script, the modules aren’t the best but it is in a format that would allow me to quickly iterate. In future work, I plan on deploying this model as an API on a cloud server." } ]
TypeScript - String search()
This method executes the search for a match between a regular expression and this String object. string.search(regexp); regexp − A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). If successful, the search returns the index of the regular expression inside the string. Otherwise, it returns -1. var re = /apples/gi; var str = "Apples are round, and apples are juicy."; if (str.search(re) == -1 ) { console.log("Does not contain Apples" ); } else { console.log("Contains Apples" ); } On compiling, it will generate the same code in JavaScript. Its output is as follows − Contains Apples 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2145, "s": 2048, "text": "This method executes the search for a match between a regular expression and this String object." }, { "code": null, "e": 2169, "s": 2145, "text": "string.search(regexp);\n" }, { "code": null, "e": 2310, "s": 2169, "text": "regexp − A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj)." }, { "code": null, "e": 2425, "s": 2310, "text": "If successful, the search returns the index of the regular expression inside the string. Otherwise, it returns -1." }, { "code": null, "e": 2626, "s": 2425, "text": "var re = /apples/gi; \nvar str = \"Apples are round, and apples are juicy.\";\nif (str.search(re) == -1 ) { \n console.log(\"Does not contain Apples\" ); \n} else { \n console.log(\"Contains Apples\" ); \n} \n" }, { "code": null, "e": 2686, "s": 2626, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2713, "s": 2686, "text": "Its output is as follows −" }, { "code": null, "e": 2730, "s": 2713, "text": "Contains Apples\n" }, { "code": null, "e": 2763, "s": 2730, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 2777, "s": 2763, "text": " Antonio Papa" }, { "code": null, "e": 2810, "s": 2777, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 2824, "s": 2810, "text": " Haider Malik" }, { "code": null, "e": 2859, "s": 2824, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2879, "s": 2859, "text": " Skillbakerystudios" }, { "code": null, "e": 2912, "s": 2879, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 2926, "s": 2912, "text": " Sean Bradley" }, { "code": null, "e": 2961, "s": 2926, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2977, "s": 2961, "text": " TELCOMA Global" }, { "code": null, "e": 3010, "s": 2977, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 3030, "s": 3010, "text": " Christopher Frewin" }, { "code": null, "e": 3037, "s": 3030, "text": " Print" }, { "code": null, "e": 3048, "s": 3037, "text": " Add Notes" } ]
What makes Scala scalable? - GeeksforGeeks
22 Apr, 2021 Scalability of a language is effected by some factors ranging from syntax details to component abstraction construct. The main aspect of scala that makes it scalable is that it is a combination of both object-oriented and functional programming. It has good support for both the programming constructs like high-order functions, tail-call optimization, immutable values, pattern matching, polymorphism, abstraction, inheritance etc. Scala also includes its own interpreter which can be used to execute instruction directly, without previous compiling. Another key feature is parallel collections library designed to help developers address parallel programming patterns. Some Another features are as follow : Scala is concise. it provides a better support for backend operations. Scala programs tend to be short upto a factor of 10 compared to Java. It avoids code that shows up again and again in order to get some result that burdens Java program. Example: In Java, a class with constructor looks like: Java class Geek{ // data members of the class. String name; int id; // constructor would initialized data members // with the values of passed arguments while // object of that class created. Geek(String name, int id) { this.name = name; this.id = id; }} In Scala it’ll be written as: Scala class Geek(name: String, id: Int) {} Scala helps you manage complexity by letting we raise the level of abstraction in the interfaces we design. Java treats stings as low-level entities that are stepped through character by character in a loop. The Scala code treats same string as higher-level sequences of character that can be queried. Scala provides the facility to develop the frameworks and libraries. Example: In Java,to find the first uppercase letter. Java // Function to find string which has // first character of each word. static char first(String str) { for (int i = 0; i < str.length(); i++) if (Character.isUpperCase(str.charAt(i))) return str.charAt(i); return 0; } In scala it will be written as: Scala val first = str.exists(_.isUpperCase) In Java code, string is low level entities whereas in Scala same string is treated as high level entities. In Scala _.isUpperCase is a function literals. It supports static typing in which computations are formed as statements that change program state at compile time. It is an approach that can provide improved runtime efficiencies. By the values they hold and compute a static type system classifies variables and expressions. A system of nested class types much like Java’s, it allows us to parameterize types with generics, to hide details using abstract types, and by using intersections it combine types . It is implemented on Java Virtual Machine(JVM) so it can access all Java methods and fields, inherit from Java classes and implement Java interface. It does not require any special syntax, explicit interface descriptions, or glue code. It uses Java’s types and dresses them up to look nicer. The Scala compiler compiles the program into .class file, containing the Bytecode that can be executed by JVM. All the classes of Java SDK can be used by Scala. With the help of Scala user can customize the Java classes. arorakashish0911 Picked Scala Scala-Basics 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 Scala List length() method with example How to install Scala on Windows? Scala | Traits Scala | Case Class and Case Object Inheritance in Scala
[ { "code": null, "e": 23695, "s": 23667, "text": "\n22 Apr, 2021" }, { "code": null, "e": 24406, "s": 23695, "text": "Scalability of a language is effected by some factors ranging from syntax details to component abstraction construct. The main aspect of scala that makes it scalable is that it is a combination of both object-oriented and functional programming. It has good support for both the programming constructs like high-order functions, tail-call optimization, immutable values, pattern matching, polymorphism, abstraction, inheritance etc. Scala also includes its own interpreter which can be used to execute instruction directly, without previous compiling. Another key feature is parallel collections library designed to help developers address parallel programming patterns. Some Another features are as follow : " }, { "code": null, "e": 24704, "s": 24406, "text": "Scala is concise. it provides a better support for backend operations. Scala programs tend to be short upto a factor of 10 compared to Java. It avoids code that shows up again and again in order to get some result that burdens Java program. Example: In Java, a class with constructor looks like: " }, { "code": null, "e": 24709, "s": 24704, "text": "Java" }, { "code": "class Geek{ // data members of the class. String name; int id; // constructor would initialized data members // with the values of passed arguments while // object of that class created. Geek(String name, int id) { this.name = name; this.id = id; }}", "e": 25003, "s": 24709, "text": null }, { "code": null, "e": 25033, "s": 25003, "text": "In Scala it’ll be written as:" }, { "code": null, "e": 25039, "s": 25033, "text": "Scala" }, { "code": "class Geek(name: String, id: Int) {}", "e": 25076, "s": 25039, "text": null }, { "code": null, "e": 25502, "s": 25076, "text": "Scala helps you manage complexity by letting we raise the level of abstraction in the interfaces we design. Java treats stings as low-level entities that are stepped through character by character in a loop. The Scala code treats same string as higher-level sequences of character that can be queried. Scala provides the facility to develop the frameworks and libraries. Example: In Java,to find the first uppercase letter. " }, { "code": null, "e": 25507, "s": 25502, "text": "Java" }, { "code": "// Function to find string which has // first character of each word. static char first(String str) { for (int i = 0; i < str.length(); i++) if (Character.isUpperCase(str.charAt(i))) return str.charAt(i); return 0; }", "e": 25768, "s": 25507, "text": null }, { "code": null, "e": 25802, "s": 25768, "text": "In scala it will be written as: " }, { "code": null, "e": 25808, "s": 25802, "text": "Scala" }, { "code": "val first = str.exists(_.isUpperCase)", "e": 25846, "s": 25808, "text": null }, { "code": null, "e": 26002, "s": 25846, "text": "In Java code, string is low level entities whereas in Scala same string is treated as high level entities. In Scala _.isUpperCase is a function literals. " }, { "code": null, "e": 26462, "s": 26002, "text": "It supports static typing in which computations are formed as statements that change program state at compile time. It is an approach that can provide improved runtime efficiencies. By the values they hold and compute a static type system classifies variables and expressions. A system of nested class types much like Java’s, it allows us to parameterize types with generics, to hide details using abstract types, and by using intersections it combine types ." }, { "code": null, "e": 26975, "s": 26462, "text": "It is implemented on Java Virtual Machine(JVM) so it can access all Java methods and fields, inherit from Java classes and implement Java interface. It does not require any special syntax, explicit interface descriptions, or glue code. It uses Java’s types and dresses them up to look nicer. The Scala compiler compiles the program into .class file, containing the Bytecode that can be executed by JVM. All the classes of Java SDK can be used by Scala. With the help of Scala user can customize the Java classes." }, { "code": null, "e": 26994, "s": 26977, "text": "arorakashish0911" }, { "code": null, "e": 27001, "s": 26994, "text": "Picked" }, { "code": null, "e": 27007, "s": 27001, "text": "Scala" }, { "code": null, "e": 27020, "s": 27007, "text": "Scala-Basics" }, { "code": null, "e": 27026, "s": 27020, "text": "Scala" }, { "code": null, "e": 27124, "s": 27026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27133, "s": 27124, "text": "Comments" }, { "code": null, "e": 27146, "s": 27133, "text": "Old Comments" }, { "code": null, "e": 27167, "s": 27146, "text": "Hello World in Scala" }, { "code": null, "e": 27203, "s": 27167, "text": "Scala Map get() method with example" }, { "code": null, "e": 27220, "s": 27203, "text": "Scala ListBuffer" }, { "code": null, "e": 27257, "s": 27220, "text": "Scala List map() method with example" }, { "code": null, "e": 27297, "s": 27257, "text": "Scala List length() method with example" }, { "code": null, "e": 27330, "s": 27297, "text": "How to install Scala on Windows?" }, { "code": null, "e": 27345, "s": 27330, "text": "Scala | Traits" }, { "code": null, "e": 27380, "s": 27345, "text": "Scala | Case Class and Case Object" } ]
Adding WYSIWYG editor to Django Project - GeeksforGeeks
01 Nov, 2020 Often, to manage content efficiently we use WYSIWYG (What You See Is What You Get) editor which stores our content in html and is also helpful to upload images, creating links, lists and works almost like WordPress editor. This article is in continuation of Blog CMS Project in Django. Check this out here – Building Blog CMS (Content Management System) with Django 1. Install summernote – # installing wysiwyg editor pip3 install django-summernote 2. Add the editor to installed apps in the settings file Python3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # adding in installed apps 'django_summernote', ] 3. Migrate the project # migrate django summernote python3 manage.py migrate 4.Customize admin interface – Now we will customize the admin interface for the app. For that open the admin.py file and add the below code Python3 # importing admin and posts modelfrom django.contrib import adminfrom .models import postsfrom django_summernote.admin import SummernoteModelAdmin # creating admin classclass blogadmin(SummernoteModelAdmin): # displaying posts with title slug and created time list_display = ('title', 'slug', 'status', 'created_on') list_filter = ("status", ) search_fields = ['title', 'content'] # prepopulating slug from title prepopulated_fields = {'slug': ('title', )} summernote_fields = ('content', ) # registering admin classadmin.site.register(posts, blogadmin) 5. Adding media setting for our editor Open your python settings file and add these lines Python3 # add it in settings.pyMEDIA_URL = '/media/'MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # allows to load iframe from same hostnameX_FRAME_OPTIONS = 'SAMEORIGIN' The editor works well in production but for the development server it won’t work because of the way the static files load so to make that work we need to add a condition in django projects urls.py Python3 # add condition in django urls fileif settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) 6. Customizing Admin Page – Django also gives the option to customize Admin page, we will do an minimal customization of changing the name from django default to GeeksForGeeks. go to urls.py file in django project and add these lines Python3 # customizing admin interfaceadmin.site.site_header = 'GeeksForGeeks'admin.site.site_title = 'GeeksForGeeks'admin.site.index_title = 'GeeksForGeeks Administration' urlpatterns = [...... # urls handling WYSIWYG editor path('editor/', include('django_summernote.urls')),......] Now run the server and login into admin panel using the superuser credentials. You will see something like in the below picture. So we have created and customized admin class for creating, managing and listing posts for our CMS with custom admin login. 7. Output Screenshots – Custom Admin Login listing posts editor for posts Python Django Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n01 Nov, 2020" }, { "code": null, "e": 24658, "s": 24292, "text": "Often, to manage content efficiently we use WYSIWYG (What You See Is What You Get) editor which stores our content in html and is also helpful to upload images, creating links, lists and works almost like WordPress editor. This article is in continuation of Blog CMS Project in Django. Check this out here – Building Blog CMS (Content Management System) with Django" }, { "code": null, "e": 24683, "s": 24658, "text": "1. Install summernote – " }, { "code": null, "e": 24742, "s": 24683, "text": "# installing wysiwyg editor\npip3 install django-summernote" }, { "code": null, "e": 24799, "s": 24742, "text": "2. Add the editor to installed apps in the settings file" }, { "code": null, "e": 24807, "s": 24799, "text": "Python3" }, { "code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # adding in installed apps 'django_summernote', ]", "e": 25063, "s": 24807, "text": null }, { "code": null, "e": 25086, "s": 25063, "text": "3. Migrate the project" }, { "code": null, "e": 25140, "s": 25086, "text": "# migrate django summernote\npython3 manage.py migrate" }, { "code": null, "e": 25171, "s": 25140, "text": "4.Customize admin interface – " }, { "code": null, "e": 25281, "s": 25171, "text": "Now we will customize the admin interface for the app. For that open the admin.py file and add the below code" }, { "code": null, "e": 25289, "s": 25281, "text": "Python3" }, { "code": "# importing admin and posts modelfrom django.contrib import adminfrom .models import postsfrom django_summernote.admin import SummernoteModelAdmin # creating admin classclass blogadmin(SummernoteModelAdmin): # displaying posts with title slug and created time list_display = ('title', 'slug', 'status', 'created_on') list_filter = (\"status\", ) search_fields = ['title', 'content'] # prepopulating slug from title prepopulated_fields = {'slug': ('title', )} summernote_fields = ('content', ) # registering admin classadmin.site.register(posts, blogadmin)", "e": 25866, "s": 25289, "text": null }, { "code": null, "e": 25905, "s": 25866, "text": "5. Adding media setting for our editor" }, { "code": null, "e": 25956, "s": 25905, "text": "Open your python settings file and add these lines" }, { "code": null, "e": 25964, "s": 25956, "text": "Python3" }, { "code": "# add it in settings.pyMEDIA_URL = '/media/'MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # allows to load iframe from same hostnameX_FRAME_OPTIONS = 'SAMEORIGIN'", "e": 26128, "s": 25964, "text": null }, { "code": null, "e": 26325, "s": 26128, "text": "The editor works well in production but for the development server it won’t work because of the way the static files load so to make that work we need to add a condition in django projects urls.py" }, { "code": null, "e": 26333, "s": 26325, "text": "Python3" }, { "code": "# add condition in django urls fileif settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)", "e": 26469, "s": 26333, "text": null }, { "code": null, "e": 26498, "s": 26469, "text": "6. Customizing Admin Page – " }, { "code": null, "e": 26704, "s": 26498, "text": "Django also gives the option to customize Admin page, we will do an minimal customization of changing the name from django default to GeeksForGeeks. go to urls.py file in django project and add these lines" }, { "code": null, "e": 26712, "s": 26704, "text": "Python3" }, { "code": "# customizing admin interfaceadmin.site.site_header = 'GeeksForGeeks'admin.site.site_title = 'GeeksForGeeks'admin.site.index_title = 'GeeksForGeeks Administration' urlpatterns = [...... # urls handling WYSIWYG editor path('editor/', include('django_summernote.urls')),......]", "e": 26992, "s": 26712, "text": null }, { "code": null, "e": 27245, "s": 26992, "text": "Now run the server and login into admin panel using the superuser credentials. You will see something like in the below picture. So we have created and customized admin class for creating, managing and listing posts for our CMS with custom admin login." }, { "code": null, "e": 27270, "s": 27245, "text": "7. Output Screenshots – " }, { "code": null, "e": 27289, "s": 27270, "text": "Custom Admin Login" }, { "code": null, "e": 27303, "s": 27289, "text": "listing posts" }, { "code": null, "e": 27320, "s": 27303, "text": "editor for posts" }, { "code": null, "e": 27334, "s": 27320, "text": "Python Django" }, { "code": null, "e": 27358, "s": 27334, "text": "Technical Scripter 2020" }, { "code": null, "e": 27365, "s": 27358, "text": "Python" }, { "code": null, "e": 27384, "s": 27365, "text": "Technical Scripter" }, { "code": null, "e": 27482, "s": 27384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27514, "s": 27482, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27556, "s": 27514, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27612, "s": 27556, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27654, "s": 27612, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27709, "s": 27654, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27740, "s": 27709, "text": "Python | os.path.join() method" }, { "code": null, "e": 27762, "s": 27740, "text": "Defaultdict in Python" }, { "code": null, "e": 27791, "s": 27762, "text": "Create a directory in Python" }, { "code": null, "e": 27830, "s": 27791, "text": "Python | Get unique values from a list" } ]
Count the Specials | Practice | GeeksforGeeks
Given an array A (may contain duplicates) of N elements and a positive integer K. The task is to count the number of elements which occurs exactly floor(N/K) times in the array. Example: Input:N = 5K = 2A[] = 1 4 1 2 4Output:2Explanation:In the given array, 1 and 4 occurs floor(5/2) = 2 times. So count is 2. Your Task:Your task is to complete the function countSpecials() which should count the elements which occurs exactly floor(N/K) times. Constrains:1 <= N <= 1031 <= Ai <= 1031 <= K <= 103 0 hgaur7011 month ago TIME COMPLEXITY : O(n+m) , TIME TAKEN : 0.0 BY USING MAP :- int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int cot = 0; map<int, int> ob; map<int, int>::iterator it; for (int i = 0; i < sizeof_array; i++) { ob[arr[i]]++; } for (auto &&i : ob) { if (i.second == f) { count++; } } return count; } 0 sumitd12991 month ago SIMPLEST CODE WITH LEAST TIME COMPLEXITY YOU WILL GET HERE IS : int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int arr2[1000]={0}; // Your code here for(int i=0;i<sizeof_array;i++){ arr2[arr[i]]++; } for(int i=0;i<1000;i++){ if(arr2[i]==f){ count++; } } return count; } +1 benklomp2 months ago int countSpecials(int arr[], int n, int K) { int f = floor(n/K), count = 0; // Your code here // simple bubble sort for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) if(arr[i] > arr[j]) { int T = arr[i]; arr[i] = arr[j]; arr[j] = T; } int counter = 0, p = -1; for(int i = 0; i < n; i += 1) { if(arr[i] == p) continue; int counter = 1, j = i; while(++j < n && arr[i] == arr[j]) ++counter; if(counter == f) ++count; p = arr[i]; } return count; 0 sumitrodge272 months ago i dont know how map works, someone help! int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int t=0; for(int i=0;i<sizeof_array;i++) { for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) { t++; } } if(t==f) { count++; } t=0; } count=ceil(count/f); return count; } 0 sumitrodge273 months ago someone please tell me what's wrong with my code int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int p=0; for(int i=0;i<sizeof_array;i++) { for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) { p+=1; } } if(p==f) { count+=1; } p=0; } return count; } -2 dipawalimandaokar3213 months ago // { Driver Code Starts//Initial Template for C++#include <bits/stdc++.h>using namespace std; // Function Prototypeint countSpecials(int[], int, int); // } Driver Code Ends//User function Template for C++ /*Function to count number of elements with occurrence* exactly equal to floor(sizeof_array/K)* arr : input array* sizeof_array : number of array elements*/int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K),p=0; for(int i=0;i<sizeof_array;i++) { int count; for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) count++ ; } if(count==f) p++; } // Your code here return p; } // { Driver Code Starts. // Driver code to rest countSpecials functionint main() {// Testcase inputint testcase;cin >> testcase;while(testcase--){ // sizeof_array : number of array elements // K : as given in statement int sizeof_array, K; cin >> sizeof_array >> K; // array of size sizeof_array int arr[sizeof_array]; for(int i = 0;i<sizeof_array;i++){ cin >> arr[i]; } // calling function and printing count the occurrence cout << countSpecials(arr, sizeof_array, K) << endl; }return 0;} // } Driver Code Ends Whats the problem in countspecial function..am unable to understand. 0 hitentandon3 months ago JS Sol: let f = Math.floor(N/K), count = 0, cc=1; arr.sort(); for(let i = 1; i < N; i++) if(arr[i]==arr[i-1]) cc++; else if(cc===f) { count++; cc=1; } else cc=1; if(cc===f) count++; return count; C++ Sol: int f = floor(N/K), count = 0, cc=1; sort(arr, arr+N); for(int i = 1; i < N; i++) if(arr[i]==arr[i-1]) cc++; else if(cc==f) { count++; cc=1; } else cc=1; if(cc==f) count++; return count; +1 sourabhsingh191220014 months ago Easy C++ Solution int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), cnt = 0; unordered_map<int,int>mp; // Your code here for(int i=0;i<sizeof_array;i++){ if(mp.find(arr[i]) == mp.end()){ mp[arr[i]]=1; }else mp[arr[i]]++; } for(auto &i:mp){ if(i.second==f) cnt++; } return cnt; } 0 harshitd8914 months ago int countSpecials(int arr[], int N, int K){ int f = floor(N/K), count = 0;int array[1000];for(int i=0;i<1000;i++){array[i]=0; } for(int i=0;i<1000;i++){ if(i<N){ int p=arr[i]; array[p]=array[p]+1; } else{ break; }}for(int i=0;i<1000;i++){ if(array[i]==f){ count++; }} return count; } 0 ayushnautiyal11106 months ago int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; unordered_map<int,int>mp; for(int i=0;i<sizeof_array;i++){ mp[arr[i]]++; } for(auto it =mp.begin();it!=mp.end();it++){ if(it->second==f){ count++; } } return count;} 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": 456, "s": 278, "text": "Given an array A (may contain duplicates) of N elements and a positive integer K. The task is to count the number of elements which occurs exactly floor(N/K) times in the array." }, { "code": null, "e": 465, "s": 456, "text": "Example:" }, { "code": null, "e": 588, "s": 465, "text": "Input:N = 5K = 2A[] = 1 4 1 2 4Output:2Explanation:In the given array, 1 and 4 occurs floor(5/2) = 2 times. So count is 2." }, { "code": null, "e": 723, "s": 588, "text": "Your Task:Your task is to complete the function countSpecials() which should count the elements which occurs exactly floor(N/K) times." }, { "code": null, "e": 775, "s": 723, "text": "Constrains:1 <= N <= 1031 <= Ai <= 1031 <= K <= 103" }, { "code": null, "e": 777, "s": 775, "text": "0" }, { "code": null, "e": 797, "s": 777, "text": "hgaur7011 month ago" }, { "code": null, "e": 841, "s": 797, "text": "TIME COMPLEXITY : O(n+m) , TIME TAKEN : 0.0" }, { "code": null, "e": 857, "s": 841, "text": "BY USING MAP :-" }, { "code": null, "e": 1258, "s": 857, "text": "int countSpecials(int arr[], int sizeof_array, int K){\n \n int f = floor(sizeof_array/K), count = 0;\n \n int cot = 0;\n \n map<int, int> ob;\n map<int, int>::iterator it;\n\n for (int i = 0; i < sizeof_array; i++)\n {\n ob[arr[i]]++;\n }\n\n for (auto &&i : ob)\n {\n if (i.second == f)\n {\n count++;\n }\n }\n\n \n return count;\n \n}" }, { "code": null, "e": 1260, "s": 1258, "text": "0" }, { "code": null, "e": 1282, "s": 1260, "text": "sumitd12991 month ago" }, { "code": null, "e": 1346, "s": 1282, "text": "SIMPLEST CODE WITH LEAST TIME COMPLEXITY YOU WILL GET HERE IS :" }, { "code": null, "e": 1636, "s": 1348, "text": "int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int arr2[1000]={0}; // Your code here for(int i=0;i<sizeof_array;i++){ arr2[arr[i]]++; } for(int i=0;i<1000;i++){ if(arr2[i]==f){ count++; } }" }, { "code": null, "e": 1650, "s": 1636, "text": "return count;" }, { "code": null, "e": 1652, "s": 1650, "text": "}" }, { "code": null, "e": 1655, "s": 1652, "text": "+1" }, { "code": null, "e": 1676, "s": 1655, "text": "benklomp2 months ago" }, { "code": null, "e": 2394, "s": 1676, "text": "int countSpecials(int arr[], int n, int K)\n{\n int f = floor(n/K), count = 0;\n \n // Your code here\n \n // simple bubble sort\n for(int i = 0; i < n; ++i)\n for(int j = 0; j < n; ++j)\n if(arr[i] > arr[j])\n {\n int T = arr[i];\n arr[i] = arr[j];\n arr[j] = T;\n }\n \n int counter = 0, p = -1;\n for(int i = 0; i < n; i += 1)\n {\n if(arr[i] == p) continue;\n \n int counter = 1, j = i;\n while(++j < n && arr[i] == arr[j])\n ++counter;\n \n if(counter == f)\n ++count;\n \n p = arr[i];\n }\n \n return count;" }, { "code": null, "e": 2396, "s": 2394, "text": "0" }, { "code": null, "e": 2421, "s": 2396, "text": "sumitrodge272 months ago" }, { "code": null, "e": 2462, "s": 2421, "text": "i dont know how map works, someone help!" }, { "code": null, "e": 2900, "s": 2462, "text": "int countSpecials(int arr[], int sizeof_array, int K){\n \n int f = floor(sizeof_array/K), count = 0;\n int t=0;\n for(int i=0;i<sizeof_array;i++)\n {\n for(int j=0;j<sizeof_array;j++)\n {\n if(arr[i]==arr[j])\n {\n t++;\n }\n }\n if(t==f)\n {\n count++;\n }\n t=0;\n }\n \n count=ceil(count/f);\n \n return count;\n \n}" }, { "code": null, "e": 2902, "s": 2900, "text": "0" }, { "code": null, "e": 2927, "s": 2902, "text": "sumitrodge273 months ago" }, { "code": null, "e": 2977, "s": 2927, "text": "someone please tell me what's wrong with my code " }, { "code": null, "e": 3347, "s": 2979, "text": "int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int p=0; for(int i=0;i<sizeof_array;i++) { for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) { p+=1; } } if(p==f) { count+=1; } p=0; } return count; }" }, { "code": null, "e": 3352, "s": 3349, "text": "-2" }, { "code": null, "e": 3385, "s": 3352, "text": "dipawalimandaokar3213 months ago" }, { "code": null, "e": 3479, "s": 3385, "text": "// { Driver Code Starts//Initial Template for C++#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 3536, "s": 3479, "text": "// Function Prototypeint countSpecials(int[], int, int);" }, { "code": null, "e": 3590, "s": 3536, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 3938, "s": 3590, "text": "/*Function to count number of elements with occurrence* exactly equal to floor(sizeof_array/K)* arr : input array* sizeof_array : number of array elements*/int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K),p=0; for(int i=0;i<sizeof_array;i++) { int count; for(int j=0;j<sizeof_array;j++)" }, { "code": null, "e": 4082, "s": 3938, "text": " { if(arr[i]==arr[j]) count++ ; } if(count==f) p++; } // Your code here return p; }" }, { "code": null, "e": 4107, "s": 4082, "text": "// { Driver Code Starts." }, { "code": null, "e": 4651, "s": 4107, "text": "// Driver code to rest countSpecials functionint main() {// Testcase inputint testcase;cin >> testcase;while(testcase--){ // sizeof_array : number of array elements // K : as given in statement int sizeof_array, K; cin >> sizeof_array >> K; // array of size sizeof_array int arr[sizeof_array]; for(int i = 0;i<sizeof_array;i++){ cin >> arr[i]; } // calling function and printing count the occurrence cout << countSpecials(arr, sizeof_array, K) << endl; }return 0;} // } Driver Code Ends" }, { "code": null, "e": 4720, "s": 4651, "text": "Whats the problem in countspecial function..am unable to understand." }, { "code": null, "e": 4722, "s": 4720, "text": "0" }, { "code": null, "e": 4746, "s": 4722, "text": "hitentandon3 months ago" }, { "code": null, "e": 4754, "s": 4746, "text": "JS Sol:" }, { "code": null, "e": 5104, "s": 4754, "text": " let f = Math.floor(N/K), count = 0, cc=1;\n arr.sort();\n for(let i = 1; i < N; i++)\n if(arr[i]==arr[i-1])\n cc++;\n else if(cc===f)\n {\n count++;\n cc=1;\n }\n else\n cc=1;\n if(cc===f)\n count++;\n return count;" }, { "code": null, "e": 5113, "s": 5104, "text": "C++ Sol:" }, { "code": null, "e": 5401, "s": 5113, "text": " int f = floor(N/K), count = 0, cc=1;\n sort(arr, arr+N);\n for(int i = 1; i < N; i++)\n if(arr[i]==arr[i-1])\n cc++;\n else if(cc==f)\n {\n count++;\n cc=1;\n }\n else\n cc=1;\n if(cc==f)\n count++;\n return count;" }, { "code": null, "e": 5404, "s": 5401, "text": "+1" }, { "code": null, "e": 5437, "s": 5404, "text": "sourabhsingh191220014 months ago" }, { "code": null, "e": 5456, "s": 5437, "text": "Easy C++ Solution " }, { "code": null, "e": 5856, "s": 5456, "text": "int countSpecials(int arr[], int sizeof_array, int K){\n \n int f = floor(sizeof_array/K), cnt = 0;\n unordered_map<int,int>mp;\n \n // Your code here\n for(int i=0;i<sizeof_array;i++){\n if(mp.find(arr[i]) == mp.end()){\n mp[arr[i]]=1;\n }else\n mp[arr[i]]++;\n }\n for(auto &i:mp){\n if(i.second==f)\n cnt++;\n }\n \n return cnt;\n \n}" }, { "code": null, "e": 5858, "s": 5856, "text": "0" }, { "code": null, "e": 5882, "s": 5858, "text": "harshitd8914 months ago" }, { "code": null, "e": 6014, "s": 5882, "text": "int countSpecials(int arr[], int N, int K){ int f = floor(N/K), count = 0;int array[1000];for(int i=0;i<1000;i++){array[i]=0; }" }, { "code": null, "e": 6207, "s": 6014, "text": "for(int i=0;i<1000;i++){ if(i<N){ int p=arr[i]; array[p]=array[p]+1; } else{ break; }}for(int i=0;i<1000;i++){ if(array[i]==f){ count++; }} return count; } " }, { "code": null, "e": 6209, "s": 6207, "text": "0" }, { "code": null, "e": 6239, "s": 6209, "text": "ayushnautiyal11106 months ago" }, { "code": null, "e": 6547, "s": 6239, "text": "int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; unordered_map<int,int>mp; for(int i=0;i<sizeof_array;i++){ mp[arr[i]]++; } for(auto it =mp.begin();it!=mp.end();it++){ if(it->second==f){ count++; } } return count;}" }, { "code": null, "e": 6693, "s": 6547, "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": 6729, "s": 6693, "text": " Login to access your submissions. " }, { "code": null, "e": 6739, "s": 6729, "text": "\nProblem\n" }, { "code": null, "e": 6749, "s": 6739, "text": "\nContest\n" }, { "code": null, "e": 6812, "s": 6749, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6960, "s": 6812, "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": 7168, "s": 6960, "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": 7274, "s": 7168, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to create shadow in Android Buttons?
This example demonstrates how How to create shadow in Android Buttons. 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"?> <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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:width="200dp" android:layout_gravity="center" android:text="Shadow Button" android:background="@drawable/shadow_button_layer_list"/> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java package com.medkart.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 4 − Add the following code to res/drawable/shadow_button_layer_list.xml <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Gray shadow. --> <item android:left="3dp" android:top="5dp"> <shape> <solid android:color="@android:color/darker_gray" /> <corners android:radius="15dp" /> </shape> </item> <!-- White foreground. --> <item android:bottom="5dp" android:right="3dp"> <shape> <solid android:color="@android:color/white" /> <corners android:radius="15dp" /> </shape> </item> </layer-list> Step 5 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.medkart.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1133, "s": 1062, "text": "This example demonstrates how How to create shadow in Android Buttons." }, { "code": null, "e": 1263, "s": 1133, "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": 1329, "s": 1263, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2390, "s": 1329, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n 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 <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20dp\"\n android:width=\"200dp\"\n android:layout_gravity=\"center\"\n android:text=\"Shadow Button\"\n android:background=\"@drawable/shadow_button_layer_list\"/>\n</androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 2448, "s": 2390, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2769, "s": 2448, "text": "package com.medkart.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 2847, "s": 2769, "text": "Step 4 − Add the following code to res/drawable/shadow_button_layer_list.xml" }, { "code": null, "e": 3409, "s": 2847, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <!-- Gray shadow. -->\n <item android:left=\"3dp\" android:top=\"5dp\">\n <shape>\n <solid android:color=\"@android:color/darker_gray\" />\n <corners android:radius=\"15dp\" />\n </shape>\n </item>\n <!-- White foreground. -->\n <item android:bottom=\"5dp\" android:right=\"3dp\">\n <shape>\n <solid android:color=\"@android:color/white\" />\n <corners android:radius=\"15dp\" />\n </shape>\n </item>\n</layer-list>" }, { "code": null, "e": 3475, "s": 3409, "text": "Step 5 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 4152, "s": 3475, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.medkart.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4499, "s": 4152, "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": 4540, "s": 4499, "text": "Click here to download the project code." } ]
Privacy-Preserving Deep Learning with Federated Learning | Towards Data Science
Apple has recently announced a 47% YOY increase of its iPhone revenue with 49.26 million smartphones sold in the second quarter of 2021 [1]. For AAPL holders, this is absolutely good news. But what does it means for us, Data Science and AI enthusiasts? Well, let’s do some calculations here. On average, every human creates about 1.7 MB (Megabyte) of data per second [2] and people usually spends approximately 3 hours on their phone every day. This means 848.46 PB (Petabyte) of data generated from iPhones on a daily basis which is 200 times bigger than the amount of data generated on Facebook every day (around 4 PB). Remember that this is just the amount of data from iPhones alone. Although the numbers are not precise, you will now get the idea of how big this data is and why it becomes a new source of big data these days. As you might see, this copious source of data exceeds the size of information any single organisation can hold. These data can be used to create personalised experiences and it can help improve user satisfaction for the services or applications. Therefore, big organisations around the world are trying to utilise this new resource to increase the added value of their existing products or to create new business models around them. However, there are many challenges arising when using this type of information. Unlike traditional big data source which is centrally stored and managed by an organisation, data on mobile devices is often distributed at a large scale and owned by the users instead of the service providers. And because the users own it, they have the right to keep it private on their devices due to privacy concerns and this is, therefore, the biggest challenge for the service providers who want to utilise this data. On one hand, the business needs more data to serve their customers better but on the other hand, private data cannot be shared. Dealing with private and sensitive information is not easy, and the easiest approach to this problem is to not touch it. You rather don’t add the new feature using this data into the service than breach the user privacy and this is absolutely a valid point. However, if your competitors can somehow build AI applications with this data, provide better and personalised services without violating any privacy restrictions, then they will gain competitive advantages while you’re losing it. The technology that enables this capability will be a disruptive technology. Feel convinced now? let’s keep reading! Okay, so now you want to build an AI model on top of this gold mine of data without getting them out of users’ devices. When you think about data privacy and the related protections, encryption is one of the most popular methods in which data can be encrypted with user’s private key and then sent to the server. Nevertheless, encrypting also means you can no longer access the information since you don’t have the private keys from users. A rock is just a rock if you cannot get the gold inside. The solution is indeed simpler than what you might think of. Instead of loading all the data to your server for model training, you can ship the model training to users’ devices where the data belongs and where your users have complete control of the data. This is the key idea of Federated Learning. Federated Learning is a new paradigm of AI system architecture that essentially trains the model on client devices so that no private data will be sent out. There are generally four steps involved in the training process of Federated Learning: Step 1: start training the model on all devices participating in the Federated Learning using their local data. Step 2: devices send their locally trained models to the server. Note that it’s the model that is being uploaded instead of the private data. No private data will leave the devices. Step 3: server combines all models received from devices by using an aggregation algorithm. There are many aggregation algorithms developed by researchers but the most popular algorithm is Federated Averaging published by Google in 2017. Step 4: server distributes the aggregated model to all devices. The aggregated model can then be used to serve the AI features or be ready for the next training round if needed. Learning from everyone without knowing about anyone Aggregation algorithms play an important role in Federated Learning as it is responsible for combining the knowledge from all devices without knowing about users’ private data. In this article, I will only explain Federated Averaging (FedAvg) as it is a simple but effective algorithm that is being used in production for a Google’s product (although I am working on a new algorithm that can potentially beat the performance of FedAvg). Federated Averaging algorithm produces the aggregated model by taking the weighted average of all model updates. To help you understand this better, I will provide an oversimplified example ignoring the “weighted” part of the algorithm. Given a system with three devices, here is how their models are aggregated. - Device A sends model A with value 0.6 to the sever- Device B sends model B with value 0.1 to the sever- Device C sends model C with value 0.2 to the sever- Server takes the average of these three values: (0.6 + 0.1 + 0.2)/3 = 0.3- Server sends aggregated model with value 0.3 to A, B and C And that’s it! The algorithm is simple but putting them all together, this idea has been proved to be “productionisable” by Google when they use it for the next word prediction feature of their Google Keyboard product on billions of Android devices. Their Natural Language Processing (NLP) model is super accurate since it learns from billions of users from multiple languages and cultures. However, the advantage here is that no typing data is collected and user privacy constraint is respected. This is the competitive advantage you might want for your data product. You can check out the introduction from Google’s CEO, Sundar Pichai, about Federated Learning in this video: Federated Learning is an emerging technology being adopted, researched and developed by many organisations around the world because of its enormous potentials. One can use Federated Learning to build a super-powerful diagnostic AI model for hospitals while reserving the privacy of the patients. One can also train self-driving cars using the driving behaviours of real drivers on the street. Personalised recommendation systems based on personal data can also be built to recommend products or services matching the customer’s needs accurately (most of the recommendation systems these days are product-centric, not customer-centric). In terms of the maturity of this technology, Google has been using this in their products for a while now. Besides, there are many Federated Learning frameworks backed by big companies so that you don’t start from scratch when adopting this technology. Two frameworks that I have tried myself are OpenFL by Intel and TensorFlow Federated by Google. These frameworks provide easy-to-use programming interfaces so that your Data Scientists can build and deploy their first Federated Learning application with just a small piece of code. Every great opportunity comes with great challenges. Nevertheless, the biggest challenges, as usual, do not come from the technology itself but instead arise from the overall design of the product implementing the technology solution. When Google and Apple apply a new technology in Android and iOS, you’re opt-in by default as a user. They never ask you something like: “Will you give us access to your private and sensitive data to help improve your experience? We promise to not send your data out”. The minute you see this popup, I guess you will press “No Thanks” immediately. Since Google and Apple own the Operating System (OS), the users have no choice unless they stop using the device. However, as a company develops applications on top of the OS, you don’t have that luxury. Every time the app needs access to user’s data, it will still have to specifically ask for permission even though the data won’t be uploaded somewhere else. Imagine if you have to explain the “we only send the model out” part to your customers to get their permissions, you will realise that not only this is impossible but also the reputation of your organisation might be impacted as you sounds like a spy company unless you do it the way Facebook does (you know what I mean). Otherwise, your products or services must be valuable enough so that the users are willing to “compromise” their data even though your intention is to keep the data on their devices. When I use the word “compromise”, I am expressing the thinking of the user rather than the intention of the service provider. For example, everyone is making compromises when using Facebook since they are all aware that it is collecting their data but still, they keep using it. While customer’s consent is a challenge for B2C, it is an easier problem to solve for B2B. Two or more companies can agree upon a deal of sharing data that is beneficial for all parties and, in fact, this approach is quite popular these days. Now with Federated Learning, they can even share the data without actually sending it out. For instance, an Internet Service Provider (ISP) can exchange the internet traffic data of its users with a bank to build some advanced AI applications bringing values to both sides. The ISP can build a demand prediction model using its own data enriched by the transaction data from the bank. There might be a connection between the expenditure of a household with their internet usage. An example of this could be that a family have just visited a home entertainment retail store (those selling tablets, laptops and game consoles) and made the payment worth around $3000. That could also mean the family now have more smart devices at home and hence they will need more internet bandwidth. The prediction model can help the ISP offers better plans to their customers and be more initiative in their infrastructure planning. On the other hand, the bank can build a better cash flow forecasting model for their institutional clients (retail stores for example) using transaction data enriched with internet traffic data provided by the ISP. There might be a correlation between the amount of traffic to a specific website and the next-week revenue of the company owning that website. For example, the ISP reports an increase in traffic to the address www.theretailstore.com this week, the bank can then combine this information with the historical transaction data of this retail store to predict the revenue of next week because maybe the customers are looking for information on the website before they purchase the products. There are a lot more applications and ideas I can list out here and the potential is limitless. So whether it is B2B or B2C, you might want to think about the values you will get out of the data you can never access before because of the privacy concerns and investing in this technology in order to get competitive advantages against your competitors. Every great opportunity comes with great challenges and those who can manage the risks arising from those challenges will get the opportunity and disrupt the market. Apple sales miss expectations, Tim Cook says supply issues cost company $6 billionHow Much Data Is Created Every Day in 2021?Federated Learning: Collaborative Machine Learning without Centralized Training DataFederated Learning with GoogleIntel® Open Federated LearningTensorFlow Federated: Machine Learning on Decentralized DataCommunication-Efficient Learning of Deep Networks from Decentralized Data Apple sales miss expectations, Tim Cook says supply issues cost company $6 billion How Much Data Is Created Every Day in 2021? Federated Learning: Collaborative Machine Learning without Centralized Training Data Federated Learning with Google Intel® Open Federated Learning TensorFlow Federated: Machine Learning on Decentralized Data Communication-Efficient Learning of Deep Networks from Decentralized Data
[ { "code": null, "e": 418, "s": 165, "text": "Apple has recently announced a 47% YOY increase of its iPhone revenue with 49.26 million smartphones sold in the second quarter of 2021 [1]. For AAPL holders, this is absolutely good news. But what does it means for us, Data Science and AI enthusiasts?" }, { "code": null, "e": 853, "s": 418, "text": "Well, let’s do some calculations here. On average, every human creates about 1.7 MB (Megabyte) of data per second [2] and people usually spends approximately 3 hours on their phone every day. This means 848.46 PB (Petabyte) of data generated from iPhones on a daily basis which is 200 times bigger than the amount of data generated on Facebook every day (around 4 PB). Remember that this is just the amount of data from iPhones alone." }, { "code": null, "e": 1430, "s": 853, "text": "Although the numbers are not precise, you will now get the idea of how big this data is and why it becomes a new source of big data these days. As you might see, this copious source of data exceeds the size of information any single organisation can hold. These data can be used to create personalised experiences and it can help improve user satisfaction for the services or applications. Therefore, big organisations around the world are trying to utilise this new resource to increase the added value of their existing products or to create new business models around them." }, { "code": null, "e": 2062, "s": 1430, "text": "However, there are many challenges arising when using this type of information. Unlike traditional big data source which is centrally stored and managed by an organisation, data on mobile devices is often distributed at a large scale and owned by the users instead of the service providers. And because the users own it, they have the right to keep it private on their devices due to privacy concerns and this is, therefore, the biggest challenge for the service providers who want to utilise this data. On one hand, the business needs more data to serve their customers better but on the other hand, private data cannot be shared." }, { "code": null, "e": 2628, "s": 2062, "text": "Dealing with private and sensitive information is not easy, and the easiest approach to this problem is to not touch it. You rather don’t add the new feature using this data into the service than breach the user privacy and this is absolutely a valid point. However, if your competitors can somehow build AI applications with this data, provide better and personalised services without violating any privacy restrictions, then they will gain competitive advantages while you’re losing it. The technology that enables this capability will be a disruptive technology." }, { "code": null, "e": 2668, "s": 2628, "text": "Feel convinced now? let’s keep reading!" }, { "code": null, "e": 3165, "s": 2668, "text": "Okay, so now you want to build an AI model on top of this gold mine of data without getting them out of users’ devices. When you think about data privacy and the related protections, encryption is one of the most popular methods in which data can be encrypted with user’s private key and then sent to the server. Nevertheless, encrypting also means you can no longer access the information since you don’t have the private keys from users. A rock is just a rock if you cannot get the gold inside." }, { "code": null, "e": 3466, "s": 3165, "text": "The solution is indeed simpler than what you might think of. Instead of loading all the data to your server for model training, you can ship the model training to users’ devices where the data belongs and where your users have complete control of the data. This is the key idea of Federated Learning." }, { "code": null, "e": 3710, "s": 3466, "text": "Federated Learning is a new paradigm of AI system architecture that essentially trains the model on client devices so that no private data will be sent out. There are generally four steps involved in the training process of Federated Learning:" }, { "code": null, "e": 3822, "s": 3710, "text": "Step 1: start training the model on all devices participating in the Federated Learning using their local data." }, { "code": null, "e": 4004, "s": 3822, "text": "Step 2: devices send their locally trained models to the server. Note that it’s the model that is being uploaded instead of the private data. No private data will leave the devices." }, { "code": null, "e": 4242, "s": 4004, "text": "Step 3: server combines all models received from devices by using an aggregation algorithm. There are many aggregation algorithms developed by researchers but the most popular algorithm is Federated Averaging published by Google in 2017." }, { "code": null, "e": 4420, "s": 4242, "text": "Step 4: server distributes the aggregated model to all devices. The aggregated model can then be used to serve the AI features or be ready for the next training round if needed." }, { "code": null, "e": 4472, "s": 4420, "text": "Learning from everyone without knowing about anyone" }, { "code": null, "e": 4909, "s": 4472, "text": "Aggregation algorithms play an important role in Federated Learning as it is responsible for combining the knowledge from all devices without knowing about users’ private data. In this article, I will only explain Federated Averaging (FedAvg) as it is a simple but effective algorithm that is being used in production for a Google’s product (although I am working on a new algorithm that can potentially beat the performance of FedAvg)." }, { "code": null, "e": 5222, "s": 4909, "text": "Federated Averaging algorithm produces the aggregated model by taking the weighted average of all model updates. To help you understand this better, I will provide an oversimplified example ignoring the “weighted” part of the algorithm. Given a system with three devices, here is how their models are aggregated." }, { "code": null, "e": 5514, "s": 5222, "text": "- Device A sends model A with value 0.6 to the sever- Device B sends model B with value 0.1 to the sever- Device C sends model C with value 0.2 to the sever- Server takes the average of these three values: (0.6 + 0.1 + 0.2)/3 = 0.3- Server sends aggregated model with value 0.3 to A, B and C" }, { "code": null, "e": 6083, "s": 5514, "text": "And that’s it! The algorithm is simple but putting them all together, this idea has been proved to be “productionisable” by Google when they use it for the next word prediction feature of their Google Keyboard product on billions of Android devices. Their Natural Language Processing (NLP) model is super accurate since it learns from billions of users from multiple languages and cultures. However, the advantage here is that no typing data is collected and user privacy constraint is respected. This is the competitive advantage you might want for your data product." }, { "code": null, "e": 6192, "s": 6083, "text": "You can check out the introduction from Google’s CEO, Sundar Pichai, about Federated Learning in this video:" }, { "code": null, "e": 6828, "s": 6192, "text": "Federated Learning is an emerging technology being adopted, researched and developed by many organisations around the world because of its enormous potentials. One can use Federated Learning to build a super-powerful diagnostic AI model for hospitals while reserving the privacy of the patients. One can also train self-driving cars using the driving behaviours of real drivers on the street. Personalised recommendation systems based on personal data can also be built to recommend products or services matching the customer’s needs accurately (most of the recommendation systems these days are product-centric, not customer-centric)." }, { "code": null, "e": 7363, "s": 6828, "text": "In terms of the maturity of this technology, Google has been using this in their products for a while now. Besides, there are many Federated Learning frameworks backed by big companies so that you don’t start from scratch when adopting this technology. Two frameworks that I have tried myself are OpenFL by Intel and TensorFlow Federated by Google. These frameworks provide easy-to-use programming interfaces so that your Data Scientists can build and deploy their first Federated Learning application with just a small piece of code." }, { "code": null, "e": 7416, "s": 7363, "text": "Every great opportunity comes with great challenges." }, { "code": null, "e": 7598, "s": 7416, "text": "Nevertheless, the biggest challenges, as usual, do not come from the technology itself but instead arise from the overall design of the product implementing the technology solution." }, { "code": null, "e": 7945, "s": 7598, "text": "When Google and Apple apply a new technology in Android and iOS, you’re opt-in by default as a user. They never ask you something like: “Will you give us access to your private and sensitive data to help improve your experience? We promise to not send your data out”. The minute you see this popup, I guess you will press “No Thanks” immediately." }, { "code": null, "e": 9090, "s": 7945, "text": "Since Google and Apple own the Operating System (OS), the users have no choice unless they stop using the device. However, as a company develops applications on top of the OS, you don’t have that luxury. Every time the app needs access to user’s data, it will still have to specifically ask for permission even though the data won’t be uploaded somewhere else. Imagine if you have to explain the “we only send the model out” part to your customers to get their permissions, you will realise that not only this is impossible but also the reputation of your organisation might be impacted as you sounds like a spy company unless you do it the way Facebook does (you know what I mean). Otherwise, your products or services must be valuable enough so that the users are willing to “compromise” their data even though your intention is to keep the data on their devices. When I use the word “compromise”, I am expressing the thinking of the user rather than the intention of the service provider. For example, everyone is making compromises when using Facebook since they are all aware that it is collecting their data but still, they keep using it." }, { "code": null, "e": 9607, "s": 9090, "text": "While customer’s consent is a challenge for B2C, it is an easier problem to solve for B2B. Two or more companies can agree upon a deal of sharing data that is beneficial for all parties and, in fact, this approach is quite popular these days. Now with Federated Learning, they can even share the data without actually sending it out. For instance, an Internet Service Provider (ISP) can exchange the internet traffic data of its users with a bank to build some advanced AI applications bringing values to both sides." }, { "code": null, "e": 10250, "s": 9607, "text": "The ISP can build a demand prediction model using its own data enriched by the transaction data from the bank. There might be a connection between the expenditure of a household with their internet usage. An example of this could be that a family have just visited a home entertainment retail store (those selling tablets, laptops and game consoles) and made the payment worth around $3000. That could also mean the family now have more smart devices at home and hence they will need more internet bandwidth. The prediction model can help the ISP offers better plans to their customers and be more initiative in their infrastructure planning." }, { "code": null, "e": 10952, "s": 10250, "text": "On the other hand, the bank can build a better cash flow forecasting model for their institutional clients (retail stores for example) using transaction data enriched with internet traffic data provided by the ISP. There might be a correlation between the amount of traffic to a specific website and the next-week revenue of the company owning that website. For example, the ISP reports an increase in traffic to the address www.theretailstore.com this week, the bank can then combine this information with the historical transaction data of this retail store to predict the revenue of next week because maybe the customers are looking for information on the website before they purchase the products." }, { "code": null, "e": 11471, "s": 10952, "text": "There are a lot more applications and ideas I can list out here and the potential is limitless. So whether it is B2B or B2C, you might want to think about the values you will get out of the data you can never access before because of the privacy concerns and investing in this technology in order to get competitive advantages against your competitors. Every great opportunity comes with great challenges and those who can manage the risks arising from those challenges will get the opportunity and disrupt the market." }, { "code": null, "e": 11874, "s": 11471, "text": "Apple sales miss expectations, Tim Cook says supply issues cost company $6 billionHow Much Data Is Created Every Day in 2021?Federated Learning: Collaborative Machine Learning without Centralized Training DataFederated Learning with GoogleIntel® Open Federated LearningTensorFlow Federated: Machine Learning on Decentralized DataCommunication-Efficient Learning of Deep Networks from Decentralized Data" }, { "code": null, "e": 11957, "s": 11874, "text": "Apple sales miss expectations, Tim Cook says supply issues cost company $6 billion" }, { "code": null, "e": 12001, "s": 11957, "text": "How Much Data Is Created Every Day in 2021?" }, { "code": null, "e": 12086, "s": 12001, "text": "Federated Learning: Collaborative Machine Learning without Centralized Training Data" }, { "code": null, "e": 12117, "s": 12086, "text": "Federated Learning with Google" }, { "code": null, "e": 12148, "s": 12117, "text": "Intel® Open Federated Learning" }, { "code": null, "e": 12209, "s": 12148, "text": "TensorFlow Federated: Machine Learning on Decentralized Data" } ]
Tryit Editor v3.7
Tryit: A bordered list
[]
A single MySQL query to search multiple words from different column values
For this, you can use WHERE clause with multiple LIKE. Let us first create a table − mysql> create table DemoTable1536 -> ( -> Sentence text -> ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1536 values('I like MySQL database.'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1536 values('Java is an Object Oriented Programming Language'); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable1536 values('I only like data structure'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1536 values('MongoDB is NoSQL database'); Query OK, 1 row affected (0.46 sec) Display all records from the table using select statement − mysql> select * from DemoTable1536; This will produce the following output − +--------------------------------------------------+ | Sentence | +--------------------------------------------------+ | I like MySQL database. | | Java is an Object Oriented Programming Language | | I only like data structure | | MongoDB is NoSQL database | +--------------------------------------------------+ 4 rows in set (0.00 sec) Following is the query to search multiple words − mysql> select * from DemoTable1536 -> where ( Sentence like '%like%') or (Sentence like '%database%') or (Sentence like '%data%'); This will produce the following output − +----------------------------+ | Sentence | +----------------------------+ | I like MySQL database. | | I only like data structure | | MongoDB is NoSQL database | +----------------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1147, "s": 1062, "text": "For this, you can use WHERE clause with multiple LIKE. Let us first create a table −" }, { "code": null, "e": 1255, "s": 1147, "text": "mysql> create table DemoTable1536\n -> (\n -> Sentence text\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1311, "s": 1255, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1755, "s": 1311, "text": "mysql> insert into DemoTable1536 values('I like MySQL database.');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable1536 values('Java is an Object Oriented Programming Language');\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable1536 values('I only like data structure');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable1536 values('MongoDB is NoSQL database');\nQuery OK, 1 row affected (0.46 sec)" }, { "code": null, "e": 1815, "s": 1755, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1851, "s": 1815, "text": "mysql> select * from DemoTable1536;" }, { "code": null, "e": 1892, "s": 1851, "text": "This will produce the following output −" }, { "code": null, "e": 2341, "s": 1892, "text": "+--------------------------------------------------+\n| Sentence |\n+--------------------------------------------------+\n| I like MySQL database. |\n| Java is an Object Oriented Programming Language |\n| I only like data structure |\n| MongoDB is NoSQL database |\n+--------------------------------------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2391, "s": 2341, "text": "Following is the query to search multiple words −" }, { "code": null, "e": 2525, "s": 2391, "text": "mysql> select * from DemoTable1536\n -> where ( Sentence like '%like%') or (Sentence like '%database%') or (Sentence like '%data%');" }, { "code": null, "e": 2566, "s": 2525, "text": "This will produce the following output −" }, { "code": null, "e": 2808, "s": 2566, "text": "+----------------------------+\n| Sentence |\n+----------------------------+\n| I like MySQL database. |\n| I only like data structure |\n| MongoDB is NoSQL database |\n+----------------------------+\n3 rows in set (0.00 sec)" } ]
Categories of SQL Functions - GeeksforGeeks
02 Dec, 2021 SQL Functions are developed into Oracle Database and are available to use in various appropriate SQL Statements. Functions in SQL and User defined function in Pl/SQL both are different. In query, if you call a SQL function with an argument with different datatype other than expected by the function, then Oracle will convert the argument datatype to the expected datatype before performing the SQL function and if you call function with null argument, it will return null. Categories of Functions: 1. Single_row_function 2. Aggregate_function 3. Analytic_function 4. Model_function 5. User_defined_function 6. Scalar functions Some of these functions are explained as following below. Single row function: Single row functions are those functions which return a single result row for each row of queried table or view. This functions exists in Select lists, WHERE clause, START WITH, CONNECT BY clause and HAVING clause. Numeric_functionsCharacter_functionData_mining_functionDatetime_functionsConversion_functionCollection_functionXML_function Numeric_functions Character_function Data_mining_function Datetime_functions Conversion_function Collection_function XML_function Aggregate function: While using Aggregate function it will returns single row result based on group of rows, instead of single rows.Aggregate function appears in Select lists and ORDER BY and HAVING clause.They are usually used with GROUP BY clause and SELECT Statements. If you use GROUP BY clause, then Oracle applies aggregate function in the select list to all the rows in the queried table or view. All the Aggregate functions except GROUPING and COUNT(*) ignores null values. You can also use NVL function in the argument to an aggregate function to substitute a value in place of null. You can also nest aggregate functions.For example:- If you use GROUP BY clause, then Oracle applies aggregate function in the select list to all the rows in the queried table or view. All the Aggregate functions except GROUPING and COUNT(*) ignores null values. You can also use NVL function in the argument to an aggregate function to substitute a value in place of null. You can also nest aggregate functions.For example:- SELECT AVG(MAX(salary) FROM employees GROUP BY department_id AVG(MAX(salary)) ---------------- 10925 Most frequently used Aggregate functions are AVG, COUNT, DENSE_RANK, MAX, MIN, RANK, SUM. Analytic function: Analytic function calculate aggregate value based on group of rows.Difference between Analytic function and Aggregate function is they return multiple rows for each group. The group of rows is termed as window and it is defined by analytic_clause. Analytic function are the last set of operations performed in a query except the final ORDER BY clause. Analytic_clauseQuery_partition_clauseOrder_by_clauseWindowing_clause Analytic function are the last set of operations performed in a query except the final ORDER BY clause. Analytic_clause Query_partition_clause Order_by_clause Windowing_clause Model Functions: Within SELECT statements, Model Functions can be used with model_clause. Model Functions are: CVIteration_NumberPesentnnvPresentvPrevious Model Functions are: CV Iteration_Number Pesentnnv Presentv Previous User defined function: You can use User defined functions in PL/SQL or Java to provide functionality that is not available in SQL or SQL built in functions. SQL functions and User defined functions can be appear anywhere, that is, wherever an expression occur. For example, It can be used in: Select list of SELECT statement.Condition of WHERE clause.CONNECT BY, ORDER BY, START WITH and GROUP BYThe VALUES clause of INSERT statement.The SET clause of UPDATE statement. Basically we use CREATE Function to create User defined functions in SQL. For example, It can be used in: Select list of SELECT statement. Condition of WHERE clause. CONNECT BY, ORDER BY, START WITH and GROUP BY The VALUES clause of INSERT statement. The SET clause of UPDATE statement. Basically we use CREATE Function to create User defined functions in SQL. Scalar functions: You can use scalar functions in SQL to return a single value, based on the input value. Input: SELECT UCASE(geeksforgeeks) ; Output: GEEKSFORGEEKS Most frequently used Scalar functions are UCASE() to convert a field to upper case, LCASE() to convert a field to lower case, LEN() to find the length of a text field, ROUND() to round the number of decimals specified, NOW() to find the current system date and time. khushboogoyal499 surinderdawra388 sagar0719kumar germanshephered48 DBMS-SQL SQL-Functions DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS KDD Process in Data Mining Relational Model in DBMS What is Temporary Table in SQL? SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 24249, "s": 24221, "text": "\n02 Dec, 2021" }, { "code": null, "e": 24436, "s": 24249, "text": "SQL Functions are developed into Oracle Database and are available to use in various appropriate SQL Statements. Functions in SQL and User defined function in Pl/SQL both are different. " }, { "code": null, "e": 24725, "s": 24436, "text": "In query, if you call a SQL function with an argument with different datatype other than expected by the function, then Oracle will convert the argument datatype to the expected datatype before performing the SQL function and if you call function with null argument, it will return null. " }, { "code": null, "e": 24751, "s": 24725, "text": "Categories of Functions: " }, { "code": null, "e": 24882, "s": 24751, "text": "1. Single_row_function\n2. Aggregate_function\n3. Analytic_function\n4. Model_function\n5. User_defined_function \n6. Scalar functions " }, { "code": null, "e": 24941, "s": 24882, "text": "Some of these functions are explained as following below. " }, { "code": null, "e": 25301, "s": 24941, "text": "Single row function: Single row functions are those functions which return a single result row for each row of queried table or view. This functions exists in Select lists, WHERE clause, START WITH, CONNECT BY clause and HAVING clause. Numeric_functionsCharacter_functionData_mining_functionDatetime_functionsConversion_functionCollection_functionXML_function" }, { "code": null, "e": 25319, "s": 25301, "text": "Numeric_functions" }, { "code": null, "e": 25338, "s": 25319, "text": "Character_function" }, { "code": null, "e": 25359, "s": 25338, "text": "Data_mining_function" }, { "code": null, "e": 25378, "s": 25359, "text": "Datetime_functions" }, { "code": null, "e": 25398, "s": 25378, "text": "Conversion_function" }, { "code": null, "e": 25418, "s": 25398, "text": "Collection_function" }, { "code": null, "e": 25431, "s": 25418, "text": "XML_function" }, { "code": null, "e": 26077, "s": 25431, "text": "Aggregate function: While using Aggregate function it will returns single row result based on group of rows, instead of single rows.Aggregate function appears in Select lists and ORDER BY and HAVING clause.They are usually used with GROUP BY clause and SELECT Statements. If you use GROUP BY clause, then Oracle applies aggregate function in the select list to all the rows in the queried table or view. All the Aggregate functions except GROUPING and COUNT(*) ignores null values. You can also use NVL function in the argument to an aggregate function to substitute a value in place of null. You can also nest aggregate functions.For example:- " }, { "code": null, "e": 26210, "s": 26077, "text": "If you use GROUP BY clause, then Oracle applies aggregate function in the select list to all the rows in the queried table or view. " }, { "code": null, "e": 26452, "s": 26210, "text": "All the Aggregate functions except GROUPING and COUNT(*) ignores null values. You can also use NVL function in the argument to an aggregate function to substitute a value in place of null. You can also nest aggregate functions.For example:- " }, { "code": null, "e": 26566, "s": 26452, "text": "SELECT AVG(MAX(salary) \nFROM employees \nGROUP BY department_id\n\nAVG(MAX(salary))\n----------------\n 10925 " }, { "code": null, "e": 26657, "s": 26566, "text": "Most frequently used Aggregate functions are AVG, COUNT, DENSE_RANK, MAX, MIN, RANK, SUM. " }, { "code": null, "e": 27097, "s": 26657, "text": "Analytic function: Analytic function calculate aggregate value based on group of rows.Difference between Analytic function and Aggregate function is they return multiple rows for each group. The group of rows is termed as window and it is defined by analytic_clause. Analytic function are the last set of operations performed in a query except the final ORDER BY clause. Analytic_clauseQuery_partition_clauseOrder_by_clauseWindowing_clause" }, { "code": null, "e": 27202, "s": 27097, "text": "Analytic function are the last set of operations performed in a query except the final ORDER BY clause. " }, { "code": null, "e": 27218, "s": 27202, "text": "Analytic_clause" }, { "code": null, "e": 27241, "s": 27218, "text": "Query_partition_clause" }, { "code": null, "e": 27257, "s": 27241, "text": "Order_by_clause" }, { "code": null, "e": 27274, "s": 27257, "text": "Windowing_clause" }, { "code": null, "e": 27429, "s": 27274, "text": "Model Functions: Within SELECT statements, Model Functions can be used with model_clause. Model Functions are: CVIteration_NumberPesentnnvPresentvPrevious" }, { "code": null, "e": 27451, "s": 27429, "text": "Model Functions are: " }, { "code": null, "e": 27454, "s": 27451, "text": "CV" }, { "code": null, "e": 27471, "s": 27454, "text": "Iteration_Number" }, { "code": null, "e": 27481, "s": 27471, "text": "Pesentnnv" }, { "code": null, "e": 27490, "s": 27481, "text": "Presentv" }, { "code": null, "e": 27499, "s": 27490, "text": "Previous" }, { "code": null, "e": 28044, "s": 27499, "text": "User defined function: You can use User defined functions in PL/SQL or Java to provide functionality that is not available in SQL or SQL built in functions. SQL functions and User defined functions can be appear anywhere, that is, wherever an expression occur. For example, It can be used in: Select list of SELECT statement.Condition of WHERE clause.CONNECT BY, ORDER BY, START WITH and GROUP BYThe VALUES clause of INSERT statement.The SET clause of UPDATE statement. Basically we use CREATE Function to create User defined functions in SQL. " }, { "code": null, "e": 28077, "s": 28044, "text": "For example, It can be used in: " }, { "code": null, "e": 28110, "s": 28077, "text": "Select list of SELECT statement." }, { "code": null, "e": 28137, "s": 28110, "text": "Condition of WHERE clause." }, { "code": null, "e": 28183, "s": 28137, "text": "CONNECT BY, ORDER BY, START WITH and GROUP BY" }, { "code": null, "e": 28222, "s": 28183, "text": "The VALUES clause of INSERT statement." }, { "code": null, "e": 28333, "s": 28222, "text": "The SET clause of UPDATE statement. Basically we use CREATE Function to create User defined functions in SQL. " }, { "code": null, "e": 28440, "s": 28333, "text": "Scalar functions: You can use scalar functions in SQL to return a single value, based on the input value. " }, { "code": null, "e": 28500, "s": 28440, "text": "Input: SELECT UCASE(geeksforgeeks) ;\nOutput: GEEKSFORGEEKS " }, { "code": null, "e": 28768, "s": 28500, "text": "Most frequently used Scalar functions are UCASE() to convert a field to upper case, LCASE() to convert a field to lower case, LEN() to find the length of a text field, ROUND() to round the number of decimals specified, NOW() to find the current system date and time. " }, { "code": null, "e": 28785, "s": 28768, "text": "khushboogoyal499" }, { "code": null, "e": 28802, "s": 28785, "text": "surinderdawra388" }, { "code": null, "e": 28817, "s": 28802, "text": "sagar0719kumar" }, { "code": null, "e": 28835, "s": 28817, "text": "germanshephered48" }, { "code": null, "e": 28844, "s": 28835, "text": "DBMS-SQL" }, { "code": null, "e": 28858, "s": 28844, "text": "SQL-Functions" }, { "code": null, "e": 28863, "s": 28858, "text": "DBMS" }, { "code": null, "e": 28867, "s": 28863, "text": "SQL" }, { "code": null, "e": 28872, "s": 28867, "text": "DBMS" }, { "code": null, "e": 28876, "s": 28872, "text": "SQL" }, { "code": null, "e": 28974, "s": 28876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28983, "s": 28974, "text": "Comments" }, { "code": null, "e": 28996, "s": 28983, "text": "Old Comments" }, { "code": null, "e": 29021, "s": 28996, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 29064, "s": 29021, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 29091, "s": 29064, "text": "KDD Process in Data Mining" }, { "code": null, "e": 29116, "s": 29091, "text": "Relational Model in DBMS" }, { "code": null, "e": 29148, "s": 29116, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 29190, "s": 29148, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 29234, "s": 29190, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 29255, "s": 29234, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 29321, "s": 29255, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Spring Boot - Building RESTful Web Services
Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot. Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file. If you are a Maven user, use the following code to add the below dependency in your pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> If you are a Gradle user, use the following code to add the below dependency in your build.gradle file. compile('org.springframework.boot:spring-boot-starter-web') The code for complete build configuration file Maven build – pom.xml is given below − <?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for complete build configuration file Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = '1.5.8.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') } Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following annotations − The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below − @RestController public class ProductServiceController { } The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET. @RequestMapping(value = "/products") public ResponseEntity<Object> getProducts() { } The @RequestBody annotation is used to define the request body content type. public ResponseEntity<Object> createProduct(@RequestBody Product product) { } The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below − public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) { } The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here − public ResponseEntity<Object> getProduct( @RequestParam(value = "name", required = false, defaultValue = "honey") String name) { } The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL. The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored. Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class. Here, the request URI is /products, and it will return the String after storing the product into HashMap repository. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } } The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class. Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } } The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class. The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the Path variable {id} which defines the products ID that needs to be deleted. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } } This section gives you the complete set of source code. Observe the following codes for their respective functionalities − The Spring Boot main application class – DemoApplication.java package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The POJO class – Product.java package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } The Rest Controller class – ProductServiceController.java package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } You can create an executable JAR file, and run the spring boot application by using the below Maven or Gradle commands as shown − For Maven, use the command shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. You can run the JAR file by using the command shown below − java –jar <JARFILE> This will start the application on the Tomcat port 8080 as shown below − Now hit the URL shown below in POSTMAN application and see the output. GET API URL is: http://localhost:8080/products POST API URL is: http://localhost:8080/products PUT API URL is: http://localhost:8080/products/3 DELETE API URL is: http://localhost:8080/products/3 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3219, "s": 3025, "text": "Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot." }, { "code": null, "e": 3352, "s": 3219, "text": "Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file." }, { "code": null, "e": 3451, "s": 3352, "text": "If you are a Maven user, use the following code to add the below dependency in your pom.xml file −" }, { "code": null, "e": 3581, "s": 3451, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId> \n</dependency>" }, { "code": null, "e": 3685, "s": 3581, "text": "If you are a Gradle user, use the following code to add the below dependency in your build.gradle file." }, { "code": null, "e": 3746, "s": 3685, "text": "compile('org.springframework.boot:spring-boot-starter-web')\n" }, { "code": null, "e": 3832, "s": 3746, "text": "The code for complete build configuration file Maven build – pom.xml is given below −" }, { "code": null, "e": 5390, "s": 3832, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>demo</name>\n <description>Demo project for Spring Boot</description>\n \n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.8.RELEASE</version>\n <relativePath/> \n </parent>\n \n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n \n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n \n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>" }, { "code": null, "e": 5482, "s": 5390, "text": "The code for complete build configuration file Gradle Build – build.gradle is given below −" }, { "code": null, "e": 6066, "s": 5482, "text": "buildscript {\n ext {\n springBootVersion = '1.5.8.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter-web')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n}" }, { "code": null, "e": 6188, "s": 6066, "text": "Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following annotations −" }, { "code": null, "e": 6332, "s": 6188, "text": "The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below −" }, { "code": null, "e": 6392, "s": 6332, "text": "@RestController\npublic class ProductServiceController { \n}\n" }, { "code": null, "e": 6582, "s": 6392, "text": "The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET." }, { "code": null, "e": 6668, "s": 6582, "text": "@RequestMapping(value = \"/products\")\npublic ResponseEntity<Object> getProducts() { }\n" }, { "code": null, "e": 6745, "s": 6668, "text": "The @RequestBody annotation is used to define the request body content type." }, { "code": null, "e": 6824, "s": 6745, "text": "public ResponseEntity<Object> createProduct(@RequestBody Product product) {\n}\n" }, { "code": null, "e": 6986, "s": 6824, "text": "The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below −" }, { "code": null, "e": 7066, "s": 6986, "text": "public ResponseEntity<Object> updateProduct(@PathVariable(\"id\") String id) {\n}\n" }, { "code": null, "e": 7265, "s": 7066, "text": "The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here −" }, { "code": null, "e": 7400, "s": 7265, "text": "public ResponseEntity<Object> getProduct(\n @RequestParam(value = \"name\", required = false, defaultValue = \"honey\") String name) {\n}\n" }, { "code": null, "e": 7575, "s": 7400, "text": "The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL." }, { "code": null, "e": 7760, "s": 7575, "text": "The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored." }, { "code": null, "e": 7941, "s": 7760, "text": "Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint." }, { "code": null, "e": 8896, "s": 7941, "text": "package com.tutorialspoint.demo.controller;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.tutorialspoint.demo.model.Product;\n\n@RestController\npublic class ProductServiceController {\n private static Map<String, Product> productRepo = new HashMap<>();\n static {\n Product honey = new Product();\n honey.setId(\"1\");\n honey.setName(\"Honey\");\n productRepo.put(honey.getId(), honey);\n \n Product almond = new Product();\n almond.setId(\"2\");\n almond.setName(\"Almond\");\n productRepo.put(almond.getId(), almond);\n }\n @RequestMapping(value = \"/products\")\n public ResponseEntity<Object> getProduct() {\n return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);\n }\n}" }, { "code": null, "e": 9074, "s": 8896, "text": "The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL." }, { "code": null, "e": 9248, "s": 9074, "text": "The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class." }, { "code": null, "e": 9365, "s": 9248, "text": "Here, the request URI is /products, and it will return the String after storing the product into HashMap repository." }, { "code": null, "e": 10271, "s": 9365, "text": "package com.tutorialspoint.demo.controller;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.tutorialspoint.demo.model.Product;\n\n@RestController\npublic class ProductServiceController {\n private static Map<String, Product> productRepo = new HashMap<>();\n \n @RequestMapping(value = \"/products\", method = RequestMethod.POST)\n public ResponseEntity<Object> createProduct(@RequestBody Product product) {\n productRepo.put(product.getId(), product);\n return new ResponseEntity<>(\"Product is created successfully\", HttpStatus.CREATED);\n }\n}" }, { "code": null, "e": 10457, "s": 10271, "text": "The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL." }, { "code": null, "e": 10630, "s": 10457, "text": "The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class." }, { "code": null, "e": 10842, "s": 10630, "text": "Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated." }, { "code": null, "e": 11885, "s": 10842, "text": "package com.tutorialspoint.demo.controller;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\nimport com.tutorialspoint.demo.model.Product;\n\n@RestController\npublic class ProductServiceController {\n private static Map<String, Product> productRepo = new HashMap<>();\n \n @RequestMapping(value = \"/products/{id}\", method = RequestMethod.PUT)\n public ResponseEntity<Object> updateProduct(@PathVariable(\"id\") String id, @RequestBody Product product) { \n productRepo.remove(id);\n product.setId(id);\n productRepo.put(id, product);\n return new ResponseEntity<>(\"Product is updated successsfully\", HttpStatus.OK);\n } \n}" }, { "code": null, "e": 12084, "s": 11885, "text": "The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL." }, { "code": null, "e": 12248, "s": 12084, "text": "The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class." }, { "code": null, "e": 12451, "s": 12248, "text": "The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the Path variable {id} which defines the products ID that needs to be deleted." }, { "code": null, "e": 13397, "s": 12451, "text": "package com.tutorialspoint.demo.controller;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.tutorialspoint.demo.model.Product;\n\n@RestController\npublic class ProductServiceController {\n private static Map<String, Product> productRepo = new HashMap<>();\n \n @RequestMapping(value = \"/products/{id}\", method = RequestMethod.DELETE)\n public ResponseEntity<Object> delete(@PathVariable(\"id\") String id) { \n productRepo.remove(id);\n return new ResponseEntity<>(\"Product is deleted successsfully\", HttpStatus.OK);\n }\n}" }, { "code": null, "e": 13520, "s": 13397, "text": "This section gives you the complete set of source code. Observe the following codes for their respective functionalities −" }, { "code": null, "e": 13582, "s": 13520, "text": "The Spring Boot main application class – DemoApplication.java" }, { "code": null, "e": 13900, "s": 13582, "text": "package com.tutorialspoint.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class DemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n}" }, { "code": null, "e": 13930, "s": 13900, "text": "The POJO class – Product.java" }, { "code": null, "e": 14270, "s": 13930, "text": "package com.tutorialspoint.demo.model;\n\npublic class Product {\n private String id;\n private String name;\n\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 14328, "s": 14270, "text": "The Rest Controller class – ProductServiceController.java" }, { "code": null, "e": 16411, "s": 14328, "text": "package com.tutorialspoint.demo.controller;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\nimport com.tutorialspoint.demo.model.Product;\n\n@RestController\npublic class ProductServiceController {\n private static Map<String, Product> productRepo = new HashMap<>();\n static {\n Product honey = new Product();\n honey.setId(\"1\");\n honey.setName(\"Honey\");\n productRepo.put(honey.getId(), honey);\n \n Product almond = new Product();\n almond.setId(\"2\");\n almond.setName(\"Almond\");\n productRepo.put(almond.getId(), almond);\n }\n \n @RequestMapping(value = \"/products/{id}\", method = RequestMethod.DELETE)\n public ResponseEntity<Object> delete(@PathVariable(\"id\") String id) { \n productRepo.remove(id);\n return new ResponseEntity<>(\"Product is deleted successsfully\", HttpStatus.OK);\n }\n \n @RequestMapping(value = \"/products/{id}\", method = RequestMethod.PUT)\n public ResponseEntity<Object> updateProduct(@PathVariable(\"id\") String id, @RequestBody Product product) { \n productRepo.remove(id);\n product.setId(id);\n productRepo.put(id, product);\n return new ResponseEntity<>(\"Product is updated successsfully\", HttpStatus.OK);\n }\n \n @RequestMapping(value = \"/products\", method = RequestMethod.POST)\n public ResponseEntity<Object> createProduct(@RequestBody Product product) {\n productRepo.put(product.getId(), product);\n return new ResponseEntity<>(\"Product is created successfully\", HttpStatus.CREATED);\n }\n \n @RequestMapping(value = \"/products\")\n public ResponseEntity<Object> getProduct() {\n return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);\n }\n}" }, { "code": null, "e": 16541, "s": 16411, "text": "You can create an executable JAR file, and run the spring boot application by using the below Maven or Gradle commands as shown −" }, { "code": null, "e": 16582, "s": 16541, "text": "For Maven, use the command shown below −" }, { "code": null, "e": 16601, "s": 16582, "text": "mvn clean install\n" }, { "code": null, "e": 16678, "s": 16601, "text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory." }, { "code": null, "e": 16720, "s": 16678, "text": "For Gradle, use the command shown below −" }, { "code": null, "e": 16740, "s": 16720, "text": "gradle clean build\n" }, { "code": null, "e": 16824, "s": 16740, "text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory." }, { "code": null, "e": 16884, "s": 16824, "text": "You can run the JAR file by using the command shown below −" }, { "code": null, "e": 16906, "s": 16884, "text": "java –jar <JARFILE> \n" }, { "code": null, "e": 16979, "s": 16906, "text": "This will start the application on the Tomcat port 8080 as shown below −" }, { "code": null, "e": 17050, "s": 16979, "text": "Now hit the URL shown below in POSTMAN application and see the output." }, { "code": null, "e": 17097, "s": 17050, "text": "GET API URL is: http://localhost:8080/products" }, { "code": null, "e": 17145, "s": 17097, "text": "POST API URL is: http://localhost:8080/products" }, { "code": null, "e": 17194, "s": 17145, "text": "PUT API URL is: http://localhost:8080/products/3" }, { "code": null, "e": 17246, "s": 17194, "text": "DELETE API URL is: http://localhost:8080/products/3" }, { "code": null, "e": 17280, "s": 17246, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 17294, "s": 17280, "text": " Karthikeya T" }, { "code": null, "e": 17327, "s": 17294, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 17342, "s": 17327, "text": " Chaand Sheikh" }, { "code": null, "e": 17377, "s": 17342, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 17389, "s": 17377, "text": " Senol Atac" }, { "code": null, "e": 17424, "s": 17389, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 17436, "s": 17424, "text": " Senol Atac" }, { "code": null, "e": 17471, "s": 17436, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 17483, "s": 17471, "text": " Senol Atac" }, { "code": null, "e": 17516, "s": 17483, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 17528, "s": 17516, "text": " Senol Atac" }, { "code": null, "e": 17535, "s": 17528, "text": " Print" }, { "code": null, "e": 17546, "s": 17535, "text": " Add Notes" } ]
PyQt5 QCalendarWidget - Getting Selected Date - GeeksforGeeks
06 Aug, 2021 In this article we will see how we can get the selected date of QCalendarWidget, selected date is the date that is currently highlighted user can change the selected date using mouse and cursor by default selected date is the real-time date although we can set the selected date any time with the help of setSelectedDate method. Note : The selected date must be within the date range specified by the minimumDate and maximumDate properties. In order to do this we will use selectedDate method with the QCalendarWidget object.Syntax : calendar.selectedDate(date)Argument : It takes no argumentReturn : It returns QDate object Below is the implementation Python3 # importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # date date = QDate(2021, 1, 1) # setting selected date calendar.setSelectedDate(date) # creating label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 270, 250, 60) # making label multi line label.setWordWrap(True) # getting the selected date value = calendar.selectedDate() # setting text to the label label.setText("Selected Date: " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : clintra Python PyQt-QCalendarWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25112, "s": 25084, "text": "\n06 Aug, 2021" }, { "code": null, "e": 25441, "s": 25112, "text": "In this article we will see how we can get the selected date of QCalendarWidget, selected date is the date that is currently highlighted user can change the selected date using mouse and cursor by default selected date is the real-time date although we can set the selected date any time with the help of setSelectedDate method." }, { "code": null, "e": 25554, "s": 25441, "text": "Note : The selected date must be within the date range specified by the minimumDate and maximumDate properties. " }, { "code": null, "e": 25740, "s": 25554, "text": "In order to do this we will use selectedDate method with the QCalendarWidget object.Syntax : calendar.selectedDate(date)Argument : It takes no argumentReturn : It returns QDate object " }, { "code": null, "e": 25770, "s": 25740, "text": "Below is the implementation " }, { "code": null, "e": 25778, "s": 25770, "text": "Python3" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # date date = QDate(2021, 1, 1) # setting selected date calendar.setSelectedDate(date) # creating label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 270, 250, 60) # making label multi line label.setWordWrap(True) # getting the selected date value = calendar.selectedDate() # setting text to the label label.setText(\"Selected Date: \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27085, "s": 25778, "text": null }, { "code": null, "e": 27095, "s": 27085, "text": "Output : " }, { "code": null, "e": 27105, "s": 27097, "text": "clintra" }, { "code": null, "e": 27133, "s": 27105, "text": "Python PyQt-QCalendarWidget" }, { "code": null, "e": 27144, "s": 27133, "text": "Python-gui" }, { "code": null, "e": 27156, "s": 27144, "text": "Python-PyQt" }, { "code": null, "e": 27163, "s": 27156, "text": "Python" }, { "code": null, "e": 27261, "s": 27163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27270, "s": 27261, "text": "Comments" }, { "code": null, "e": 27283, "s": 27270, "text": "Old Comments" }, { "code": null, "e": 27301, "s": 27283, "text": "Python Dictionary" }, { "code": null, "e": 27333, "s": 27301, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27355, "s": 27333, "text": "Enumerate() in Python" }, { "code": null, "e": 27390, "s": 27355, "text": "Read a file line by line in Python" }, { "code": null, "e": 27420, "s": 27390, "text": "Iterate over a list in Python" }, { "code": null, "e": 27462, "s": 27420, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27505, "s": 27462, "text": "Python program to convert a list to string" }, { "code": null, "e": 27549, "s": 27505, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27570, "s": 27549, "text": "Python OOPs Concepts" } ]
C Program find nCr and nPr.
In C programming language, nCr is referred as the combination. nCr is the selection of r objects from a set of n objects, where the order of objects does not matter. nPr is referred as the permutation. nPr is arrangement of 'r' objects from a set of 'n' objects, which should be in an order or sequence. The formulas to find the permutation and combination of given numbers in C language are given below − nCr = n!/(r!*(n-r)!) nPr = n!/(n-r)!. The logic used to find nCr is as follows − result = factorial(n)/(factorial(r)*factorial(n-r)); The logic used to find nPr is as follows − result = factorial(n)/factorial(n-r); Following is the C program to find the permutation and combination of given numbers − #include <stdio.h> long factorial(int); long find_ncr(int, int); long find_npr(int, int); int main(){ int n, r; long ncr, npr; printf("Enter the value of n and r\n"); scanf("%d%d",&n,&r); ncr = find_ncr(n, r); npr = find_npr(n, r); printf("%dC%d = %ld\n", n, r, ncr); printf("%dP%d = %ld\n", n, r, npr); return 0; } long find_ncr(int n, int r) { long result; result = factorial(n)/(factorial(r)*factorial(n-r)); return result; } long find_npr(int n, int r) { long result; result = factorial(n)/factorial(n-r); return result; } long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result*c; return result; } When the above program is executed, it produces the following output − Enter the value of n and r 5 2 5C2 = 10 5P2 = 20
[ { "code": null, "e": 1228, "s": 1062, "text": "In C programming language, nCr is referred as the combination. nCr is the selection of r objects from a set of n objects, where the order of objects does not matter." }, { "code": null, "e": 1366, "s": 1228, "text": "nPr is referred as the permutation. nPr is arrangement of 'r' objects from a set of 'n' objects, which should be in an order or sequence." }, { "code": null, "e": 1468, "s": 1366, "text": "The formulas to find the permutation and combination of given numbers in C language are given below −" }, { "code": null, "e": 1489, "s": 1468, "text": "nCr = n!/(r!*(n-r)!)" }, { "code": null, "e": 1506, "s": 1489, "text": "nPr = n!/(n-r)!." }, { "code": null, "e": 1549, "s": 1506, "text": "The logic used to find nCr is as follows −" }, { "code": null, "e": 1602, "s": 1549, "text": "result = factorial(n)/(factorial(r)*factorial(n-r));" }, { "code": null, "e": 1645, "s": 1602, "text": "The logic used to find nPr is as follows −" }, { "code": null, "e": 1683, "s": 1645, "text": "result = factorial(n)/factorial(n-r);" }, { "code": null, "e": 1769, "s": 1683, "text": "Following is the C program to find the permutation and combination of given numbers −" }, { "code": null, "e": 2465, "s": 1769, "text": "#include <stdio.h>\nlong factorial(int);\nlong find_ncr(int, int);\nlong find_npr(int, int);\nint main(){\n int n, r;\n long ncr, npr;\n printf(\"Enter the value of n and r\\n\");\n scanf(\"%d%d\",&n,&r);\n ncr = find_ncr(n, r);\n npr = find_npr(n, r);\n printf(\"%dC%d = %ld\\n\", n, r, ncr);\n printf(\"%dP%d = %ld\\n\", n, r, npr);\n return 0;\n}\nlong find_ncr(int n, int r) {\n long result;\n result = factorial(n)/(factorial(r)*factorial(n-r));\n return result;\n}\nlong find_npr(int n, int r) {\n long result;\n result = factorial(n)/factorial(n-r);\n return result;\n}\nlong factorial(int n) {\n int c;\n long result = 1;\n for (c = 1; c <= n; c++)\n result = result*c;\n return result;\n}" }, { "code": null, "e": 2536, "s": 2465, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2585, "s": 2536, "text": "Enter the value of n and r\n5 2\n5C2 = 10\n5P2 = 20" } ]
Special Operators in SQL
The different special operators in SQL are as follows − ALL operator ANY Operator BETWEEN Operator EXISTS Operator IN Operator LIKE Operator Now let us create a table to understand the examples of special operators − <Employee> <Dependents> Details of all the special operators using the above tables are − The ALL operator compares a value with all the values returned by the subquery and is true only if the given condition is satisfied for all the values. For example − Select * from Employee Where Emp_Salary > ALL (select Emp_Salary from Employee where Emp_DeptID=30); This query returns the details of all the employees whose salary is greater than the salary of all the employees in Department number 30 i.e. Angel in this case. The ANY operator compares a value with all the values returned by the subquery and is true only if the given condition is satisfied for any value in the set of values. For example − Select * from Employee Where Emp_salary > ANY (select Emp_Salary from Employee where Emp_DeptID=30); This query returns the details of all the employees whose salary is greater than the salary of even one employee in Department number 30 i.e. Aaron, Harry, Angel and Will in this case. The BETWEEN operator returns the information within a given range of values, where the minimum and maximum of the range is specified. For example − Select * from Employee Where Emp_Salary BETWEEN 20000 AND 60000; This query returns information about all the employees whose salary is between the range of 20000 and 60000 i.e. Angel and Will in this case. The EXISTS operator only returns true if the subquery returns at least one record i.e if some data exists for the given subquery. For example − Select * from Employee Where EXISTS (select * from Dependents where Employee.Emp_ID=dependents.Emp_ID); This query will return results for only those employees who have any dependents i.e. Harry, Mary and Will. The IN operator is true if the query results in values that are contained in the list of constant values for the IN operator. For example − Select * from Employee Where Emp_ID IN (1,2,5); This query gives details about the employees whose Employee number is 1,2 or 5 i.e Aaron, Harry and Will. The LIKE operator is used to select the values that match the patterns specified in the query. Two wildcard operators are used for this. For example − Select * from Employee Where Emp_Name LIKE “A%” This query returns the data of all the employees whose name starts with A i.e. Aaron and Angel in our example.
[ { "code": null, "e": 1118, "s": 1062, "text": "The different special operators in SQL are as follows −" }, { "code": null, "e": 1131, "s": 1118, "text": "ALL operator" }, { "code": null, "e": 1144, "s": 1131, "text": "ANY Operator" }, { "code": null, "e": 1161, "s": 1144, "text": "BETWEEN Operator" }, { "code": null, "e": 1177, "s": 1161, "text": "EXISTS Operator" }, { "code": null, "e": 1189, "s": 1177, "text": "IN Operator" }, { "code": null, "e": 1203, "s": 1189, "text": "LIKE Operator" }, { "code": null, "e": 1279, "s": 1203, "text": "Now let us create a table to understand the examples of special operators −" }, { "code": null, "e": 1290, "s": 1279, "text": "<Employee>" }, { "code": null, "e": 1303, "s": 1290, "text": "<Dependents>" }, { "code": null, "e": 1369, "s": 1303, "text": "Details of all the special operators using the above tables are −" }, { "code": null, "e": 1535, "s": 1369, "text": "The ALL operator compares a value with all the values returned by the subquery and is true only if the given condition is satisfied for all the values. For example −" }, { "code": null, "e": 1636, "s": 1535, "text": "Select * from Employee\nWhere Emp_Salary > ALL (select Emp_Salary from Employee\nwhere Emp_DeptID=30);" }, { "code": null, "e": 1798, "s": 1636, "text": "This query returns the details of all the employees whose salary is greater than the salary of all the employees in Department number 30 i.e. Angel in this case." }, { "code": null, "e": 1980, "s": 1798, "text": "The ANY operator compares a value with all the values returned by the subquery and is true only if the given condition is satisfied for any value in the set of values. For example −" }, { "code": null, "e": 2081, "s": 1980, "text": "Select * from Employee\nWhere Emp_salary > ANY (select Emp_Salary from Employee\nwhere Emp_DeptID=30);" }, { "code": null, "e": 2266, "s": 2081, "text": "This query returns the details of all the employees whose salary is greater than the salary of even one employee in Department number 30 i.e. Aaron, Harry, Angel and Will in this case." }, { "code": null, "e": 2414, "s": 2266, "text": "The BETWEEN operator returns the information within a given range of values, where the minimum and maximum of the range is specified. For example −" }, { "code": null, "e": 2479, "s": 2414, "text": "Select * from Employee\nWhere Emp_Salary BETWEEN 20000 AND 60000;" }, { "code": null, "e": 2621, "s": 2479, "text": "This query returns information about all the employees whose salary is between the range of 20000 and 60000 i.e. Angel and Will in this case." }, { "code": null, "e": 2765, "s": 2621, "text": "The EXISTS operator only returns true if the subquery returns at least one record i.e if some data exists for the given subquery. For example −" }, { "code": null, "e": 2869, "s": 2765, "text": "Select * from Employee\nWhere EXISTS (select * from Dependents where\nEmployee.Emp_ID=dependents.Emp_ID);" }, { "code": null, "e": 2976, "s": 2869, "text": "This query will return results for only those employees who have any dependents i.e. Harry, Mary and Will." }, { "code": null, "e": 3116, "s": 2976, "text": "The IN operator is true if the query results in values that are contained in the list of constant values for the IN operator. For example −" }, { "code": null, "e": 3164, "s": 3116, "text": "Select * from Employee\nWhere Emp_ID IN (1,2,5);" }, { "code": null, "e": 3270, "s": 3164, "text": "This query gives details about the employees whose Employee number is 1,2 or 5 i.e Aaron, Harry and Will." }, { "code": null, "e": 3421, "s": 3270, "text": "The LIKE operator is used to select the values that match the patterns specified in the query. Two wildcard operators are used for this. For example −" }, { "code": null, "e": 3469, "s": 3421, "text": "Select * from Employee\nWhere Emp_Name LIKE “A%”" }, { "code": null, "e": 3580, "s": 3469, "text": "This query returns the data of all the employees whose name starts with A i.e. Aaron and Angel in our example." } ]
How to Get the names of the table in SQL - GeeksforGeeks
14 Aug, 2020 The syntax provided in this article works only for SQL Server and MySQL. If you want to know how many tables are present in your database and the details of the table like TABLE_SCHEMA, TABLE_TYPE and all. Syntax (When we have only single database): Select * from schema_name.table_name Syntax (When we have multiple databases): Select * from database_name.schema_name.table_name Example: SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE 1. INFORMATION_SCHEMA views allow you to retrieve metadata about the objects within a database. These views can be found in the master database under Views / System Views and be called from any database in your SQL Server instance. 2. INFORMATION_SCHEMA.TABLES The INFORMATION_SCHEMA.TABLES view allows you to get information about all tables and views within a database. Output: khushboogoyal499 SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database Difference between SQL and NoSQL SQL | Views Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE SQL | GROUP BY What is Cursor in SQL ? How to Update Multiple Columns in Single Update Statement in SQL? SQL | TRANSACTIONS CTE in SQL
[ { "code": null, "e": 24212, "s": 24184, "text": "\n14 Aug, 2020" }, { "code": null, "e": 24286, "s": 24212, "text": "The syntax provided in this article works only for SQL Server and MySQL. " }, { "code": null, "e": 24420, "s": 24286, "text": "If you want to know how many tables are present in your database and the details of the table like TABLE_SCHEMA, TABLE_TYPE and all. " }, { "code": null, "e": 24466, "s": 24420, "text": "Syntax (When we have only single database): " }, { "code": null, "e": 24503, "s": 24466, "text": "Select * from schema_name.table_name" }, { "code": null, "e": 24546, "s": 24503, "text": "Syntax (When we have multiple databases): " }, { "code": null, "e": 24597, "s": 24546, "text": "Select * from database_name.schema_name.table_name" }, { "code": null, "e": 24607, "s": 24597, "text": "Example: " }, { "code": null, "e": 24648, "s": 24607, "text": "SELECT * FROM INFORMATION_SCHEMA.TABLES " }, { "code": null, "e": 24655, "s": 24648, "text": "WHERE " }, { "code": null, "e": 24888, "s": 24655, "text": "1. INFORMATION_SCHEMA views allow you to retrieve metadata about the objects within a database. These views can be found in the master database under Views / System Views and be called from any database in your SQL Server instance. " }, { "code": null, "e": 25029, "s": 24888, "text": "2. INFORMATION_SCHEMA.TABLES The INFORMATION_SCHEMA.TABLES view allows you to get information about all tables and views within a database. " }, { "code": null, "e": 25039, "s": 25029, "text": "Output: " }, { "code": null, "e": 25058, "s": 25041, "text": "khushboogoyal499" }, { "code": null, "e": 25062, "s": 25058, "text": "SQL" }, { "code": null, "e": 25066, "s": 25062, "text": "SQL" }, { "code": null, "e": 25164, "s": 25066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25173, "s": 25164, "text": "Comments" }, { "code": null, "e": 25186, "s": 25173, "text": "Old Comments" }, { "code": null, "e": 25217, "s": 25186, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 25250, "s": 25217, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 25262, "s": 25250, "text": "SQL | Views" }, { "code": null, "e": 25301, "s": 25262, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25346, "s": 25301, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 25361, "s": 25346, "text": "SQL | GROUP BY" }, { "code": null, "e": 25385, "s": 25361, "text": "What is Cursor in SQL ?" }, { "code": null, "e": 25451, "s": 25385, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25470, "s": 25451, "text": "SQL | TRANSACTIONS" } ]
The Future of Machine Learning and why it looks a lot like Julia 🤖 | by Logan Kilpatrick | Towards Data Science
TLDR; the future of ML is Julia. If you are looking for a quick answer, there you have it. If you want the well reasoned explanation, stick around. And don’t just take my word for it: dev-discuss.pytorch.org (The post above summarized: PyTorch devs want all the features Julia provides, but they don’t want to re-write PyTorch in Julia yet because the ecosystem isn’t mature enough) First, let me address the elephant in the room: the Julia ecosystem is not as mature as the Python ecosystem, yet. This is the present reality, but as you might discover in this post, that does not mean you can’t use Julia successfully in your machine learning workflows. Below, I will give a brief overview of the Julia Machine Learning and Deep Learning ecosystem and then talk about why you might want to learn Julia for your ML and DL workflows. We will explore the following ideas which I think make Julia a prime candidate for use in the ML space: You get to use Julia, so you get all the benefits Julia provides 🧑‍🤝‍🧑 Flexible and Extensible 💪 It’s (actually) open source 👐 Easy to use the internals 🍳 ML + Science = breakthrough results 🧬🧪 And more! If you want to do Machine Learning in Julia, there are a few places you should look: Flux.jl, Deep Learning (Ecosystem Overview) MLJ.jl, General Machine Learning Knet.jl, Deep Learning JuliaML, GitHub org hosting common ML packages JuliaAI, hosts repos for the MLJ ecosystem FastAI.jl, Repository of best practices for deep learning in Julia In general during this post, we will focus on Flux.jl as a Deep Learning framework but that is not to say Knet and MLJ are not well made or useful packages. I simply have less experience using them so I will save my impression for a later post. As a language, Julia is designed to enable developer productivity. From the package manager, to the speed of running code, all of these features lead to a developer experience which is bringing in whole swaths of new developers. I mentioned this in my post on: medium.com but because of the way Julia handles things like Multi Dimensional arrays, you can avoid using packages like Numpy (which you would sometimes see in Tensorflow) and Tensors (which are used in PyTorch and basically a re-branded Numpy array). Here we can see the benefit of using Julia results in less mental overhead. In the case of Python, we can do: import tensorflow as tftf.ones([3, 4], tf.int32)<tf.Tensor: shape=(3, 4), dtype=int32, numpy=array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], dtype=int32)> And then in Julia we would do something like: julia> using Fluxjulia> ones(Float32, 1, 2, 3)1×2×3 Array{Float32, 3}:[:, :, 1] = 1.0 1.0[:, :, 2] = 1.0 1.0[:, :, 3] = 1.0 1.0 In the latter case, we are working with just basic arrays which at least in my opinion, makes the code a little bit more intuitive. Another point that was mentioned in the above post that bears re-iterating is the rest of the packages you would use in a Data Science / Machine Learning workflow are blazing fast in Julia. Loading CSV’s is 10–20x faster than in Python and DataFrames.jl (the analog to Pandas) also has best in class speed and performance (especially for a rather “young” package that just hit it’s 1.0 release in 2021). If you are not yet convinced at the power of Julia and that it will enable you to be more productive, do a quick search for “Why should I switch to Julia” and you will find plenty of other (hopefully compelling) literature that goes into more depth than I want to here. I tried to answer that in this 1 minute video: I also encourage you to check out https://fluxml.ai for a high level overview. An extensible system is one whose internal structure and dataflow are minimally or not affected by new or modified functionality... (via Wikipedia) Both Flexibility and Extensibility are front of mind in the design of Flux. For starters, Flux can be used to write models directly but can also be used as a backend for packages like FastAI.jl. Additionally, Flux tries to keep a minimal yet useful API such that developers have the freedom to use what is provided or build on it with their own custom functions which integrate into the Flux ecosystem automatically. If you have ever spent any significant amount of time exploring https://www.tensorflow.org/api_docs/python/tf, you will have discovered like I did that there is a lot going on (just take a look on the left hand side at all of the modules). Conversely, Flux focuses on keeping the amount of code and documentation in Flux itself minimal. Take a quick peek at the docs if you haven’t: https://fluxml.ai/Flux.jl/stable/ An example of just how simple Flux is to use: using Fluxmodel = Chain(Dense(10, 5, σ), Dense(5, 2), softmax) Here we define a simple model with 3 layers: 2 dense layers (one using the sigmoid activation function) and a softmax layer. In Tensorflow, this would look like: from keras.models import * from keras.layers import * model = Sequential([Dense(10, 'sigmoid'), Dense(5), Dense(2, 'softmax')])# Thanks to Stanisław Pitucha for the updated Keras / TF code In the case of Tensorflow, we can see that because we use the Sequential() model, we don’t actually specify the output size of the layers. The sequential nature of the model sets the output of one layer to be the input of the following layer. While libraries like PyTorch do give instructions on how to extend the library, as is noted in the docs: https://pytorch.org/docs/stable/notes/extending.html there are far more limitations than in Flux. I don’t want to harp on this topic too long, but projects claiming to be “Open” when a majority of contributors are concentrated at a single institution are always a worry to me. In fact, this is one of the things we look at when we evaluate new projects joining NumFOCUS (the non-profit behind Jupyter, Pandas, Numpy, Julia, Flux, etc). To me, a core feature of Flux is that it is not being developed by Google (in Jax and Tensorflow’s case) or Facebook (in PyTorch’s case). While there is certainly a whole host of benefits of having that backing (like lots of money to pay people 😄), if I was a user making a decision about what framework I want to build my company or project around, my preference would be one where I could be an actual stakeholder. In the case of Flux, if you want to start contributing and being a stakeholder, we would love to have you. You can jump in and start contributing to the ecosystem: https://github.com/FluxML/Flux.jl/blob/master/CONTRIBUTING.md or drop by a bi-weekly dev call: https://julialang.org/community/#events. I will again note that this isn’t meant to be a slight at the Tensorflow or PyTorch community since I know many valuable contributions come from outside the host institution, but at a high level I think the idea is worth keeping in mind. If you are wondering about the emoji choice here, it is because cooking eggs is easy, almost as easy as using Flux’s internals. Now that we have settled that mystery, let’s dive in and look at why Flux’s internals are so easy to use. Spoiler, it is because they are written in Julia. And when I say written in Julia, I mean 100% written in Julia. Take a peek at: https://github.com/FluxML/Flux.jl if you don’t believe me. The image above is in stark contrast to Tensorflow and PyTorch: Your eyes are not deceiving you, PyTorch and Tensorflow, if you are not aware, are both written mainly in C++ with a Python wrapper for users. This means that if you want to take a peek under the hood, you have to be comfortable not only with C++ and Python but also the way in which they interact. For me I am still scared by having to use pointers my freshman year of college so if I can avoid C++, I do. If we look at an example of some of the internal of Flux, as noted before, it is Julia, just plain old Julia: function onehot(x, labels, default) i = something(findfirst(isequal(x), labels), 0) i > 0 || return onehot(default, labels) OneHotVector{UInt32, length(labels)}(i)end Here we are looking at one of the definitions of a onehot encoding in Flux. I don’t see any pointers there, which is a relief. I will avoid showing any C++ code here just to make a point since I don’t want to scare you off, but if you are bold, go check out some of the internals. One of the side effects of the easy to use internals and 100% Julia code is that users of a package can very quickly become developers and critical contributors. I have seen this happen for myself as I have used Flux over the last few months. While contributing is still difficult, it is without a doubt easier to jump in than it would be in the case of other frameworks. A basic example of this is: https://github.com/FluxML/Flux.jl/pull/1801 where I found it odd that calling the gpu function on some code did not provide any warning or indication that the code was in fact not being run on the GPU. One of the areas that Flux excels is in the combination of it and other packages to create state of the art results. One example of this is https://github.com/SciML/DiffEqFlux.jl which provides: Universal neural differential equations with O(1) backprop, GPUs, and stiff+non-stiff DE solvers, demonstrating scientific machine learning (SciML) and physics-informed machine learning methods Now unless you are Chris Rackauckas, you might be asking yourself what that even means. You are not alone friend. When I read that for the first time, my brain nearly shut down for good. At a high level, Ordinary Differential equations are used to model natural processes like Population Growth and Decay, Glucose Absorption by the Body, and even the Spread of Epidemics. Neural ODE’s allow us to create a more robust system that does not rely on a fixed number of preset layers in a model. While this can lead to lower performance, the result in many cases is higher speed. You can read this paper for details: https://arxiv.org/abs/1806.07366 or alternatively this medium post: https://towardsdatascience.com/differential-equations-as-a-neural-network-layer-ac3092632255 DiffEqFlux.jl provides the following features: - Neural networks can be defined where the “activations” are nonlinear functions described by differential equations - Neural networks can be defined where some layers are ODE solves - ODEs can be defined where some terms are neural networks - Cost functions on ODEs can define neural networks Another good resource to check out is the release blog post: https://julialang.org/blog/2019/01/fluxdiffeq/ I will be honest and say that I have yet to get my hands dirty with DiffEqFlux. It is one of the things on my todo list the big take away for me is that Flux is enabling this sort of innovation which I find fascinating. I suggest you check out one of the many great talks Chris has given on the topic: I would also suggest checking out: where Dhairya Gandhi goes over many of the places where Flux is being used in the scientific community / ecosystem. Under active development is DaggerFlux.jl which will provide model parallelism (the ability to train a model on different devices / nodes in parallel) which is critically important to ensure that Flux remains competitive in the ML arms race. There has also been a lot of active work in getting Julia setup to work on TPU’s (Googles custom ML hardware): https://github.com/JuliaTPU/XLA.jl though the project seems to be in a holding pattern at the moment. Despite this, it is still an area where Julia can be used. Just as a simple point of comparison, let’s look at how long it takes to do a basic gradient in Flux vs Tensorflow. In Flux, we will do the following: julia> using Fluxjulia> f(x) = 3x^2 + 2x + 1; # define our functionjulia> @time df(x) = gradient(f, x)[1]; 0.006222 seconds (995 allocations: 73.773 KiB, 44.35% compilation time) # longer time on the first run, Julia is compiledjulia> @time df(x) = gradient(f, x)[1];0.000241 seconds (20 allocations: 1.234 KiB)julia> @time df(2)0.000001 seconds14.0julia> @time df(2)0.000000 seconds14.0 Now, let’s look at an example in Tensorflow using Gradient tapes: import tensorflow as tfimport timestart = time.time()x = tf.Variable(3.0)with tf.GradientTape() as tape: y = x**2# dy = 2x * dxdy_dx = tape.gradient(y, x)dy_dx.numpy()end = time.time() - startprint(end) # 0.002371072769165039 I will note that I had to run the Python example on Google Colab since my Tensorflow installation broke midway through this tutorial and my normal go to guide for installing it on the M1 resulted in an entire terminal buffer filled with red text and errors. Perfect time to mention that Julia runs natively on the M1 mac and many other platforms: https://julialang.org/downloads/#current_stable_release Again at a high level, this tutorial seems relevant since under the hood, machine learning is just taking gradients. One of the biggest areas that Flux is behind other ML libraries is in community written content. If I want to do something in TF or PyTorch, it really is usually one search away. This is something we are working on in the Flux community. If you are interested in contributing to this work, which it is worth noting is extremely high impact, please check out: https://github.com/FluxML/fluxml.github.io/issues/107 If you want to get involved beyond just writing tutorials, the contributing guide here: https://github.com/FluxML/Flux.jl/blob/master/CONTRIBUTING.md is a good place to start. Transfer learning is one of the coolest things about Machine Learning. We can take models built for a specific use-case and fine tune them to fit a new use-case. Let us compare the code for transfer learning between Tensorflow and Julia. You can find the Julia code on GitHub: github.com under: https://github.com/logankilpatrick/DeepLearningWithJulia/blob/main/src/transfer_learning.ipynb and a Tensorflow example here: https://www.tensorflow.org/tutorials/images/transfer_learning One of the big differences that is worth calling out is the way that data and specifically images are handled in each framework. In my opinion, actual machine learning is easy and rather trivial in many cases. The challenge programmatically speaking is to get your data in the form in which it can be inputted to a machine learning model (and cleaned). In this case, we can look at Tensorflow: train_dataset = tf.keras.utils.image_dataset_from_directory(train_dir, shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE) To me, a function like this is what makes using frameworks like Tensorflow so easy. PyTorch also has many similar functions which make working with data simple. I think that Flux could benefit greatly from a unified interface for loading images and other common forms of data in ML. If we look at the Julia example, we are actually writing the loading code from scratch which I have documented. Again, this is actually more difficult than most of the other code that is used in the transfer learning example. const DOGS = filter(x -> occursin("dog", x), FILES)const CATS = filter(x -> occursin("cat", x), FILES)function load_batch(batchsize = 10, imagesize = (224,224); path = PATH) if ((batchsize % 2) != 0) print("Batch size must be an even number") end imgs_paths = shuffle(vcat(sample(DOGS, Int(batchsize/2)), sample(CATS, Int(batchsize/2)))) labels = map(x -> occursin("dog.", x) ? 1 : 2, imgs_paths) labels = Flux.onehotbatch(labels, [1, 2]) imgs = Images.load.(imgs_paths) imgs = map(img -> Images.imresize(img, imagesize...), imgs) imgs = map(img -> permutedims(channelview(img), (3, 2, 1)), imgs) imgs = cat(imgs..., dims = 4) Float32.(imgs), labelsend Another difference in the code that we see is in image augmentations: data_augmentation = tf.keras.Sequential([ tf.keras.layers.RandomFlip('horizontal'), tf.keras.layers.RandomRotation(0.2),]) Here we can see the TF code to do a random flip and rotation. In the case of Julia, we would need to use: https://github.com/Evizero/Augmentor.jl julia> pl = FlipX(0.5) |> Rotate(0:20) |>julia> img_new = augment(img, pl) # here we apply the augmentation Again, from a usability standpoint, there would be benefits in my view to having image augmentation as part of the core package but the idea of extracting it out to keep things minimal is understandable. Lastly, let us look at the model definition itself in Julia: model = Chain( resnet[1:end-2], Dense(2048, 1000, σ), Dense(1000, 256, σ), Dense(256, 2), softmax ); Here we take a pre-trained Resnet and grab all its layers except the last two which we will replace with our new fine tuned layers. In Tensorflow, we would do something to the effect of: base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')inputs = tf.keras.Input(shape=(160, 160, 3))x = data_augmentation(inputs)x = preprocess_input(x)x = base_model(x, training=False)x = global_average_layer(x)x = tf.keras.layers.Dropout(0.2)(x)outputs = prediction_layer(x)model = tf.keras.Model(inputs, outputs) This is one of the ways of creating a model in TF (and Flux has a similar approach) where to define the inputs and ouputs instead of the model layers but I prefer to create the model using the format we saw using the Julia chain function. While Tensorflow.jl is no longer being actively developed, you can still use Tensorflow (and any python code for that matter) in Julia. Torch.jl is also actively maintained: https://github.com/FluxML/Torch.jl which provides a wrapper of PyTorch’s C++ code in Julia. If you are interested in reading more about integrating Python and Julia together, check out: towardsdatascience.com My goal of this post was to convince someone who is unsure about using Julia for Machine Learning that it is worth while to try it. I also hope that my mention of areas where the Flux ecosystem needs further development sets the right expectation that things are not perfect, but they are definitely at the point where you can do serious science and ML. If you have comments on this post, please get in touch with me: https://twitter.com/OfficialLoganK or if you want to help out on Flux, we would love to have you!
[ { "code": null, "e": 356, "s": 172, "text": "TLDR; the future of ML is Julia. If you are looking for a quick answer, there you have it. If you want the well reasoned explanation, stick around. And don’t just take my word for it:" }, { "code": null, "e": 380, "s": 356, "text": "dev-discuss.pytorch.org" }, { "code": null, "e": 555, "s": 380, "text": "(The post above summarized: PyTorch devs want all the features Julia provides, but they don’t want to re-write PyTorch in Julia yet because the ecosystem isn’t mature enough)" }, { "code": null, "e": 827, "s": 555, "text": "First, let me address the elephant in the room: the Julia ecosystem is not as mature as the Python ecosystem, yet. This is the present reality, but as you might discover in this post, that does not mean you can’t use Julia successfully in your machine learning workflows." }, { "code": null, "e": 1109, "s": 827, "text": "Below, I will give a brief overview of the Julia Machine Learning and Deep Learning ecosystem and then talk about why you might want to learn Julia for your ML and DL workflows. We will explore the following ideas which I think make Julia a prime candidate for use in the ML space:" }, { "code": null, "e": 1180, "s": 1109, "text": "You get to use Julia, so you get all the benefits Julia provides 🧑‍🤝‍🧑" }, { "code": null, "e": 1206, "s": 1180, "text": "Flexible and Extensible 💪" }, { "code": null, "e": 1236, "s": 1206, "text": "It’s (actually) open source 👐" }, { "code": null, "e": 1264, "s": 1236, "text": "Easy to use the internals 🍳" }, { "code": null, "e": 1303, "s": 1264, "text": "ML + Science = breakthrough results 🧬🧪" }, { "code": null, "e": 1313, "s": 1303, "text": "And more!" }, { "code": null, "e": 1398, "s": 1313, "text": "If you want to do Machine Learning in Julia, there are a few places you should look:" }, { "code": null, "e": 1442, "s": 1398, "text": "Flux.jl, Deep Learning (Ecosystem Overview)" }, { "code": null, "e": 1475, "s": 1442, "text": "MLJ.jl, General Machine Learning" }, { "code": null, "e": 1498, "s": 1475, "text": "Knet.jl, Deep Learning" }, { "code": null, "e": 1545, "s": 1498, "text": "JuliaML, GitHub org hosting common ML packages" }, { "code": null, "e": 1588, "s": 1545, "text": "JuliaAI, hosts repos for the MLJ ecosystem" }, { "code": null, "e": 1655, "s": 1588, "text": "FastAI.jl, Repository of best practices for deep learning in Julia" }, { "code": null, "e": 1900, "s": 1655, "text": "In general during this post, we will focus on Flux.jl as a Deep Learning framework but that is not to say Knet and MLJ are not well made or useful packages. I simply have less experience using them so I will save my impression for a later post." }, { "code": null, "e": 2129, "s": 1900, "text": "As a language, Julia is designed to enable developer productivity. From the package manager, to the speed of running code, all of these features lead to a developer experience which is bringing in whole swaths of new developers." }, { "code": null, "e": 2161, "s": 2129, "text": "I mentioned this in my post on:" }, { "code": null, "e": 2172, "s": 2161, "text": "medium.com" }, { "code": null, "e": 2413, "s": 2172, "text": "but because of the way Julia handles things like Multi Dimensional arrays, you can avoid using packages like Numpy (which you would sometimes see in Tensorflow) and Tensors (which are used in PyTorch and basically a re-branded Numpy array)." }, { "code": null, "e": 2523, "s": 2413, "text": "Here we can see the benefit of using Julia results in less mental overhead. In the case of Python, we can do:" }, { "code": null, "e": 2692, "s": 2523, "text": "import tensorflow as tftf.ones([3, 4], tf.int32)<tf.Tensor: shape=(3, 4), dtype=int32, numpy=array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], dtype=int32)>" }, { "code": null, "e": 2738, "s": 2692, "text": "And then in Julia we would do something like:" }, { "code": null, "e": 2869, "s": 2738, "text": "julia> using Fluxjulia> ones(Float32, 1, 2, 3)1×2×3 Array{Float32, 3}:[:, :, 1] = 1.0 1.0[:, :, 2] = 1.0 1.0[:, :, 3] = 1.0 1.0" }, { "code": null, "e": 3001, "s": 2869, "text": "In the latter case, we are working with just basic arrays which at least in my opinion, makes the code a little bit more intuitive." }, { "code": null, "e": 3405, "s": 3001, "text": "Another point that was mentioned in the above post that bears re-iterating is the rest of the packages you would use in a Data Science / Machine Learning workflow are blazing fast in Julia. Loading CSV’s is 10–20x faster than in Python and DataFrames.jl (the analog to Pandas) also has best in class speed and performance (especially for a rather “young” package that just hit it’s 1.0 release in 2021)." }, { "code": null, "e": 3675, "s": 3405, "text": "If you are not yet convinced at the power of Julia and that it will enable you to be more productive, do a quick search for “Why should I switch to Julia” and you will find plenty of other (hopefully compelling) literature that goes into more depth than I want to here." }, { "code": null, "e": 3722, "s": 3675, "text": "I tried to answer that in this 1 minute video:" }, { "code": null, "e": 3801, "s": 3722, "text": "I also encourage you to check out https://fluxml.ai for a high level overview." }, { "code": null, "e": 3949, "s": 3801, "text": "An extensible system is one whose internal structure and dataflow are minimally or not affected by new or modified functionality... (via Wikipedia)" }, { "code": null, "e": 4366, "s": 3949, "text": "Both Flexibility and Extensibility are front of mind in the design of Flux. For starters, Flux can be used to write models directly but can also be used as a backend for packages like FastAI.jl. Additionally, Flux tries to keep a minimal yet useful API such that developers have the freedom to use what is provided or build on it with their own custom functions which integrate into the Flux ecosystem automatically." }, { "code": null, "e": 4783, "s": 4366, "text": "If you have ever spent any significant amount of time exploring https://www.tensorflow.org/api_docs/python/tf, you will have discovered like I did that there is a lot going on (just take a look on the left hand side at all of the modules). Conversely, Flux focuses on keeping the amount of code and documentation in Flux itself minimal. Take a quick peek at the docs if you haven’t: https://fluxml.ai/Flux.jl/stable/" }, { "code": null, "e": 4829, "s": 4783, "text": "An example of just how simple Flux is to use:" }, { "code": null, "e": 4892, "s": 4829, "text": "using Fluxmodel = Chain(Dense(10, 5, σ), Dense(5, 2), softmax)" }, { "code": null, "e": 5017, "s": 4892, "text": "Here we define a simple model with 3 layers: 2 dense layers (one using the sigmoid activation function) and a softmax layer." }, { "code": null, "e": 5054, "s": 5017, "text": "In Tensorflow, this would look like:" }, { "code": null, "e": 5432, "s": 5054, "text": "from keras.models import * from keras.layers import * model = Sequential([Dense(10, 'sigmoid'), Dense(5), Dense(2, 'softmax')])# Thanks to Stanisław Pitucha for the updated Keras / TF code" }, { "code": null, "e": 5675, "s": 5432, "text": "In the case of Tensorflow, we can see that because we use the Sequential() model, we don’t actually specify the output size of the layers. The sequential nature of the model sets the output of one layer to be the input of the following layer." }, { "code": null, "e": 5878, "s": 5675, "text": "While libraries like PyTorch do give instructions on how to extend the library, as is noted in the docs: https://pytorch.org/docs/stable/notes/extending.html there are far more limitations than in Flux." }, { "code": null, "e": 7171, "s": 5878, "text": "I don’t want to harp on this topic too long, but projects claiming to be “Open” when a majority of contributors are concentrated at a single institution are always a worry to me. In fact, this is one of the things we look at when we evaluate new projects joining NumFOCUS (the non-profit behind Jupyter, Pandas, Numpy, Julia, Flux, etc). To me, a core feature of Flux is that it is not being developed by Google (in Jax and Tensorflow’s case) or Facebook (in PyTorch’s case). While there is certainly a whole host of benefits of having that backing (like lots of money to pay people 😄), if I was a user making a decision about what framework I want to build my company or project around, my preference would be one where I could be an actual stakeholder. In the case of Flux, if you want to start contributing and being a stakeholder, we would love to have you. You can jump in and start contributing to the ecosystem: https://github.com/FluxML/Flux.jl/blob/master/CONTRIBUTING.md or drop by a bi-weekly dev call: https://julialang.org/community/#events. I will again note that this isn’t meant to be a slight at the Tensorflow or PyTorch community since I know many valuable contributions come from outside the host institution, but at a high level I think the idea is worth keeping in mind." }, { "code": null, "e": 7405, "s": 7171, "text": "If you are wondering about the emoji choice here, it is because cooking eggs is easy, almost as easy as using Flux’s internals. Now that we have settled that mystery, let’s dive in and look at why Flux’s internals are so easy to use." }, { "code": null, "e": 7593, "s": 7405, "text": "Spoiler, it is because they are written in Julia. And when I say written in Julia, I mean 100% written in Julia. Take a peek at: https://github.com/FluxML/Flux.jl if you don’t believe me." }, { "code": null, "e": 7657, "s": 7593, "text": "The image above is in stark contrast to Tensorflow and PyTorch:" }, { "code": null, "e": 8174, "s": 7657, "text": "Your eyes are not deceiving you, PyTorch and Tensorflow, if you are not aware, are both written mainly in C++ with a Python wrapper for users. This means that if you want to take a peek under the hood, you have to be comfortable not only with C++ and Python but also the way in which they interact. For me I am still scared by having to use pointers my freshman year of college so if I can avoid C++, I do. If we look at an example of some of the internal of Flux, as noted before, it is Julia, just plain old Julia:" }, { "code": null, "e": 8344, "s": 8174, "text": "function onehot(x, labels, default) i = something(findfirst(isequal(x), labels), 0) i > 0 || return onehot(default, labels) OneHotVector{UInt32, length(labels)}(i)end" }, { "code": null, "e": 8625, "s": 8344, "text": "Here we are looking at one of the definitions of a onehot encoding in Flux. I don’t see any pointers there, which is a relief. I will avoid showing any C++ code here just to make a point since I don’t want to scare you off, but if you are bold, go check out some of the internals." }, { "code": null, "e": 8997, "s": 8625, "text": "One of the side effects of the easy to use internals and 100% Julia code is that users of a package can very quickly become developers and critical contributors. I have seen this happen for myself as I have used Flux over the last few months. While contributing is still difficult, it is without a doubt easier to jump in than it would be in the case of other frameworks." }, { "code": null, "e": 9227, "s": 8997, "text": "A basic example of this is: https://github.com/FluxML/Flux.jl/pull/1801 where I found it odd that calling the gpu function on some code did not provide any warning or indication that the code was in fact not being run on the GPU." }, { "code": null, "e": 9422, "s": 9227, "text": "One of the areas that Flux excels is in the combination of it and other packages to create state of the art results. One example of this is https://github.com/SciML/DiffEqFlux.jl which provides:" }, { "code": null, "e": 9616, "s": 9422, "text": "Universal neural differential equations with O(1) backprop, GPUs, and stiff+non-stiff DE solvers, demonstrating scientific machine learning (SciML) and physics-informed machine learning methods" }, { "code": null, "e": 10389, "s": 9616, "text": "Now unless you are Chris Rackauckas, you might be asking yourself what that even means. You are not alone friend. When I read that for the first time, my brain nearly shut down for good. At a high level, Ordinary Differential equations are used to model natural processes like Population Growth and Decay, Glucose Absorption by the Body, and even the Spread of Epidemics. Neural ODE’s allow us to create a more robust system that does not rely on a fixed number of preset layers in a model. While this can lead to lower performance, the result in many cases is higher speed. You can read this paper for details: https://arxiv.org/abs/1806.07366 or alternatively this medium post: https://towardsdatascience.com/differential-equations-as-a-neural-network-layer-ac3092632255" }, { "code": null, "e": 10436, "s": 10389, "text": "DiffEqFlux.jl provides the following features:" }, { "code": null, "e": 10553, "s": 10436, "text": "- Neural networks can be defined where the “activations” are nonlinear functions described by differential equations" }, { "code": null, "e": 10619, "s": 10553, "text": "- Neural networks can be defined where some layers are ODE solves" }, { "code": null, "e": 10678, "s": 10619, "text": "- ODEs can be defined where some terms are neural networks" }, { "code": null, "e": 10730, "s": 10678, "text": "- Cost functions on ODEs can define neural networks" }, { "code": null, "e": 10838, "s": 10730, "text": "Another good resource to check out is the release blog post: https://julialang.org/blog/2019/01/fluxdiffeq/" }, { "code": null, "e": 11058, "s": 10838, "text": "I will be honest and say that I have yet to get my hands dirty with DiffEqFlux. It is one of the things on my todo list the big take away for me is that Flux is enabling this sort of innovation which I find fascinating." }, { "code": null, "e": 11140, "s": 11058, "text": "I suggest you check out one of the many great talks Chris has given on the topic:" }, { "code": null, "e": 11175, "s": 11140, "text": "I would also suggest checking out:" }, { "code": null, "e": 11291, "s": 11175, "text": "where Dhairya Gandhi goes over many of the places where Flux is being used in the scientific community / ecosystem." }, { "code": null, "e": 11533, "s": 11291, "text": "Under active development is DaggerFlux.jl which will provide model parallelism (the ability to train a model on different devices / nodes in parallel) which is critically important to ensure that Flux remains competitive in the ML arms race." }, { "code": null, "e": 11805, "s": 11533, "text": "There has also been a lot of active work in getting Julia setup to work on TPU’s (Googles custom ML hardware): https://github.com/JuliaTPU/XLA.jl though the project seems to be in a holding pattern at the moment. Despite this, it is still an area where Julia can be used." }, { "code": null, "e": 11956, "s": 11805, "text": "Just as a simple point of comparison, let’s look at how long it takes to do a basic gradient in Flux vs Tensorflow. In Flux, we will do the following:" }, { "code": null, "e": 12344, "s": 11956, "text": "julia> using Fluxjulia> f(x) = 3x^2 + 2x + 1; # define our functionjulia> @time df(x) = gradient(f, x)[1]; 0.006222 seconds (995 allocations: 73.773 KiB, 44.35% compilation time) # longer time on the first run, Julia is compiledjulia> @time df(x) = gradient(f, x)[1];0.000241 seconds (20 allocations: 1.234 KiB)julia> @time df(2)0.000001 seconds14.0julia> @time df(2)0.000000 seconds14.0" }, { "code": null, "e": 12410, "s": 12344, "text": "Now, let’s look at an example in Tensorflow using Gradient tapes:" }, { "code": null, "e": 12637, "s": 12410, "text": "import tensorflow as tfimport timestart = time.time()x = tf.Variable(3.0)with tf.GradientTape() as tape: y = x**2# dy = 2x * dxdy_dx = tape.gradient(y, x)dy_dx.numpy()end = time.time() - startprint(end) # 0.002371072769165039" }, { "code": null, "e": 13040, "s": 12637, "text": "I will note that I had to run the Python example on Google Colab since my Tensorflow installation broke midway through this tutorial and my normal go to guide for installing it on the M1 resulted in an entire terminal buffer filled with red text and errors. Perfect time to mention that Julia runs natively on the M1 mac and many other platforms: https://julialang.org/downloads/#current_stable_release" }, { "code": null, "e": 13157, "s": 13040, "text": "Again at a high level, this tutorial seems relevant since under the hood, machine learning is just taking gradients." }, { "code": null, "e": 13570, "s": 13157, "text": "One of the biggest areas that Flux is behind other ML libraries is in community written content. If I want to do something in TF or PyTorch, it really is usually one search away. This is something we are working on in the Flux community. If you are interested in contributing to this work, which it is worth noting is extremely high impact, please check out: https://github.com/FluxML/fluxml.github.io/issues/107" }, { "code": null, "e": 13746, "s": 13570, "text": "If you want to get involved beyond just writing tutorials, the contributing guide here: https://github.com/FluxML/Flux.jl/blob/master/CONTRIBUTING.md is a good place to start." }, { "code": null, "e": 14023, "s": 13746, "text": "Transfer learning is one of the coolest things about Machine Learning. We can take models built for a specific use-case and fine tune them to fit a new use-case. Let us compare the code for transfer learning between Tensorflow and Julia. You can find the Julia code on GitHub:" }, { "code": null, "e": 14034, "s": 14023, "text": "github.com" }, { "code": null, "e": 14229, "s": 14034, "text": "under: https://github.com/logankilpatrick/DeepLearningWithJulia/blob/main/src/transfer_learning.ipynb and a Tensorflow example here: https://www.tensorflow.org/tutorials/images/transfer_learning" }, { "code": null, "e": 14623, "s": 14229, "text": "One of the big differences that is worth calling out is the way that data and specifically images are handled in each framework. In my opinion, actual machine learning is easy and rather trivial in many cases. The challenge programmatically speaking is to get your data in the form in which it can be inputted to a machine learning model (and cleaned). In this case, we can look at Tensorflow:" }, { "code": null, "e": 14752, "s": 14623, "text": "train_dataset = tf.keras.utils.image_dataset_from_directory(train_dir, shuffle=True, batch_size=BATCH_SIZE, image_size=IMG_SIZE)" }, { "code": null, "e": 15035, "s": 14752, "text": "To me, a function like this is what makes using frameworks like Tensorflow so easy. PyTorch also has many similar functions which make working with data simple. I think that Flux could benefit greatly from a unified interface for loading images and other common forms of data in ML." }, { "code": null, "e": 15261, "s": 15035, "text": "If we look at the Julia example, we are actually writing the loading code from scratch which I have documented. Again, this is actually more difficult than most of the other code that is used in the transfer learning example." }, { "code": null, "e": 15953, "s": 15261, "text": "const DOGS = filter(x -> occursin(\"dog\", x), FILES)const CATS = filter(x -> occursin(\"cat\", x), FILES)function load_batch(batchsize = 10, imagesize = (224,224); path = PATH) if ((batchsize % 2) != 0) print(\"Batch size must be an even number\") end imgs_paths = shuffle(vcat(sample(DOGS, Int(batchsize/2)), sample(CATS, Int(batchsize/2)))) labels = map(x -> occursin(\"dog.\", x) ? 1 : 2, imgs_paths) labels = Flux.onehotbatch(labels, [1, 2]) imgs = Images.load.(imgs_paths) imgs = map(img -> Images.imresize(img, imagesize...), imgs) imgs = map(img -> permutedims(channelview(img), (3, 2, 1)), imgs) imgs = cat(imgs..., dims = 4) Float32.(imgs), labelsend" }, { "code": null, "e": 16023, "s": 15953, "text": "Another difference in the code that we see is in image augmentations:" }, { "code": null, "e": 16148, "s": 16023, "text": "data_augmentation = tf.keras.Sequential([ tf.keras.layers.RandomFlip('horizontal'), tf.keras.layers.RandomRotation(0.2),])" }, { "code": null, "e": 16294, "s": 16148, "text": "Here we can see the TF code to do a random flip and rotation. In the case of Julia, we would need to use: https://github.com/Evizero/Augmentor.jl" }, { "code": null, "e": 16413, "s": 16294, "text": "julia> pl = FlipX(0.5) |> Rotate(0:20) |>julia> img_new = augment(img, pl) # here we apply the augmentation" }, { "code": null, "e": 16617, "s": 16413, "text": "Again, from a usability standpoint, there would be benefits in my view to having image augmentation as part of the core package but the idea of extracting it out to keep things minimal is understandable." }, { "code": null, "e": 16678, "s": 16617, "text": "Lastly, let us look at the model definition itself in Julia:" }, { "code": null, "e": 16793, "s": 16678, "text": "model = Chain( resnet[1:end-2], Dense(2048, 1000, σ), Dense(1000, 256, σ), Dense(256, 2), softmax );" }, { "code": null, "e": 16980, "s": 16793, "text": "Here we take a pre-trained Resnet and grab all its layers except the last two which we will replace with our new fine tuned layers. In Tensorflow, we would do something to the effect of:" }, { "code": null, "e": 17440, "s": 16980, "text": "base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')inputs = tf.keras.Input(shape=(160, 160, 3))x = data_augmentation(inputs)x = preprocess_input(x)x = base_model(x, training=False)x = global_average_layer(x)x = tf.keras.layers.Dropout(0.2)(x)outputs = prediction_layer(x)model = tf.keras.Model(inputs, outputs)" }, { "code": null, "e": 17679, "s": 17440, "text": "This is one of the ways of creating a model in TF (and Flux has a similar approach) where to define the inputs and ouputs instead of the model layers but I prefer to create the model using the format we saw using the Julia chain function." }, { "code": null, "e": 17945, "s": 17679, "text": "While Tensorflow.jl is no longer being actively developed, you can still use Tensorflow (and any python code for that matter) in Julia. Torch.jl is also actively maintained: https://github.com/FluxML/Torch.jl which provides a wrapper of PyTorch’s C++ code in Julia." }, { "code": null, "e": 18039, "s": 17945, "text": "If you are interested in reading more about integrating Python and Julia together, check out:" }, { "code": null, "e": 18062, "s": 18039, "text": "towardsdatascience.com" }, { "code": null, "e": 18416, "s": 18062, "text": "My goal of this post was to convince someone who is unsure about using Julia for Machine Learning that it is worth while to try it. I also hope that my mention of areas where the Flux ecosystem needs further development sets the right expectation that things are not perfect, but they are definitely at the point where you can do serious science and ML." } ]
Delete a tail node from the given singly Linked List using C++
A Linked List is a linear Data Structure that contains nodes and each node has two fields; one is the value or data to be inserted and the other field stores the address of the next node. Our task here is to delete a node from the end of a Linked List. The last node is known as the tail node. If there is no node in the Linked List, then return NULL. For example − Input 1 − 1 → 2 → 3 → 4 → 5 Output − 1 → 2 → 3 → 4 → Explanation − In the given singly linked list, the node from the end is ‘5’. After deleting the last node, the output will be, 1 → 2 → 3 → 4 →. Input 2 − 5 → 8 →3 Output − 5 → 8 → Explanation − In the given singly linked list, the node from the end is ‘3’. After deleting the node from the end, the output will be, 5 →8 →. The simple approach to solve this particular problem is to create a previous node that later on stores the value of the current node when the current pointer will point to the last node of the linked list. Iterate over all the nodes of the linked list if the current node points to the last node. And finally, return from the linked list. Initialize the linked list by inserting the nodes into it. Initialize the linked list by inserting the nodes into it. Function insertAtFirst(node*&head, int data) will insert all the nodes in the linked list. Function insertAtFirst(node*&head, int data) will insert all the nodes in the linked list. A function deleteAtTail(node*head) takes a pointer that is currently pointing to the head. A function deleteAtTail(node*head) takes a pointer that is currently pointing to the head. Create a previous Node pointer and initialize it as NULL. Create a previous Node pointer and initialize it as NULL. Create a temporary Node pointer that is currently pointing to the head of the pointer. Create a temporary Node pointer that is currently pointing to the head of the pointer. Traverse the temporary pointer until it does not reach the end of the linked list. Traverse the temporary pointer until it does not reach the end of the linked list. Store the value of the temporary pointer in the previous node pointer. Store the value of the temporary pointer in the previous node pointer. Delete the temporary pointer. Delete the temporary pointer. Return the linked list. Return the linked list. Live Demo #include<iostream> using namespace std; class node{ public: int data; node*next; node(int d){ data=d; node*next= NULL; } }; void insertAtFirst(node*&head, int data){ node*n= new node(data); n->next= head; head=n; } void printNode(node*head){ while(head!=NULL){ cout<<head->data<<"->"; head=head->next; } cout<<endl; } void deleteatTail(node*head){ node*prev= NULL; node*temp= head; while(temp->next!=NULL){ prev= temp; temp=temp->next; } delete temp; prev->next= NULL; return; } int main(){ node*head= NULL; insertAtFirst(head,5); insertAtFirst(head,4); insertAtFirst(head,3); insertAtFirst(head,2); insertAtFirst(head,1); deleteatTail(head); printNode(head); } Running the above code will generate the output as, 1→2→3→4→ In the given input singly linked list, 1 → 2 → 3 → 4 → 5, the last node of the linked list is ‘5’. Hence, after deletion of the last node, the linked list will become 1 → 2 → 3 → 4 →.
[ { "code": null, "e": 1250, "s": 1062, "text": "A Linked List is a linear Data Structure that contains nodes and each node has two fields; one is the value or data to be inserted and the other field stores the address of the next node." }, { "code": null, "e": 1414, "s": 1250, "text": "Our task here is to delete a node from the end of a Linked List. The last node is known as the tail node. If there is no node in the Linked List, then return NULL." }, { "code": null, "e": 1428, "s": 1414, "text": "For example −" }, { "code": null, "e": 1456, "s": 1428, "text": "Input 1 − 1 → 2 → 3 → 4 → 5" }, { "code": null, "e": 1481, "s": 1456, "text": "Output − 1 → 2 → 3 → 4 →" }, { "code": null, "e": 1625, "s": 1481, "text": "Explanation − In the given singly linked list, the node from the end is ‘5’. After deleting the last node, the output will be, 1 → 2 → 3 → 4 →." }, { "code": null, "e": 1644, "s": 1625, "text": "Input 2 − 5 → 8 →3" }, { "code": null, "e": 1661, "s": 1644, "text": "Output − 5 → 8 →" }, { "code": null, "e": 1804, "s": 1661, "text": "Explanation − In the given singly linked list, the node from the end is ‘3’. After deleting the node from the end, the output will be, 5 →8 →." }, { "code": null, "e": 2010, "s": 1804, "text": "The simple approach to solve this particular problem is to create a previous node that later on stores the value of the current node when the current pointer will point to the last node of the linked list." }, { "code": null, "e": 2143, "s": 2010, "text": "Iterate over all the nodes of the linked list if the current node points to the last node. And finally, return from the linked list." }, { "code": null, "e": 2202, "s": 2143, "text": "Initialize the linked list by inserting the nodes into it." }, { "code": null, "e": 2261, "s": 2202, "text": "Initialize the linked list by inserting the nodes into it." }, { "code": null, "e": 2352, "s": 2261, "text": "Function insertAtFirst(node*&head, int data) will insert all the nodes in the linked list." }, { "code": null, "e": 2443, "s": 2352, "text": "Function insertAtFirst(node*&head, int data) will insert all the nodes in the linked list." }, { "code": null, "e": 2534, "s": 2443, "text": "A function deleteAtTail(node*head) takes a pointer that is currently pointing to the head." }, { "code": null, "e": 2625, "s": 2534, "text": "A function deleteAtTail(node*head) takes a pointer that is currently pointing to the head." }, { "code": null, "e": 2683, "s": 2625, "text": "Create a previous Node pointer and initialize it as NULL." }, { "code": null, "e": 2741, "s": 2683, "text": "Create a previous Node pointer and initialize it as NULL." }, { "code": null, "e": 2828, "s": 2741, "text": "Create a temporary Node pointer that is currently pointing to the head of the pointer." }, { "code": null, "e": 2915, "s": 2828, "text": "Create a temporary Node pointer that is currently pointing to the head of the pointer." }, { "code": null, "e": 2998, "s": 2915, "text": "Traverse the temporary pointer until it does not reach the end of the linked list." }, { "code": null, "e": 3081, "s": 2998, "text": "Traverse the temporary pointer until it does not reach the end of the linked list." }, { "code": null, "e": 3152, "s": 3081, "text": "Store the value of the temporary pointer in the previous node pointer." }, { "code": null, "e": 3223, "s": 3152, "text": "Store the value of the temporary pointer in the previous node pointer." }, { "code": null, "e": 3253, "s": 3223, "text": "Delete the temporary pointer." }, { "code": null, "e": 3283, "s": 3253, "text": "Delete the temporary pointer." }, { "code": null, "e": 3307, "s": 3283, "text": "Return the linked list." }, { "code": null, "e": 3331, "s": 3307, "text": "Return the linked list." }, { "code": null, "e": 3342, "s": 3331, "text": " Live Demo" }, { "code": null, "e": 4118, "s": 3342, "text": "#include<iostream>\nusing namespace std;\nclass node{\n public:\n int data;\n node*next;\n node(int d){\n data=d;\n node*next= NULL;\n }\n};\nvoid insertAtFirst(node*&head, int data){\n node*n= new node(data);\n n->next= head;\n head=n;\n}\nvoid printNode(node*head){\n while(head!=NULL){\n cout<<head->data<<\"->\";\n head=head->next;\n }\n cout<<endl;\n}\nvoid deleteatTail(node*head){\n node*prev= NULL;\n node*temp= head;\n while(temp->next!=NULL){\n prev= temp;\n temp=temp->next;\n }\n delete temp;\n prev->next= NULL;\n return;\n}\nint main(){\n node*head= NULL;\n insertAtFirst(head,5);\n insertAtFirst(head,4);\n insertAtFirst(head,3);\n insertAtFirst(head,2);\n insertAtFirst(head,1);\n deleteatTail(head);\n printNode(head);\n}" }, { "code": null, "e": 4170, "s": 4118, "text": "Running the above code will generate the output as," }, { "code": null, "e": 4179, "s": 4170, "text": "1→2→3→4→" }, { "code": null, "e": 4363, "s": 4179, "text": "In the given input singly linked list, 1 → 2 → 3 → 4 → 5, the last node of the linked list is ‘5’. Hence, after deletion of the last node, the linked list will become 1 → 2 → 3 → 4 →." } ]
Part 2: Hyperopt.. In this blog series, I am comparing... | by Jakub Czakon | Towards Data Science
In this blog series, I am comparing python HPO libraries. Before reading this post, I would highly advise that you read Part 0: Introduction where I: talked about what HPO is, selected libraries to compare, selected the evaluation criteria, defined an example problem for the HPO. Code for this blog post and other parts of the series is available on github while all the experiments with scripts, hyperparameters, charts, and results (that you can download) are available for you in Neptune. For more information, read this post about organizing the experimentation process. Ok, let’s do this. This is the classic in the HPO space. This project has over 3300 stars, 600 forks and 40 contributors(2 main ones). There are even projects built on top of it like: hyperas: hyperopt + keras hyperopt-sklearn: hyperopt + sklearn The API is pretty simple and easy to use. We need to define a search space, objective and run the optimization function: First, define the search space. It can be a regular dictionary or as in this case OrderedDict: What is kind of awkward is that I have to define the name twice, once as a dictionary key and once as a label in the parameter sampler. Then, define the objective function. Remember that hyperopt minimizes the function, so change the sign if you need to: Finally, instantiate the Trials object, and run the optimization: ...and done! All the information, hyperparameters, loss and other things are kept inside the trialsobject. You can access it with no problems or pickle it for later. If you want to see a full example script with training curves, diagnostic charts and all that, see this versioned ml experiment. I give it a score of 9/10 because of the name duplication in the space search definition and the fact that for simple problems I would rather not have to instantiate thetrialsobject but simply have it instantiated asTrials() by default. Score 9/10 Search Space This is where hyperopt shines. There is a ton of sampling options to choose from: Categorical parameters-use hp.choice Integer parameters-you can use hp.randit, hp.quniform, hp.qloguniform or hp.qlognormal which really gives you a lot of options to model your integer hyperparameter space Float parameters- similarly to integer parameters you really get to choose what works for your problem with hp.normal, hp.uniform, hp.lognormal and hp.loguniform But that is not it. You can easily define nested spaces where values of some parameters depend on others. Taking the example from the documentation: we can see that by combining hp.choice with other sampling methods we can have conditional search spaces. This is very useful when searching over complicated spaces with hyperparameters spanning from your feature preprocessing, through model selection methods all the way to model hyperparameters. Optimization methods There are two optimization algorithms to try. tpe.rand.suggest Your standard random search over the parameters. tpe.suggest Similarly to what was explained in the previous blog post about Scikit-Optimize we want to use a cheap surrogate model that estimates the performance of the expensive objective function on a set of parameters. The difference is that instead of estimating the actual performance (point estimation) we want to estimate the density in the tails. I like the following explanation taken from the AutoML_Book by amazing folks over at AutoML.org Freiburg. Instead of modeling the probability p(y|λ) of observations y given the configurations λ, the Tree Parzen Estimator models density functions p(λ|y < α) and p(λ|y ≥ α). Given a percentile α (usually set to 15%), the observations are divided in good observations and bad observations and simple 1-d Parzen windows are used to model the two distributions. By using p(λ|y < α) and p(λ|y ≥ α) one can estimate the Expected Improvement (EI) of a given run. Interestingly there are no options to specify the λ parameter in the optimizer. Callbacks There are no callbacks per se, but you can put your callback function inside the objective and it will be executed every time the objective is called. I don’t love it but I guess I can live with that. Summing up, a big plus for the nested search space but I don’t like the fact that there are no clean callbacks. TPE doesn’t have any (hyper)hyperparameters which on one hand is great (less work, less overfitting) but on the other hand, it doesn’t allow you to adjust things when they are not working. I give it 7/10. Score 7/10 Putting it mildly, it could use a lot of love. The official documentation page is hosted on wiki. It is more of a library tour than proper documentation if you ask me. That being said, having read it, you should be able to use this library effectively. The problem is, when you want to find one particular thing, you need to go through the entire wiki looking for it. It is missing basic examples. The only one I found (hyperopt/recipes) is 6 years old and with errors. The vast majority of functions and main class methods are missing docstrings. Unfortunately, it makes it difficult to navigate and answer simple questions like what does this function actually do? The good thing is, there are a lot of blog posts about it. Some of them that I found useful are: “Parameter Tuning with Hyperopt” by District Data Labs “Hyperopt tutorial for Optimizing Neural Networks’ Hyperparameters” by Vooban “On Using Hyperopt: Advanced Machine Learning” by Tanay Agrawal “An Introductory Example of Bayesian Optimization in Python with Hyperopt” by Will Koehrsen The documentation is definitely not a strong side of this project but because it’s a classic there are a lot of outside resources. I give it 3/10. Score 3/10 Note If you are thinking about doing something good for the community, you can go ahead, add docstrings, a bunch of examples, and create read-the-docs documentation for this project. I, for one, would be grateful. hyperopt has a visualization module plotting.py. It has three functions: main_plot_history -it shows you the results of each iteration and highlights the best score. main_plot_histogram -shows you the histogram of results over all iterations. main_plot_vars -which... I don’t really know what it does as I couldn’t get it to run and there were no docstrings nor examples (again, the documentation is far from perfect). There are some basic visualization utilities but they are not super useful. Feels like 3/10. Score 3/10 Note As I mentioned in my last post I like the plots that come with Scikit-Optimize and I implemented a set of functions that help with conversions between different HPO libraries so that you could use those visualizations for every lib. I’ve put them in the neptune-contribpackage and you can check how to use it here. You can just pickle the trialsobject and use it later. For example, the saving part could read: Loading again is done by pickle while restarting is as simple as passing the trials object (now not empty) and changing the max_evals from 100 to 200. Simple and works with no problems: 10/10. Score 10/10 With hyperopt, you can distribute your computation over a cluster of machines. Good step-by-step instructions can be found in this blog post by Tanay Agrawal but in a nutshell, you need to: Start a server with MongoDB on it which will consume results from your worker training scripts and send out the next parameter set to try, In your training script, instead of Trials()create a MongoTrials object pointing to the database server you have started in the previous step, Move your objective function to a separate objective.py script and rename it to function, Compile your Python training script, Run hyperopt-mongo-worker Though it gets the job done it doesn’t feel quite perfect. You need to do some juggling around the objective function, and starting MongoDB could have been provided in the CLI to makes things easier. Because of the above 8/10 feels fair to me. Score 8/10 You can explore all the versioned ml experiments in Neptune. Every experiment has a script attached to it. For example, you can see the code for the best one here. You can also download experiment metadata to pandas.DataFrame by running: Let’s take a look at the experiment results: Thetpemethod was a slight winner but only when we run it for more iterations. At the predefined budget of 100 iterations randomsearch has slightly outperformed tpe . Looking at the plot_evaluations chart from Scikit-Optimize for the best 100 iterations experiment: we can see that only for the feature_fraction parameter the search has actually steered in some direction. Otherwise, it was pretty much random all the way( which explains why the results are so close to random search). Overall the highest score I got for 100 iteration runs was merely 0.84509 which was actually worse than a random search (from Scikit-Optimize) 0.8464 by ~0.001. I will translate that to -1 point (-0.001*100). Score –1 Hyperopt is a classic and it has served the community for many years. It has an easy to use API, can parallelize computations on a cluster of machines, and has really great support for nested search spaces. However, it’s limited documentation with little examples and docstrings can make it hard to use, especially outside of the golden path. Visualization suite is quite limited as well and doesn’t bring a lot of value. What is a bit troubling, is the fact that for our example problem it couldn’t beat random search. Let’s take a look at the results for all of the criteria: The score of 39 is way lower than that of Scikit-Optimize. The big factors were documentation, visualizations and experimental results. Next time we will take a close look at another Tree-Parzen estimator library for hyperparameter optimization Optuna. You can check out part 3 of the series Optuna vs Hyperopt here. You can also go and read other posts from this series in my HPO in Python column. If you liked this, you can find more posts like this on our Neptune blog. You can also find me tweeting @Neptune_ai or posting on LinkedIn about ML and Data Science stuff. @book{automl_book, editor = {Hutter, Frank and Kotthoff, Lars and Vanschoren, Joaquin}, note = {In press, available at http://automl.org/book.}, publisher = {Springer}, title = {Automated Machine Learning: Methods, Systems, Challenges}, year = {2018}}
[ { "code": null, "e": 321, "s": 171, "text": "In this blog series, I am comparing python HPO libraries. Before reading this post, I would highly advise that you read Part 0: Introduction where I:" }, { "code": null, "e": 347, "s": 321, "text": "talked about what HPO is," }, { "code": null, "e": 378, "s": 347, "text": "selected libraries to compare," }, { "code": null, "e": 412, "s": 378, "text": "selected the evaluation criteria," }, { "code": null, "e": 452, "s": 412, "text": "defined an example problem for the HPO." }, { "code": null, "e": 747, "s": 452, "text": "Code for this blog post and other parts of the series is available on github while all the experiments with scripts, hyperparameters, charts, and results (that you can download) are available for you in Neptune. For more information, read this post about organizing the experimentation process." }, { "code": null, "e": 766, "s": 747, "text": "Ok, let’s do this." }, { "code": null, "e": 931, "s": 766, "text": "This is the classic in the HPO space. This project has over 3300 stars, 600 forks and 40 contributors(2 main ones). There are even projects built on top of it like:" }, { "code": null, "e": 957, "s": 931, "text": "hyperas: hyperopt + keras" }, { "code": null, "e": 994, "s": 957, "text": "hyperopt-sklearn: hyperopt + sklearn" }, { "code": null, "e": 1115, "s": 994, "text": "The API is pretty simple and easy to use. We need to define a search space, objective and run the optimization function:" }, { "code": null, "e": 1210, "s": 1115, "text": "First, define the search space. It can be a regular dictionary or as in this case OrderedDict:" }, { "code": null, "e": 1346, "s": 1210, "text": "What is kind of awkward is that I have to define the name twice, once as a dictionary key and once as a label in the parameter sampler." }, { "code": null, "e": 1465, "s": 1346, "text": "Then, define the objective function. Remember that hyperopt minimizes the function, so change the sign if you need to:" }, { "code": null, "e": 1531, "s": 1465, "text": "Finally, instantiate the Trials object, and run the optimization:" }, { "code": null, "e": 1544, "s": 1531, "text": "...and done!" }, { "code": null, "e": 1826, "s": 1544, "text": "All the information, hyperparameters, loss and other things are kept inside the trialsobject. You can access it with no problems or pickle it for later. If you want to see a full example script with training curves, diagnostic charts and all that, see this versioned ml experiment." }, { "code": null, "e": 2063, "s": 1826, "text": "I give it a score of 9/10 because of the name duplication in the space search definition and the fact that for simple problems I would rather not have to instantiate thetrialsobject but simply have it instantiated asTrials() by default." }, { "code": null, "e": 2074, "s": 2063, "text": "Score 9/10" }, { "code": null, "e": 2087, "s": 2074, "text": "Search Space" }, { "code": null, "e": 2169, "s": 2087, "text": "This is where hyperopt shines. There is a ton of sampling options to choose from:" }, { "code": null, "e": 2206, "s": 2169, "text": "Categorical parameters-use hp.choice" }, { "code": null, "e": 2376, "s": 2206, "text": "Integer parameters-you can use hp.randit, hp.quniform, hp.qloguniform or hp.qlognormal which really gives you a lot of options to model your integer hyperparameter space" }, { "code": null, "e": 2538, "s": 2376, "text": "Float parameters- similarly to integer parameters you really get to choose what works for your problem with hp.normal, hp.uniform, hp.lognormal and hp.loguniform" }, { "code": null, "e": 2687, "s": 2538, "text": "But that is not it. You can easily define nested spaces where values of some parameters depend on others. Taking the example from the documentation:" }, { "code": null, "e": 2793, "s": 2687, "text": "we can see that by combining hp.choice with other sampling methods we can have conditional search spaces." }, { "code": null, "e": 2985, "s": 2793, "text": "This is very useful when searching over complicated spaces with hyperparameters spanning from your feature preprocessing, through model selection methods all the way to model hyperparameters." }, { "code": null, "e": 3006, "s": 2985, "text": "Optimization methods" }, { "code": null, "e": 3052, "s": 3006, "text": "There are two optimization algorithms to try." }, { "code": null, "e": 3069, "s": 3052, "text": "tpe.rand.suggest" }, { "code": null, "e": 3118, "s": 3069, "text": "Your standard random search over the parameters." }, { "code": null, "e": 3130, "s": 3118, "text": "tpe.suggest" }, { "code": null, "e": 3473, "s": 3130, "text": "Similarly to what was explained in the previous blog post about Scikit-Optimize we want to use a cheap surrogate model that estimates the performance of the expensive objective function on a set of parameters. The difference is that instead of estimating the actual performance (point estimation) we want to estimate the density in the tails." }, { "code": null, "e": 3579, "s": 3473, "text": "I like the following explanation taken from the AutoML_Book by amazing folks over at AutoML.org Freiburg." }, { "code": null, "e": 3931, "s": 3579, "text": "Instead of modeling the probability p(y|λ) of observations y given the configurations λ, the Tree Parzen Estimator models density functions p(λ|y < α) and p(λ|y ≥ α). Given a percentile α (usually set to 15%), the observations are divided in good observations and bad observations and simple 1-d Parzen windows are used to model the two distributions." }, { "code": null, "e": 4029, "s": 3931, "text": "By using p(λ|y < α) and p(λ|y ≥ α) one can estimate the Expected Improvement (EI) of a given run." }, { "code": null, "e": 4109, "s": 4029, "text": "Interestingly there are no options to specify the λ parameter in the optimizer." }, { "code": null, "e": 4119, "s": 4109, "text": "Callbacks" }, { "code": null, "e": 4270, "s": 4119, "text": "There are no callbacks per se, but you can put your callback function inside the objective and it will be executed every time the objective is called." }, { "code": null, "e": 4320, "s": 4270, "text": "I don’t love it but I guess I can live with that." }, { "code": null, "e": 4637, "s": 4320, "text": "Summing up, a big plus for the nested search space but I don’t like the fact that there are no clean callbacks. TPE doesn’t have any (hyper)hyperparameters which on one hand is great (less work, less overfitting) but on the other hand, it doesn’t allow you to adjust things when they are not working. I give it 7/10." }, { "code": null, "e": 4648, "s": 4637, "text": "Score 7/10" }, { "code": null, "e": 4695, "s": 4648, "text": "Putting it mildly, it could use a lot of love." }, { "code": null, "e": 5016, "s": 4695, "text": "The official documentation page is hosted on wiki. It is more of a library tour than proper documentation if you ask me. That being said, having read it, you should be able to use this library effectively. The problem is, when you want to find one particular thing, you need to go through the entire wiki looking for it." }, { "code": null, "e": 5118, "s": 5016, "text": "It is missing basic examples. The only one I found (hyperopt/recipes) is 6 years old and with errors." }, { "code": null, "e": 5315, "s": 5118, "text": "The vast majority of functions and main class methods are missing docstrings. Unfortunately, it makes it difficult to navigate and answer simple questions like what does this function actually do?" }, { "code": null, "e": 5412, "s": 5315, "text": "The good thing is, there are a lot of blog posts about it. Some of them that I found useful are:" }, { "code": null, "e": 5467, "s": 5412, "text": "“Parameter Tuning with Hyperopt” by District Data Labs" }, { "code": null, "e": 5545, "s": 5467, "text": "“Hyperopt tutorial for Optimizing Neural Networks’ Hyperparameters” by Vooban" }, { "code": null, "e": 5609, "s": 5545, "text": "“On Using Hyperopt: Advanced Machine Learning” by Tanay Agrawal" }, { "code": null, "e": 5701, "s": 5609, "text": "“An Introductory Example of Bayesian Optimization in Python with Hyperopt” by Will Koehrsen" }, { "code": null, "e": 5848, "s": 5701, "text": "The documentation is definitely not a strong side of this project but because it’s a classic there are a lot of outside resources. I give it 3/10." }, { "code": null, "e": 5859, "s": 5848, "text": "Score 3/10" }, { "code": null, "e": 5864, "s": 5859, "text": "Note" }, { "code": null, "e": 6073, "s": 5864, "text": "If you are thinking about doing something good for the community, you can go ahead, add docstrings, a bunch of examples, and create read-the-docs documentation for this project. I, for one, would be grateful." }, { "code": null, "e": 6146, "s": 6073, "text": "hyperopt has a visualization module plotting.py. It has three functions:" }, { "code": null, "e": 6239, "s": 6146, "text": "main_plot_history -it shows you the results of each iteration and highlights the best score." }, { "code": null, "e": 6316, "s": 6239, "text": "main_plot_histogram -shows you the histogram of results over all iterations." }, { "code": null, "e": 6492, "s": 6316, "text": "main_plot_vars -which... I don’t really know what it does as I couldn’t get it to run and there were no docstrings nor examples (again, the documentation is far from perfect)." }, { "code": null, "e": 6585, "s": 6492, "text": "There are some basic visualization utilities but they are not super useful. Feels like 3/10." }, { "code": null, "e": 6596, "s": 6585, "text": "Score 3/10" }, { "code": null, "e": 6601, "s": 6596, "text": "Note" }, { "code": null, "e": 6916, "s": 6601, "text": "As I mentioned in my last post I like the plots that come with Scikit-Optimize and I implemented a set of functions that help with conversions between different HPO libraries so that you could use those visualizations for every lib. I’ve put them in the neptune-contribpackage and you can check how to use it here." }, { "code": null, "e": 7012, "s": 6916, "text": "You can just pickle the trialsobject and use it later. For example, the saving part could read:" }, { "code": null, "e": 7163, "s": 7012, "text": "Loading again is done by pickle while restarting is as simple as passing the trials object (now not empty) and changing the max_evals from 100 to 200." }, { "code": null, "e": 7205, "s": 7163, "text": "Simple and works with no problems: 10/10." }, { "code": null, "e": 7217, "s": 7205, "text": "Score 10/10" }, { "code": null, "e": 7407, "s": 7217, "text": "With hyperopt, you can distribute your computation over a cluster of machines. Good step-by-step instructions can be found in this blog post by Tanay Agrawal but in a nutshell, you need to:" }, { "code": null, "e": 7546, "s": 7407, "text": "Start a server with MongoDB on it which will consume results from your worker training scripts and send out the next parameter set to try," }, { "code": null, "e": 7689, "s": 7546, "text": "In your training script, instead of Trials()create a MongoTrials object pointing to the database server you have started in the previous step," }, { "code": null, "e": 7779, "s": 7689, "text": "Move your objective function to a separate objective.py script and rename it to function," }, { "code": null, "e": 7816, "s": 7779, "text": "Compile your Python training script," }, { "code": null, "e": 7842, "s": 7816, "text": "Run hyperopt-mongo-worker" }, { "code": null, "e": 8042, "s": 7842, "text": "Though it gets the job done it doesn’t feel quite perfect. You need to do some juggling around the objective function, and starting MongoDB could have been provided in the CLI to makes things easier." }, { "code": null, "e": 8086, "s": 8042, "text": "Because of the above 8/10 feels fair to me." }, { "code": null, "e": 8097, "s": 8086, "text": "Score 8/10" }, { "code": null, "e": 8261, "s": 8097, "text": "You can explore all the versioned ml experiments in Neptune. Every experiment has a script attached to it. For example, you can see the code for the best one here." }, { "code": null, "e": 8335, "s": 8261, "text": "You can also download experiment metadata to pandas.DataFrame by running:" }, { "code": null, "e": 8380, "s": 8335, "text": "Let’s take a look at the experiment results:" }, { "code": null, "e": 8546, "s": 8380, "text": "Thetpemethod was a slight winner but only when we run it for more iterations. At the predefined budget of 100 iterations randomsearch has slightly outperformed tpe ." }, { "code": null, "e": 8645, "s": 8546, "text": "Looking at the plot_evaluations chart from Scikit-Optimize for the best 100 iterations experiment:" }, { "code": null, "e": 8865, "s": 8645, "text": "we can see that only for the feature_fraction parameter the search has actually steered in some direction. Otherwise, it was pretty much random all the way( which explains why the results are so close to random search)." }, { "code": null, "e": 9074, "s": 8865, "text": "Overall the highest score I got for 100 iteration runs was merely 0.84509 which was actually worse than a random search (from Scikit-Optimize) 0.8464 by ~0.001. I will translate that to -1 point (-0.001*100)." }, { "code": null, "e": 9083, "s": 9074, "text": "Score –1" }, { "code": null, "e": 9290, "s": 9083, "text": "Hyperopt is a classic and it has served the community for many years. It has an easy to use API, can parallelize computations on a cluster of machines, and has really great support for nested search spaces." }, { "code": null, "e": 9603, "s": 9290, "text": "However, it’s limited documentation with little examples and docstrings can make it hard to use, especially outside of the golden path. Visualization suite is quite limited as well and doesn’t bring a lot of value. What is a bit troubling, is the fact that for our example problem it couldn’t beat random search." }, { "code": null, "e": 9661, "s": 9603, "text": "Let’s take a look at the results for all of the criteria:" }, { "code": null, "e": 9797, "s": 9661, "text": "The score of 39 is way lower than that of Scikit-Optimize. The big factors were documentation, visualizations and experimental results." }, { "code": null, "e": 9914, "s": 9797, "text": "Next time we will take a close look at another Tree-Parzen estimator library for hyperparameter optimization Optuna." }, { "code": null, "e": 9978, "s": 9914, "text": "You can check out part 3 of the series Optuna vs Hyperopt here." }, { "code": null, "e": 10060, "s": 9978, "text": "You can also go and read other posts from this series in my HPO in Python column." }, { "code": null, "e": 10134, "s": 10060, "text": "If you liked this, you can find more posts like this on our Neptune blog." }, { "code": null, "e": 10232, "s": 10134, "text": "You can also find me tweeting @Neptune_ai or posting on LinkedIn about ML and Data Science stuff." } ]
What is an array of structures in C language?
The most common use of structure in C programming language is an array of structures. To declare an array of structures, first the structure must be defined and then, an array variable of that type can be defined. For example, struct book b[10]; //10 elements in an array of structures of type ‘book’ Given below is the C program for accepting and printing details of 3 students with regards to an array of structures − Live Demo #include <stdio.h> #include <string.h> struct student{ int id; char name[30]; float percentage; }; int main(){ int i; struct student record[2]; // 1st student's record record[0].id=1; strcpy(record[0].name, "Bhanu"); record[0].percentage = 86.5; // 2nd student's record record[1].id=2; strcpy(record[1].name, "Priya"); record[1].percentage = 90.5; // 3rd student's record record[2].id=3; strcpy(record[2].name, "Hari"); record[2].percentage = 81.5; for(i=0; i<3; i++){ printf(" Records of STUDENT : %d \n", i+1); printf(" Id is: %d \n", record[i].id); printf(" Name is: %s \n", record[i].name); printf(" Percentage is: %f\n\n",record[i].percentage); } return 0; } When the above program is executed, it produces the following result − Records of STUDENT : 1 Id is: 1 Name is: Bhanu Percentage is: 86.500000 Records of STUDENT : 2 Id is: 2 Name is: Priya Percentage is: 90.500000 Records of STUDENT : 3 Id is: 3 Name is: Hari Percentage is: 81.500000
[ { "code": null, "e": 1148, "s": 1062, "text": "The most common use of structure in C programming language is an array of structures." }, { "code": null, "e": 1276, "s": 1148, "text": "To declare an array of structures, first the structure must be defined and then, an array variable of that type can be defined." }, { "code": null, "e": 1363, "s": 1276, "text": "For example, struct book b[10]; //10 elements in an array of structures of type ‘book’" }, { "code": null, "e": 1482, "s": 1363, "text": "Given below is the C program for accepting and printing details of 3 students with regards to an array of structures −" }, { "code": null, "e": 1493, "s": 1482, "text": " Live Demo" }, { "code": null, "e": 2241, "s": 1493, "text": "#include <stdio.h>\n#include <string.h>\nstruct student{\n int id;\n char name[30];\n float percentage;\n};\nint main(){\n int i;\n struct student record[2];\n // 1st student's record\n record[0].id=1;\n strcpy(record[0].name, \"Bhanu\");\n record[0].percentage = 86.5;\n // 2nd student's record\n record[1].id=2;\n strcpy(record[1].name, \"Priya\");\n record[1].percentage = 90.5;\n // 3rd student's record\n record[2].id=3;\n strcpy(record[2].name, \"Hari\");\n record[2].percentage = 81.5;\n for(i=0; i<3; i++){\n printf(\" Records of STUDENT : %d \\n\", i+1);\n printf(\" Id is: %d \\n\", record[i].id);\n printf(\" Name is: %s \\n\", record[i].name);\n printf(\" Percentage is: %f\\n\\n\",record[i].percentage);\n }\n return 0;\n}" }, { "code": null, "e": 2312, "s": 2241, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2527, "s": 2312, "text": "Records of STUDENT : 1\nId is: 1\nName is: Bhanu\nPercentage is: 86.500000\nRecords of STUDENT : 2\nId is: 2\nName is: Priya\nPercentage is: 90.500000\nRecords of STUDENT : 3\nId is: 3\nName is: Hari\nPercentage is: 81.500000" } ]
Create a Pipeline in Pandas - GeeksforGeeks
17 Jan, 2022 Pipelines play a useful role in transforming and manipulating tons of data. Pipeline are a sequence of data processing mechanisms. Pandas pipeline feature allows us to string together various user-defined Python functions in order to build a pipeline of data processing. There are two ways to create a Pipeline in pandas. By calling .pipe() function and by importing pdpipe package. Through pandas pipeline function i.e. pipe() function we can call more than one function at a time and in a single line for data processing. Let’s understand and create a pipeline by using the pipe() function. Below are various examples that depict how to create a pipeline using pandas. Example 1: Python3 # importing pandas libraryimport pandas as pd # Create empty dataframedf = pd.DataFrame() # Creating a simple dataframedf['name'] = ['Reema', 'Shyam', 'Jai', 'Nimisha', 'Rohit', 'Riya']df['gender'] = ['Female', 'Male', 'Male', 'Female', 'Male', 'Female']df['age'] = [31, 32, 19, 23, 28, 33] # View dataframedf Output: Now, creating functions for data processing. Python3 # function to find meandef mean_age_by_group(dataframe, col): # groups the data by a column and # returns the mean age per group return dataframe.groupby(col).mean() # function to convert to uppercasedef uppercase_column_name(dataframe): # Converts all the column names into uppercase dataframe.columns = dataframe.columns.str.upper() # And returns them return dataframe Now, creating a pipeline using .pipe() function. Python3 # Create a pipeline that applies both the functions created abovepipeline = df.pipe(mean_age_by_group, col='gender').pipe(uppercase_column_name) # calling pipelinepipeline Output: Now, let’s understand and create a pipeline by importing pdpipe package. The pdpipe Python package provides a concise interface for building pandas pipelines that have pre-conditions. The pdpipe is a pre-processing pipeline package for Python’s panda data frame. The pdpipe API helps to easily break down or compose complex-ed panda processing pipelines with few lines of codes. We can install this package by simply writing: pip install pdpipe Example 2: Python3 # importing the packageimport pdpipe as pdpimport pandas as pd # creating a empty dataframe named datasetdataset = pd.DataFrame() # Creating a simple dataframedataset['name'] = ['Reema', 'Shyam', 'Jai', 'Nimisha', 'Rohit', 'Riya'] dataset['gender'] = ['Female', 'Male', 'Male', 'Female', 'Male', 'Female'] dataset['age'] = [31, 32, 19, 23, 28, 33] dataset['department'] = ['Accounts', 'Management', 'IT', 'IT', 'Management', 'Advertising'] dataset['index'] = [1, 2, 3, 4, 5, 6] # View dataframedataset Output: Removing a column from dataframe using pdpipe. Python3 # creating a pipeline and# dropping the unwanted columndropCol = pdp.ColDrop("index").apply(dataset) # display the new dataframe# after column dropdropCol Output: There is another way to drop columns through pdpipe. Python3 # creating a pipeline and# dropping the unwanted columndropCol2 = pdp.ColDrop("index") # applying the ColDrop to dataframedf2 = dropCol2(dataset) # display dataframedf2 Output: Here, the column is dropped in two steps. In the first step, we created a pipeline and in the second step, we applied it to the dataframe. Now we are adding one column to dataframe using pdpipe. Python3 # importing the packageimport pdpipe as pdpimport pandas as pd # creating a empty dataframe named datasetdataset = pd.DataFrame() # Creating a simple dataframedataset['name'] = ['Reema', 'Shyam', 'Jai', 'Nimisha', 'Rohit', 'Riya'] dataset['gender'] = ['Female', 'Male', 'Male', 'Female', 'Male', 'Female'] dataset['age'] = [31, 32, 19, 23, 28, 33] dataset['department'] = ['Accounts', 'Management', 'IT', 'IT', 'Management', 'Advertising'] dataset['index'] = [1, 2, 3, 4, 5, 6] # View dataframedataset Output: Now, dropping the values from dataframe. Python3 #dropping the values using ValDropdf3 = pdp.ValDrop(['IT'],'department').apply(dataset) #display dataframedf3 Output: The row containing ‘ IT ‘ value is dropped. abhishek0719kadiyan prachisoda1234 rajeev0719singh rs1686740 saurabh1990aror Picked Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n17 Jan, 2022" }, { "code": null, "e": 24596, "s": 24212, "text": "Pipelines play a useful role in transforming and manipulating tons of data. Pipeline are a sequence of data processing mechanisms. Pandas pipeline feature allows us to string together various user-defined Python functions in order to build a pipeline of data processing. There are two ways to create a Pipeline in pandas. By calling .pipe() function and by importing pdpipe package. " }, { "code": null, "e": 24806, "s": 24596, "text": "Through pandas pipeline function i.e. pipe() function we can call more than one function at a time and in a single line for data processing. Let’s understand and create a pipeline by using the pipe() function." }, { "code": null, "e": 24884, "s": 24806, "text": "Below are various examples that depict how to create a pipeline using pandas." }, { "code": null, "e": 24895, "s": 24884, "text": "Example 1:" }, { "code": null, "e": 24903, "s": 24895, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Create empty dataframedf = pd.DataFrame() # Creating a simple dataframedf['name'] = ['Reema', 'Shyam', 'Jai', 'Nimisha', 'Rohit', 'Riya']df['gender'] = ['Female', 'Male', 'Male', 'Female', 'Male', 'Female']df['age'] = [31, 32, 19, 23, 28, 33] # View dataframedf", "e": 25241, "s": 24903, "text": null }, { "code": null, "e": 25249, "s": 25241, "text": "Output:" }, { "code": null, "e": 25294, "s": 25249, "text": "Now, creating functions for data processing." }, { "code": null, "e": 25302, "s": 25294, "text": "Python3" }, { "code": "# function to find meandef mean_age_by_group(dataframe, col): # groups the data by a column and # returns the mean age per group return dataframe.groupby(col).mean() # function to convert to uppercasedef uppercase_column_name(dataframe): # Converts all the column names into uppercase dataframe.columns = dataframe.columns.str.upper() # And returns them return dataframe ", "e": 25708, "s": 25302, "text": null }, { "code": null, "e": 25757, "s": 25708, "text": "Now, creating a pipeline using .pipe() function." }, { "code": null, "e": 25765, "s": 25757, "text": "Python3" }, { "code": "# Create a pipeline that applies both the functions created abovepipeline = df.pipe(mean_age_by_group, col='gender').pipe(uppercase_column_name) # calling pipelinepipeline", "e": 25937, "s": 25765, "text": null }, { "code": null, "e": 25945, "s": 25937, "text": "Output:" }, { "code": null, "e": 26018, "s": 25945, "text": "Now, let’s understand and create a pipeline by importing pdpipe package." }, { "code": null, "e": 26325, "s": 26018, "text": "The pdpipe Python package provides a concise interface for building pandas pipelines that have pre-conditions. The pdpipe is a pre-processing pipeline package for Python’s panda data frame. The pdpipe API helps to easily break down or compose complex-ed panda processing pipelines with few lines of codes. " }, { "code": null, "e": 26372, "s": 26325, "text": "We can install this package by simply writing:" }, { "code": null, "e": 26391, "s": 26372, "text": "pip install pdpipe" }, { "code": null, "e": 26402, "s": 26391, "text": "Example 2:" }, { "code": null, "e": 26410, "s": 26402, "text": "Python3" }, { "code": "# importing the packageimport pdpipe as pdpimport pandas as pd # creating a empty dataframe named datasetdataset = pd.DataFrame() # Creating a simple dataframedataset['name'] = ['Reema', 'Shyam', 'Jai', 'Nimisha', 'Rohit', 'Riya'] dataset['gender'] = ['Female', 'Male', 'Male', 'Female', 'Male', 'Female'] dataset['age'] = [31, 32, 19, 23, 28, 33] dataset['department'] = ['Accounts', 'Management', 'IT', 'IT', 'Management', 'Advertising'] dataset['index'] = [1, 2, 3, 4, 5, 6] # View dataframedataset", "e": 26998, "s": 26410, "text": null }, { "code": null, "e": 27006, "s": 26998, "text": "Output:" }, { "code": null, "e": 27053, "s": 27006, "text": "Removing a column from dataframe using pdpipe." }, { "code": null, "e": 27061, "s": 27053, "text": "Python3" }, { "code": "# creating a pipeline and# dropping the unwanted columndropCol = pdp.ColDrop(\"index\").apply(dataset) # display the new dataframe# after column dropdropCol", "e": 27216, "s": 27061, "text": null }, { "code": null, "e": 27224, "s": 27216, "text": "Output:" }, { "code": null, "e": 27277, "s": 27224, "text": "There is another way to drop columns through pdpipe." }, { "code": null, "e": 27285, "s": 27277, "text": "Python3" }, { "code": "# creating a pipeline and# dropping the unwanted columndropCol2 = pdp.ColDrop(\"index\") # applying the ColDrop to dataframedf2 = dropCol2(dataset) # display dataframedf2", "e": 27454, "s": 27285, "text": null }, { "code": null, "e": 27462, "s": 27454, "text": "Output:" }, { "code": null, "e": 27601, "s": 27462, "text": "Here, the column is dropped in two steps. In the first step, we created a pipeline and in the second step, we applied it to the dataframe." }, { "code": null, "e": 27657, "s": 27601, "text": "Now we are adding one column to dataframe using pdpipe." }, { "code": null, "e": 27665, "s": 27657, "text": "Python3" }, { "code": "# importing the packageimport pdpipe as pdpimport pandas as pd # creating a empty dataframe named datasetdataset = pd.DataFrame() # Creating a simple dataframedataset['name'] = ['Reema', 'Shyam', 'Jai', 'Nimisha', 'Rohit', 'Riya'] dataset['gender'] = ['Female', 'Male', 'Male', 'Female', 'Male', 'Female'] dataset['age'] = [31, 32, 19, 23, 28, 33] dataset['department'] = ['Accounts', 'Management', 'IT', 'IT', 'Management', 'Advertising'] dataset['index'] = [1, 2, 3, 4, 5, 6] # View dataframedataset", "e": 28253, "s": 27665, "text": null }, { "code": null, "e": 28261, "s": 28253, "text": "Output:" }, { "code": null, "e": 28302, "s": 28261, "text": "Now, dropping the values from dataframe." }, { "code": null, "e": 28310, "s": 28302, "text": "Python3" }, { "code": "#dropping the values using ValDropdf3 = pdp.ValDrop(['IT'],'department').apply(dataset) #display dataframedf3", "e": 28420, "s": 28310, "text": null }, { "code": null, "e": 28431, "s": 28423, "text": "Output:" }, { "code": null, "e": 28479, "s": 28435, "text": "The row containing ‘ IT ‘ value is dropped." }, { "code": null, "e": 28501, "s": 28481, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28516, "s": 28501, "text": "prachisoda1234" }, { "code": null, "e": 28532, "s": 28516, "text": "rajeev0719singh" }, { "code": null, "e": 28542, "s": 28532, "text": "rs1686740" }, { "code": null, "e": 28558, "s": 28542, "text": "saurabh1990aror" }, { "code": null, "e": 28565, "s": 28558, "text": "Picked" }, { "code": null, "e": 28579, "s": 28565, "text": "Python-pandas" }, { "code": null, "e": 28586, "s": 28579, "text": "Python" }, { "code": null, "e": 28684, "s": 28586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28693, "s": 28684, "text": "Comments" }, { "code": null, "e": 28706, "s": 28693, "text": "Old Comments" }, { "code": null, "e": 28738, "s": 28706, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28794, "s": 28738, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28815, "s": 28794, "text": "Python OOPs Concepts" }, { "code": null, "e": 28854, "s": 28815, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28896, "s": 28854, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28923, "s": 28896, "text": "Python Classes and Objects" }, { "code": null, "e": 28954, "s": 28923, "text": "Python | os.path.join() method" }, { "code": null, "e": 28996, "s": 28954, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29032, "s": 28996, "text": "Python | Pandas dataframe.groupby()" } ]
10 tips to improve your plotting. Because in real-life data science... | by Gonzalo Ferreiro Volpi | Towards Data Science
I have to be honest with you: when I was studying Data Science I completely underestimated the importance of plotting. It’s true, everything was a mess back then: in between learning Python from scratch, getting my head around all the possible algorithms and understanding the math behind everything, plotting was the very last of my problems. And why shouldn’t it be? We were always plotting the same kind of things. You know: pairplots, distplots, qqplots...those charts you use when visualizing the data is the only way of understanding it. Very useful charts. But very generic and default charts too. So copying and pasting a bunch of code became my best friend those days. For my projects, the deliverable was always a model. Hopefully with some reasonable score thanks to hours and hours of cleaning and feature engineering. I was the only person involved in my projects and my professors already knew everything about that data since they gave it to me. So who would I be plotting for? Myself? C’mon...unnecessary! Right? I knew better than no one what was I trying to achieve in each step. I needed to explain nothing to nobody. But apart from all this, let’s be honest, plotting it’s not fancy at all. Anyone can plot. My 60 years old father can pull some charts out of the hat just by using Excel. And if everybody can do it then, of course, that’s the definition of not being fancy. Cause here my friends, we’re doing Data Science and Machine Learning. And most of the people can’t even understand what that is. That’s why we’re all so cool and sexy, as Harvard Business Review magazine said. The problem is peeps -if you haven’t found out yet by my excessive irony, that this is not how real life works. And I believe that was probably the biggest failure in my Data Science immersive: not weighting up enough the importance of explainability and interpretability. You might be a genius, but if you are not able to explain to a third party how and why you’re getting those wonderful predictions, then you might have nothing. For example, at Ravelin Technology we offer machine learning-based solutions for fraud prevention. Imagine telling a client, that we’re blocking X% of the transactions because the machine learning model says so, but without having any idea at all about why is doing it. Surely not very appealing for any e-commerce out there trying to maximize conversion and sells, right? Imagine now this same kind of situation in some other sensitive domains as healthcare...disaster would be just around the corner. Now, apart from business-related problems, and even aside from a legal point of view or from the fact that maybe your business only cares about predictions -no matter how you get them, understanding how an algorithm is actually working can help. Not only to better explain outputs to customers but also to better align the activities of data scientists and analysts. So it comes up that in the real world, the picture is completely different from the one I had when I was working in my academic data science projects: I’m never the only person involved in a project and my workmates and/or clients usually don’t know much about the data I’m using. So who would I be plotting for now? Does it still sound unnecessary? Probably not. And being able to explain your thinking process to people is a key part of any data-related job. That’s why copying and pasting charts is not enough and charts personalization becomes very important. In what’s left of this post I’ll like to share with you 10basic, intermediate and advanced tools I’ve found very useful in real life when it comes to plotting for explaining things about your data. The libraries I’ll be referencing in the following lines we’ll be: Seaborn | From: import seaborn as sns Matplotlib | From: matplotlib.pyplot as plt Additionally, if you want, you can set up a style and your favourite format like: plt.style.use(‘fivethirtyeight’)%config InlineBackend.figure_format = ‘retina’%matplotlib inline Having said that, let’s jump straight to the tools: There will be opportunities in which you’ll want to plot several things within one chart, and we’ll cover that in brief. But some other times, you’ll want to throw different charts in the same row or column, complementing each other and/or showing different pieces of information. For this, we’re going to see a very basic but essential tool: subplots. How to use it? Very simple. A chart in matplotlib is a construction using: A figure: the background or canvas for drawing our charts Axes: our chart or charts Usually, these things are set up automatically on the background of our code, but if we want to draw several plots, we only need to create our figure and axes objects in the following way: fig, ax = plt.subplots(ncols=number_of_cols, nrows=number_of_rows, figsize=(x,y)) So for example, if we set up ncols = 1 and nrows = 2, we’ll be creating a figure of size x,y with only 2 charts, distributed in two different rows. The only thing left would be to specify the order for the different plots using the ‘ax’ parameter and starting from 0. For example: sns.scatterplot(x=horizontal_data_1, y=vertical_data_1, ax=ax[0]);sns.scatterplot(x=horizontal_data_2, y=vertical_data_2, ax=ax[1]); This might appear unnecessary, or not very helpful, but you cannot imagine how many times you can be asked what’s on the X/Y axis if your chart is somehow confusing, or who is seeing it is not very familiar with the data. Following our previous example with two plots, if we want to set up a specific name for our axis, we’ll have to use the following code lines: ax[0].set(xlabel=’My X label’, ylabel=’My Y label’)ax[1].set(xlabel=’My second X label’, ylabel=’My second and very creative Y label’) Another basic but key tool if we’re presenting our data to a third party is using titles, and it works in a very similar way as our previous axis labelling point: ax[0].title.set_text(‘This title has to be very clear and explicative’)ax[1].title.set_text(‘And this title has to explain what’s different in this chart’) More often than note, just having the y-scale to the right or left of our chart is not going to be very clear by itself. Whether it is because all values are very close in between them or because precision is very important for the thing being analyzed. Whatever the case, annotating the value on the plot can be very useful to add clarification and self-explanation to it. Suppose now we’re using subplots, so we have several charts, and one of them is a Seaborn’s barplot in the position ax[0]. In this case, the code for getting the annotation on each bar is a bit more complex but very easy to implement: for p in ax[0].patches:ax[0].annotate(“%.2f” % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),ha=’center’, va=’center’, fontsize=12, color=’white’, xytext=(0, -10), textcoords=’offset points’) For each ‘patch’ or bar in our chart, the code till the ‘ha’ parameter gets the location, height and width of the bar, to put the value annotation in the right position. In a similar way, we can also specify alignment, fontsize and colour of the annotation, while the ‘xytext’ parameter indicates whether we want to move our annotation in some x or y direction. In our example above, we would be moving the text down on the y axis. In some cases, over a period of time or a range of values, we might have measured a different kind of objects. For example, suppose that over 6 months we measure the weight of dogs and cats. At the end of the period, we want to plot the weight of each animal, but differencing in between dogs and cats using blue and red respectively. For that, in most of the traditional plots, we can use the parameter ‘hue’ to provide a list of colours for our elements. Take the following example: weight = [5,4,8,2,6,2]month = [‘febrero’,’enero’,’abril’,’junio’,’marzo’,’mayo’]animal_type = [‘dog’,’cat’,’cat’,’dog’,’dog’,’dog’]hue = [‘blue’,’red’,’red’,’blue’,’blue’,’blue’]sns.scatterplot(x=month, y=weight, hue=hue); Using the same example from above, we could want also to add into the chart the size of the weighted animal, using a scale from 1 to 5. A good option for adding this extra metric into the plot would be modifying the size of the scatterplot, assigning the sizes to a new additional vector through the ‘size’ parameter and using ‘sizes’ to adjust the relationship in between them: size = [2,3,5,1,4,1]sns.scatterplot(x=month, y=weight, hue=hue, size=size, sizes=(50,300)); And by the way, if as in the chart above, the legend is making the plot harder to read instead of helping, you can always remove it setting the ‘legend’ parameter equal False ;) In many cases in real life, having data above or below a certain threshold might be a signal of problems or a warning for errors. If we want to clearly show this on a plot, we can add a line using the following command: ax[0].axvline(32,0,c=’r’) Where: ax[0] will be the chart in which we want to insert the line 32 is going to be the value in which the line is going to be drawn And c=’r’ draws in colour red If we are working with subplots, it is as simple as adding an axvline to the corresponding axe as in the example above. However, if we are not using subplots, we should do the following: g = sns.scatterplot(x=month, y=weight, hue=hue, legend=False)g.axvline(2,c=’r’)plt.show() This might be the simplest, but also one of the most helpful tips. Sometimes we just need to add more information to our chat, and there’s no other way around it than adding a new metric on the right y-axis of our plot: ax2 = ax[0].twinx() Now you can add any chart you want pointing the ‘ax’ parameter to ‘ax2’ sns.lineplot(x=month, y=average_animal_weight, ax=ax2) Mind that this example assumes again you’re working with subplots. If you’re not, you should follow the same kind of logic as in the previous point: g = sns.scatterplot(x=month, y=weight, hue=hue, legend=False)g.axvline(2,c=’r’)ax2 = g.twinx()sns.lineplot(x=month, y=average_animal_weight, ax=ax2, c=’y’)plt.show() Mind that for this to work, you should set up always the same data for x-axis in both charts. Otherwise, they’re not going to match. Overlapping charts on the same axis is easy: we just need to write the code for all the plots we want, and afterwards, we can simply call ‘plt.show()’ for all of them to be drawn together: a = [1,2,3,4,5]b = [4,5,6,2,2]c = [2,5,6,2,1]sns.lineplot(x=a, y=b, c=’r’)sns.lineplot(x=a, y=c, c=’b’)plt.show() However, sometimes overlapping can result in confusion, so we might want to personalize our chart a beat for making eat clearer. For example, suppose you want to overlap in the same figure the height distribution of two different samples you took: one from your workmates and another from your local basketball team. It would be nice to personalize things such as the colour of both plots and add a legend specifying which is which, right? Well, easy peasy: Setting up the ‘colour’ label we can set up a specific colour for each one. Be aware that sometimes this parameter can change to simply ‘c’ And with the ‘label’ parameter we can specify any text for them to appear by simply calling after ‘x.legend()’ Take the following example: g = sns.distplot(workmates_height, color=’b’, label=’Workmates’)sns.distplot(basketball_team, color=’r’, ax=g, label=’Basket team’)g.legend()plt.show() Finally, a very specific tool if you like using barplots, you might have faced the problem of not having your bars in the order you’d like them to be. In that case, there’s a simple fix for that, passing a list with the specific order you want to the ‘order’ parameter: a=[‘second’,’first’,’third’]b=[15,10,20]sns.barplot(x=a,y=b,order=[‘first’,’second’,’third’]); Plotting is a world by itself, and in my experience, the best world of improving your skills is by practising. But I hope these tools and tips help you when the real-world Data Science hits you as it happened to me :) Finally, don’t forget to check out some of my last articles, like 6 amateur mistakes I’ve made working with train-test splits or Web scraping in 5 minutes. All of them available in my profile. Also, if you want to receive my latest articles directly on your email, just subscribe to my newsletter :) See you around!
[ { "code": null, "e": 516, "s": 172, "text": "I have to be honest with you: when I was studying Data Science I completely underestimated the importance of plotting. It’s true, everything was a mess back then: in between learning Python from scratch, getting my head around all the possible algorithms and understanding the math behind everything, plotting was the very last of my problems." }, { "code": null, "e": 850, "s": 516, "text": "And why shouldn’t it be? We were always plotting the same kind of things. You know: pairplots, distplots, qqplots...those charts you use when visualizing the data is the only way of understanding it. Very useful charts. But very generic and default charts too. So copying and pasting a bunch of code became my best friend those days." }, { "code": null, "e": 1309, "s": 850, "text": "For my projects, the deliverable was always a model. Hopefully with some reasonable score thanks to hours and hours of cleaning and feature engineering. I was the only person involved in my projects and my professors already knew everything about that data since they gave it to me. So who would I be plotting for? Myself? C’mon...unnecessary! Right? I knew better than no one what was I trying to achieve in each step. I needed to explain nothing to nobody." }, { "code": null, "e": 1776, "s": 1309, "text": "But apart from all this, let’s be honest, plotting it’s not fancy at all. Anyone can plot. My 60 years old father can pull some charts out of the hat just by using Excel. And if everybody can do it then, of course, that’s the definition of not being fancy. Cause here my friends, we’re doing Data Science and Machine Learning. And most of the people can’t even understand what that is. That’s why we’re all so cool and sexy, as Harvard Business Review magazine said." }, { "code": null, "e": 2712, "s": 1776, "text": "The problem is peeps -if you haven’t found out yet by my excessive irony, that this is not how real life works. And I believe that was probably the biggest failure in my Data Science immersive: not weighting up enough the importance of explainability and interpretability. You might be a genius, but if you are not able to explain to a third party how and why you’re getting those wonderful predictions, then you might have nothing. For example, at Ravelin Technology we offer machine learning-based solutions for fraud prevention. Imagine telling a client, that we’re blocking X% of the transactions because the machine learning model says so, but without having any idea at all about why is doing it. Surely not very appealing for any e-commerce out there trying to maximize conversion and sells, right? Imagine now this same kind of situation in some other sensitive domains as healthcare...disaster would be just around the corner." }, { "code": null, "e": 3079, "s": 2712, "text": "Now, apart from business-related problems, and even aside from a legal point of view or from the fact that maybe your business only cares about predictions -no matter how you get them, understanding how an algorithm is actually working can help. Not only to better explain outputs to customers but also to better align the activities of data scientists and analysts." }, { "code": null, "e": 3643, "s": 3079, "text": "So it comes up that in the real world, the picture is completely different from the one I had when I was working in my academic data science projects: I’m never the only person involved in a project and my workmates and/or clients usually don’t know much about the data I’m using. So who would I be plotting for now? Does it still sound unnecessary? Probably not. And being able to explain your thinking process to people is a key part of any data-related job. That’s why copying and pasting charts is not enough and charts personalization becomes very important." }, { "code": null, "e": 3841, "s": 3643, "text": "In what’s left of this post I’ll like to share with you 10basic, intermediate and advanced tools I’ve found very useful in real life when it comes to plotting for explaining things about your data." }, { "code": null, "e": 3908, "s": 3841, "text": "The libraries I’ll be referencing in the following lines we’ll be:" }, { "code": null, "e": 3946, "s": 3908, "text": "Seaborn | From: import seaborn as sns" }, { "code": null, "e": 3990, "s": 3946, "text": "Matplotlib | From: matplotlib.pyplot as plt" }, { "code": null, "e": 4072, "s": 3990, "text": "Additionally, if you want, you can set up a style and your favourite format like:" }, { "code": null, "e": 4169, "s": 4072, "text": "plt.style.use(‘fivethirtyeight’)%config InlineBackend.figure_format = ‘retina’%matplotlib inline" }, { "code": null, "e": 4221, "s": 4169, "text": "Having said that, let’s jump straight to the tools:" }, { "code": null, "e": 4502, "s": 4221, "text": "There will be opportunities in which you’ll want to plot several things within one chart, and we’ll cover that in brief. But some other times, you’ll want to throw different charts in the same row or column, complementing each other and/or showing different pieces of information." }, { "code": null, "e": 4649, "s": 4502, "text": "For this, we’re going to see a very basic but essential tool: subplots. How to use it? Very simple. A chart in matplotlib is a construction using:" }, { "code": null, "e": 4707, "s": 4649, "text": "A figure: the background or canvas for drawing our charts" }, { "code": null, "e": 4733, "s": 4707, "text": "Axes: our chart or charts" }, { "code": null, "e": 4922, "s": 4733, "text": "Usually, these things are set up automatically on the background of our code, but if we want to draw several plots, we only need to create our figure and axes objects in the following way:" }, { "code": null, "e": 5004, "s": 4922, "text": "fig, ax = plt.subplots(ncols=number_of_cols, nrows=number_of_rows, figsize=(x,y))" }, { "code": null, "e": 5285, "s": 5004, "text": "So for example, if we set up ncols = 1 and nrows = 2, we’ll be creating a figure of size x,y with only 2 charts, distributed in two different rows. The only thing left would be to specify the order for the different plots using the ‘ax’ parameter and starting from 0. For example:" }, { "code": null, "e": 5418, "s": 5285, "text": "sns.scatterplot(x=horizontal_data_1, y=vertical_data_1, ax=ax[0]);sns.scatterplot(x=horizontal_data_2, y=vertical_data_2, ax=ax[1]);" }, { "code": null, "e": 5782, "s": 5418, "text": "This might appear unnecessary, or not very helpful, but you cannot imagine how many times you can be asked what’s on the X/Y axis if your chart is somehow confusing, or who is seeing it is not very familiar with the data. Following our previous example with two plots, if we want to set up a specific name for our axis, we’ll have to use the following code lines:" }, { "code": null, "e": 5917, "s": 5782, "text": "ax[0].set(xlabel=’My X label’, ylabel=’My Y label’)ax[1].set(xlabel=’My second X label’, ylabel=’My second and very creative Y label’)" }, { "code": null, "e": 6080, "s": 5917, "text": "Another basic but key tool if we’re presenting our data to a third party is using titles, and it works in a very similar way as our previous axis labelling point:" }, { "code": null, "e": 6236, "s": 6080, "text": "ax[0].title.set_text(‘This title has to be very clear and explicative’)ax[1].title.set_text(‘And this title has to explain what’s different in this chart’)" }, { "code": null, "e": 6610, "s": 6236, "text": "More often than note, just having the y-scale to the right or left of our chart is not going to be very clear by itself. Whether it is because all values are very close in between them or because precision is very important for the thing being analyzed. Whatever the case, annotating the value on the plot can be very useful to add clarification and self-explanation to it." }, { "code": null, "e": 6845, "s": 6610, "text": "Suppose now we’re using subplots, so we have several charts, and one of them is a Seaborn’s barplot in the position ax[0]. In this case, the code for getting the annotation on each bar is a bit more complex but very easy to implement:" }, { "code": null, "e": 7056, "s": 6845, "text": "for p in ax[0].patches:ax[0].annotate(“%.2f” % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),ha=’center’, va=’center’, fontsize=12, color=’white’, xytext=(0, -10), textcoords=’offset points’)" }, { "code": null, "e": 7488, "s": 7056, "text": "For each ‘patch’ or bar in our chart, the code till the ‘ha’ parameter gets the location, height and width of the bar, to put the value annotation in the right position. In a similar way, we can also specify alignment, fontsize and colour of the annotation, while the ‘xytext’ parameter indicates whether we want to move our annotation in some x or y direction. In our example above, we would be moving the text down on the y axis." }, { "code": null, "e": 7945, "s": 7488, "text": "In some cases, over a period of time or a range of values, we might have measured a different kind of objects. For example, suppose that over 6 months we measure the weight of dogs and cats. At the end of the period, we want to plot the weight of each animal, but differencing in between dogs and cats using blue and red respectively. For that, in most of the traditional plots, we can use the parameter ‘hue’ to provide a list of colours for our elements." }, { "code": null, "e": 7973, "s": 7945, "text": "Take the following example:" }, { "code": null, "e": 8196, "s": 7973, "text": "weight = [5,4,8,2,6,2]month = [‘febrero’,’enero’,’abril’,’junio’,’marzo’,’mayo’]animal_type = [‘dog’,’cat’,’cat’,’dog’,’dog’,’dog’]hue = [‘blue’,’red’,’red’,’blue’,’blue’,’blue’]sns.scatterplot(x=month, y=weight, hue=hue);" }, { "code": null, "e": 8575, "s": 8196, "text": "Using the same example from above, we could want also to add into the chart the size of the weighted animal, using a scale from 1 to 5. A good option for adding this extra metric into the plot would be modifying the size of the scatterplot, assigning the sizes to a new additional vector through the ‘size’ parameter and using ‘sizes’ to adjust the relationship in between them:" }, { "code": null, "e": 8667, "s": 8575, "text": "size = [2,3,5,1,4,1]sns.scatterplot(x=month, y=weight, hue=hue, size=size, sizes=(50,300));" }, { "code": null, "e": 8845, "s": 8667, "text": "And by the way, if as in the chart above, the legend is making the plot harder to read instead of helping, you can always remove it setting the ‘legend’ parameter equal False ;)" }, { "code": null, "e": 9065, "s": 8845, "text": "In many cases in real life, having data above or below a certain threshold might be a signal of problems or a warning for errors. If we want to clearly show this on a plot, we can add a line using the following command:" }, { "code": null, "e": 9091, "s": 9065, "text": "ax[0].axvline(32,0,c=’r’)" }, { "code": null, "e": 9098, "s": 9091, "text": "Where:" }, { "code": null, "e": 9158, "s": 9098, "text": "ax[0] will be the chart in which we want to insert the line" }, { "code": null, "e": 9225, "s": 9158, "text": "32 is going to be the value in which the line is going to be drawn" }, { "code": null, "e": 9255, "s": 9225, "text": "And c=’r’ draws in colour red" }, { "code": null, "e": 9442, "s": 9255, "text": "If we are working with subplots, it is as simple as adding an axvline to the corresponding axe as in the example above. However, if we are not using subplots, we should do the following:" }, { "code": null, "e": 9532, "s": 9442, "text": "g = sns.scatterplot(x=month, y=weight, hue=hue, legend=False)g.axvline(2,c=’r’)plt.show()" }, { "code": null, "e": 9599, "s": 9532, "text": "This might be the simplest, but also one of the most helpful tips." }, { "code": null, "e": 9752, "s": 9599, "text": "Sometimes we just need to add more information to our chat, and there’s no other way around it than adding a new metric on the right y-axis of our plot:" }, { "code": null, "e": 9772, "s": 9752, "text": "ax2 = ax[0].twinx()" }, { "code": null, "e": 9844, "s": 9772, "text": "Now you can add any chart you want pointing the ‘ax’ parameter to ‘ax2’" }, { "code": null, "e": 9899, "s": 9844, "text": "sns.lineplot(x=month, y=average_animal_weight, ax=ax2)" }, { "code": null, "e": 10048, "s": 9899, "text": "Mind that this example assumes again you’re working with subplots. If you’re not, you should follow the same kind of logic as in the previous point:" }, { "code": null, "e": 10214, "s": 10048, "text": "g = sns.scatterplot(x=month, y=weight, hue=hue, legend=False)g.axvline(2,c=’r’)ax2 = g.twinx()sns.lineplot(x=month, y=average_animal_weight, ax=ax2, c=’y’)plt.show()" }, { "code": null, "e": 10347, "s": 10214, "text": "Mind that for this to work, you should set up always the same data for x-axis in both charts. Otherwise, they’re not going to match." }, { "code": null, "e": 10536, "s": 10347, "text": "Overlapping charts on the same axis is easy: we just need to write the code for all the plots we want, and afterwards, we can simply call ‘plt.show()’ for all of them to be drawn together:" }, { "code": null, "e": 10650, "s": 10536, "text": "a = [1,2,3,4,5]b = [4,5,6,2,2]c = [2,5,6,2,1]sns.lineplot(x=a, y=b, c=’r’)sns.lineplot(x=a, y=c, c=’b’)plt.show()" }, { "code": null, "e": 10779, "s": 10650, "text": "However, sometimes overlapping can result in confusion, so we might want to personalize our chart a beat for making eat clearer." }, { "code": null, "e": 11108, "s": 10779, "text": "For example, suppose you want to overlap in the same figure the height distribution of two different samples you took: one from your workmates and another from your local basketball team. It would be nice to personalize things such as the colour of both plots and add a legend specifying which is which, right? Well, easy peasy:" }, { "code": null, "e": 11248, "s": 11108, "text": "Setting up the ‘colour’ label we can set up a specific colour for each one. Be aware that sometimes this parameter can change to simply ‘c’" }, { "code": null, "e": 11359, "s": 11248, "text": "And with the ‘label’ parameter we can specify any text for them to appear by simply calling after ‘x.legend()’" }, { "code": null, "e": 11387, "s": 11359, "text": "Take the following example:" }, { "code": null, "e": 11539, "s": 11387, "text": "g = sns.distplot(workmates_height, color=’b’, label=’Workmates’)sns.distplot(basketball_team, color=’r’, ax=g, label=’Basket team’)g.legend()plt.show()" }, { "code": null, "e": 11809, "s": 11539, "text": "Finally, a very specific tool if you like using barplots, you might have faced the problem of not having your bars in the order you’d like them to be. In that case, there’s a simple fix for that, passing a list with the specific order you want to the ‘order’ parameter:" }, { "code": null, "e": 11904, "s": 11809, "text": "a=[‘second’,’first’,’third’]b=[15,10,20]sns.barplot(x=a,y=b,order=[‘first’,’second’,’third’]);" }, { "code": null, "e": 12122, "s": 11904, "text": "Plotting is a world by itself, and in my experience, the best world of improving your skills is by practising. But I hope these tools and tips help you when the real-world Data Science hits you as it happened to me :)" }, { "code": null, "e": 12422, "s": 12122, "text": "Finally, don’t forget to check out some of my last articles, like 6 amateur mistakes I’ve made working with train-test splits or Web scraping in 5 minutes. All of them available in my profile. Also, if you want to receive my latest articles directly on your email, just subscribe to my newsletter :)" } ]
Convert Java Boolean Primitive to Boolean object
To convert Boolean Primitive to Boolean object, use the valueOf() method in Java. Firstly, let us take a boolean primitive. boolean val = false; To convert it into an object, use the valueOf() method and set the argument as the boolean primitive. Boolean res = Boolean.valueOf(val); Let us see the complete example to learn how to convert Boolean Primitive to Boolean object. Live Demo public class Demo { public static void main(String[] args) { boolean val = false; // converting to object Boolean res = Boolean.valueOf(val); System.out.println(res); } } False
[ { "code": null, "e": 1144, "s": 1062, "text": "To convert Boolean Primitive to Boolean object, use the valueOf() method in Java." }, { "code": null, "e": 1186, "s": 1144, "text": "Firstly, let us take a boolean primitive." }, { "code": null, "e": 1207, "s": 1186, "text": "boolean val = false;" }, { "code": null, "e": 1309, "s": 1207, "text": "To convert it into an object, use the valueOf() method and set the argument as the boolean primitive." }, { "code": null, "e": 1345, "s": 1309, "text": "Boolean res = Boolean.valueOf(val);" }, { "code": null, "e": 1438, "s": 1345, "text": "Let us see the complete example to learn how to convert Boolean Primitive to Boolean object." }, { "code": null, "e": 1449, "s": 1438, "text": " Live Demo" }, { "code": null, "e": 1650, "s": 1449, "text": "public class Demo {\n public static void main(String[] args) {\n boolean val = false;\n // converting to object\n Boolean res = Boolean.valueOf(val);\n System.out.println(res);\n }\n}" }, { "code": null, "e": 1656, "s": 1650, "text": "False" } ]
How to create a simple counter Using ReactJS? - GeeksforGeeks
05 Jan, 2021 React is a front-end, open-source JavaScript library that is used to create interactive UI. It is developed and maintained by Facebook. It can be used for the development of single-page and mobile applications. We’ll be creating a simple application where we have 2 buttons one to increment and one to decrement. Initial Setup: The npx is a CLI tool used to install and manage dependencies in the npm registry. NPX comes pre-bundled with npm 5.2+, else we can install it using the following command: npm i -g npx // -g flag indicates global installation Creating React Application: Step 1: Create a React application using the following command: npx create-react-app counter Step 2: After creating your project folder i.e. counter, move to it using the following command: cd counter Project Structure: It will look like the following. Project Structure Filename: App.js: Javascript import React, { useState } from "react"; // Importing app.css is css file to add stylingimport "./App.css"; const App = () => { // Counter is a state initialized to 0 const [counter, setCounter] = useState(0) // Function is called everytime increment button is clicked const handleClick1 = () => { // Counter state is incremented setCounter(counter + 1) } // Function is called everytime decrement button is clicked const handleClick2 = () => { // Counter state is decremented setCounter(counter - 1) } return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontSize: '300%', position: 'absolute', width: '100%', height: '100%', top: '-15%', }}> Counter App <div style={{ fontSize: '120%', position: 'relative', top: '10vh', }}> {counter} </div> <div className="buttons"> <button style={{ fontSize: '60%', position: 'relative', top: '20vh', marginRight: '5px', backgroundColor: 'green', borderRadius: '8%', color: 'white', }} onClick={handleClick1}>Increment</button> <button style={{ fontSize: '60%', position: 'relative', top: '20vh', marginLeft: '5px', backgroundColor: 'red', borderRadius: '8%', color: 'white', }} onClick={handleClick2}>Decrement</button> </div> </div> )} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: react-js CSS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? Design a web page using HTML and CSS Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 25691, "s": 25663, "text": "\n05 Jan, 2021" }, { "code": null, "e": 25902, "s": 25691, "text": "React is a front-end, open-source JavaScript library that is used to create interactive UI. It is developed and maintained by Facebook. It can be used for the development of single-page and mobile applications." }, { "code": null, "e": 26004, "s": 25902, "text": "We’ll be creating a simple application where we have 2 buttons one to increment and one to decrement." }, { "code": null, "e": 26191, "s": 26004, "text": "Initial Setup: The npx is a CLI tool used to install and manage dependencies in the npm registry. NPX comes pre-bundled with npm 5.2+, else we can install it using the following command:" }, { "code": null, "e": 26248, "s": 26191, "text": "npm i -g npx // -g flag indicates global installation" }, { "code": null, "e": 26276, "s": 26248, "text": "Creating React Application:" }, { "code": null, "e": 26340, "s": 26276, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26369, "s": 26340, "text": "npx create-react-app counter" }, { "code": null, "e": 26466, "s": 26369, "text": "Step 2: After creating your project folder i.e. counter, move to it using the following command:" }, { "code": null, "e": 26477, "s": 26466, "text": "cd counter" }, { "code": null, "e": 26529, "s": 26477, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26547, "s": 26529, "text": "Project Structure" }, { "code": null, "e": 26565, "s": 26547, "text": "Filename: App.js:" }, { "code": null, "e": 26576, "s": 26565, "text": "Javascript" }, { "code": "import React, { useState } from \"react\"; // Importing app.css is css file to add stylingimport \"./App.css\"; const App = () => { // Counter is a state initialized to 0 const [counter, setCounter] = useState(0) // Function is called everytime increment button is clicked const handleClick1 = () => { // Counter state is incremented setCounter(counter + 1) } // Function is called everytime decrement button is clicked const handleClick2 = () => { // Counter state is decremented setCounter(counter - 1) } return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontSize: '300%', position: 'absolute', width: '100%', height: '100%', top: '-15%', }}> Counter App <div style={{ fontSize: '120%', position: 'relative', top: '10vh', }}> {counter} </div> <div className=\"buttons\"> <button style={{ fontSize: '60%', position: 'relative', top: '20vh', marginRight: '5px', backgroundColor: 'green', borderRadius: '8%', color: 'white', }} onClick={handleClick1}>Increment</button> <button style={{ fontSize: '60%', position: 'relative', top: '20vh', marginLeft: '5px', backgroundColor: 'red', borderRadius: '8%', color: 'white', }} onClick={handleClick2}>Decrement</button> </div> </div> )} export default App", "e": 28147, "s": 26576, "text": null }, { "code": null, "e": 28260, "s": 28147, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28270, "s": 28260, "text": "npm start" }, { "code": null, "e": 28278, "s": 28270, "text": "Output:" }, { "code": null, "e": 28287, "s": 28278, "text": "react-js" }, { "code": null, "e": 28291, "s": 28287, "text": "CSS" }, { "code": null, "e": 28302, "s": 28291, "text": "JavaScript" }, { "code": null, "e": 28319, "s": 28302, "text": "Web Technologies" }, { "code": null, "e": 28417, "s": 28319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28465, "s": 28417, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28502, "s": 28465, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28566, "s": 28502, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28605, "s": 28566, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28642, "s": 28605, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28682, "s": 28642, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28727, "s": 28682, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28788, "s": 28727, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28860, "s": 28788, "text": "Differences between Functional Components and Class Components in React" } ]
Count Integral points inside a Triangle - GeeksforGeeks
11 Jan, 2022 Given three non-collinear integral points in XY plane, find the number of integral points inside the triangle formed by the three points. (A point in XY plane is said to be integral/lattice point if both its co-ordinates are integral). Example: Input: p = (0, 0), q = (0, 5) and r = (5,0) Output: 6 Explanation: The points (1,1) (1,2) (1,3) (2,1) (2,2) and (3,1) are the integral points inside the triangle. We can use the Pick’s theorem, which states that the following equation holds true for a simple Polygon. Pick's Theorem: A = I + (B/2) -1 A ==> Area of Polygon B ==> Number of integral points on edges of polygon I ==> Number of integral points inside the polygon Using the above formula, we can deduce, I = (2A - B + 2) / 2 We can find A (area of triangle) using below Shoelace formula. A = 1/2 * abs(x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2)) How to find B (number of integral points on edges of a triangle)? We can find the number of integral points between any two vertex (V1, V2) of the triangle using the following algorithm. 1. If the edge formed by joining V1 and V2 is parallel to the X-axis, then the number of integral points between the vertices is : abs(V1.x - V2.x) - 1 2. Similarly, if edge is parallel to the Y-axis, then the number of integral points in between is : abs(V1.y - V2.y) - 1 3. Else, we can find the integral points between the vertices using below formula: GCD(abs(V1.x-V2.x), abs(V1.y-V2.y)) - 1 The above formula is a well known fact and can be verified using simple geometry. (Hint: Shift the edge such that one of the vertex lies at the Origin.) Please refer below link for detailed explanation. https://www.geeksforgeeks.org/number-integral-points-two-points/ Below is the implementation of the above algorithm. C++ Java Python3 C# Javascript // C++ program to find Integral points inside a triangle#include<bits/stdc++.h>using namespace std; // Class to represent an Integral point on XY plane.class Point{public: int x, y; Point(int a=0, int b=0):x(a),y(b) {}}; //utility function to find GCD of two numbers// GCD of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a%b);} // Finds the no. of Integral points between// two given points.int getBoundaryCount(Point p,Point q){ // Check if line parallel to axes if (p.x==q.x) return abs(p.y - q.y) - 1; if (p.y == q.y) return abs(p.x - q.x) - 1; return gcd(abs(p.x-q.x), abs(p.y-q.y)) - 1;} // Returns count of points inside the triangleint getInternalCount(Point p, Point q, Point r){ // 3 extra integer points for the vertices int BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle int doubleArea = abs(p.x*(q.y - r.y) + q.x*(r.y - p.y) + r.x*(p.y - q.y)); // Use Pick's theorem to calculate the no. of Interior points return (doubleArea - BoundaryPoints + 2)/2;} // driver function to check the program.int main(){ Point p(0, 0); Point q(5, 0); Point r(0, 5); cout << "Number of integral points inside given triangle is " << getInternalCount(p, q, r); return 0;} // Java program to find Integral points inside a triangle// Class to represent an Integral point on XY plane.class Point{ int x, y; public Point(int a, int b) { x = a; y = b; }} class GFG{ // utility function to find GCD of two numbers // GCD of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Finds the no. of Integral points between // two given points. static int getBoundaryCount(Point p, Point q) { // Check if line parallel to axes if (p.x == q.x) return Math.abs(p.y - q.y) - 1; if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1; } // Returns count of points inside the triangle static int getInternalCount(Point p, Point q, Point r) { // 3 extra integer points for the vertices int BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle int doubleArea = Math.abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)); // Use Pick's theorem to calculate // the no. of Interior points return (doubleArea - BoundaryPoints + 2) / 2; } // Driver Code public static void main(String[] args) { Point p = new Point(0, 0); Point q = new Point(5, 0); Point r = new Point(0, 5); System.out.println("Number of integral points" + " inside given triangle is " + getInternalCount(p, q, r)); }} // This code is contributed by Vivek Kumar Singh # Python3 program to find Integral# points inside a triangle # Class to represent an Integral# point on XY plane.class Point: def __init__(self, x, y): self.x = x self.y = y # Utility function to find GCD of# two numbers GCD of a and bdef gcd(a, b): if (b == 0): return a return gcd(b, a % b) # Finds the no. of Integral points# between two given pointsdef getBoundaryCount(p, q): # Check if line parallel to axes if (p.x == q.x): return abs(p.y - q.y) - 1 if (p.y == q.y): return abs(p.x - q.x) - 1 return gcd(abs(p.x - q.x), abs(p.y - q.y)) - 1 # Returns count of points inside the triangledef getInternalCount(p, q, r): # 3 extra integer points for the vertices BoundaryPoints = (getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3) # Calculate 2*A for the triangle doubleArea = abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)) # Use Pick's theorem to calculate # the no. of Interior points return (doubleArea - BoundaryPoints + 2) // 2 # Driver codeif __name__=="__main__": p = Point(0, 0) q = Point(5, 0) r = Point(0, 5) print("Number of integral points " "inside given triangle is ", getInternalCount(p, q, r)) # This code is contributed by rutvik_56 // C# program to find Integral points// inside a triangleusing System; // Class to represent an Integral point// on XY plane.public class Point{ public int x, y; public Point(int a, int b) { x = a; y = b; }} class GFG{ // utility function to find GCD of // two numbers a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Finds the no. of Integral points between // two given points. static int getBoundaryCount(Point p, Point q) { // Check if line parallel to axes if (p.x == q.x) return Math.Abs(p.y - q.y) - 1; if (p.y == q.y) return Math.Abs(p.x - q.x) - 1; return gcd(Math.Abs(p.x - q.x), Math.Abs(p.y - q.y)) - 1; } // Returns count of points inside the triangle static int getInternalCount(Point p, Point q, Point r) { // 3 extra integer points for the vertices int BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle int doubleArea = Math.Abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)); // Use Pick's theorem to calculate // the no. of Interior points return (doubleArea - BoundaryPoints + 2) / 2; } // Driver Code public static void Main(String[] args) { Point p = new Point(0, 0); Point q = new Point(5, 0); Point r = new Point(0, 5); Console.WriteLine("Number of integral points" + " inside given triangle is " + getInternalCount(p, q, r)); }} // This code is contributed by 29AjayKumar <script> // JavaScript program to find Integral points inside a triangle// Class to represent an Integral point on XY plane. class Point{ constructor(a,b) { this.x=a; this.y=b; }} // utility function to find GCD of two numbers // GCD of a and bfunction gcd(a,b){ if (b == 0) return a; return gcd(b, a % b);} // Finds the no. of Integral points between // two given points.function getBoundaryCount(p,q){ // Check if line parallel to axes if (p.x == q.x) return Math.abs(p.y - q.y) - 1; if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1;} // Returns count of points inside the trianglefunction getInternalCount(p,q,r){ // 3 extra integer points for the vertices let BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle let doubleArea = Math.abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)); // Use Pick's theorem to calculate // the no. of Interior points return (doubleArea - BoundaryPoints + 2) / 2;} // Driver Codelet p = new Point(0, 0);let q = new Point(5, 0);let r = new Point(0, 5);document.write("Number of integral points" + " inside given triangle is " + getInternalCount(p, q, r)); // This code is contributed by rag2127 </script> Output: Number of integral points inside given triangle is 6 This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Vivekkumar Singh 29AjayKumar nitish6174 rutvik_56 rag2127 varshagumber28 triangle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Optimum location of point to minimize total distance Program to find area of a triangle Given n line segments, find if any two segments intersect Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26365, "s": 26337, "text": "\n11 Jan, 2022" }, { "code": null, "e": 26601, "s": 26365, "text": "Given three non-collinear integral points in XY plane, find the number of integral points inside the triangle formed by the three points. (A point in XY plane is said to be integral/lattice point if both its co-ordinates are integral)." }, { "code": null, "e": 26611, "s": 26601, "text": "Example: " }, { "code": null, "e": 26803, "s": 26611, "text": "Input: p = (0, 0), q = (0, 5) and r = (5,0) \n\nOutput: 6\n\nExplanation: The points (1,1) (1,2) (1,3) (2,1)\n (2,2) and (3,1) are the integral\n points inside the triangle." }, { "code": null, "e": 26911, "s": 26805, "text": "We can use the Pick’s theorem, which states that the following equation holds true for a simple Polygon. " }, { "code": null, "e": 27134, "s": 26911, "text": "Pick's Theorem:\n A = I + (B/2) -1\n\nA ==> Area of Polygon\nB ==> Number of integral points on edges of polygon\nI ==> Number of integral points inside the polygon\n\nUsing the above formula, we can deduce,\nI = (2A - B + 2) / 2 " }, { "code": null, "e": 27198, "s": 27134, "text": "We can find A (area of triangle) using below Shoelace formula. " }, { "code": null, "e": 27255, "s": 27198, "text": "A = 1/2 * abs(x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2)) " }, { "code": null, "e": 27443, "s": 27255, "text": "How to find B (number of integral points on edges of a triangle)? We can find the number of integral points between any two vertex (V1, V2) of the triangle using the following algorithm. " }, { "code": null, "e": 28155, "s": 27443, "text": "1. If the edge formed by joining V1 and V2 is parallel \n to the X-axis, then the number of integral points \n between the vertices is : \n abs(V1.x - V2.x) - 1\n\n2. Similarly, if edge is parallel to the Y-axis, then \n the number of integral points in between is :\n abs(V1.y - V2.y) - 1\n\n3. Else, we can find the integral points between the\n vertices using below formula:\n GCD(abs(V1.x-V2.x), abs(V1.y-V2.y)) - 1\n The above formula is a well known fact and can be \n verified using simple geometry. (Hint: Shift the \n edge such that one of the vertex lies at the Origin.) \n\nPlease refer below link for detailed explanation.\nhttps://www.geeksforgeeks.org/number-integral-points-two-points/" }, { "code": null, "e": 28208, "s": 28155, "text": "Below is the implementation of the above algorithm. " }, { "code": null, "e": 28212, "s": 28208, "text": "C++" }, { "code": null, "e": 28217, "s": 28212, "text": "Java" }, { "code": null, "e": 28225, "s": 28217, "text": "Python3" }, { "code": null, "e": 28228, "s": 28225, "text": "C#" }, { "code": null, "e": 28239, "s": 28228, "text": "Javascript" }, { "code": "// C++ program to find Integral points inside a triangle#include<bits/stdc++.h>using namespace std; // Class to represent an Integral point on XY plane.class Point{public: int x, y; Point(int a=0, int b=0):x(a),y(b) {}}; //utility function to find GCD of two numbers// GCD of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a%b);} // Finds the no. of Integral points between// two given points.int getBoundaryCount(Point p,Point q){ // Check if line parallel to axes if (p.x==q.x) return abs(p.y - q.y) - 1; if (p.y == q.y) return abs(p.x - q.x) - 1; return gcd(abs(p.x-q.x), abs(p.y-q.y)) - 1;} // Returns count of points inside the triangleint getInternalCount(Point p, Point q, Point r){ // 3 extra integer points for the vertices int BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle int doubleArea = abs(p.x*(q.y - r.y) + q.x*(r.y - p.y) + r.x*(p.y - q.y)); // Use Pick's theorem to calculate the no. of Interior points return (doubleArea - BoundaryPoints + 2)/2;} // driver function to check the program.int main(){ Point p(0, 0); Point q(5, 0); Point r(0, 5); cout << \"Number of integral points inside given triangle is \" << getInternalCount(p, q, r); return 0;}", "e": 29667, "s": 28239, "text": null }, { "code": "// Java program to find Integral points inside a triangle// Class to represent an Integral point on XY plane.class Point{ int x, y; public Point(int a, int b) { x = a; y = b; }} class GFG{ // utility function to find GCD of two numbers // GCD of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Finds the no. of Integral points between // two given points. static int getBoundaryCount(Point p, Point q) { // Check if line parallel to axes if (p.x == q.x) return Math.abs(p.y - q.y) - 1; if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1; } // Returns count of points inside the triangle static int getInternalCount(Point p, Point q, Point r) { // 3 extra integer points for the vertices int BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle int doubleArea = Math.abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)); // Use Pick's theorem to calculate // the no. of Interior points return (doubleArea - BoundaryPoints + 2) / 2; } // Driver Code public static void main(String[] args) { Point p = new Point(0, 0); Point q = new Point(5, 0); Point r = new Point(0, 5); System.out.println(\"Number of integral points\" + \" inside given triangle is \" + getInternalCount(p, q, r)); }} // This code is contributed by Vivek Kumar Singh", "e": 31513, "s": 29667, "text": null }, { "code": "# Python3 program to find Integral# points inside a triangle # Class to represent an Integral# point on XY plane.class Point: def __init__(self, x, y): self.x = x self.y = y # Utility function to find GCD of# two numbers GCD of a and bdef gcd(a, b): if (b == 0): return a return gcd(b, a % b) # Finds the no. of Integral points# between two given pointsdef getBoundaryCount(p, q): # Check if line parallel to axes if (p.x == q.x): return abs(p.y - q.y) - 1 if (p.y == q.y): return abs(p.x - q.x) - 1 return gcd(abs(p.x - q.x), abs(p.y - q.y)) - 1 # Returns count of points inside the triangledef getInternalCount(p, q, r): # 3 extra integer points for the vertices BoundaryPoints = (getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3) # Calculate 2*A for the triangle doubleArea = abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)) # Use Pick's theorem to calculate # the no. of Interior points return (doubleArea - BoundaryPoints + 2) // 2 # Driver codeif __name__==\"__main__\": p = Point(0, 0) q = Point(5, 0) r = Point(0, 5) print(\"Number of integral points \" \"inside given triangle is \", getInternalCount(p, q, r)) # This code is contributed by rutvik_56", "e": 32951, "s": 31513, "text": null }, { "code": "// C# program to find Integral points// inside a triangleusing System; // Class to represent an Integral point// on XY plane.public class Point{ public int x, y; public Point(int a, int b) { x = a; y = b; }} class GFG{ // utility function to find GCD of // two numbers a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Finds the no. of Integral points between // two given points. static int getBoundaryCount(Point p, Point q) { // Check if line parallel to axes if (p.x == q.x) return Math.Abs(p.y - q.y) - 1; if (p.y == q.y) return Math.Abs(p.x - q.x) - 1; return gcd(Math.Abs(p.x - q.x), Math.Abs(p.y - q.y)) - 1; } // Returns count of points inside the triangle static int getInternalCount(Point p, Point q, Point r) { // 3 extra integer points for the vertices int BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle int doubleArea = Math.Abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)); // Use Pick's theorem to calculate // the no. of Interior points return (doubleArea - BoundaryPoints + 2) / 2; } // Driver Code public static void Main(String[] args) { Point p = new Point(0, 0); Point q = new Point(5, 0); Point r = new Point(0, 5); Console.WriteLine(\"Number of integral points\" + \" inside given triangle is \" + getInternalCount(p, q, r)); }} // This code is contributed by 29AjayKumar", "e": 34807, "s": 32951, "text": null }, { "code": "<script> // JavaScript program to find Integral points inside a triangle// Class to represent an Integral point on XY plane. class Point{ constructor(a,b) { this.x=a; this.y=b; }} // utility function to find GCD of two numbers // GCD of a and bfunction gcd(a,b){ if (b == 0) return a; return gcd(b, a % b);} // Finds the no. of Integral points between // two given points.function getBoundaryCount(p,q){ // Check if line parallel to axes if (p.x == q.x) return Math.abs(p.y - q.y) - 1; if (p.y == q.y) return Math.abs(p.x - q.x) - 1; return gcd(Math.abs(p.x - q.x), Math.abs(p.y - q.y)) - 1;} // Returns count of points inside the trianglefunction getInternalCount(p,q,r){ // 3 extra integer points for the vertices let BoundaryPoints = getBoundaryCount(p, q) + getBoundaryCount(p, r) + getBoundaryCount(q, r) + 3; // Calculate 2*A for the triangle let doubleArea = Math.abs(p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y)); // Use Pick's theorem to calculate // the no. of Interior points return (doubleArea - BoundaryPoints + 2) / 2;} // Driver Codelet p = new Point(0, 0);let q = new Point(5, 0);let r = new Point(0, 5);document.write(\"Number of integral points\" + \" inside given triangle is \" + getInternalCount(p, q, r)); // This code is contributed by rag2127 </script>", "e": 36439, "s": 34807, "text": null }, { "code": null, "e": 36448, "s": 36439, "text": "Output: " }, { "code": null, "e": 36501, "s": 36448, "text": "Number of integral points inside given triangle is 6" }, { "code": null, "e": 36894, "s": 36501, "text": "This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36911, "s": 36894, "text": "Vivekkumar Singh" }, { "code": null, "e": 36923, "s": 36911, "text": "29AjayKumar" }, { "code": null, "e": 36934, "s": 36923, "text": "nitish6174" }, { "code": null, "e": 36944, "s": 36934, "text": "rutvik_56" }, { "code": null, "e": 36952, "s": 36944, "text": "rag2127" }, { "code": null, "e": 36967, "s": 36952, "text": "varshagumber28" }, { "code": null, "e": 36976, "s": 36967, "text": "triangle" }, { "code": null, "e": 36986, "s": 36976, "text": "Geometric" }, { "code": null, "e": 36999, "s": 36986, "text": "Mathematical" }, { "code": null, "e": 37012, "s": 36999, "text": "Mathematical" }, { "code": null, "e": 37022, "s": 37012, "text": "Geometric" }, { "code": null, "e": 37120, "s": 37022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37169, "s": 37120, "text": "Program for distance between two points on earth" }, { "code": null, "e": 37220, "s": 37169, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 37273, "s": 37220, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 37308, "s": 37273, "text": "Program to find area of a triangle" }, { "code": null, "e": 37366, "s": 37308, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 37396, "s": 37366, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 37411, "s": 37396, "text": "C++ Data Types" }, { "code": null, "e": 37471, "s": 37411, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37514, "s": 37471, "text": "Set in C++ Standard Template Library (STL)" } ]
How to sort a nested Python dictionary?
If you have a dictionary of the following format: { 'KEY1':{'name':'foo','data':1351,'completed':100}, 'KEY2':{'name':'bar','data':1541,'completed':12}, 'KEY3':{'name':'baz','data':58413,'completed':18} } And you want to sort by the key, completed within each entry, in a ascending order, you can use the sorted function with a lambda that specifies which key to use to sort the data. For example, my_collection = { 'KEY1':{'name':'foo','data':1351,'completed':100}, 'KEY2':{'name':'bar','data':1541,'completed':12}, 'KEY3':{'name':'baz','data':58413,'completed':18} } sorted_keys = sorted(my_collection, key=lambda x: (my_collection[x]['completed'])) print(sorted_keys) This will give the output: ['KEY2', 'KEY3', 'KEY1']
[ { "code": null, "e": 1112, "s": 1062, "text": "If you have a dictionary of the following format:" }, { "code": null, "e": 1276, "s": 1112, "text": "{\n 'KEY1':{'name':'foo','data':1351,'completed':100},\n 'KEY2':{'name':'bar','data':1541,'completed':12},\n 'KEY3':{'name':'baz','data':58413,'completed':18}\n}" }, { "code": null, "e": 1469, "s": 1276, "text": "And you want to sort by the key, completed within each entry, in a ascending order, you can use the sorted function with a lambda that specifies which key to use to sort the data. For example," }, { "code": null, "e": 1751, "s": 1469, "text": "my_collection = {\n 'KEY1':{'name':'foo','data':1351,'completed':100},\n 'KEY2':{'name':'bar','data':1541,'completed':12},\n 'KEY3':{'name':'baz','data':58413,'completed':18}\n}\nsorted_keys = sorted(my_collection, key=lambda x: (my_collection[x]['completed']))\nprint(sorted_keys)" }, { "code": null, "e": 1778, "s": 1751, "text": "This will give the output:" }, { "code": null, "e": 1803, "s": 1778, "text": "['KEY2', 'KEY3', 'KEY1']" } ]
Async & await keyword in C#
The async and await keyword is used in C# for asynchronous programming. An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding to messages if the processing takes more time than expected. Let us see what is discussed above − private void OnRequestDownload(object sender, RoutedEventArgs e) { var req = HttpWebRequest.Create(_requestedUri); var res = req.GetResponse(); } To solve the above issue, use the async and await keywords − private async void OnRequestDownload(object sender, RoutedEventArgs e) { var req= HttpWebRequest.Create(_requestedUri); var res = await req.GetResponseAsync(); }
[ { "code": null, "e": 1134, "s": 1062, "text": "The async and await keyword is used in C# for asynchronous programming." }, { "code": null, "e": 1449, "s": 1134, "text": "An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding to messages if the processing takes more time than expected." }, { "code": null, "e": 1486, "s": 1449, "text": "Let us see what is discussed above −" }, { "code": null, "e": 1638, "s": 1486, "text": "private void OnRequestDownload(object sender, RoutedEventArgs e) {\n var req = HttpWebRequest.Create(_requestedUri);\n var res = req.GetResponse();\n}" }, { "code": null, "e": 1699, "s": 1638, "text": "To solve the above issue, use the async and await keywords −" }, { "code": null, "e": 1867, "s": 1699, "text": "private async void OnRequestDownload(object sender, RoutedEventArgs e) {\n var req= HttpWebRequest.Create(_requestedUri);\n var res = await req.GetResponseAsync();\n}" } ]
Convert to Strictly increasing integer array with minimum changes - GeeksforGeeks
20 Apr, 2022 Given an array of n integers. Write a program to find minimum number of changes in array so that array is strictly increasing of integers. In strictly increasing array A[i] < A[i+1] for 0 <= i < nExamples: Input : arr[] = { 1, 2, 6, 5, 4} Output : 2 We can change a[2] to any value between 2 and 5. and a[4] to any value greater then 5. Input : arr[] = { 1, 2, 3, 5, 7, 11 } Output : 0 Array is already strictly increasing. The problem is variation of Longest Increasing Subsequence. The numbers which are already a part of LIS need not to be changed. So minimum elements to change is difference of size of array and number of elements in LIS. Note that we also need to make sure that the numbers are integers. So while making LIS, we do not consider those elements as part of LIS that cannot form strictly increasing by inserting elements in middle. Example { 1, 2, 5, 3, 4 }, we consider length of LIS as three {1, 2, 5}, not as {1, 2, 3, 4} because we cannot make a strictly increasing array of integers with this LIS. C++ C Java Python3 C# PHP Javascript // CPP program to find min elements to// change so array is strictly increasing#include <bits/stdc++.h>using namespace std; // To find min elements to remove from array// to make it strictly increasingint minRemove(int arr[], int n){ int LIS[n], len = 0; // Mark all elements of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i - j) <= (arr[i] - arr[j])) { LIS[i] = max(LIS[i], LIS[j] + 1); } } len = max(len, LIS[i]); } // Return min changes for array to strictly increasing return n - len;} // Driver program to test minRemove()int main(){ int arr[] = { 1, 2, 6, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minRemove(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta // C program to find min elements to// change so array is strictly increasing#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // To find min elements to remove from array// to make it strictly increasingint minRemove(int arr[], int n){ int LIS[n], len = 0; // Mark all elements of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i - j) <= (arr[i] - arr[j])) { LIS[i] = max(LIS[i], LIS[j] + 1); } } len = max(len, LIS[i]); } // Return min changes for array to strictly increasing return n - len;} // Driver program to test minRemove()int main(){ int arr[] = { 1, 2, 6, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", minRemove(arr, n)); return 0;} // This code is contributed by Sania Kumari Gupta // Java program to find min elements to// change so array is strictly increasingpublic class Main { // To find min elements to remove from array // to make it strictly increasing static int minRemove(int arr[], int n) { int LIS[] = new int[n]; int len = 0; // Mark all elements of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i - j) <= (arr[i] - arr[j])) LIS[i] = Math.max(LIS[i], LIS[j] + 1); } len = Math.max(len, LIS[i]); } // Return min changes for array to strictly // increasing return n - len; } // Driver program to test minRemove() public static void main(String[] args) { int arr[] = { 1, 2, 6, 5, 4 }; int n = arr.length; System.out.println(minRemove(arr, n)); }} // This code is contributed by Sania Kumari Gupta # Python3 program to find min elements to# change so array is strictly increasing # Find min elements to remove from array# to make it strictly increasingdef minRemove(arr, n): LIS = [0 for i in range(n)] len = 0 # Mark all elements of LIS as 1 for i in range(n): LIS[i] = 1 # Find LIS of array for i in range(1, n): for j in range(i): if (arr[i] > arr[j] and (i-j)<=(arr[i]-arr[j]) ): LIS[i] = max(LIS[i], LIS[j] + 1) len = max(len, LIS[i]) # Return min changes for array # to strictly increasing return (n - len) # Driver Codearr = [ 1, 2, 6, 5, 4 ]n = len(arr)print(minRemove(arr, n)) # This code is contributed by Azkia Anam. // C# program to find min elements to change so// array is strictly increasingusing System; class GFG{ // To find min elements to remove from array to // make it strictly increasing static int minRemove(int []arr, int n) { int []LIS = new int[n]; int len = 0; // Mark all elements // of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i-j)<=(arr[i]-arr[j])) LIS[i] = Math.Max(LIS[i], LIS[j] + 1); } len = Math.Max(len, LIS[i]); } // Return min changes for array // to strictly increasing return n - len; } // Driver Code public static void Main() { int []arr = {1, 2, 6, 5, 4}; int n = arr.Length; Console.WriteLine(minRemove(arr, n)); }} // This code is contributed// by anuj_67. <?php// PHP program to find min elements to change so// array is strictly increasing // To find min elements to remove from array // to make it strictly increasingfunction minRemove($arr, $n){ $LIS = array(); $len = 0; // Mark all elements // of LIS as 1 for ($i = 0; $i < $n; $i++) $LIS[$i] = 1; // Find LIS of array for ($i = 1; $i < $n; $i++) { for ($j = 0; $j < $i; $j++) { if ($arr[$i] > $arr[$j]) $LIS[$i] = max($LIS[$i], $LIS[$j] + 1); } $len = max($len, $LIS[$i]); } // Return min changes for array to strictly // increasing return $n - $len;} // Driver Code$arr = array(1, 2, 6, 5, 4);$n = count($arr); echo minRemove($arr, $n); // This code is contributed// by anuj_6?> <script> // Javascript program to find min elements to// change so array is strictly increasing // To find min elements to remove from array // to make it strictly increasing function minRemove(arr, n) { let LIS = new Array(n).fill(0); let len = 0; // Mark all elements of LIS as 1 for (let i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (let i = 1; i < n; i++) { for (let j = 0; j < i; j++) { if (arr[i] > arr[j] && (i-j)<=(arr[i]-arr[j])) LIS[i] = Math.max(LIS[i], LIS[j] + 1); } len = Math.max(len, LIS[i]); } // Return min changes for array // to strictly increasing return n - len; } // driver program let arr = [ 1, 2, 6, 5, 4 ]; let n = arr.length; document.write(minRemove(arr, n)); // This code is contributed by Code_hunt.</script> Output: 2 This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m surya jeet singh code_hunt krisania804 LIS Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 25334, "s": 25306, "text": "\n20 Apr, 2022" }, { "code": null, "e": 25542, "s": 25334, "text": "Given an array of n integers. Write a program to find minimum number of changes in array so that array is strictly increasing of integers. In strictly increasing array A[i] < A[i+1] for 0 <= i < nExamples: " }, { "code": null, "e": 25763, "s": 25542, "text": "Input : arr[] = { 1, 2, 6, 5, 4}\nOutput : 2\nWe can change a[2] to any value \nbetween 2 and 5.\nand a[4] to any value greater then 5. \n\nInput : arr[] = { 1, 2, 3, 5, 7, 11 }\nOutput : 0\nArray is already strictly increasing." }, { "code": null, "e": 26365, "s": 25765, "text": "The problem is variation of Longest Increasing Subsequence. The numbers which are already a part of LIS need not to be changed. So minimum elements to change is difference of size of array and number of elements in LIS. Note that we also need to make sure that the numbers are integers. So while making LIS, we do not consider those elements as part of LIS that cannot form strictly increasing by inserting elements in middle. Example { 1, 2, 5, 3, 4 }, we consider length of LIS as three {1, 2, 5}, not as {1, 2, 3, 4} because we cannot make a strictly increasing array of integers with this LIS. " }, { "code": null, "e": 26369, "s": 26365, "text": "C++" }, { "code": null, "e": 26371, "s": 26369, "text": "C" }, { "code": null, "e": 26376, "s": 26371, "text": "Java" }, { "code": null, "e": 26384, "s": 26376, "text": "Python3" }, { "code": null, "e": 26387, "s": 26384, "text": "C#" }, { "code": null, "e": 26391, "s": 26387, "text": "PHP" }, { "code": null, "e": 26402, "s": 26391, "text": "Javascript" }, { "code": "// CPP program to find min elements to// change so array is strictly increasing#include <bits/stdc++.h>using namespace std; // To find min elements to remove from array// to make it strictly increasingint minRemove(int arr[], int n){ int LIS[n], len = 0; // Mark all elements of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i - j) <= (arr[i] - arr[j])) { LIS[i] = max(LIS[i], LIS[j] + 1); } } len = max(len, LIS[i]); } // Return min changes for array to strictly increasing return n - len;} // Driver program to test minRemove()int main(){ int arr[] = { 1, 2, 6, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minRemove(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 27327, "s": 26402, "text": null }, { "code": "// C program to find min elements to// change so array is strictly increasing#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // To find min elements to remove from array// to make it strictly increasingint minRemove(int arr[], int n){ int LIS[n], len = 0; // Mark all elements of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i - j) <= (arr[i] - arr[j])) { LIS[i] = max(LIS[i], LIS[j] + 1); } } len = max(len, LIS[i]); } // Return min changes for array to strictly increasing return n - len;} // Driver program to test minRemove()int main(){ int arr[] = { 1, 2, 6, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", minRemove(arr, n)); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 28335, "s": 27327, "text": null }, { "code": "// Java program to find min elements to// change so array is strictly increasingpublic class Main { // To find min elements to remove from array // to make it strictly increasing static int minRemove(int arr[], int n) { int LIS[] = new int[n]; int len = 0; // Mark all elements of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i - j) <= (arr[i] - arr[j])) LIS[i] = Math.max(LIS[i], LIS[j] + 1); } len = Math.max(len, LIS[i]); } // Return min changes for array to strictly // increasing return n - len; } // Driver program to test minRemove() public static void main(String[] args) { int arr[] = { 1, 2, 6, 5, 4 }; int n = arr.length; System.out.println(minRemove(arr, n)); }} // This code is contributed by Sania Kumari Gupta", "e": 29370, "s": 28335, "text": null }, { "code": "# Python3 program to find min elements to# change so array is strictly increasing # Find min elements to remove from array# to make it strictly increasingdef minRemove(arr, n): LIS = [0 for i in range(n)] len = 0 # Mark all elements of LIS as 1 for i in range(n): LIS[i] = 1 # Find LIS of array for i in range(1, n): for j in range(i): if (arr[i] > arr[j] and (i-j)<=(arr[i]-arr[j]) ): LIS[i] = max(LIS[i], LIS[j] + 1) len = max(len, LIS[i]) # Return min changes for array # to strictly increasing return (n - len) # Driver Codearr = [ 1, 2, 6, 5, 4 ]n = len(arr)print(minRemove(arr, n)) # This code is contributed by Azkia Anam.", "e": 30103, "s": 29370, "text": null }, { "code": "// C# program to find min elements to change so// array is strictly increasingusing System; class GFG{ // To find min elements to remove from array to // make it strictly increasing static int minRemove(int []arr, int n) { int []LIS = new int[n]; int len = 0; // Mark all elements // of LIS as 1 for (int i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i-j)<=(arr[i]-arr[j])) LIS[i] = Math.Max(LIS[i], LIS[j] + 1); } len = Math.Max(len, LIS[i]); } // Return min changes for array // to strictly increasing return n - len; } // Driver Code public static void Main() { int []arr = {1, 2, 6, 5, 4}; int n = arr.Length; Console.WriteLine(minRemove(arr, n)); }} // This code is contributed// by anuj_67.", "e": 31172, "s": 30103, "text": null }, { "code": "<?php// PHP program to find min elements to change so// array is strictly increasing // To find min elements to remove from array // to make it strictly increasingfunction minRemove($arr, $n){ $LIS = array(); $len = 0; // Mark all elements // of LIS as 1 for ($i = 0; $i < $n; $i++) $LIS[$i] = 1; // Find LIS of array for ($i = 1; $i < $n; $i++) { for ($j = 0; $j < $i; $j++) { if ($arr[$i] > $arr[$j]) $LIS[$i] = max($LIS[$i], $LIS[$j] + 1); } $len = max($len, $LIS[$i]); } // Return min changes for array to strictly // increasing return $n - $len;} // Driver Code$arr = array(1, 2, 6, 5, 4);$n = count($arr); echo minRemove($arr, $n); // This code is contributed// by anuj_6?>", "e": 31979, "s": 31172, "text": null }, { "code": "<script> // Javascript program to find min elements to// change so array is strictly increasing // To find min elements to remove from array // to make it strictly increasing function minRemove(arr, n) { let LIS = new Array(n).fill(0); let len = 0; // Mark all elements of LIS as 1 for (let i = 0; i < n; i++) LIS[i] = 1; // Find LIS of array for (let i = 1; i < n; i++) { for (let j = 0; j < i; j++) { if (arr[i] > arr[j] && (i-j)<=(arr[i]-arr[j])) LIS[i] = Math.max(LIS[i], LIS[j] + 1); } len = Math.max(len, LIS[i]); } // Return min changes for array // to strictly increasing return n - len; } // driver program let arr = [ 1, 2, 6, 5, 4 ]; let n = arr.length; document.write(minRemove(arr, n)); // This code is contributed by Code_hunt.</script>", "e": 32968, "s": 31979, "text": null }, { "code": null, "e": 32978, "s": 32968, "text": "Output: " }, { "code": null, "e": 32980, "s": 32978, "text": "2" }, { "code": null, "e": 33396, "s": 32980, "text": "This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33401, "s": 33396, "text": "vt_m" }, { "code": null, "e": 33418, "s": 33401, "text": "surya jeet singh" }, { "code": null, "e": 33428, "s": 33418, "text": "code_hunt" }, { "code": null, "e": 33440, "s": 33428, "text": "krisania804" }, { "code": null, "e": 33444, "s": 33440, "text": "LIS" }, { "code": null, "e": 33451, "s": 33444, "text": "Arrays" }, { "code": null, "e": 33471, "s": 33451, "text": "Dynamic Programming" }, { "code": null, "e": 33478, "s": 33471, "text": "Arrays" }, { "code": null, "e": 33498, "s": 33478, "text": "Dynamic Programming" }, { "code": null, "e": 33596, "s": 33498, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33640, "s": 33596, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33688, "s": 33640, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33711, "s": 33688, "text": "Introduction to Arrays" }, { "code": null, "e": 33743, "s": 33711, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33757, "s": 33743, "text": "Linear Search" }, { "code": null, "e": 33786, "s": 33757, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 33816, "s": 33786, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33850, "s": 33816, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33881, "s": 33850, "text": "Bellman–Ford Algorithm | DP-23" } ]
Changing year in MySQL date?
To change the year in MySQL date, you need to use DATE_FORMAT() function with UPDATE command. The syntax is as follows. UPDATE yourTableName SET yourDateColumnName = DATE_FORMAT(yourDateColumnName ,'yourYearValue-%m-%d'); To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table ChangeYear -> ( -> id int not null auto_increment, -> ArrivalTime date, -> PRIMARY KEY(id) -> ); Query OK, 0 rows affected (0.83 sec) Insert some records in the table using insert command − mysql> insert into ChangeYear(ArrivalTime) values(date_add(now(),interval -2 year)); Query OK, 1 row affected, 1 warning (0.20 sec) mysql> insert into ChangeYear(ArrivalTime) values('2012-10-24'); Query OK, 1 row affected (0.18 sec) mysql> insert into ChangeYear(ArrivalTime) values('2016-3-21'); Query OK, 1 row affected (0.19 sec) mysql> insert into ChangeYear(ArrivalTime) values('2015-4-24'); Query OK, 1 row affected (0.20 sec) mysql> insert into ChangeYear(ArrivalTime) values(curdate()); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement. The query is as follows. mysql> select *from ChangeYear; The following is the output. +----+-------------+ | id | ArrivalTime | +----+-------------+ | 1 | 2017-01-07 | | 2 | 2012-10-24 | | 3 | 2016-03-21 | | 4 | 2015-04-24 | | 5 | 2019-01-07 | +----+-------------+ 5 rows in set (0.00 sec) Here is the query to update only the year in the date column. For our example, let us change the year to 2019 − mysql> update ChangeYear -> set ArrivalTime = DATE_FORMAT(ArrivalTime,'2019-%m-%d'); Query OK, 4 rows affected (0.12 sec) Rows matched − 5 Changed − 4 Warnings − 0 Check all the updated records from the table using select statement. The query is as follows − mysql> select *from ChangeYear; The following is the output displaying the updated year 2019, but rest of the date remains the same − +----+-------------+ | id | ArrivalTime | +----+-------------+ | 1 | 2019-01-07 | | 2 | 2019-10-24 | | 3 | 2019-03-21 | | 4 | 2019-04-24 | | 5 | 2019-01-07 | +----+-------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1182, "s": 1062, "text": "To change the year in MySQL date, you need to use DATE_FORMAT() function with UPDATE\ncommand. The syntax is as follows." }, { "code": null, "e": 1284, "s": 1182, "text": "UPDATE yourTableName\nSET yourDateColumnName = DATE_FORMAT(yourDateColumnName ,'yourYearValue-%m-%d');" }, { "code": null, "e": 1383, "s": 1284, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1552, "s": 1383, "text": "mysql> create table ChangeYear\n -> (\n -> id int not null auto_increment,\n -> ArrivalTime date,\n -> PRIMARY KEY(id)\n -> );\nQuery OK, 0 rows affected (0.83 sec)" }, { "code": null, "e": 1608, "s": 1552, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2143, "s": 1608, "text": "mysql> insert into ChangeYear(ArrivalTime) values(date_add(now(),interval -2 year));\nQuery OK, 1 row affected, 1 warning (0.20 sec)\n\nmysql> insert into ChangeYear(ArrivalTime) values('2012-10-24');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into ChangeYear(ArrivalTime) values('2016-3-21');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into ChangeYear(ArrivalTime) values('2015-4-24');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into ChangeYear(ArrivalTime) values(curdate());\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2227, "s": 2143, "text": "Display all records from the table using select statement. The query is as follows." }, { "code": null, "e": 2259, "s": 2227, "text": "mysql> select *from ChangeYear;" }, { "code": null, "e": 2288, "s": 2259, "text": "The following is the output." }, { "code": null, "e": 2492, "s": 2288, "text": "+----+-------------+\n| id | ArrivalTime |\n+----+-------------+\n| 1 | 2017-01-07 |\n| 2 | 2012-10-24 |\n| 3 | 2016-03-21 |\n| 4 | 2015-04-24 |\n| 5 | 2019-01-07 |\n+----+-------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2604, "s": 2492, "text": "Here is the query to update only the year in the date column. For our example, let us change the\nyear to 2019 −" }, { "code": null, "e": 2771, "s": 2604, "text": "mysql> update ChangeYear\n -> set ArrivalTime = DATE_FORMAT(ArrivalTime,'2019-%m-%d');\nQuery OK, 4 rows affected (0.12 sec)\nRows matched − 5 Changed − 4 Warnings − 0" }, { "code": null, "e": 2866, "s": 2771, "text": "Check all the updated records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2898, "s": 2866, "text": "mysql> select *from ChangeYear;" }, { "code": null, "e": 3000, "s": 2898, "text": "The following is the output displaying the updated year 2019, but rest of the date remains the same −" }, { "code": null, "e": 3214, "s": 3000, "text": "+----+-------------+\n| id | ArrivalTime |\n+----+-------------+\n| 1 | 2019-01-07 |\n| 2 | 2019-10-24 |\n| 3 | 2019-03-21 |\n| 4 | 2019-04-24 |\n| 5 | 2019-01-07 |\n+----+-------------+\n5 rows in set (0.00 sec)" } ]
RTTI (Run-time type Information) in C++ program
In this section, we will see what is the RTTI (Runtime Type Information) in C++. In C++ the RTTI is a mechanism, that exposes information about an object’s datatype during runtime. This feature can be available only when the class has at least one virtual function. It allows the type of an object to be determined when the program is executing. In the following example, the first code will not work. It will generate an error like “cannot dynamic_cast base_ptr (of type Base*) to type ‘class Derived*’ (Source type is not polymorphic)”. This error comes because there is no virtual function in this example. #include<iostream> using namespace std; class Base { }; class Derived: public Base {}; int main() { Base *base_ptr = new Derived; Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr); if(derived_ptr != NULL) cout<<"It is working"; else cout<<"cannot cast Base* to Derived*"; return 0; } Now after adding a virtual method, it will work. #include<iostream> using namespace std; class Base { virtual void function() { //empty function } }; class Derived: public Base {}; int main() { Base *base_ptr = new Derived; Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr); if(derived_ptr != NULL) cout<<"It is working"; else cout<<"cannot cast Base* to Derived*"; return 0; } It is working
[ { "code": null, "e": 1408, "s": 1062, "text": "In this section, we will see what is the RTTI (Runtime Type Information) in C++. In C++ the RTTI is a mechanism, that exposes information about an object’s datatype during runtime. This feature can be available only when the class has at least one virtual function. It allows the type of an object to be determined when the program is executing." }, { "code": null, "e": 1672, "s": 1408, "text": "In the following example, the first code will not work. It will generate an error like “cannot dynamic_cast base_ptr (of type Base*) to type ‘class Derived*’ (Source type is not polymorphic)”. This error comes because there is no virtual function in this example." }, { "code": null, "e": 1989, "s": 1672, "text": "#include<iostream>\nusing namespace std;\nclass Base { };\nclass Derived: public Base {};\nint main() {\n Base *base_ptr = new Derived;\n Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);\n if(derived_ptr != NULL)\n cout<<\"It is working\";\n else\n cout<<\"cannot cast Base* to Derived*\";\n return 0;\n}" }, { "code": null, "e": 2038, "s": 1989, "text": "Now after adding a virtual method, it will work." }, { "code": null, "e": 2412, "s": 2038, "text": "#include<iostream>\nusing namespace std;\nclass Base {\n virtual void function() {\n //empty function\n }\n};\nclass Derived: public Base {};\nint main() {\n Base *base_ptr = new Derived;\n Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);\n if(derived_ptr != NULL)\n cout<<\"It is working\";\n else\n cout<<\"cannot cast Base* to Derived*\";\n return 0;\n}" }, { "code": null, "e": 2426, "s": 2412, "text": "It is working" } ]
Cheat sheet for implementing 7 methods for selecting the optimal number of clusters in Python | by Indraneel Dutta Baruah | Towards Data Science
Segmentation provides a data driven angle for examining meaningful segments that executives can use to take targeted actions and improve business outcomes. Many executives run the risk of making decisions based on overgeneralizations because they utilize a one-size-fits-all approach to assess their business ecosystem. Segmentation, however, improves decision-making by providing multiple meaningful lenses to break apart data and take action. One of the most perplexing issues we face while trying to segment customers or products is choosing the ideal number of segments. This is a key parameter for multiple clustering algorithms like K means, agglomerative clustering and GMM clustering. Unless our data has just 2 or 3 dimensions, it is not possible to visually understand the clusters present in the data. And in most practical applications, we will have more than 3 dimensions. This blog will help the readers understand and quickly implement the most popular techniques for selecting optimal number of clusters: Gap StatisticElbow MethodSilhouette CoefficientCalinski-Harabasz IndexDavies-Bouldin IndexDendrogramBayesian information criterion (BIC) Gap Statistic Elbow Method Silhouette Coefficient Calinski-Harabasz Index Davies-Bouldin Index Dendrogram Bayesian information criterion (BIC) For this exercise, we will be working with clickstream data from an online store offering clothing for pregnant women. It has data from April 2008 to August 2008 and includes variables like product category, location of the photo on the webpage, country of origin of the IP address and product price in US dollars. Before selecting optimal number of clusters, we will need to prepare the data for segmentation. I encourage you to check out the article below for an in-depth explanation of different steps for preparing data for segmentation before proceeding further: One Hot Encoding, Standardization, PCA: Data preparation for segmentation in python The gap statistic was developed by Stanford researchers Tibshirani, Walther and Hastie in their 2001 paper. The idea behind their approach was to find a way to compare cluster compactness with a null reference distribution of the data, i.e. a distribution with no obvious clustering. Their estimate for the optimal number of clusters is the value for which cluster compactness on the original data falls the farthest below this reference curve. This information is contained in the following formula for the gap statistic: where Wk is measure of the compactness of our clustering based on the Within-Cluster-Sum of Squared Errors (WSS): Within-Cluster-Sum of Squared Errors is calculated by the inertia_ attribute of KMeans function as follows: The square of the distance of each point from the centre of the cluster (Squared Errors) The WSS score is the sum of these Squared Errors for all the points Calculating gap statistic in python for k means clustering involves the following steps: Cluster the observed data on various number of clusters and compute compactness of our clustering Generate reference data sets and cluster each of them with varying number of clusters. The reference datasets are created from a “continuous uniform” distribution using the random_sample function. Calculate average of compactness of our clustering on reference datasets Calculate gap statistics as difference in compactness between clustering on reference data and original data # Gap Statistic for K meansdef optimalK(data, nrefs=3, maxClusters=15): """ Calculates KMeans optimal K using Gap Statistic Params: data: ndarry of shape (n_samples, n_features) nrefs: number of sample reference datasets to create maxClusters: Maximum number of clusters to test for Returns: (gaps, optimalK) """ gaps = np.zeros((len(range(1, maxClusters)),)) resultsdf = pd.DataFrame({'clusterCount':[], 'gap':[]}) for gap_index, k in enumerate(range(1, maxClusters)):# Holder for reference dispersion results refDisps = np.zeros(nrefs)# For n references, generate random sample and perform kmeans getting resulting dispersion of each loop for i in range(nrefs): # Create new random reference set randomReference = np.random.random_sample(size=data.shape) # Fit to it km = KMeans(k) km.fit(randomReference) refDisp = km.inertia_ refDisps[i] = refDisp# Fit cluster to original data and create dispersion km = KMeans(k) km.fit(data) origDisp = km.inertia_# Calculate gap statistic gap = np.log(np.mean(refDisps)) - np.log(origDisp)# Assign this loop's gap statistic to gaps gaps[gap_index] = gap resultsdf = resultsdf.append({'clusterCount':k, 'gap':gap}, ignore_index=True)return (gaps.argmax() + 1, resultsdf)score_g, df = optimalK(cluster_df, nrefs=5, maxClusters=30)plt.plot(df['clusterCount'], df['gap'], linestyle='--', marker='o', color='b');plt.xlabel('K');plt.ylabel('Gap Statistic');plt.title('Gap Statistic vs. K'); As seen in Figure 1, the gap statistics is maximized with 29 clusters and hence, we can chose 29 clusters for our K means. It is the most popular method for determining the optimal number of clusters. The method is based on calculating the Within-Cluster-Sum of Squared Errors (WSS) for different number of clusters (k) and selecting the k for which change in WSS first starts to diminish. The idea behind the elbow method is that the explained variation changes rapidly for a small number of clusters and then it slows down leading to an elbow formation in the curve. The elbow point is the number of clusters we can use for our clustering algorithm. Further details on this method can be found in this paper by Chunhui Yuan and Haitao Yang. We will be using the YellowBrick library which can implement the elbow method with few lines of code. It is a wrapper around Scikit-Learn and has some cool machine learning visualizations! # Elbow Method for K means# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(2,30), timings= True)visualizer.fit(cluster_df) # Fit data to visualizervisualizer.show() # Finalize and render figure The KElbowVisualizer function fits the KMeans model for a range of clusters values between 2 to 30. As shown in Figure 2, the elbow point is achieved with 8 clusters which is highlighted by the function itself. The function also informs us about how much time was needed to plot models for various numbers of clusters through the green line. The Silhouette Coefficient for a point i is defined as follows: where b(i) is the smallest average distance of point i to all points in any other cluster and a(i) is the average distance of i from all other points in its cluster. For example, if we have only 3 clusters A,B and C and i belongs to cluster C, then b(i) is calculated by measuring the average distance of i from every point in cluster A, the average distance of i from every point in cluster B and taking the smallest resulting value. The Silhouette Coefficient for the dataset is the average of the Silhouette Coefficient of individual points. The Silhouette Coefficient tells us if individual points are correctly assigned to their clusters. We can use the following thumb rules while using Silhouette Coefficient: S(i) close to 0 means that the point is between two clustersIf it is closer to -1, then we would be better off assigning it to the other clustersIf S(i) is close to 1, then the point belongs to the ‘correct’ cluster S(i) close to 0 means that the point is between two clusters If it is closer to -1, then we would be better off assigning it to the other clusters If S(i) is close to 1, then the point belongs to the ‘correct’ cluster For more details on this method, please refer to this 2018 paper by N. Kaoungku, K. Suksut , R. Chanklan and K. Kerdprasop. We will be using the KElbowVisualizer function to implement Silhouette Coefficient for K means clustering algorithm: # Silhouette Score for K means# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(2,30),metric='silhouette', timings= True)visualizer.fit(cluster_df) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure The optimal number of clusters based on Silhouette Score is 4. The Calinski-Harabasz Index is based on the idea that clusters that are (1) themselves very compact and (2) well-spaced from each other are good clusters. The index is calculated by dividing the variance of the sums of squares of the distances of individual objects to their cluster center by the sum of squares of the distance between the cluster centers. Higher the Calinski-Harabasz Index value, better the clustering model. The formula for Calinski-Harabasz Index is defined as: where k is the number of clusters, n is the number of records in data, BCSM (between cluster scatter matrix) calculates separation between clusters and WCSM (within cluster scatter matrix) calculates compactness within clusters. KElbowVisualizer function is able to calculate Calinski-Harabasz Index as well: # Calinski Harabasz Score for K means# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(2,30),metric='calinski_harabasz', timings= True)visualizer.fit(cluster_df) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure As seen in Figure 4, the Calinski Harabasz Index is maximized when number of clusters is 2 for the K means clustering algorithm. To dig deeper on this index, kindly refer to this paper by Xu Wang and Yusheng Xu. The Davies-Bouldin (DB) Index is defined as: where n is the count of clusters and σi is the average distance of all points in cluster i from the cluster centre ci. Like silhouette coefficient and Calinski-Harabasz index, the DB index captures both the separation and compactness of the clusters.This is due to the fact that the measure’s ‘max’ statement repeatedly selects the values where the average point is farthest away from its center, and where the centers are closest together. But unlike silhouette coefficient and Calinski-Harabasz index, as DB index falls, the clustering improves. # Davies Bouldin score for K meansfrom sklearn.metrics import davies_bouldin_scoredef get_kmeans_score(data, center): ''' returns the kmeans score regarding Davies Bouldin for points to centers INPUT: data - the dataset you want to fit kmeans to center - the number of centers you want (the k value) OUTPUT: score - the Davies Bouldin score for the kmeans model fit to the data ''' #instantiate kmeans kmeans = KMeans(n_clusters=center)# Then fit the model to your data using the fit method model = kmeans.fit_predict(cluster_df) # Calculate Davies Bouldin scorescore = davies_bouldin_score(cluster_df, model) return scorescores = []centers = list(range(2,30))for center in centers: scores.append(get_kmeans_score(cluster_df, center)) plt.plot(centers, scores, linestyle='--', marker='o', color='b');plt.xlabel('K');plt.ylabel('Davies Bouldin score');plt.title('Davies Bouldin score vs. K'); As seen in Figure 5, the Davies Bouldin score is minimized with 4 clusters and can be considered for the k means algorithm. Further details on the DB score can be found here in a paper by Slobodan Petrovic. This technique is specific to the agglomerative hierarchical method of clustering. The agglomerative hierarchical method of clustering starts by considering each point as a separate cluster and starts joining points to clusters in a hierarchical fashion based on their distances. In a separate blog, we will focus on the details of this method. To get the optimal number of clusters for hierarchical clustering, we make use a dendrogram which is tree-like chart that shows the sequences of merges or splits of clusters. If two clusters are merged, the dendrogram will join them in a graph and the height of the join will be the distance between those clusters. We will plot the graph using the dendogram function from scipy library. # Dendogram for Heirarchical Clusteringimport scipy.cluster.hierarchy as shcfrom matplotlib import pyplotpyplot.figure(figsize=(10, 7)) pyplot.title("Dendrograms") dend = shc.dendrogram(shc.linkage(cluster_df, method='ward')) As shown in Figure 6, we can chose the optimal number of clusters based on hierarchical structure of the dendrogram. As highlighted by other cluster validation metrics, 4 clusters can be considered for the agglomerative hierarchical as well. Bayesian information criterion (BIC) score is a method for scoring a model which is using the maximum likelihood estimation framework. The BIC statistic is calculated as follows: BIC = (k*ln(n)) — (2ln(L)) where L is the maximized value of the likelihood function of the model, k is the number of parameters and n is the number of records The lower the BIC score, better is the model. We can use the BIC score for the Gaussian Mixture Modelling approach for clustering. We will discuss details of this model in a separate blog but key thing to note here is that in the model we need to select number of clusters as well as type of covariance. We try out various combinations of the parameters and select the model with the lowest BIC score. # BIC for GMMfrom sklearn.mixture import GaussianMixturen_components = range(1, 30)covariance_type = ['spherical', 'tied', 'diag', 'full']score=[]for cov in covariance_type: for n_comp in n_components: gmm=GaussianMixture(n_components=n_comp,covariance_type=cov) gmm.fit(cluster_df) score.append((cov,n_comp,gmm.bic(cluster_df)))score Conclusion In this post, we learnt about 7 different methods to select optimal number of clusters for various clustering algorithms. Specifically, we learned: How various metrics for selecting optimal number of clusters are calculated The thumb rules to select optimal number of clusters using these metrics How to implement the cluster validation methods in python How to interpret results of these methods Finally, given the multiple metrics we have for selecting optimal number of clusters, we can take the average/median/mode across various metrics to be the optimal number of clusters. Do you have any questions or suggestions about this blog? Please feel free to drop in a note. If you, like me, are passionate about AI, Data Science, or Economics, please feel free to add/follow me on LinkedIn, Github and Medium. Tibshirani R, Walther G and Hastie T, Estimating the number of clusters in a data set via the gap statistic, J. R. Statist. Soc. B (2001) 63, Part 2, pp. 411–423Yuan C and Yang H, Research on K-Value Selection Method of K-Means Clustering Algorithm, MDPI, 18 June 2019Kaoungku, N. & Suksut, K. & Chanklan, R. & Kerdprasop, K. & Kerdprasop, Nittaya. (2018). The silhouette width criterion for clustering and association mining to select image features. International Journal of Machine Learning and Computing. 8. 69–73. 10.18178/ijmlc.2018.8.1.665.Wang X & Xu Y, An improved index for clustering validation based on Silhouette index and Calinski-Harabasz index, 2019 IOP Conf. Ser.: Mater. Sci. Eng. 569 052024Petrovic S, A Comparison Between the Silhouette Index and the Davies-Bouldin Index in Labelling IDS Clusters Tibshirani R, Walther G and Hastie T, Estimating the number of clusters in a data set via the gap statistic, J. R. Statist. Soc. B (2001) 63, Part 2, pp. 411–423 Yuan C and Yang H, Research on K-Value Selection Method of K-Means Clustering Algorithm, MDPI, 18 June 2019 Kaoungku, N. & Suksut, K. & Chanklan, R. & Kerdprasop, K. & Kerdprasop, Nittaya. (2018). The silhouette width criterion for clustering and association mining to select image features. International Journal of Machine Learning and Computing. 8. 69–73. 10.18178/ijmlc.2018.8.1.665. Wang X & Xu Y, An improved index for clustering validation based on Silhouette index and Calinski-Harabasz index, 2019 IOP Conf. Ser.: Mater. Sci. Eng. 569 052024 Petrovic S, A Comparison Between the Silhouette Index and the Davies-Bouldin Index in Labelling IDS Clusters
[ { "code": null, "e": 617, "s": 172, "text": "Segmentation provides a data driven angle for examining meaningful segments that executives can use to take targeted actions and improve business outcomes. Many executives run the risk of making decisions based on overgeneralizations because they utilize a one-size-fits-all approach to assess their business ecosystem. Segmentation, however, improves decision-making by providing multiple meaningful lenses to break apart data and take action." }, { "code": null, "e": 1193, "s": 617, "text": "One of the most perplexing issues we face while trying to segment customers or products is choosing the ideal number of segments. This is a key parameter for multiple clustering algorithms like K means, agglomerative clustering and GMM clustering. Unless our data has just 2 or 3 dimensions, it is not possible to visually understand the clusters present in the data. And in most practical applications, we will have more than 3 dimensions. This blog will help the readers understand and quickly implement the most popular techniques for selecting optimal number of clusters:" }, { "code": null, "e": 1330, "s": 1193, "text": "Gap StatisticElbow MethodSilhouette CoefficientCalinski-Harabasz IndexDavies-Bouldin IndexDendrogramBayesian information criterion (BIC)" }, { "code": null, "e": 1344, "s": 1330, "text": "Gap Statistic" }, { "code": null, "e": 1357, "s": 1344, "text": "Elbow Method" }, { "code": null, "e": 1380, "s": 1357, "text": "Silhouette Coefficient" }, { "code": null, "e": 1404, "s": 1380, "text": "Calinski-Harabasz Index" }, { "code": null, "e": 1425, "s": 1404, "text": "Davies-Bouldin Index" }, { "code": null, "e": 1436, "s": 1425, "text": "Dendrogram" }, { "code": null, "e": 1473, "s": 1436, "text": "Bayesian information criterion (BIC)" }, { "code": null, "e": 1884, "s": 1473, "text": "For this exercise, we will be working with clickstream data from an online store offering clothing for pregnant women. It has data from April 2008 to August 2008 and includes variables like product category, location of the photo on the webpage, country of origin of the IP address and product price in US dollars. Before selecting optimal number of clusters, we will need to prepare the data for segmentation." }, { "code": null, "e": 2041, "s": 1884, "text": "I encourage you to check out the article below for an in-depth explanation of different steps for preparing data for segmentation before proceeding further:" }, { "code": null, "e": 2125, "s": 2041, "text": "One Hot Encoding, Standardization, PCA: Data preparation for segmentation in python" }, { "code": null, "e": 2648, "s": 2125, "text": "The gap statistic was developed by Stanford researchers Tibshirani, Walther and Hastie in their 2001 paper. The idea behind their approach was to find a way to compare cluster compactness with a null reference distribution of the data, i.e. a distribution with no obvious clustering. Their estimate for the optimal number of clusters is the value for which cluster compactness on the original data falls the farthest below this reference curve. This information is contained in the following formula for the gap statistic:" }, { "code": null, "e": 2762, "s": 2648, "text": "where Wk is measure of the compactness of our clustering based on the Within-Cluster-Sum of Squared Errors (WSS):" }, { "code": null, "e": 2870, "s": 2762, "text": "Within-Cluster-Sum of Squared Errors is calculated by the inertia_ attribute of KMeans function as follows:" }, { "code": null, "e": 2959, "s": 2870, "text": "The square of the distance of each point from the centre of the cluster (Squared Errors)" }, { "code": null, "e": 3027, "s": 2959, "text": "The WSS score is the sum of these Squared Errors for all the points" }, { "code": null, "e": 3116, "s": 3027, "text": "Calculating gap statistic in python for k means clustering involves the following steps:" }, { "code": null, "e": 3214, "s": 3116, "text": "Cluster the observed data on various number of clusters and compute compactness of our clustering" }, { "code": null, "e": 3411, "s": 3214, "text": "Generate reference data sets and cluster each of them with varying number of clusters. The reference datasets are created from a “continuous uniform” distribution using the random_sample function." }, { "code": null, "e": 3484, "s": 3411, "text": "Calculate average of compactness of our clustering on reference datasets" }, { "code": null, "e": 3593, "s": 3484, "text": "Calculate gap statistics as difference in compactness between clustering on reference data and original data" }, { "code": null, "e": 5250, "s": 3593, "text": "# Gap Statistic for K meansdef optimalK(data, nrefs=3, maxClusters=15): \"\"\" Calculates KMeans optimal K using Gap Statistic Params: data: ndarry of shape (n_samples, n_features) nrefs: number of sample reference datasets to create maxClusters: Maximum number of clusters to test for Returns: (gaps, optimalK) \"\"\" gaps = np.zeros((len(range(1, maxClusters)),)) resultsdf = pd.DataFrame({'clusterCount':[], 'gap':[]}) for gap_index, k in enumerate(range(1, maxClusters)):# Holder for reference dispersion results refDisps = np.zeros(nrefs)# For n references, generate random sample and perform kmeans getting resulting dispersion of each loop for i in range(nrefs): # Create new random reference set randomReference = np.random.random_sample(size=data.shape) # Fit to it km = KMeans(k) km.fit(randomReference) refDisp = km.inertia_ refDisps[i] = refDisp# Fit cluster to original data and create dispersion km = KMeans(k) km.fit(data) origDisp = km.inertia_# Calculate gap statistic gap = np.log(np.mean(refDisps)) - np.log(origDisp)# Assign this loop's gap statistic to gaps gaps[gap_index] = gap resultsdf = resultsdf.append({'clusterCount':k, 'gap':gap}, ignore_index=True)return (gaps.argmax() + 1, resultsdf)score_g, df = optimalK(cluster_df, nrefs=5, maxClusters=30)plt.plot(df['clusterCount'], df['gap'], linestyle='--', marker='o', color='b');plt.xlabel('K');plt.ylabel('Gap Statistic');plt.title('Gap Statistic vs. K');" }, { "code": null, "e": 5373, "s": 5250, "text": "As seen in Figure 1, the gap statistics is maximized with 29 clusters and hence, we can chose 29 clusters for our K means." }, { "code": null, "e": 5640, "s": 5373, "text": "It is the most popular method for determining the optimal number of clusters. The method is based on calculating the Within-Cluster-Sum of Squared Errors (WSS) for different number of clusters (k) and selecting the k for which change in WSS first starts to diminish." }, { "code": null, "e": 5993, "s": 5640, "text": "The idea behind the elbow method is that the explained variation changes rapidly for a small number of clusters and then it slows down leading to an elbow formation in the curve. The elbow point is the number of clusters we can use for our clustering algorithm. Further details on this method can be found in this paper by Chunhui Yuan and Haitao Yang." }, { "code": null, "e": 6182, "s": 5993, "text": "We will be using the YellowBrick library which can implement the elbow method with few lines of code. It is a wrapper around Scikit-Learn and has some cool machine learning visualizations!" }, { "code": null, "e": 6504, "s": 6182, "text": "# Elbow Method for K means# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(2,30), timings= True)visualizer.fit(cluster_df) # Fit data to visualizervisualizer.show() # Finalize and render figure" }, { "code": null, "e": 6846, "s": 6504, "text": "The KElbowVisualizer function fits the KMeans model for a range of clusters values between 2 to 30. As shown in Figure 2, the elbow point is achieved with 8 clusters which is highlighted by the function itself. The function also informs us about how much time was needed to plot models for various numbers of clusters through the green line." }, { "code": null, "e": 6910, "s": 6846, "text": "The Silhouette Coefficient for a point i is defined as follows:" }, { "code": null, "e": 7455, "s": 6910, "text": "where b(i) is the smallest average distance of point i to all points in any other cluster and a(i) is the average distance of i from all other points in its cluster. For example, if we have only 3 clusters A,B and C and i belongs to cluster C, then b(i) is calculated by measuring the average distance of i from every point in cluster A, the average distance of i from every point in cluster B and taking the smallest resulting value. The Silhouette Coefficient for the dataset is the average of the Silhouette Coefficient of individual points." }, { "code": null, "e": 7627, "s": 7455, "text": "The Silhouette Coefficient tells us if individual points are correctly assigned to their clusters. We can use the following thumb rules while using Silhouette Coefficient:" }, { "code": null, "e": 7843, "s": 7627, "text": "S(i) close to 0 means that the point is between two clustersIf it is closer to -1, then we would be better off assigning it to the other clustersIf S(i) is close to 1, then the point belongs to the ‘correct’ cluster" }, { "code": null, "e": 7904, "s": 7843, "text": "S(i) close to 0 means that the point is between two clusters" }, { "code": null, "e": 7990, "s": 7904, "text": "If it is closer to -1, then we would be better off assigning it to the other clusters" }, { "code": null, "e": 8061, "s": 7990, "text": "If S(i) is close to 1, then the point belongs to the ‘correct’ cluster" }, { "code": null, "e": 8302, "s": 8061, "text": "For more details on this method, please refer to this 2018 paper by N. Kaoungku, K. Suksut , R. Chanklan and K. Kerdprasop. We will be using the KElbowVisualizer function to implement Silhouette Coefficient for K means clustering algorithm:" }, { "code": null, "e": 8660, "s": 8302, "text": "# Silhouette Score for K means# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(2,30),metric='silhouette', timings= True)visualizer.fit(cluster_df) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure" }, { "code": null, "e": 8723, "s": 8660, "text": "The optimal number of clusters based on Silhouette Score is 4." }, { "code": null, "e": 9206, "s": 8723, "text": "The Calinski-Harabasz Index is based on the idea that clusters that are (1) themselves very compact and (2) well-spaced from each other are good clusters. The index is calculated by dividing the variance of the sums of squares of the distances of individual objects to their cluster center by the sum of squares of the distance between the cluster centers. Higher the Calinski-Harabasz Index value, better the clustering model. The formula for Calinski-Harabasz Index is defined as:" }, { "code": null, "e": 9435, "s": 9206, "text": "where k is the number of clusters, n is the number of records in data, BCSM (between cluster scatter matrix) calculates separation between clusters and WCSM (within cluster scatter matrix) calculates compactness within clusters." }, { "code": null, "e": 9515, "s": 9435, "text": "KElbowVisualizer function is able to calculate Calinski-Harabasz Index as well:" }, { "code": null, "e": 9887, "s": 9515, "text": "# Calinski Harabasz Score for K means# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(2,30),metric='calinski_harabasz', timings= True)visualizer.fit(cluster_df) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure" }, { "code": null, "e": 10099, "s": 9887, "text": "As seen in Figure 4, the Calinski Harabasz Index is maximized when number of clusters is 2 for the K means clustering algorithm. To dig deeper on this index, kindly refer to this paper by Xu Wang and Yusheng Xu." }, { "code": null, "e": 10144, "s": 10099, "text": "The Davies-Bouldin (DB) Index is defined as:" }, { "code": null, "e": 10263, "s": 10144, "text": "where n is the count of clusters and σi is the average distance of all points in cluster i from the cluster centre ci." }, { "code": null, "e": 10692, "s": 10263, "text": "Like silhouette coefficient and Calinski-Harabasz index, the DB index captures both the separation and compactness of the clusters.This is due to the fact that the measure’s ‘max’ statement repeatedly selects the values where the average point is farthest away from its center, and where the centers are closest together. But unlike silhouette coefficient and Calinski-Harabasz index, as DB index falls, the clustering improves." }, { "code": null, "e": 11649, "s": 10692, "text": "# Davies Bouldin score for K meansfrom sklearn.metrics import davies_bouldin_scoredef get_kmeans_score(data, center): ''' returns the kmeans score regarding Davies Bouldin for points to centers INPUT: data - the dataset you want to fit kmeans to center - the number of centers you want (the k value) OUTPUT: score - the Davies Bouldin score for the kmeans model fit to the data ''' #instantiate kmeans kmeans = KMeans(n_clusters=center)# Then fit the model to your data using the fit method model = kmeans.fit_predict(cluster_df) # Calculate Davies Bouldin scorescore = davies_bouldin_score(cluster_df, model) return scorescores = []centers = list(range(2,30))for center in centers: scores.append(get_kmeans_score(cluster_df, center)) plt.plot(centers, scores, linestyle='--', marker='o', color='b');plt.xlabel('K');plt.ylabel('Davies Bouldin score');plt.title('Davies Bouldin score vs. K');" }, { "code": null, "e": 11856, "s": 11649, "text": "As seen in Figure 5, the Davies Bouldin score is minimized with 4 clusters and can be considered for the k means algorithm. Further details on the DB score can be found here in a paper by Slobodan Petrovic." }, { "code": null, "e": 12376, "s": 11856, "text": "This technique is specific to the agglomerative hierarchical method of clustering. The agglomerative hierarchical method of clustering starts by considering each point as a separate cluster and starts joining points to clusters in a hierarchical fashion based on their distances. In a separate blog, we will focus on the details of this method. To get the optimal number of clusters for hierarchical clustering, we make use a dendrogram which is tree-like chart that shows the sequences of merges or splits of clusters." }, { "code": null, "e": 12589, "s": 12376, "text": "If two clusters are merged, the dendrogram will join them in a graph and the height of the join will be the distance between those clusters. We will plot the graph using the dendogram function from scipy library." }, { "code": null, "e": 12817, "s": 12589, "text": "# Dendogram for Heirarchical Clusteringimport scipy.cluster.hierarchy as shcfrom matplotlib import pyplotpyplot.figure(figsize=(10, 7)) pyplot.title(\"Dendrograms\") dend = shc.dendrogram(shc.linkage(cluster_df, method='ward'))" }, { "code": null, "e": 13059, "s": 12817, "text": "As shown in Figure 6, we can chose the optimal number of clusters based on hierarchical structure of the dendrogram. As highlighted by other cluster validation metrics, 4 clusters can be considered for the agglomerative hierarchical as well." }, { "code": null, "e": 13238, "s": 13059, "text": "Bayesian information criterion (BIC) score is a method for scoring a model which is using the maximum likelihood estimation framework. The BIC statistic is calculated as follows:" }, { "code": null, "e": 13265, "s": 13238, "text": "BIC = (k*ln(n)) — (2ln(L))" }, { "code": null, "e": 13398, "s": 13265, "text": "where L is the maximized value of the likelihood function of the model, k is the number of parameters and n is the number of records" }, { "code": null, "e": 13800, "s": 13398, "text": "The lower the BIC score, better is the model. We can use the BIC score for the Gaussian Mixture Modelling approach for clustering. We will discuss details of this model in a separate blog but key thing to note here is that in the model we need to select number of clusters as well as type of covariance. We try out various combinations of the parameters and select the model with the lowest BIC score." }, { "code": null, "e": 14159, "s": 13800, "text": "# BIC for GMMfrom sklearn.mixture import GaussianMixturen_components = range(1, 30)covariance_type = ['spherical', 'tied', 'diag', 'full']score=[]for cov in covariance_type: for n_comp in n_components: gmm=GaussianMixture(n_components=n_comp,covariance_type=cov) gmm.fit(cluster_df) score.append((cov,n_comp,gmm.bic(cluster_df)))score" }, { "code": null, "e": 14170, "s": 14159, "text": "Conclusion" }, { "code": null, "e": 14292, "s": 14170, "text": "In this post, we learnt about 7 different methods to select optimal number of clusters for various clustering algorithms." }, { "code": null, "e": 14318, "s": 14292, "text": "Specifically, we learned:" }, { "code": null, "e": 14394, "s": 14318, "text": "How various metrics for selecting optimal number of clusters are calculated" }, { "code": null, "e": 14467, "s": 14394, "text": "The thumb rules to select optimal number of clusters using these metrics" }, { "code": null, "e": 14525, "s": 14467, "text": "How to implement the cluster validation methods in python" }, { "code": null, "e": 14567, "s": 14525, "text": "How to interpret results of these methods" }, { "code": null, "e": 14750, "s": 14567, "text": "Finally, given the multiple metrics we have for selecting optimal number of clusters, we can take the average/median/mode across various metrics to be the optimal number of clusters." }, { "code": null, "e": 14844, "s": 14750, "text": "Do you have any questions or suggestions about this blog? Please feel free to drop in a note." }, { "code": null, "e": 14980, "s": 14844, "text": "If you, like me, are passionate about AI, Data Science, or Economics, please feel free to add/follow me on LinkedIn, Github and Medium." }, { "code": null, "e": 15798, "s": 14980, "text": "Tibshirani R, Walther G and Hastie T, Estimating the number of clusters in a data set via the gap statistic, J. R. Statist. Soc. B (2001) 63, Part 2, pp. 411–423Yuan C and Yang H, Research on K-Value Selection Method of K-Means Clustering Algorithm, MDPI, 18 June 2019Kaoungku, N. & Suksut, K. & Chanklan, R. & Kerdprasop, K. & Kerdprasop, Nittaya. (2018). The silhouette width criterion for clustering and association mining to select image features. International Journal of Machine Learning and Computing. 8. 69–73. 10.18178/ijmlc.2018.8.1.665.Wang X & Xu Y, An improved index for clustering validation based on Silhouette index and Calinski-Harabasz index, 2019 IOP Conf. Ser.: Mater. Sci. Eng. 569 052024Petrovic S, A Comparison Between the Silhouette Index and the Davies-Bouldin Index in Labelling IDS Clusters" }, { "code": null, "e": 15960, "s": 15798, "text": "Tibshirani R, Walther G and Hastie T, Estimating the number of clusters in a data set via the gap statistic, J. R. Statist. Soc. B (2001) 63, Part 2, pp. 411–423" }, { "code": null, "e": 16068, "s": 15960, "text": "Yuan C and Yang H, Research on K-Value Selection Method of K-Means Clustering Algorithm, MDPI, 18 June 2019" }, { "code": null, "e": 16348, "s": 16068, "text": "Kaoungku, N. & Suksut, K. & Chanklan, R. & Kerdprasop, K. & Kerdprasop, Nittaya. (2018). The silhouette width criterion for clustering and association mining to select image features. International Journal of Machine Learning and Computing. 8. 69–73. 10.18178/ijmlc.2018.8.1.665." }, { "code": null, "e": 16511, "s": 16348, "text": "Wang X & Xu Y, An improved index for clustering validation based on Silhouette index and Calinski-Harabasz index, 2019 IOP Conf. Ser.: Mater. Sci. Eng. 569 052024" } ]
Find all substrings that are anagrams of another substring of the string S - GeeksforGeeks
25 Aug, 2021 Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at the different index. Examples: Input: S = “aba”Output: a a ab baExplanation:Following substrings are anagrams of another substring of the string S: “a”: Substring “a” is anagram of the substring “a”(= {S[0]}).“a”: Substring “a” is anagram of the substring “a”(= {S[2]}).“ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}).“ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]}). “a”: Substring “a” is anagram of the substring “a”(= {S[0]}). “a”: Substring “a” is anagram of the substring “a”(= {S[2]}). “ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}). “ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]}). Input: S = “abcd”Output: [] Approach: The given problem can be solved by using Hashing by storing the anagrams of each substring of the string S and print the resultant substring. Follow the below steps to solve the given problem: Initialize a HashMap that stores all the anagrams of each substring of the string S. Generate all the possible substrings of S and for each substring, say str store the substring in the HashMap mapped with the key as the sorted string str. Traverse the HashMap and print all the strings associated with each key whose number of strings associated with each string is at least 1. Below is the implementation of the above approach: Python3 # Python program for the above approach import collections # Function to find all the substrings# whose anagram exist as a different# substring in Sdef findAnagrams(S): # Stores the lists of anagrams of # each substring of S Map = collections.defaultdict(list) # Stores the length of S N = len(S) # Generate all substrings of S for i in range(N): for j in range(i, N): # Store the current substring # of the string S curr = S[i: j + 1] # Key is the sorted substring key = "".join(sorted(curr)) # Add the sorted substring # to the dictionary Map[key].append(curr) # Store the final result result = [] # Iterate over values of dictionary for vals in Map.values(): # If length of list > 1 if len(vals) > 1: # Print all the strings for v in vals: print(v, end =" ") # Driver Code S = "aba"findAnagrams(S) ab ba a a Time Complexity: O(N3)Auxiliary Space: O(N2) clintra anagram substring Hash Sorting Strings Hash Strings Sorting anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Most frequent element in an array Counting frequencies of array elements Double Hashing Quadratic Probing in Hashing Implementing our Own Hash Table with Separate Chaining in Java
[ { "code": null, "e": 25002, "s": 24974, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25218, "s": 25002, "text": "Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at the different index." }, { "code": null, "e": 25228, "s": 25218, "text": "Examples:" }, { "code": null, "e": 25345, "s": 25228, "text": "Input: S = “aba”Output: a a ab baExplanation:Following substrings are anagrams of another substring of the string S:" }, { "code": null, "e": 25608, "s": 25345, "text": "“a”: Substring “a” is anagram of the substring “a”(= {S[0]}).“a”: Substring “a” is anagram of the substring “a”(= {S[2]}).“ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]}).“ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]})." }, { "code": null, "e": 25670, "s": 25608, "text": "“a”: Substring “a” is anagram of the substring “a”(= {S[0]})." }, { "code": null, "e": 25732, "s": 25670, "text": "“a”: Substring “a” is anagram of the substring “a”(= {S[2]})." }, { "code": null, "e": 25803, "s": 25732, "text": "“ab”: Substring “ab” is anagram of the substring “ba”(= {S[1], S[2]})." }, { "code": null, "e": 25874, "s": 25803, "text": "“ba”: Substring “ba” is anagram of the substring “ab”(= {S[0], S[2]})." }, { "code": null, "e": 25902, "s": 25874, "text": "Input: S = “abcd”Output: []" }, { "code": null, "e": 26105, "s": 25902, "text": "Approach: The given problem can be solved by using Hashing by storing the anagrams of each substring of the string S and print the resultant substring. Follow the below steps to solve the given problem:" }, { "code": null, "e": 26190, "s": 26105, "text": "Initialize a HashMap that stores all the anagrams of each substring of the string S." }, { "code": null, "e": 26345, "s": 26190, "text": "Generate all the possible substrings of S and for each substring, say str store the substring in the HashMap mapped with the key as the sorted string str." }, { "code": null, "e": 26484, "s": 26345, "text": "Traverse the HashMap and print all the strings associated with each key whose number of strings associated with each string is at least 1." }, { "code": null, "e": 26535, "s": 26484, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26543, "s": 26535, "text": "Python3" }, { "code": "# Python program for the above approach import collections # Function to find all the substrings# whose anagram exist as a different# substring in Sdef findAnagrams(S): # Stores the lists of anagrams of # each substring of S Map = collections.defaultdict(list) # Stores the length of S N = len(S) # Generate all substrings of S for i in range(N): for j in range(i, N): # Store the current substring # of the string S curr = S[i: j + 1] # Key is the sorted substring key = \"\".join(sorted(curr)) # Add the sorted substring # to the dictionary Map[key].append(curr) # Store the final result result = [] # Iterate over values of dictionary for vals in Map.values(): # If length of list > 1 if len(vals) > 1: # Print all the strings for v in vals: print(v, end =\" \") # Driver Code S = \"aba\"findAnagrams(S)", "e": 27611, "s": 26543, "text": null }, { "code": null, "e": 27621, "s": 27611, "text": "ab ba a a" }, { "code": null, "e": 27668, "s": 27623, "text": "Time Complexity: O(N3)Auxiliary Space: O(N2)" }, { "code": null, "e": 27676, "s": 27668, "text": "clintra" }, { "code": null, "e": 27684, "s": 27676, "text": "anagram" }, { "code": null, "e": 27694, "s": 27684, "text": "substring" }, { "code": null, "e": 27699, "s": 27694, "text": "Hash" }, { "code": null, "e": 27707, "s": 27699, "text": "Sorting" }, { "code": null, "e": 27715, "s": 27707, "text": "Strings" }, { "code": null, "e": 27720, "s": 27715, "text": "Hash" }, { "code": null, "e": 27728, "s": 27720, "text": "Strings" }, { "code": null, "e": 27736, "s": 27728, "text": "Sorting" }, { "code": null, "e": 27744, "s": 27736, "text": "anagram" }, { "code": null, "e": 27842, "s": 27744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27851, "s": 27842, "text": "Comments" }, { "code": null, "e": 27864, "s": 27851, "text": "Old Comments" }, { "code": null, "e": 27898, "s": 27864, "text": "Most frequent element in an array" }, { "code": null, "e": 27937, "s": 27898, "text": "Counting frequencies of array elements" }, { "code": null, "e": 27952, "s": 27937, "text": "Double Hashing" }, { "code": null, "e": 27981, "s": 27952, "text": "Quadratic Probing in Hashing" } ]
Factorial recursion in JavaScript
We are required to write a JavaScript function that computes the Factorial of a number n by making use of recursive approach. Here, we are finding the factorial recursion and creating a custom function recursiceFactorial() − const num = 9; const recursiceFactorial = (num, res = 1) => { if(num){ return recursiceFactorial(num-1, res * num); }; return res; }; Now, we will call the function and pass the value to find recursion − console.log(recursiceFactorial(num)); console.log(recursiceFactorial(6)); console.log(recursiceFactorial(10)); Let’s write the code for this function − const num = 9; const recursiceFactorial = (num, res = 1) => { if(num){ return recursiceFactorial(num-1, res * num); }; return res; }; console.log(recursiceFactorial(num)); console.log(recursiceFactorial(6)); console.log(recursiceFactorial(10)); console.log(recursiceFactorial(5)); console.log(recursiceFactorial(13)); Following is the output in the console − 362880 720 3628800 120 6227020800
[ { "code": null, "e": 1188, "s": 1062, "text": "We are required to write a JavaScript function that computes the Factorial of a number n by making use of recursive approach." }, { "code": null, "e": 1287, "s": 1188, "text": "Here, we are finding the factorial recursion and creating a custom function recursiceFactorial() −" }, { "code": null, "e": 1436, "s": 1287, "text": "const num = 9;\nconst recursiceFactorial = (num, res = 1) => {\n if(num){\n return recursiceFactorial(num-1, res * num);\n };\n return res;\n};" }, { "code": null, "e": 1506, "s": 1436, "text": "Now, we will call the function and pass the value to find recursion −" }, { "code": null, "e": 1617, "s": 1506, "text": "console.log(recursiceFactorial(num));\nconsole.log(recursiceFactorial(6));\nconsole.log(recursiceFactorial(10));" }, { "code": null, "e": 1658, "s": 1617, "text": "Let’s write the code for this function −" }, { "code": null, "e": 1991, "s": 1658, "text": "const num = 9;\nconst recursiceFactorial = (num, res = 1) => {\n if(num){\n return recursiceFactorial(num-1, res * num);\n };\n return res;\n};\nconsole.log(recursiceFactorial(num));\nconsole.log(recursiceFactorial(6));\nconsole.log(recursiceFactorial(10));\nconsole.log(recursiceFactorial(5));\nconsole.log(recursiceFactorial(13));" }, { "code": null, "e": 2032, "s": 1991, "text": "Following is the output in the console −" }, { "code": null, "e": 2066, "s": 2032, "text": "362880\n720\n3628800\n120\n6227020800" } ]
Custom Named Entity Recognition Using spaCy | by Kaustumbh Jaiswal | Towards Data Science
Named entity recognition (NER) is a sub-task of information extraction (IE) that seeks out and categorises specified entities in a body or bodies of texts. NER is also simply known as entity identification, entity chunking and entity extraction. NER is used in many fields in Artificial Intelligence (AI) including Natural Language Processing (NLP) and Machine Learning. SpaCy is an open-source library for advanced Natural Language Processing in Python. It is designed specifically for production use and helps build applications that process and “understand” large volumes of text. It can be used to build information extraction or natural language understanding systems, or to pre-process text for deep learning. Some of the features provided by spaCy are- Tokenization, Parts-of-Speech (PoS) Tagging, Text Classification and Named Entity Recognition. SpaCy provides an exceptionally efficient statistical system for NER in python, which can assign labels to groups of tokens which are contiguous. It provides a default model which can recognize a wide range of named or numerical entities, which include person, organization, language, event etc. Apart from these default entities, spaCy also gives us the liberty to add arbitrary classes to the NER model, by training the model to update it with newer trained examples. SpaCy can be installed using a simple pip install. You will also need to download the language model for the language you wish to use spaCy for. pip install -U spacy python -m spacy download en The dataset which we are going to work on can be downloaded from here. We will be using the ner_dataset.csv file and train only on 260 sentences. The dataset consists of the following tags- geo = Geographical Entity org = Organization per = Person gpe = Geopolitical Entity tim = Time indicator art = Artifact eve = Event nat = Natural Phenomenon The dataset follows a BIO type tagging. SpaCy requires the training data to be in the the following format- So we have to convert our data which is in .csv format to the above format. (There are also other forms of training data which spaCy accepts. Refer the documentation for more details.) We first drop the columns Sentence # and POS as we don’t need them and then convert the .csv file to .tsv file. Next, we have to run the script below to get the training data in .json format. Now the data should look like, The next step is to convert the above data into format needed by spaCy. It can be done using the following script- Now we have the the data ready for training! Let’s train a NER model by adding our custom entities. SpaCy NER already supports the entity types like- PERSONPeople, including fictional.NORPNationalities or religious or political groups.FACBuildings, airports, highways, bridges, etc.ORGCompanies, agencies, institutions, etc.GPECountries, cities, states, etc. Our aim is to further train this model to incorporate for our own custom entities present in our dataset. To do this we have to go through the following steps- Load the model, or create an empty model using spacy.blank with the ID of desired language. If a blank model is being used, we have to add the entity recognizer to the pipeline. If an existing model is being used, we have to disable all other pipeline components during training using nlp.disable_pipes. This way, only the entity recognizer gets trained. Load the model, or create an empty model using spacy.blank with the ID of desired language. If a blank model is being used, we have to add the entity recognizer to the pipeline. If an existing model is being used, we have to disable all other pipeline components during training using nlp.disable_pipes. This way, only the entity recognizer gets trained. # Setting up the pipeline and entity recognizer.if model is not None: nlp = spacy.load(model) # load existing spacy model print("Loaded model '%s'" % model)else: nlp = spacy.blank('en') # create blank Language class print("Created blank 'en' model")if 'ner' not in nlp.pipe_names: ner = nlp.create_pipe('ner') nlp.add_pipe(ner)else: ner = nlp.get_pipe('ner') 2. Add the new entity label to the entity recognizer using the add_label method. # Add new entity labels to entity recognizerfor i in LABEL: ner.add_label(i)# Inititalizing optimizerif model is None: optimizer = nlp.begin_training()else: optimizer = nlp.entity.create_optimizer() 3. Loop over the examples and call nlp.update, which steps through the words of the input. At each word, it makes a prediction. It then consults the annotations, to see whether it was right. If it was wrong, it adjusts its weights so that the correct action will score higher next time. # Get names of other pipes to disable them during training to train # only NER and update the weightsother_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']with nlp.disable_pipes(*other_pipes): # only train NER for itn in range(n_iter): random.shuffle(TRAIN_DATA) losses = {} batches = minibatch(TRAIN_DATA, size=compounding(4., 32., 1.001)) for batch in batches: texts, annotations = zip(*batch) # Updating the weights nlp.update(texts, annotations, sgd=optimizer, drop=0.35, losses=losses) print('Losses', losses) nlp.update(texts, annotations, sgd=optimizer, drop=0.35, losses=losses) print('Losses', losses) 4. Save the trained model using nlp.to_disk. # Save model if output_dir is not None: output_dir = Path(output_dir) if not output_dir.exists(): output_dir.mkdir() nlp.meta['name'] = new_model_name # rename model nlp.to_disk(output_dir) print("Saved model to", output_dir) 5. Test the model to make sure the new entity is recognized correctly. # Test the saved modelprint("Loading from", output_dir)nlp2 = spacy.load(output_dir)doc2 = nlp2(test_text)for ent in doc2.ents: print(ent.label_, ent.text) Use this script to train and test the model- Execution instructions- python spacy_ner_custom_entities.py \-m=en \ -o=path/to/output/directory \-n=1000 When tested for the queries- ['John Lee is the chief of CBSE', 'Americans suffered from H5N1'] , the model identified the following entities- John Lee is the chief of CBSE.B-per JohnI-per LeeB-org CBSEAmericans suffered from H5N1 virus in 2002.B-gpe AmericansB-nat H5N1B-tim 2002 I hope you have now understood how to train your own NER model on top of the spaCy NER model. Thanks for reading! 😊
[ { "code": null, "e": 543, "s": 172, "text": "Named entity recognition (NER) is a sub-task of information extraction (IE) that seeks out and categorises specified entities in a body or bodies of texts. NER is also simply known as entity identification, entity chunking and entity extraction. NER is used in many fields in Artificial Intelligence (AI) including Natural Language Processing (NLP) and Machine Learning." }, { "code": null, "e": 1027, "s": 543, "text": "SpaCy is an open-source library for advanced Natural Language Processing in Python. It is designed specifically for production use and helps build applications that process and “understand” large volumes of text. It can be used to build information extraction or natural language understanding systems, or to pre-process text for deep learning. Some of the features provided by spaCy are- Tokenization, Parts-of-Speech (PoS) Tagging, Text Classification and Named Entity Recognition." }, { "code": null, "e": 1497, "s": 1027, "text": "SpaCy provides an exceptionally efficient statistical system for NER in python, which can assign labels to groups of tokens which are contiguous. It provides a default model which can recognize a wide range of named or numerical entities, which include person, organization, language, event etc. Apart from these default entities, spaCy also gives us the liberty to add arbitrary classes to the NER model, by training the model to update it with newer trained examples." }, { "code": null, "e": 1642, "s": 1497, "text": "SpaCy can be installed using a simple pip install. You will also need to download the language model for the language you wish to use spaCy for." }, { "code": null, "e": 1691, "s": 1642, "text": "pip install -U spacy python -m spacy download en" }, { "code": null, "e": 1837, "s": 1691, "text": "The dataset which we are going to work on can be downloaded from here. We will be using the ner_dataset.csv file and train only on 260 sentences." }, { "code": null, "e": 1881, "s": 1837, "text": "The dataset consists of the following tags-" }, { "code": null, "e": 1907, "s": 1881, "text": "geo = Geographical Entity" }, { "code": null, "e": 1926, "s": 1907, "text": "org = Organization" }, { "code": null, "e": 1939, "s": 1926, "text": "per = Person" }, { "code": null, "e": 1965, "s": 1939, "text": "gpe = Geopolitical Entity" }, { "code": null, "e": 1986, "s": 1965, "text": "tim = Time indicator" }, { "code": null, "e": 2001, "s": 1986, "text": "art = Artifact" }, { "code": null, "e": 2013, "s": 2001, "text": "eve = Event" }, { "code": null, "e": 2038, "s": 2013, "text": "nat = Natural Phenomenon" }, { "code": null, "e": 2078, "s": 2038, "text": "The dataset follows a BIO type tagging." }, { "code": null, "e": 2146, "s": 2078, "text": "SpaCy requires the training data to be in the the following format-" }, { "code": null, "e": 2523, "s": 2146, "text": "So we have to convert our data which is in .csv format to the above format. (There are also other forms of training data which spaCy accepts. Refer the documentation for more details.) We first drop the columns Sentence # and POS as we don’t need them and then convert the .csv file to .tsv file. Next, we have to run the script below to get the training data in .json format." }, { "code": null, "e": 2554, "s": 2523, "text": "Now the data should look like," }, { "code": null, "e": 2669, "s": 2554, "text": "The next step is to convert the above data into format needed by spaCy. It can be done using the following script-" }, { "code": null, "e": 2769, "s": 2669, "text": "Now we have the the data ready for training! Let’s train a NER model by adding our custom entities." }, { "code": null, "e": 3028, "s": 2769, "text": "SpaCy NER already supports the entity types like- PERSONPeople, including fictional.NORPNationalities or religious or political groups.FACBuildings, airports, highways, bridges, etc.ORGCompanies, agencies, institutions, etc.GPECountries, cities, states, etc." }, { "code": null, "e": 3188, "s": 3028, "text": "Our aim is to further train this model to incorporate for our own custom entities present in our dataset. To do this we have to go through the following steps-" }, { "code": null, "e": 3543, "s": 3188, "text": "Load the model, or create an empty model using spacy.blank with the ID of desired language. If a blank model is being used, we have to add the entity recognizer to the pipeline. If an existing model is being used, we have to disable all other pipeline components during training using nlp.disable_pipes. This way, only the entity recognizer gets trained." }, { "code": null, "e": 3898, "s": 3543, "text": "Load the model, or create an empty model using spacy.blank with the ID of desired language. If a blank model is being used, we have to add the entity recognizer to the pipeline. If an existing model is being used, we have to disable all other pipeline components during training using nlp.disable_pipes. This way, only the entity recognizer gets trained." }, { "code": null, "e": 4280, "s": 3898, "text": "# Setting up the pipeline and entity recognizer.if model is not None: nlp = spacy.load(model) # load existing spacy model print(\"Loaded model '%s'\" % model)else: nlp = spacy.blank('en') # create blank Language class print(\"Created blank 'en' model\")if 'ner' not in nlp.pipe_names: ner = nlp.create_pipe('ner') nlp.add_pipe(ner)else: ner = nlp.get_pipe('ner')" }, { "code": null, "e": 4361, "s": 4280, "text": "2. Add the new entity label to the entity recognizer using the add_label method." }, { "code": null, "e": 4569, "s": 4361, "text": "# Add new entity labels to entity recognizerfor i in LABEL: ner.add_label(i)# Inititalizing optimizerif model is None: optimizer = nlp.begin_training()else: optimizer = nlp.entity.create_optimizer()" }, { "code": null, "e": 4856, "s": 4569, "text": "3. Loop over the examples and call nlp.update, which steps through the words of the input. At each word, it makes a prediction. It then consults the annotations, to see whether it was right. If it was wrong, it adjusts its weights so that the correct action will score higher next time." }, { "code": null, "e": 5642, "s": 4856, "text": "# Get names of other pipes to disable them during training to train # only NER and update the weightsother_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']with nlp.disable_pipes(*other_pipes): # only train NER for itn in range(n_iter): random.shuffle(TRAIN_DATA) losses = {} batches = minibatch(TRAIN_DATA, size=compounding(4., 32., 1.001)) for batch in batches: texts, annotations = zip(*batch) # Updating the weights nlp.update(texts, annotations, sgd=optimizer, drop=0.35, losses=losses) print('Losses', losses) nlp.update(texts, annotations, sgd=optimizer, drop=0.35, losses=losses) print('Losses', losses)" }, { "code": null, "e": 5687, "s": 5642, "text": "4. Save the trained model using nlp.to_disk." }, { "code": null, "e": 5936, "s": 5687, "text": "# Save model if output_dir is not None: output_dir = Path(output_dir) if not output_dir.exists(): output_dir.mkdir() nlp.meta['name'] = new_model_name # rename model nlp.to_disk(output_dir) print(\"Saved model to\", output_dir)" }, { "code": null, "e": 6007, "s": 5936, "text": "5. Test the model to make sure the new entity is recognized correctly." }, { "code": null, "e": 6166, "s": 6007, "text": "# Test the saved modelprint(\"Loading from\", output_dir)nlp2 = spacy.load(output_dir)doc2 = nlp2(test_text)for ent in doc2.ents: print(ent.label_, ent.text)" }, { "code": null, "e": 6211, "s": 6166, "text": "Use this script to train and test the model-" }, { "code": null, "e": 6235, "s": 6211, "text": "Execution instructions-" }, { "code": null, "e": 6317, "s": 6235, "text": "python spacy_ner_custom_entities.py \\-m=en \\ -o=path/to/output/directory \\-n=1000" }, { "code": null, "e": 6459, "s": 6317, "text": "When tested for the queries- ['John Lee is the chief of CBSE', 'Americans suffered from H5N1'] , the model identified the following entities-" }, { "code": null, "e": 6597, "s": 6459, "text": "John Lee is the chief of CBSE.B-per JohnI-per LeeB-org CBSEAmericans suffered from H5N1 virus in 2002.B-gpe AmericansB-nat H5N1B-tim 2002" } ]
How to count the number of rows in a table in Selenium with python?
We can count the total number of rows in a table in Selenium. The rows of a table are represented by <tr> tag in html code. To get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned. Next we need to compute the size of the list with the help of len method. The html code snippet of a table row count is as described below − driver.find_elements_by_xpath("//table/tbody/tr") Code Implementation for getting row count. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm") #to refresh the browser driver.refresh() # identifying the number of rows having <tr> tag rows = driver.find_elements_by_xpath("//table/tbody/tr") # len method is used to get the size of that list print(len(rows)) #to close the browser driver.close()
[ { "code": null, "e": 1391, "s": 1062, "text": "We can count the total number of rows in a table in Selenium. The rows of a table are represented by <tr> tag in html code. To get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned. Next we need to compute the size of the list with the help of len method." }, { "code": null, "e": 1458, "s": 1391, "text": "The html code snippet of a table row count is as described below −" }, { "code": null, "e": 1508, "s": 1458, "text": "driver.find_elements_by_xpath(\"//table/tbody/tr\")" }, { "code": null, "e": 1551, "s": 1508, "text": "Code Implementation for getting row count." }, { "code": null, "e": 2194, "s": 1551, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the number of rows having <tr> tag\nrows = driver.find_elements_by_xpath(\"//table/tbody/tr\")\n# len method is used to get the size of that list\nprint(len(rows))\n#to close the browser\ndriver.close()" } ]
Silverlight - Getting Started
In this chapter, we will look at a working example of Silverlight. We need two things − First, we require a web page. Silverlight is intended for rich internet applications, It is designed to run inside of a web browser as part of a web page. The page needs to incorporate a suitable tag to load the Silverlight plug-in. It can also include the logic to detect whether Silverlight is installed, and can provide some fallback user interface, when it is absent. First, we require a web page. Silverlight is intended for rich internet applications, It is designed to run inside of a web browser as part of a web page. The page needs to incorporate a suitable tag to load the Silverlight plug-in. It can also include the logic to detect whether Silverlight is installed, and can provide some fallback user interface, when it is absent. The second thing we need is the Silverlight content itself. This tutorial will focus on the .NET programming model for Silverlight. We will create a compiled Silverlight application containing a mixture of XAML, the mockup language we use to define Silverlight user interfaces, and .NET code written in C#. The second thing we need is the Silverlight content itself. This tutorial will focus on the .NET programming model for Silverlight. We will create a compiled Silverlight application containing a mixture of XAML, the mockup language we use to define Silverlight user interfaces, and .NET code written in C#. The easiest way to start using Silverlight is to create an ordinary website with HTML pages and no server side code. Let us look at a very simple example. Step 1 − Open Visual Studio. Click the File menu, point to New and then click Project. Step 2 − A New Project dialog box will open. Under Templates, select Visual C# and then click Silverlight. In the right pane, choose Silverlight Application. Enter a project name and a location on your hard drive to save your project and then click OK to create the project. The Silverlight project itself is just going to build the Silverlight content, and that content is just one asset amongst many that are going to make up the whole web application. Click OK. Step 3 − Check the Host the Silverlight application checkbox. The default is an ASP.NET Web Application Project. Step 4 − MS-Visual Studio has created two projects, the Silverlight project and an ASP.NET web application. Now, we do need an ASP.NET web application. You can see this in the Solution Explorer window as shown below. Anything that can serve up the content via HTTP will do but this is Visual Studio, and it understands the ASP.NET web technology, so that is what it gives us. To demonstrate that Silverlight does not depend on any particular server-side technology, let us delete this .aspx file, leaving just the plain static HTML file. Step 5 − Right-click FirstExampleTestpage.aspx. From the list of options, click Delete. Step 6 − Set FirstExampleTestPage.html as the Start page. The MainPage.xaml file defines the user interface for Silverlight content. Either you can write XAML code directly or you can also use Toolbox to drag and drop different UI elements. Step 7 − Given below is a simple code in MainPage.xaml in which a Button and a TextBlock are defined inside the StackPanel. <UserControl x:Class = "FirstExample.MainPage" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "400"> <Grid x:Name = "LayoutRoot" Background = "White"> <StackPanel> <TextBlock x:Name = "TextMessage" Text = "Hello World!" Margin = "5"> </TextBlock> <Button x:Name = "ClickMe" Click = "ClickMe_Click" Content = "Click Me!" Margin = "5"> </Button> </StackPanel> </Grid> </UserControl> Step 8 − This example assumes that you have created an event-handling method named ClickMe_Click. Here is what it looks like in the MainPage.xaml.cs file. using System.Windows; using System.Windows.Controls; namespace FirstExample { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void ClickMe_Click(object sender, RoutedEventArgs e) { TextMessage.Text = "Congratulations! you have created your first Silverlight Applicatoin"; } } } Step 9 − A Silverlight application can be run on any installed browsers. Step 10 − When the above code is compiled and executed, you will see the following webpage. Step 11 − Now, when you click the Click Me button, it will update the text in the TextBlock as shown below. We recommend you to execute the above example by adding some more UI elements. Print Add Notes Bookmark this page
[ { "code": null, "e": 2420, "s": 2332, "text": "In this chapter, we will look at a working example of Silverlight. We need two things −" }, { "code": null, "e": 2792, "s": 2420, "text": "First, we require a web page. Silverlight is intended for rich internet applications, It is designed to run inside of a web browser as part of a web page. The page needs to incorporate a suitable tag to load the Silverlight plug-in. It can also include the logic to detect whether Silverlight is installed, and can provide some fallback user interface, when it is absent." }, { "code": null, "e": 3164, "s": 2792, "text": "First, we require a web page. Silverlight is intended for rich internet applications, It is designed to run inside of a web browser as part of a web page. The page needs to incorporate a suitable tag to load the Silverlight plug-in. It can also include the logic to detect whether Silverlight is installed, and can provide some fallback user interface, when it is absent." }, { "code": null, "e": 3471, "s": 3164, "text": "The second thing we need is the Silverlight content itself. This tutorial will focus on the .NET programming model for Silverlight. We will create a compiled Silverlight application containing a mixture of XAML, the mockup language we use to define Silverlight user interfaces, and .NET code written in C#." }, { "code": null, "e": 3778, "s": 3471, "text": "The second thing we need is the Silverlight content itself. This tutorial will focus on the .NET programming model for Silverlight. We will create a compiled Silverlight application containing a mixture of XAML, the mockup language we use to define Silverlight user interfaces, and .NET code written in C#." }, { "code": null, "e": 3933, "s": 3778, "text": "The easiest way to start using Silverlight is to create an ordinary website with HTML pages and no server side code. Let us look at a very simple example." }, { "code": null, "e": 4020, "s": 3933, "text": "Step 1 − Open Visual Studio. Click the File menu, point to New and then click Project." }, { "code": null, "e": 4178, "s": 4020, "text": "Step 2 − A New Project dialog box will open. Under Templates, select Visual C# and then click Silverlight. In the right pane, choose Silverlight Application." }, { "code": null, "e": 4295, "s": 4178, "text": "Enter a project name and a location on your hard drive to save your project and then click OK to create the project." }, { "code": null, "e": 4475, "s": 4295, "text": "The Silverlight project itself is just going to build the Silverlight content, and that content is just one asset amongst many that are going to make up the whole web application." }, { "code": null, "e": 4485, "s": 4475, "text": "Click OK." }, { "code": null, "e": 4598, "s": 4485, "text": "Step 3 − Check the Host the Silverlight application checkbox. The default is an ASP.NET Web Application Project." }, { "code": null, "e": 4815, "s": 4598, "text": "Step 4 − MS-Visual Studio has created two projects, the Silverlight project and an ASP.NET web application. Now, we do need an ASP.NET web application. You can see this in the Solution Explorer window as shown below." }, { "code": null, "e": 4974, "s": 4815, "text": "Anything that can serve up the content via HTTP will do but this is Visual Studio, and it understands the ASP.NET web technology, so that is what it gives us." }, { "code": null, "e": 5136, "s": 4974, "text": "To demonstrate that Silverlight does not depend on any particular server-side technology, let us delete this .aspx file, leaving just the plain static HTML file." }, { "code": null, "e": 5224, "s": 5136, "text": "Step 5 − Right-click FirstExampleTestpage.aspx. From the list of options, click Delete." }, { "code": null, "e": 5282, "s": 5224, "text": "Step 6 − Set FirstExampleTestPage.html as the Start page." }, { "code": null, "e": 5465, "s": 5282, "text": "The MainPage.xaml file defines the user interface for Silverlight content. Either you can write XAML code directly or you can also use Toolbox to drag and drop different UI elements." }, { "code": null, "e": 5589, "s": 5465, "text": "Step 7 − Given below is a simple code in MainPage.xaml in which a Button and a TextBlock are defined inside the StackPanel." }, { "code": null, "e": 6416, "s": 5589, "text": "<UserControl x:Class = \"FirstExample.MainPage\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n mc:Ignorable = \"d\" \n d:DesignHeight = \"300\" d:DesignWidth = \"400\"> \n \n <Grid x:Name = \"LayoutRoot\" Background = \"White\"> \n <StackPanel> \n\t\t\n <TextBlock x:Name = \"TextMessage\" \n Text = \"Hello World!\" \n Margin = \"5\">\n </TextBlock> \n\t\t\t\n <Button x:Name = \"ClickMe\" \n Click = \"ClickMe_Click\" \n Content = \"Click Me!\" \n Margin = \"5\"> \n </Button> \n\t\t\t\n </StackPanel> \n </Grid> \n\t\n</UserControl>" }, { "code": null, "e": 6571, "s": 6416, "text": "Step 8 − This example assumes that you have created an event-handling method named ClickMe_Click. Here is what it looks like in the MainPage.xaml.cs file." }, { "code": null, "e": 6968, "s": 6571, "text": "using System.Windows; \nusing System.Windows.Controls;\n \nnamespace FirstExample { \n\n public partial class MainPage : UserControl { \n\t\n public MainPage() { \n InitializeComponent(); \n } \n\t \n private void ClickMe_Click(object sender, RoutedEventArgs e) { \n TextMessage.Text = \"Congratulations! you have created your first Silverlight Applicatoin\"; \n } \n } \n}" }, { "code": null, "e": 7041, "s": 6968, "text": "Step 9 − A Silverlight application can be run on any installed browsers." }, { "code": null, "e": 7133, "s": 7041, "text": "Step 10 − When the above code is compiled and executed, you will see the following webpage." }, { "code": null, "e": 7241, "s": 7133, "text": "Step 11 − Now, when you click the Click Me button, it will update the text in the TextBlock as shown below." }, { "code": null, "e": 7320, "s": 7241, "text": "We recommend you to execute the above example by adding some more UI elements." }, { "code": null, "e": 7327, "s": 7320, "text": " Print" }, { "code": null, "e": 7338, "s": 7327, "text": " Add Notes" } ]
How to set the line breakpoint in the PowerShell?
To set the line breakpoint in the script, we can use the Set-PSBreakpoint command with -Line parameter and need to give the path of the script on which the Line breakpoint needs to set. Consider we have the script below which retrieves the value up to 99, starting from 1, We will set the Line Breakpoint at line number 3 so we will use the below command. Here the script name is WhieScript.ps1 and stored at C:\temp. Set-PSBreakpoint C:\temp\WhileScript.ps1 -Line 3 Once you run the above command, you will get the output with the details as shown below. ID Script Line Command Variable Action -- ------ ---- ------- -------- ------ 6 WhileScript.ps1 3 To check all the applied breakpoints, you can use the Get-PSBreakPoint command. Now to enter the debug mode, you need to run the script. You can see in the above image that the console has entered debug mode. To continue till the next breakpoint, press ‘C’. There are other keywords for step in, step out, exit, etc. You can check them below at the MS site. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_debuggers?view=powershell-7.1
[ { "code": null, "e": 1248, "s": 1062, "text": "To set the line breakpoint in the script, we can use the Set-PSBreakpoint command with -Line parameter and need to give the path of the script on which the Line breakpoint needs to set." }, { "code": null, "e": 1335, "s": 1248, "text": "Consider we have the script below which retrieves the value up to 99, starting from 1," }, { "code": null, "e": 1480, "s": 1335, "text": "We will set the Line Breakpoint at line number 3 so we will use the below command. Here the script name is WhieScript.ps1 and stored at C:\\temp." }, { "code": null, "e": 1529, "s": 1480, "text": "Set-PSBreakpoint C:\\temp\\WhileScript.ps1 -Line 3" }, { "code": null, "e": 1618, "s": 1529, "text": "Once you run the above command, you will get the output with the details as shown below." }, { "code": null, "e": 1722, "s": 1618, "text": "ID Script Line Command Variable Action\n -- ------ ---- ------- -------- ------\n6 WhileScript.ps1 3" }, { "code": null, "e": 1802, "s": 1722, "text": "To check all the applied breakpoints, you can use the Get-PSBreakPoint command." }, { "code": null, "e": 1859, "s": 1802, "text": "Now to enter the debug mode, you need to run the script." }, { "code": null, "e": 1980, "s": 1859, "text": "You can see in the above image that the console has entered debug mode. To continue till the next breakpoint, press ‘C’." }, { "code": null, "e": 2080, "s": 1980, "text": "There are other keywords for step in, step out, exit, etc. You can check them below at the MS site." }, { "code": null, "e": 2200, "s": 2080, "text": " https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_debuggers?view=powershell-7.1" } ]
MySQL - CREATE TABLESPACE Statement
A logical group of datafiles in a database is known as a table space each database contains at least one tablespace. You can create a tablespace in MySQL using the CREATE TABLESPACE Statement. Following is the syntax to create a table space in MySQL − CREATE [UNDO] TABLESPACE tablespace_name Where, tablespace_name is the name of the table space you need to create. Following query creates a table with name Employee − mysql> CREATE TABLESPACE sample_tablespace; Following query creates another tablespace with name test − mysql> CREATE TABLESPACE sample ADD DATAFILE 'sample.ibd' ENGINE = INNODB; Query OK, 0 rows affected (0.59 sec) You can verify the creation of the above tablespace using the following query − mysql> select * from INFORMATION_SCHEMA.FILES where TABLESPACE_NAME ='sample'\G *************************** 1. row *************************** FILE_ID: 73 FILE_NAME: ./sample.ibd FILE_TYPE: TABLESPACE TABLESPACE_NAME: sample TABLE_CATALOG: TABLE_SCHEMA: NULL TABLE_NAME: NULL LOGFILE_GROUP_NAME: NULL LOGFILE_GROUP_NUMBER: NULL ENGINE: InnoDB FULLTEXT_KEYS: NULL DELETED_ROWS: NULL UPDATE_COUNT: NUL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 row in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2450, "s": 2333, "text": "A logical group of datafiles in a database is known as a table space each database contains at least one tablespace." }, { "code": null, "e": 2526, "s": 2450, "text": "You can create a tablespace in MySQL using the CREATE TABLESPACE Statement." }, { "code": null, "e": 2585, "s": 2526, "text": "Following is the syntax to create a table space in MySQL −" }, { "code": null, "e": 2627, "s": 2585, "text": "CREATE [UNDO] TABLESPACE tablespace_name\n" }, { "code": null, "e": 2701, "s": 2627, "text": "Where, tablespace_name is the name of the table space you need to create." }, { "code": null, "e": 2754, "s": 2701, "text": "Following query creates a table with name Employee −" }, { "code": null, "e": 2799, "s": 2754, "text": "mysql> CREATE TABLESPACE sample_tablespace;\n" }, { "code": null, "e": 2859, "s": 2799, "text": "Following query creates another tablespace with name test −" }, { "code": null, "e": 2972, "s": 2859, "text": "mysql> CREATE TABLESPACE sample ADD DATAFILE 'sample.ibd' ENGINE = INNODB;\nQuery OK, 0 rows affected (0.59 sec)\n" }, { "code": null, "e": 3052, "s": 2972, "text": "You can verify the creation of the above tablespace using the following query −" }, { "code": null, "e": 4078, "s": 3052, "text": "mysql> select * from INFORMATION_SCHEMA.FILES where TABLESPACE_NAME ='sample'\\G\n*************************** 1. row ***************************\n FILE_ID: 73\n FILE_NAME: ./sample.ibd\n FILE_TYPE: TABLESPACE\n TABLESPACE_NAME: sample\n TABLE_CATALOG:\n TABLE_SCHEMA: NULL\n TABLE_NAME: NULL\n LOGFILE_GROUP_NAME: NULL\nLOGFILE_GROUP_NUMBER: NULL\n ENGINE: InnoDB\n FULLTEXT_KEYS: NULL\n DELETED_ROWS: NULL \n UPDATE_COUNT: NUL\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n1 row in set (0.00 sec)" }, { "code": null, "e": 4111, "s": 4078, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 4139, "s": 4111, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4174, "s": 4139, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4191, "s": 4174, "text": " Frahaan Hussain" }, { "code": null, "e": 4225, "s": 4191, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4260, "s": 4225, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4294, "s": 4260, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 4322, "s": 4294, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4355, "s": 4322, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 4375, "s": 4355, "text": " Harshit Srivastava" }, { "code": null, "e": 4408, "s": 4375, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 4426, "s": 4408, "text": " Trevoir Williams" }, { "code": null, "e": 4433, "s": 4426, "text": " Print" }, { "code": null, "e": 4444, "s": 4433, "text": " Add Notes" } ]
Inheritance in Java
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance, the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as a subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). Live Demo class Calculation { int z; public void addition(int x, int y) { z = x + y; System.out.println("The sum of the given numbers:"+z); } public void Subtraction(int x, int y) { z = x - y; System.out.println("The difference between the given numbers:"+z); } } public class My_Calculation extends Calculation { public void multiplication(int x, int y) { z = x * y; System.out.println("The product of the given numbers:"+z); } public static void main(String args[]) { int a = 20, b = 10; My_Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Subtraction(a, b); demo.multiplication(a, b); } } Compile and execute the above code as shown below. javac My_Calculation.java java My_Calculation After executing the program, it will produce the following result − The sum of the given numbers:30 The difference between the given numbers:10 The product of the given numbers:200
[ { "code": null, "e": 1267, "s": 1062, "text": "Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance, the information is made manageable in a hierarchical order. " }, { "code": null, "e": 1464, "s": 1267, "text": "The class which inherits the properties of other is known as a subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class)." }, { "code": null, "e": 1476, "s": 1464, "text": " Live Demo " }, { "code": null, "e": 2169, "s": 1476, "text": "class Calculation {\n int z;\n public void addition(int x, int y) {\n z = x + y;\n System.out.println(\"The sum of the given numbers:\"+z);\n }\n public void Subtraction(int x, int y) {\n z = x - y;\n System.out.println(\"The difference between the given numbers:\"+z);\n }\n}\npublic class My_Calculation extends Calculation {\n public void multiplication(int x, int y) {\n z = x * y;\n System.out.println(\"The product of the given numbers:\"+z);\n }\n public static void main(String args[]) {\n int a = 20, b = 10;\n My_Calculation demo = new My_Calculation();\n demo.addition(a, b);\n demo.Subtraction(a, b);\n demo.multiplication(a, b);\n }\n}" }, { "code": null, "e": 2220, "s": 2169, "text": "Compile and execute the above code as shown below." }, { "code": null, "e": 2267, "s": 2220, "text": "javac My_Calculation.java\njava My_Calculation " }, { "code": null, "e": 2336, "s": 2267, "text": "After executing the program, it will produce the following result − " }, { "code": null, "e": 2449, "s": 2336, "text": "The sum of the given numbers:30\nThe difference between the given numbers:10\nThe product of the given numbers:200" } ]
Check whether a binary tree is a full binary tree or not - GeeksforGeeks
20 Jan, 2022 A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : To check whether a binary tree is a full binary tree we need to test the following cases:-1) If a binary tree node is NULL then it is a full binary tree. 2) If a binary tree node does have empty left and right sub-trees, then it is a full binary tree by definition. 3) If a binary tree node has left and right sub-trees, then it is a part of a full binary tree by definition. In this case recursively check if the left and right sub-trees are also binary trees themselves. 4) In all other combinations of right and left sub-trees, the binary tree is not a full binary tree. Following is the implementation for checking if a binary tree is a full binary tree. C++ C Java Python3 C# Javascript // C++ program to check whether a given Binary Tree is full or not#include <bits/stdc++.h> using namespace std; /* Tree node structure */struct Node{ int key; struct Node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointer. */struct Node *newNode(char k){ struct Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} /* This function tests if a binary tree is a full binary tree. */bool isFullTree (struct Node* root){ // If empty tree if (root == NULL) return true; // If leaf node if (root->left == NULL && root->right == NULL) return true; // If both left and right are not NULL, and left & right subtrees // are full if ((root->left) && (root->right)) return (isFullTree(root->left) && isFullTree(root->right)); // We reach here when none of the above if conditions work return false;} // Driver Programint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->right = newNode(40); root->left->left = newNode(50); root->right->left = newNode(60); root->right->right = newNode(70); root->left->left->left = newNode(80); root->left->left->right = newNode(90); root->left->right->left = newNode(80); root->left->right->right = newNode(90); root->right->left->left = newNode(80); root->right->left->right = newNode(90); root->right->right->left = newNode(80); root->right->right->right = newNode(90); if (isFullTree(root)) cout << "The Binary Tree is full\n"; else cout << "The Binary Tree is not full\n"; return(0);} // This code is contributed by shubhamsingh10 // C program to check whether a given Binary Tree is full or not#include<stdio.h>#include<stdlib.h>#include<stdbool.h> /* Tree node structure */struct Node{ int key; struct Node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointer. */struct Node *newNode(char k){ struct Node *node = (struct Node*)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} /* This function tests if a binary tree is a full binary tree. */bool isFullTree (struct Node* root){ // If empty tree if (root == NULL) return true; // If leaf node if (root->left == NULL && root->right == NULL) return true; // If both left and right are not NULL, and left & right subtrees // are full if ((root->left) && (root->right)) return (isFullTree(root->left) && isFullTree(root->right)); // We reach here when none of the above if conditions work return false;} // Driver Programint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->right = newNode(40); root->left->left = newNode(50); root->right->left = newNode(60); root->right->right = newNode(70); root->left->left->left = newNode(80); root->left->left->right = newNode(90); root->left->right->left = newNode(80); root->left->right->right = newNode(90); root->right->left->left = newNode(80); root->right->left->right = newNode(90); root->right->right->left = newNode(80); root->right->right->right = newNode(90); if (isFullTree(root)) printf("The Binary Tree is full\n"); else printf("The Binary Tree is not full\n"); return(0);} // Java program to check if binary tree is full or not /* Tree node structure */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* this function checks if a binary tree is full or not */ boolean isFullTree(Node node) { // if empty tree if(node == null) return true; // if leaf node if(node.left == null && node.right == null ) return true; // if both left and right subtrees are not null // the are full if((node.left!=null) && (node.right!=null)) return (isFullTree(node.left) && isFullTree(node.right)); // if none work return false; } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.right = new Node(40); tree.root.left.left = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.left = new Node(80); tree.root.right.right = new Node(70); tree.root.left.left.right = new Node(90); tree.root.left.right.left = new Node(80); tree.root.left.right.right = new Node(90); tree.root.right.left.left = new Node(80); tree.root.right.left.right = new Node(90); tree.root.right.right.left = new Node(80); tree.root.right.right.right = new Node(90); if(tree.isFullTree(tree.root)) System.out.print("The binary tree is full"); else System.out.print("The binary tree is not full"); }} // This code is contributed by Mayank Jaiswal # Python program to check whether given Binary tree is full or not # Tree node structureclass Node: # Constructor of the node class for creating the node def __init__(self , key): self.key = key self.left = None self.right = None # Checks if the binary tree is full or notdef isFullTree(root): # If empty tree if root is None: return True # If leaf node if root.left is None and root.right is None: return True # If both left and right subtress are not None and # left and right subtress are full if root.left is not None and root.right is not None: return (isFullTree(root.left) and isFullTree(root.right)) # We reach here when none of the above if conditions work return False # Driver Programroot = Node(10);root.left = Node(20);root.right = Node(30); root.left.right = Node(40);root.left.left = Node(50);root.right.left = Node(60);root.right.right = Node(70); root.left.left.left = Node(80);root.left.left.right = Node(90);root.left.right.left = Node(80);root.left.right.right = Node(90);root.right.left.left = Node(80);root.right.left.right = Node(90);root.right.right.left = Node(80);root.right.right.right = Node(90); if isFullTree(root): print ("The Binary tree is full")else: print ("Binary tree is not full") # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to check if binary tree// is full or notusing System; /* Tree node structure */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; /* This function checks if a binarytree is full or not */public virtual bool isFullTree(Node node){ // if empty tree if (node == null) { return true; } // if leaf node if (node.left == null && node.right == null) { return true; } // if both left and right subtrees // are not null they are full if ((node.left != null) && (node.right != null)) { return (isFullTree(node.left) && isFullTree(node.right)); } // if none work return false;} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.right = new Node(40); tree.root.left.left = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.left = new Node(80); tree.root.right.right = new Node(70); tree.root.left.left.right = new Node(90); tree.root.left.right.left = new Node(80); tree.root.left.right.right = new Node(90); tree.root.right.left.left = new Node(80); tree.root.right.left.right = new Node(90); tree.root.right.right.left = new Node(80); tree.root.right.right.right = new Node(90); if (tree.isFullTree(tree.root)) { Console.Write("The binary tree is full"); } else { Console.Write("The binary tree is not full"); }}} // This code is contributed by Shrikant13 <script>// javascript program to check if binary tree is full or not /* Tree node structure */class Node { constructor(item) { this.data = item; this.left = this.right = null; }} var root; /* this function checks if a binary tree is full or not */ function isFullTree( node) { // if empty tree if (node == null) return true; // if leaf node if (node.left == null && node.right == null) return true; // if both left and right subtrees are not null // the are full if ((node.left != null) && (node.right != null)) return (isFullTree(node.left) && isFullTree(node.right)); // if none work return false; } // Driver program root = new Node(10); root.left = new Node(20); root.right = new Node(30); root.left.right = new Node(40); root.left.left = new Node(50); root.right.left = new Node(60); root.left.left.left = new Node(80); root.right.right = new Node(70); root.left.left.right = new Node(90); root.left.right.left = new Node(80); root.left.right.right = new Node(90); root.right.left.left = new Node(80); root.right.left.right = new Node(90); root.right.right.left = new Node(80); root.right.right.right = new Node(90); if(isFullTree(root)) document.write("The binary tree is full"); else document.write("The binary tree is not full"); // This code contributed by gauravrajput1</script> The Binary Tree is full Time complexity of the above code is O(n) where n is number of nodes in given binary tree. YouTubeGeeksforGeeks502K subscribersCheck whether a binary tree is a full binary tree or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_Hehd1KSq7Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Gaurav Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above lostboy24 shrikanth13 SHUBHAMSINGH10 GauravRajput1 surindertarika1234 surinderdawra388 amartyaghoshgfg Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree Sorted Array to Balanced BST
[ { "code": null, "e": 25516, "s": 25488, "text": "\n20 Jan, 2022" }, { "code": null, "e": 25757, "s": 25516, "text": "A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here." }, { "code": null, "e": 25773, "s": 25757, "text": "For Example : " }, { "code": null, "e": 26347, "s": 25773, "text": "To check whether a binary tree is a full binary tree we need to test the following cases:-1) If a binary tree node is NULL then it is a full binary tree. 2) If a binary tree node does have empty left and right sub-trees, then it is a full binary tree by definition. 3) If a binary tree node has left and right sub-trees, then it is a part of a full binary tree by definition. In this case recursively check if the left and right sub-trees are also binary trees themselves. 4) In all other combinations of right and left sub-trees, the binary tree is not a full binary tree." }, { "code": null, "e": 26433, "s": 26347, "text": "Following is the implementation for checking if a binary tree is a full binary tree. " }, { "code": null, "e": 26437, "s": 26433, "text": "C++" }, { "code": null, "e": 26439, "s": 26437, "text": "C" }, { "code": null, "e": 26444, "s": 26439, "text": "Java" }, { "code": null, "e": 26452, "s": 26444, "text": "Python3" }, { "code": null, "e": 26455, "s": 26452, "text": "C#" }, { "code": null, "e": 26466, "s": 26455, "text": "Javascript" }, { "code": "// C++ program to check whether a given Binary Tree is full or not#include <bits/stdc++.h> using namespace std; /* Tree node structure */struct Node{ int key; struct Node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointer. */struct Node *newNode(char k){ struct Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} /* This function tests if a binary tree is a full binary tree. */bool isFullTree (struct Node* root){ // If empty tree if (root == NULL) return true; // If leaf node if (root->left == NULL && root->right == NULL) return true; // If both left and right are not NULL, and left & right subtrees // are full if ((root->left) && (root->right)) return (isFullTree(root->left) && isFullTree(root->right)); // We reach here when none of the above if conditions work return false;} // Driver Programint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->right = newNode(40); root->left->left = newNode(50); root->right->left = newNode(60); root->right->right = newNode(70); root->left->left->left = newNode(80); root->left->left->right = newNode(90); root->left->right->left = newNode(80); root->left->right->right = newNode(90); root->right->left->left = newNode(80); root->right->left->right = newNode(90); root->right->right->left = newNode(80); root->right->right->right = newNode(90); if (isFullTree(root)) cout << \"The Binary Tree is full\\n\"; else cout << \"The Binary Tree is not full\\n\"; return(0);} // This code is contributed by shubhamsingh10", "e": 28246, "s": 26466, "text": null }, { "code": "// C program to check whether a given Binary Tree is full or not#include<stdio.h>#include<stdlib.h>#include<stdbool.h> /* Tree node structure */struct Node{ int key; struct Node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointer. */struct Node *newNode(char k){ struct Node *node = (struct Node*)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} /* This function tests if a binary tree is a full binary tree. */bool isFullTree (struct Node* root){ // If empty tree if (root == NULL) return true; // If leaf node if (root->left == NULL && root->right == NULL) return true; // If both left and right are not NULL, and left & right subtrees // are full if ((root->left) && (root->right)) return (isFullTree(root->left) && isFullTree(root->right)); // We reach here when none of the above if conditions work return false;} // Driver Programint main(){ struct Node* root = NULL; root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->right = newNode(40); root->left->left = newNode(50); root->right->left = newNode(60); root->right->right = newNode(70); root->left->left->left = newNode(80); root->left->left->right = newNode(90); root->left->right->left = newNode(80); root->left->right->right = newNode(90); root->right->left->left = newNode(80); root->right->left->right = newNode(90); root->right->right->left = newNode(80); root->right->right->right = newNode(90); if (isFullTree(root)) printf(\"The Binary Tree is full\\n\"); else printf(\"The Binary Tree is not full\\n\"); return(0);}", "e": 30008, "s": 28246, "text": null }, { "code": "// Java program to check if binary tree is full or not /* Tree node structure */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* this function checks if a binary tree is full or not */ boolean isFullTree(Node node) { // if empty tree if(node == null) return true; // if leaf node if(node.left == null && node.right == null ) return true; // if both left and right subtrees are not null // the are full if((node.left!=null) && (node.right!=null)) return (isFullTree(node.left) && isFullTree(node.right)); // if none work return false; } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.right = new Node(40); tree.root.left.left = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.left = new Node(80); tree.root.right.right = new Node(70); tree.root.left.left.right = new Node(90); tree.root.left.right.left = new Node(80); tree.root.left.right.right = new Node(90); tree.root.right.left.left = new Node(80); tree.root.right.left.right = new Node(90); tree.root.right.right.left = new Node(80); tree.root.right.right.right = new Node(90); if(tree.isFullTree(tree.root)) System.out.print(\"The binary tree is full\"); else System.out.print(\"The binary tree is not full\"); }} // This code is contributed by Mayank Jaiswal", "e": 31827, "s": 30008, "text": null }, { "code": "# Python program to check whether given Binary tree is full or not # Tree node structureclass Node: # Constructor of the node class for creating the node def __init__(self , key): self.key = key self.left = None self.right = None # Checks if the binary tree is full or notdef isFullTree(root): # If empty tree if root is None: return True # If leaf node if root.left is None and root.right is None: return True # If both left and right subtress are not None and # left and right subtress are full if root.left is not None and root.right is not None: return (isFullTree(root.left) and isFullTree(root.right)) # We reach here when none of the above if conditions work return False # Driver Programroot = Node(10);root.left = Node(20);root.right = Node(30); root.left.right = Node(40);root.left.left = Node(50);root.right.left = Node(60);root.right.right = Node(70); root.left.left.left = Node(80);root.left.left.right = Node(90);root.left.right.left = Node(80);root.left.right.right = Node(90);root.right.left.left = Node(80);root.right.left.right = Node(90);root.right.right.left = Node(80);root.right.right.right = Node(90); if isFullTree(root): print (\"The Binary tree is full\")else: print (\"Binary tree is not full\") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 33206, "s": 31827, "text": null }, { "code": "// C# program to check if binary tree// is full or notusing System; /* Tree node structure */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; /* This function checks if a binarytree is full or not */public virtual bool isFullTree(Node node){ // if empty tree if (node == null) { return true; } // if leaf node if (node.left == null && node.right == null) { return true; } // if both left and right subtrees // are not null they are full if ((node.left != null) && (node.right != null)) { return (isFullTree(node.left) && isFullTree(node.right)); } // if none work return false;} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.right = new Node(40); tree.root.left.left = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.left = new Node(80); tree.root.right.right = new Node(70); tree.root.left.left.right = new Node(90); tree.root.left.right.left = new Node(80); tree.root.left.right.right = new Node(90); tree.root.right.left.left = new Node(80); tree.root.right.left.right = new Node(90); tree.root.right.right.left = new Node(80); tree.root.right.right.right = new Node(90); if (tree.isFullTree(tree.root)) { Console.Write(\"The binary tree is full\"); } else { Console.Write(\"The binary tree is not full\"); }}} // This code is contributed by Shrikant13", "e": 34907, "s": 33206, "text": null }, { "code": "<script>// javascript program to check if binary tree is full or not /* Tree node structure */class Node { constructor(item) { this.data = item; this.left = this.right = null; }} var root; /* this function checks if a binary tree is full or not */ function isFullTree( node) { // if empty tree if (node == null) return true; // if leaf node if (node.left == null && node.right == null) return true; // if both left and right subtrees are not null // the are full if ((node.left != null) && (node.right != null)) return (isFullTree(node.left) && isFullTree(node.right)); // if none work return false; } // Driver program root = new Node(10); root.left = new Node(20); root.right = new Node(30); root.left.right = new Node(40); root.left.left = new Node(50); root.right.left = new Node(60); root.left.left.left = new Node(80); root.right.right = new Node(70); root.left.left.right = new Node(90); root.left.right.left = new Node(80); root.left.right.right = new Node(90); root.right.left.left = new Node(80); root.right.left.right = new Node(90); root.right.right.left = new Node(80); root.right.right.right = new Node(90); if(isFullTree(root)) document.write(\"The binary tree is full\"); else document.write(\"The binary tree is not full\"); // This code contributed by gauravrajput1</script>", "e": 36499, "s": 34907, "text": null }, { "code": null, "e": 36523, "s": 36499, "text": "The Binary Tree is full" }, { "code": null, "e": 36616, "s": 36525, "text": "Time complexity of the above code is O(n) where n is number of nodes in given binary tree." }, { "code": null, "e": 37471, "s": 36616, "text": "YouTubeGeeksforGeeks502K subscribersCheck whether a binary tree is a full binary tree or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_Hehd1KSq7Y\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 37641, "s": 37471, "text": "This article is contributed by Gaurav Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 37651, "s": 37641, "text": "lostboy24" }, { "code": null, "e": 37663, "s": 37651, "text": "shrikanth13" }, { "code": null, "e": 37678, "s": 37663, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 37692, "s": 37678, "text": "GauravRajput1" }, { "code": null, "e": 37711, "s": 37692, "text": "surindertarika1234" }, { "code": null, "e": 37728, "s": 37711, "text": "surinderdawra388" }, { "code": null, "e": 37744, "s": 37728, "text": "amartyaghoshgfg" }, { "code": null, "e": 37749, "s": 37744, "text": "Tree" }, { "code": null, "e": 37754, "s": 37749, "text": "Tree" }, { "code": null, "e": 37852, "s": 37754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37893, "s": 37852, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 37936, "s": 37893, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 37969, "s": 37936, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 37983, "s": 37969, "text": "Decision Tree" }, { "code": null, "e": 38066, "s": 37983, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 38124, "s": 38066, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 38160, "s": 38124, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 38208, "s": 38160, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 38235, "s": 38208, "text": "BFS vs DFS for Binary Tree" } ]