title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Matplotlib.pyplot.contourf() in Python
21 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The contourf() function in pyplot module of matplotlib library is used to plot contours. But contourf draw filled contours, while contourf draws contour lines. Syntax: matplotlib.pyplot.contourf(\*args, data=None, \*\*kwargs) Parameters: This method accept the following parameters that are described below: X, Y: These parameter are the coordinates of the values in Z. Z : This parameter is the height values over which the contour is drawn. levels : This parameter is used to determine the numbers and positions of the contour lines / regions. Returns: This returns the following: c :This returns the QuadContourSet. Below examples illustrate the matplotlib.pyplot.contourf() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom numpy import mafrom matplotlib import ticker, cm N = 1000x = np.linspace(-6.0, 6.0, N)y = np.linspace(-7.0, 7.0, N)X, Y = np.meshgrid(x, y) Z1 = np.exp(X * Y)z = 50 * Z1z[:5, :5] = -1z = ma.masked_where(z <= 0, z) cs = plt.contourf(X, Y, z, locator = ticker.LogLocator(), cmap ="bone") cbar = plt.colorbar(cs) plt.title('matplotlib.pyplot.contourf() Example')plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # invent some numbers, turning # the x and y arrays into simple# 2d arrays, which make combining # them together easier.x = np.linspace(-3, 15, 50).reshape(1, -1)y = np.linspace(-3, 15, 20).reshape(-1, 1)z = np.cos(x)*2 - np.sin(y)*2 # we no longer need x and y to# be 2 dimensional, so flatten them.x, y = x.flatten(), y.flatten() cs = plt.contourf(x, y, z, hatches =['-', '/', '\\', '//'], cmap ='Greens', extend ='both', alpha = 1) plt.colorbar(cs) plt.title('matplotlib.pyplot.contourf() Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 383, "s": 223, "text": "The contourf() function in pyplot module of matplotlib library is used to plot contours. But contourf draw filled contours, while contourf draws contour lines." }, { "code": null, "e": 449, "s": 383, "text": "Syntax: matplotlib.pyplot.contourf(\\*args, data=None, \\*\\*kwargs)" }, { "code": null, "e": 531, "s": 449, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 593, "s": 531, "text": "X, Y: These parameter are the coordinates of the values in Z." }, { "code": null, "e": 666, "s": 593, "text": "Z : This parameter is the height values over which the contour is drawn." }, { "code": null, "e": 769, "s": 666, "text": "levels : This parameter is used to determine the numbers and positions of the contour lines / regions." }, { "code": null, "e": 806, "s": 769, "text": "Returns: This returns the following:" }, { "code": null, "e": 842, "s": 806, "text": "c :This returns the QuadContourSet." }, { "code": null, "e": 932, "s": 842, "text": "Below examples illustrate the matplotlib.pyplot.contourf() function in matplotlib.pyplot:" }, { "code": null, "e": 944, "s": 932, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom numpy import mafrom matplotlib import ticker, cm N = 1000x = np.linspace(-6.0, 6.0, N)y = np.linspace(-7.0, 7.0, N)X, Y = np.meshgrid(x, y) Z1 = np.exp(X * Y)z = 50 * Z1z[:5, :5] = -1z = ma.masked_where(z <= 0, z) cs = plt.contourf(X, Y, z, locator = ticker.LogLocator(), cmap =\"bone\") cbar = plt.colorbar(cs) plt.title('matplotlib.pyplot.contourf() Example')plt.show()", "e": 1449, "s": 944, "text": null }, { "code": null, "e": 1457, "s": 1449, "text": "Output:" }, { "code": null, "e": 1469, "s": 1457, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np # invent some numbers, turning # the x and y arrays into simple# 2d arrays, which make combining # them together easier.x = np.linspace(-3, 15, 50).reshape(1, -1)y = np.linspace(-3, 15, 20).reshape(-1, 1)z = np.cos(x)*2 - np.sin(y)*2 # we no longer need x and y to# be 2 dimensional, so flatten them.x, y = x.flatten(), y.flatten() cs = plt.contourf(x, y, z, hatches =['-', '/', '\\\\', '//'], cmap ='Greens', extend ='both', alpha = 1) plt.colorbar(cs) plt.title('matplotlib.pyplot.contourf() Example')plt.show()", "e": 2173, "s": 1469, "text": null }, { "code": null, "e": 2181, "s": 2173, "text": "Output:" }, { "code": null, "e": 2199, "s": 2181, "text": "Python-matplotlib" }, { "code": null, "e": 2206, "s": 2199, "text": "Python" }, { "code": null, "e": 2304, "s": 2206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2336, "s": 2304, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2363, "s": 2336, "text": "Python Classes and Objects" }, { "code": null, "e": 2384, "s": 2363, "text": "Python OOPs Concepts" }, { "code": null, "e": 2407, "s": 2384, "text": "Introduction To PYTHON" }, { "code": null, "e": 2463, "s": 2407, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2494, "s": 2463, "text": "Python | os.path.join() method" }, { "code": null, "e": 2536, "s": 2494, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2578, "s": 2536, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2617, "s": 2578, "text": "Python | Get unique values from a list" } ]
How to change background color of table rows or individual cells in Bootstrap ?
20 Aug, 2021 In this article, we will discuss setting the background color of the table rows & how to set the background color for an individual cell using Bootstrap. Bootstrap provides a series of classes that can be used to apply various styling to the tables such as changing the heading appearance, making the rows stripped, adding or removing borders, making rows hoverable, etc. Bootstrap also provides classes for making tables responsive. The purpose of creating the table is to display the complex & large-size data in a simple compact structured format that provides informative content while looking at a glance. This will save time to read & analyze unstructured large data. Bootstrap helps to create & decorate the content in a standard manner. We will use bootstrap build-in classes for creating the table structure. A simple HTML table can be created using below syntax: Syntax: <table class="table"> Table Contents... <table> Before we proceed to our main discussion, the knowledge of creating tables using HTML will help you to understand the article in a better way. Please refer to Bootstrap 4 | Tables for many other cases of tables in bootstrap. Bootstrap CDN Link: Let’s take an example to understand how to set up & add a Bootstrap CDN link to apply the bootstrap pre-defined classes for creating the table. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script> Example: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Geeks For Geeks</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"/> </head> <body> <h1>Tables</h1> <h3>Change color of tables</h3> <table class="table table-bordered table-hover table-sm"> <thread> <tr> <th scope="col">Sl No.</th> <th scope="col">Country</th> <th scope="col">Capital</th> </tr> </thread> <tbody> <tr> <th scope="row">1</th> <td>India</td> <td>New Delhi</td> </tr> <tr> <th scope="row">2</th> <td>Canada</td> <td>Ottawa</td> </tr> <tr> <th scope="row">3</th> <td>Bangladesh</td> <td>Dhaka</td> </tr> <tr> <th scope="row">4</th> <td>Australia</td> <td>Canberra</td> </tr> </tbody> </table> </body></html> Output: We have added the bootstrap CDN link in our code that makes a standard & nicely structured content table. Using pre-defined classes, we can change the color of table cells and table rows. In order to change the color of the table row, we need to specify in <tr> tag with the required class & for changing the color of the table row then specify it inside <td> tag with the required class. Let us learn classes one by one. Predefined Classes: For changing the color of a row or whole table, we will use any one of the following classes. table-active: This class applies to the hover color of the table row or cell with grey color.table-default: This class is applied to change the color to white when the default row is selected.table-primary: This class indicates the important action.table-secondary: This class indicates the less important activities.table-success: This class indicates the positive or successful action.table-danger: This class indicates a potentially negative or dangerous action.table-warning: This class indicates a warning that might need attention.table-info: This class indicates a neutral informative change or action.table-light: This class is applied for table row background or light grey table.table-dark: This class is applied for a dark grey table. table-active: This class applies to the hover color of the table row or cell with grey color. table-default: This class is applied to change the color to white when the default row is selected. table-primary: This class indicates the important action. table-secondary: This class indicates the less important activities. table-success: This class indicates the positive or successful action. table-danger: This class indicates a potentially negative or dangerous action. table-warning: This class indicates a warning that might need attention. table-info: This class indicates a neutral informative change or action. table-light: This class is applied for table row background or light grey table. table-dark: This class is applied for a dark grey table. Example: In this case, we have used all the pre-defined classes to change the color of the rows. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Geeks For Geeks</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"/> </head> <body> <h1>Tables</h1> <h3>Different colour of table rows</h3> <table class="table"> <thread> <th scope="col">Sl No.</th> <th scope="col">Class</th> </thread> <tbody> <tr class="table-active"> <th scope="row">1</th> <td>table-active</td> </tr> <tr class="table-default"> <th scope="row">2</th> <td>table-default</td> </tr> <tr class="table-primary"> <th scope="row">3</th> <td>table-primary</td> </tr> <tr class="table-secondary"> <th scope="row">4</th> <td>table-secondary</td> </tr> <tr class="table-success"> <th scope="row">5</th> <td>table-success</td> </tr> <tr class="table-danger"> <th scope="row">6</th> <td>table-danger</td> </tr> <tr class="table-warning"> <th scope="row">7</th> <td>table-warning</td> </tr> <tr class="table-info"> <th scope="row">8</th> <td>table-info</td> </tr> <tr class="table-light"> <th scope="row">9</th> <td>table-light</td> </tr> <tr class="table-dark"> <th scope="row">10</th> <td>table-dark</td> </tr> </tbody> </table> </body></html> Output: For changing the color of any particular cell, you can use any one of the following classes: bg-primary: Applies to indicate positive or successful action.bg-success: Applies to indicate a successful or positive action.bg-warning: Applies to indicate a warning that might need attentionbg-danger: Applies to indicate a potentially negative or dangerous actionbg-info: Applies to indicate a neutral informative change or action. bg-primary: Applies to indicate positive or successful action. bg-success: Applies to indicate a successful or positive action. bg-warning: Applies to indicate a warning that might need attention bg-danger: Applies to indicate a potentially negative or dangerous action bg-info: Applies to indicate a neutral informative change or action. Example: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Geeks For Geeks</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"/> </head> <body> <h1>Tables</h1> <h3>Change color of single cells</h3> <table class="table"> <thread> <th scope="col">Sl No.</th> <th scope="col">Class</th> </thread> <tbody> <tr> <th scope="row">1</th> <td class="bg-primary">bg-primary</td> </tr> <tr> <th scope="row">2</th> <td class="bg-success">bg-success</td> </tr> <tr> <th scope="row">3</th> <td class="bg-warning">bg-warning</td> </tr> <tr> <th scope="row">4</th> <td class="bg-danger">bg-danger</td> </tr> <tr> <th scope="row">5</th> <td class="bg-info">bg-info</td> </tr> </tbody> </table> </body></html> Output: In order to change the color for the particular table cell, we need to specify it inside the <td> tag for the particular cell. The below example illustrates to declare for a particular cell. Example: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Geeks For Geeks</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous" /> </head> <body> <h1>Tables</h1> <h3>Change color of tables</h3> <table class="table table-bordered table-hover table-sm"> <thread> <tr> <th scope="col">Sl No.</th> <th scope="col">Country</th> <th scope="col">Capital</th> </tr> </thread> <tbody> <tr class="bg-primary"> <th scope="row">1</th> <td>India</td> <td>New Delhi</td> </tr> <tr> <th scope="row">2</th> <td class="bg-success">Canada</td> <td>Ottawa</td> </tr> <tr> <th scope="row">3</th> <td>Bangladesh</td> <td>Dhaka</td> </tr> <tr> <th scope="row">4</th> <td>Australia</td> <td>Canberra</td> </tr> </tbody> </table> </body></html> Output: Custom color Bootstrap-4 Bootstrap-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Aug, 2021" }, { "code": null, "e": 462, "s": 28, "text": "In this article, we will discuss setting the background color of the table rows & how to set the background color for an individual cell using Bootstrap. Bootstrap provides a series of classes that can be used to apply various styling to the tables such as changing the heading appearance, making the rows stripped, adding or removing borders, making rows hoverable, etc. Bootstrap also provides classes for making tables responsive." }, { "code": null, "e": 901, "s": 462, "text": "The purpose of creating the table is to display the complex & large-size data in a simple compact structured format that provides informative content while looking at a glance. This will save time to read & analyze unstructured large data. Bootstrap helps to create & decorate the content in a standard manner. We will use bootstrap build-in classes for creating the table structure. A simple HTML table can be created using below syntax:" }, { "code": null, "e": 909, "s": 901, "text": "Syntax:" }, { "code": null, "e": 957, "s": 909, "text": "<table class=\"table\"> Table Contents... <table>" }, { "code": null, "e": 1182, "s": 957, "text": "Before we proceed to our main discussion, the knowledge of creating tables using HTML will help you to understand the article in a better way. Please refer to Bootstrap 4 | Tables for many other cases of tables in bootstrap." }, { "code": null, "e": 1346, "s": 1182, "text": "Bootstrap CDN Link: Let’s take an example to understand how to set up & add a Bootstrap CDN link to apply the bootstrap pre-defined classes for creating the table." }, { "code": null, "e": 1723, "s": 1346, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script>" }, { "code": null, "e": 1732, "s": 1723, "text": "Example:" }, { "code": null, "e": 1737, "s": 1732, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <title>Geeks For Geeks</title> <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"/> </head> <body> <h1>Tables</h1> <h3>Change color of tables</h3> <table class=\"table table-bordered table-hover table-sm\"> <thread> <tr> <th scope=\"col\">Sl No.</th> <th scope=\"col\">Country</th> <th scope=\"col\">Capital</th> </tr> </thread> <tbody> <tr> <th scope=\"row\">1</th> <td>India</td> <td>New Delhi</td> </tr> <tr> <th scope=\"row\">2</th> <td>Canada</td> <td>Ottawa</td> </tr> <tr> <th scope=\"row\">3</th> <td>Bangladesh</td> <td>Dhaka</td> </tr> <tr> <th scope=\"row\">4</th> <td>Australia</td> <td>Canberra</td> </tr> </tbody> </table> </body></html>", "e": 2978, "s": 1737, "text": null }, { "code": null, "e": 2986, "s": 2978, "text": "Output:" }, { "code": null, "e": 3408, "s": 2986, "text": "We have added the bootstrap CDN link in our code that makes a standard & nicely structured content table. Using pre-defined classes, we can change the color of table cells and table rows. In order to change the color of the table row, we need to specify in <tr> tag with the required class & for changing the color of the table row then specify it inside <td> tag with the required class. Let us learn classes one by one." }, { "code": null, "e": 3522, "s": 3408, "text": "Predefined Classes: For changing the color of a row or whole table, we will use any one of the following classes." }, { "code": null, "e": 4268, "s": 3522, "text": "table-active: This class applies to the hover color of the table row or cell with grey color.table-default: This class is applied to change the color to white when the default row is selected.table-primary: This class indicates the important action.table-secondary: This class indicates the less important activities.table-success: This class indicates the positive or successful action.table-danger: This class indicates a potentially negative or dangerous action.table-warning: This class indicates a warning that might need attention.table-info: This class indicates a neutral informative change or action.table-light: This class is applied for table row background or light grey table.table-dark: This class is applied for a dark grey table." }, { "code": null, "e": 4362, "s": 4268, "text": "table-active: This class applies to the hover color of the table row or cell with grey color." }, { "code": null, "e": 4462, "s": 4362, "text": "table-default: This class is applied to change the color to white when the default row is selected." }, { "code": null, "e": 4520, "s": 4462, "text": "table-primary: This class indicates the important action." }, { "code": null, "e": 4589, "s": 4520, "text": "table-secondary: This class indicates the less important activities." }, { "code": null, "e": 4660, "s": 4589, "text": "table-success: This class indicates the positive or successful action." }, { "code": null, "e": 4739, "s": 4660, "text": "table-danger: This class indicates a potentially negative or dangerous action." }, { "code": null, "e": 4812, "s": 4739, "text": "table-warning: This class indicates a warning that might need attention." }, { "code": null, "e": 4885, "s": 4812, "text": "table-info: This class indicates a neutral informative change or action." }, { "code": null, "e": 4966, "s": 4885, "text": "table-light: This class is applied for table row background or light grey table." }, { "code": null, "e": 5023, "s": 4966, "text": "table-dark: This class is applied for a dark grey table." }, { "code": null, "e": 5120, "s": 5023, "text": "Example: In this case, we have used all the pre-defined classes to change the color of the rows." }, { "code": null, "e": 5125, "s": 5120, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <title>Geeks For Geeks</title> <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"/> </head> <body> <h1>Tables</h1> <h3>Different colour of table rows</h3> <table class=\"table\"> <thread> <th scope=\"col\">Sl No.</th> <th scope=\"col\">Class</th> </thread> <tbody> <tr class=\"table-active\"> <th scope=\"row\">1</th> <td>table-active</td> </tr> <tr class=\"table-default\"> <th scope=\"row\">2</th> <td>table-default</td> </tr> <tr class=\"table-primary\"> <th scope=\"row\">3</th> <td>table-primary</td> </tr> <tr class=\"table-secondary\"> <th scope=\"row\">4</th> <td>table-secondary</td> </tr> <tr class=\"table-success\"> <th scope=\"row\">5</th> <td>table-success</td> </tr> <tr class=\"table-danger\"> <th scope=\"row\">6</th> <td>table-danger</td> </tr> <tr class=\"table-warning\"> <th scope=\"row\">7</th> <td>table-warning</td> </tr> <tr class=\"table-info\"> <th scope=\"row\">8</th> <td>table-info</td> </tr> <tr class=\"table-light\"> <th scope=\"row\">9</th> <td>table-light</td> </tr> <tr class=\"table-dark\"> <th scope=\"row\">10</th> <td>table-dark</td> </tr> </tbody> </table> </body></html>", "e": 6928, "s": 5125, "text": null }, { "code": null, "e": 6936, "s": 6928, "text": "Output:" }, { "code": null, "e": 7029, "s": 6936, "text": "For changing the color of any particular cell, you can use any one of the following classes:" }, { "code": null, "e": 7364, "s": 7029, "text": "bg-primary: Applies to indicate positive or successful action.bg-success: Applies to indicate a successful or positive action.bg-warning: Applies to indicate a warning that might need attentionbg-danger: Applies to indicate a potentially negative or dangerous actionbg-info: Applies to indicate a neutral informative change or action." }, { "code": null, "e": 7427, "s": 7364, "text": "bg-primary: Applies to indicate positive or successful action." }, { "code": null, "e": 7492, "s": 7427, "text": "bg-success: Applies to indicate a successful or positive action." }, { "code": null, "e": 7560, "s": 7492, "text": "bg-warning: Applies to indicate a warning that might need attention" }, { "code": null, "e": 7634, "s": 7560, "text": "bg-danger: Applies to indicate a potentially negative or dangerous action" }, { "code": null, "e": 7703, "s": 7634, "text": "bg-info: Applies to indicate a neutral informative change or action." }, { "code": null, "e": 7712, "s": 7703, "text": "Example:" }, { "code": null, "e": 7717, "s": 7712, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <title>Geeks For Geeks</title> <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"/> </head> <body> <h1>Tables</h1> <h3>Change color of single cells</h3> <table class=\"table\"> <thread> <th scope=\"col\">Sl No.</th> <th scope=\"col\">Class</th> </thread> <tbody> <tr> <th scope=\"row\">1</th> <td class=\"bg-primary\">bg-primary</td> </tr> <tr> <th scope=\"row\">2</th> <td class=\"bg-success\">bg-success</td> </tr> <tr> <th scope=\"row\">3</th> <td class=\"bg-warning\">bg-warning</td> </tr> <tr> <th scope=\"row\">4</th> <td class=\"bg-danger\">bg-danger</td> </tr> <tr> <th scope=\"row\">5</th> <td class=\"bg-info\">bg-info</td> </tr> </tbody> </table> </body></html>", "e": 8938, "s": 7717, "text": null }, { "code": null, "e": 8946, "s": 8938, "text": "Output:" }, { "code": null, "e": 9137, "s": 8946, "text": "In order to change the color for the particular table cell, we need to specify it inside the <td> tag for the particular cell. The below example illustrates to declare for a particular cell." }, { "code": null, "e": 9146, "s": 9137, "text": "Example:" }, { "code": null, "e": 9151, "s": 9146, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <title>Geeks For Geeks</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\" /> </head> <body> <h1>Tables</h1> <h3>Change color of tables</h3> <table class=\"table table-bordered table-hover table-sm\"> <thread> <tr> <th scope=\"col\">Sl No.</th> <th scope=\"col\">Country</th> <th scope=\"col\">Capital</th> </tr> </thread> <tbody> <tr class=\"bg-primary\"> <th scope=\"row\">1</th> <td>India</td> <td>New Delhi</td> </tr> <tr> <th scope=\"row\">2</th> <td class=\"bg-success\">Canada</td> <td>Ottawa</td> </tr> <tr> <th scope=\"row\">3</th> <td>Bangladesh</td> <td>Dhaka</td> </tr> <tr> <th scope=\"row\">4</th> <td>Australia</td> <td>Canberra</td> </tr> </tbody> </table> </body></html>", "e": 10372, "s": 9151, "text": null }, { "code": null, "e": 10380, "s": 10372, "text": "Output:" }, { "code": null, "e": 10393, "s": 10380, "text": "Custom color" }, { "code": null, "e": 10405, "s": 10393, "text": "Bootstrap-4" }, { "code": null, "e": 10425, "s": 10405, "text": "Bootstrap-Questions" }, { "code": null, "e": 10432, "s": 10425, "text": "Picked" }, { "code": null, "e": 10442, "s": 10432, "text": "Bootstrap" }, { "code": null, "e": 10447, "s": 10442, "text": "HTML" }, { "code": null, "e": 10464, "s": 10447, "text": "Web Technologies" }, { "code": null, "e": 10469, "s": 10464, "text": "HTML" }, { "code": null, "e": 10567, "s": 10469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10608, "s": 10567, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 10641, "s": 10608, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 10686, "s": 10641, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 10712, "s": 10686, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 10779, "s": 10712, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 10827, "s": 10779, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 10889, "s": 10827, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 10939, "s": 10889, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 10963, "s": 10939, "text": "REST API (Introduction)" } ]
C# | HashSet Class
20 Dec, 2018 A HashSet<T> is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. Characteristics of HashSet Class: The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order. The capacity of a HashSet<T> object is the number of elements that the object can hold. A HashSet<T> object’s capacity automatically increases as elements are added to the object. A HashSet<T> collection is not sorted and cannot contain duplicate elements. HashSet<T> provides many mathematical set operations, such as set addition (unions) and set subtraction. Example: // C# code to create a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of odd numbers HashSet<int> odd = new HashSet<int>(); // Inserting elements in HashSet for (int i = 0; i < 5; i++) { odd.Add(2 * i + 1); } // Displaying the elements in the HashSet foreach(int i in odd) { Console.WriteLine(i); } }} Output: 1 3 5 7 9 Example: // C# code to get the number of// elements that are contained in HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting elements in HashSet for (int i = 0; i < 5; i++) { mySet.Add(i * 2); } // To get the number of // elements that are contained in HashSet Console.WriteLine(mySet.Count); }} Output: 5 Example: // C# code to Check if a HashSet is// a subset of the specified collectionusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Inserting elements in HashSet // mySet1 only contains even numbers less than // equal to 10 for (int i = 1; i <= 5; i++) mySet1.Add(2 * i); // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting elements in HashSet // mySet2 contains all numbers from 1 to 10 for (int i = 1; i <= 10; i++) mySet2.Add(i); // Check if a HashSet mySet1 is a subset // of the HashSet mySet2 Console.WriteLine(mySet1.IsSubsetOf(mySet2)); }} Output: True Example: // C# code to check if a HashSet// contains the specified elementusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet = new HashSet<string>(); // Inserting elements in HashSet mySet.Add("DS"); mySet.Add("C++"); mySet.Add("Java"); mySet.Add("JavaScript"); // Check if a HashSet contains // the specified element if (mySet.Contains("Java")) Console.WriteLine("Required Element is present"); else Console.WriteLine("Required Element is not present"); }} Output: Required Element is present Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=netframework-4.7.2 CSharp-Generic-HashSet CSharp-Generic-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Dec, 2018" }, { "code": null, "e": 348, "s": 54, "text": "A HashSet<T> is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list." }, { "code": null, "e": 382, "s": 348, "text": "Characteristics of HashSet Class:" }, { "code": null, "e": 551, "s": 382, "text": "The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order." }, { "code": null, "e": 639, "s": 551, "text": "The capacity of a HashSet<T> object is the number of elements that the object can hold." }, { "code": null, "e": 731, "s": 639, "text": "A HashSet<T> object’s capacity automatically increases as elements are added to the object." }, { "code": null, "e": 808, "s": 731, "text": "A HashSet<T> collection is not sorted and cannot contain duplicate elements." }, { "code": null, "e": 913, "s": 808, "text": "HashSet<T> provides many mathematical set operations, such as set addition (unions) and set subtraction." }, { "code": null, "e": 922, "s": 913, "text": "Example:" }, { "code": "// C# code to create a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of odd numbers HashSet<int> odd = new HashSet<int>(); // Inserting elements in HashSet for (int i = 0; i < 5; i++) { odd.Add(2 * i + 1); } // Displaying the elements in the HashSet foreach(int i in odd) { Console.WriteLine(i); } }}", "e": 1414, "s": 922, "text": null }, { "code": null, "e": 1422, "s": 1414, "text": "Output:" }, { "code": null, "e": 1433, "s": 1422, "text": "1\n3\n5\n7\n9\n" }, { "code": null, "e": 1442, "s": 1433, "text": "Example:" }, { "code": "// C# code to get the number of// elements that are contained in HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting elements in HashSet for (int i = 0; i < 5; i++) { mySet.Add(i * 2); } // To get the number of // elements that are contained in HashSet Console.WriteLine(mySet.Count); }}", "e": 1963, "s": 1442, "text": null }, { "code": null, "e": 1971, "s": 1963, "text": "Output:" }, { "code": null, "e": 1974, "s": 1971, "text": "5\n" }, { "code": null, "e": 1983, "s": 1974, "text": "Example:" }, { "code": "// C# code to Check if a HashSet is// a subset of the specified collectionusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Inserting elements in HashSet // mySet1 only contains even numbers less than // equal to 10 for (int i = 1; i <= 5; i++) mySet1.Add(2 * i); // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting elements in HashSet // mySet2 contains all numbers from 1 to 10 for (int i = 1; i <= 10; i++) mySet2.Add(i); // Check if a HashSet mySet1 is a subset // of the HashSet mySet2 Console.WriteLine(mySet1.IsSubsetOf(mySet2)); }}", "e": 2836, "s": 1983, "text": null }, { "code": null, "e": 2844, "s": 2836, "text": "Output:" }, { "code": null, "e": 2850, "s": 2844, "text": "True\n" }, { "code": null, "e": 2859, "s": 2850, "text": "Example:" }, { "code": "// C# code to check if a HashSet// contains the specified elementusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet = new HashSet<string>(); // Inserting elements in HashSet mySet.Add(\"DS\"); mySet.Add(\"C++\"); mySet.Add(\"Java\"); mySet.Add(\"JavaScript\"); // Check if a HashSet contains // the specified element if (mySet.Contains(\"Java\")) Console.WriteLine(\"Required Element is present\"); else Console.WriteLine(\"Required Element is not present\"); }}", "e": 3534, "s": 2859, "text": null }, { "code": null, "e": 3542, "s": 3534, "text": "Output:" }, { "code": null, "e": 3571, "s": 3542, "text": "Required Element is present\n" }, { "code": null, "e": 3582, "s": 3571, "text": "Reference:" }, { "code": null, "e": 3687, "s": 3582, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=netframework-4.7.2" }, { "code": null, "e": 3710, "s": 3687, "text": "CSharp-Generic-HashSet" }, { "code": null, "e": 3735, "s": 3710, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 3738, "s": 3735, "text": "C#" } ]
Program to find minimum number of bricks required to make k towers of same height in Python
Suppose we have a list of tower heights, and a positive value k. We want to select k towers and make them all the same height by adding more bricks, but using as few bricks as possible. We have to find the minimum number of bricks are needed to pick k towers and make them the same height. So, if the input is like heights = [4, 7, 31, 14, 40] k = 3, then the output will be 17, as we can select 5, 8, and 15 which requires 17 bricks to make the same height. To solve this, we will follow these steps − sort the list heights ans := infinity s := 0 for each index i and value x in heights, dos := s + xif i >= k, thens := s - heights[i - k]if i >= k - 1, thenans := minimum of ans and (x * k - s) s := s + x if i >= k, thens := s - heights[i - k] s := s - heights[i - k] if i >= k - 1, thenans := minimum of ans and (x * k - s) ans := minimum of ans and (x * k - s) return ans Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, heights, k): heights.sort() ans = float("inf") s = 0 for i, x in enumerate(heights): s += x if i >= k: s -= heights[i - k] if i >= k - 1: ans = min(ans, x * k - s) return ans ob = Solution() heights = [5, 8, 32, 15, 41] k = 3 print(ob.solve(heights, k)) [5, 8, 32, 15, 41], 3 17
[ { "code": null, "e": 1477, "s": 1187, "text": "Suppose we have a list of tower heights, and a positive value k. We want to select k towers and make them all the same height by adding more bricks, but using as few bricks as possible. We have to find the minimum number of bricks are needed to pick k towers and make them the same height." }, { "code": null, "e": 1646, "s": 1477, "text": "So, if the input is like heights = [4, 7, 31, 14, 40] k = 3, then the output will be 17, as we can select 5, 8, and 15 which requires 17 bricks to make the same height." }, { "code": null, "e": 1690, "s": 1646, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1712, "s": 1690, "text": "sort the list heights" }, { "code": null, "e": 1728, "s": 1712, "text": "ans := infinity" }, { "code": null, "e": 1735, "s": 1728, "text": "s := 0" }, { "code": null, "e": 1883, "s": 1735, "text": "for each index i and value x in heights, dos := s + xif i >= k, thens := s - heights[i - k]if i >= k - 1, thenans := minimum of ans and (x * k - s)" }, { "code": null, "e": 1894, "s": 1883, "text": "s := s + x" }, { "code": null, "e": 1933, "s": 1894, "text": "if i >= k, thens := s - heights[i - k]" }, { "code": null, "e": 1957, "s": 1933, "text": "s := s - heights[i - k]" }, { "code": null, "e": 2014, "s": 1957, "text": "if i >= k - 1, thenans := minimum of ans and (x * k - s)" }, { "code": null, "e": 2052, "s": 2014, "text": "ans := minimum of ans and (x * k - s)" }, { "code": null, "e": 2063, "s": 2052, "text": "return ans" }, { "code": null, "e": 2133, "s": 2063, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2144, "s": 2133, "text": " Live Demo" }, { "code": null, "e": 2508, "s": 2144, "text": "class Solution:\n def solve(self, heights, k): heights.sort()\n ans = float(\"inf\")\n s = 0\n for i, x in enumerate(heights):\n s += x\n if i >= k:\n s -= heights[i - k]\n if i >= k - 1:\n ans = min(ans, x * k - s)\n return ans\nob = Solution()\nheights = [5, 8, 32, 15, 41]\nk = 3\nprint(ob.solve(heights, k))" }, { "code": null, "e": 2530, "s": 2508, "text": "[5, 8, 32, 15, 41], 3" }, { "code": null, "e": 2533, "s": 2530, "text": "17" } ]
How to execute TypeScript file using command line?
05 Feb, 2020 TypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows JavaScript syntactically but adds more features to it. It is a superset of JavaScript. In order to execute or run any typescript file, first you need to install node and using it install typescript globally in your local system. To check node is installed, run command if not you have to installed it first:node -v node -v Now to install typescript, use:npm install -g typescript npm install -g typescript After installing typescript, create a .ts file, for example, greet.ts as given below: Example:var greet: string = "Greetings"; var geeks: string = "GeeksforGeeks"; console.log(greet + " from " + geeks); // save the file as hello.ts var greet: string = "Greetings"; var geeks: string = "GeeksforGeeks"; console.log(greet + " from " + geeks); // save the file as hello.ts Output:Greetings from GeeksforGeeks Greetings from GeeksforGeeks Procedure 1: This typescript file greet.ts will create a javascript file at runtime with the same name. To run any typescript file there are a few ways:Syntax: Step 1: First, run the typescript file with the following command. This will create a javascript file from typescript automatically with the same name.tsc helloWorld.ts tsc helloWorld.ts Step 2:Now run the javascript file, the greet.ts file will get executed:node helloWorld.js node helloWorld.js Procedure 2: You can merge both the commands by using a pole | and && like below :Syntax: In Windows:tsc greet.ts | node greet.js tsc greet.ts | node greet.js In Linux or MacOS:tsc helloWorld.ts && node helloWorld.js tsc helloWorld.ts && node helloWorld.js Procedure 3: You can also install ts-node along with typescript using the following command: Syntax: To install:npm install -g ts-node npm install -g ts-node To run:ts-node helloWorld.ts ts-node helloWorld.ts Output: Using any of the three ways, the output will remain the same. Greetings from GeeksforGeeks Picked TypeScript JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Feb, 2020" }, { "code": null, "e": 372, "s": 28, "text": "TypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows JavaScript syntactically but adds more features to it. It is a superset of JavaScript. In order to execute or run any typescript file, first you need to install node and using it install typescript globally in your local system." }, { "code": null, "e": 458, "s": 372, "text": "To check node is installed, run command if not you have to installed it first:node -v" }, { "code": null, "e": 466, "s": 458, "text": "node -v" }, { "code": null, "e": 523, "s": 466, "text": "Now to install typescript, use:npm install -g typescript" }, { "code": null, "e": 549, "s": 523, "text": "npm install -g typescript" }, { "code": null, "e": 635, "s": 549, "text": "After installing typescript, create a .ts file, for example, greet.ts as given below:" }, { "code": null, "e": 782, "s": 635, "text": "Example:var greet: string = \"Greetings\"; var geeks: string = \"GeeksforGeeks\"; console.log(greet + \" from \" + geeks); // save the file as hello.ts " }, { "code": "var greet: string = \"Greetings\"; var geeks: string = \"GeeksforGeeks\"; console.log(greet + \" from \" + geeks); // save the file as hello.ts ", "e": 921, "s": 782, "text": null }, { "code": null, "e": 957, "s": 921, "text": "Output:Greetings from GeeksforGeeks" }, { "code": null, "e": 986, "s": 957, "text": "Greetings from GeeksforGeeks" }, { "code": null, "e": 1146, "s": 986, "text": "Procedure 1: This typescript file greet.ts will create a javascript file at runtime with the same name. To run any typescript file there are a few ways:Syntax:" }, { "code": null, "e": 1315, "s": 1146, "text": "Step 1: First, run the typescript file with the following command. This will create a javascript file from typescript automatically with the same name.tsc helloWorld.ts" }, { "code": null, "e": 1333, "s": 1315, "text": "tsc helloWorld.ts" }, { "code": null, "e": 1424, "s": 1333, "text": "Step 2:Now run the javascript file, the greet.ts file will get executed:node helloWorld.js" }, { "code": null, "e": 1443, "s": 1424, "text": "node helloWorld.js" }, { "code": null, "e": 1533, "s": 1443, "text": "Procedure 2: You can merge both the commands by using a pole | and && like below :Syntax:" }, { "code": null, "e": 1573, "s": 1533, "text": "In Windows:tsc greet.ts | node greet.js" }, { "code": null, "e": 1602, "s": 1573, "text": "tsc greet.ts | node greet.js" }, { "code": null, "e": 1660, "s": 1602, "text": "In Linux or MacOS:tsc helloWorld.ts && node helloWorld.js" }, { "code": null, "e": 1700, "s": 1660, "text": "tsc helloWorld.ts && node helloWorld.js" }, { "code": null, "e": 1793, "s": 1700, "text": "Procedure 3: You can also install ts-node along with typescript using the following command:" }, { "code": null, "e": 1801, "s": 1793, "text": "Syntax:" }, { "code": null, "e": 1835, "s": 1801, "text": "To install:npm install -g ts-node" }, { "code": null, "e": 1858, "s": 1835, "text": "npm install -g ts-node" }, { "code": null, "e": 1887, "s": 1858, "text": "To run:ts-node helloWorld.ts" }, { "code": null, "e": 1909, "s": 1887, "text": "ts-node helloWorld.ts" }, { "code": null, "e": 1979, "s": 1909, "text": "Output: Using any of the three ways, the output will remain the same." }, { "code": null, "e": 2008, "s": 1979, "text": "Greetings from GeeksforGeeks" }, { "code": null, "e": 2015, "s": 2008, "text": "Picked" }, { "code": null, "e": 2026, "s": 2015, "text": "TypeScript" }, { "code": null, "e": 2037, "s": 2026, "text": "JavaScript" }, { "code": null, "e": 2054, "s": 2037, "text": "Web Technologies" }, { "code": null, "e": 2081, "s": 2054, "text": "Web technologies Questions" }, { "code": null, "e": 2179, "s": 2081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2240, "s": 2179, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2312, "s": 2240, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2352, "s": 2312, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2393, "s": 2352, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2445, "s": 2393, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2507, "s": 2445, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2568, "s": 2507, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2618, "s": 2568, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2661, "s": 2618, "text": "How to fetch data from an API in ReactJS ?" } ]
8 Examples to Query a NoSQL Database | by Soner Yıldırım | Towards Data Science
NoSQL refers to non-SQL or non-relational database design. It provides an organized way of storing data but not in tabular form (i.e. labelled rows and columns). The common structures adapted by NoSQL databases to store data are key-value pairs, wide column, graph, or document. There are several NoSQL databases used in the data science ecosystem. In this article, we will be using one of the popular ones which is MongoDB. MongoDB stores data as documents. A document in MongoDB consists of field-value pairs. Documents are organized in a structure called collection. To make an analogy, document can be considered as a row in a table and collection can be considered as an entire table. If you are new to NoSQL or MongoDB, here is an introductory article that will warm you up: towardsdatascience.com We will go over 10 examples to demonstrate how data can be retrieved from a MongoDB database. We have a collection called “customer”. The documents in the customer collection contains customer name, age, gender, and the amount of the last purchase. Here is a document in the customer collection: { "_id" : ObjectId("600c1806289947de938c68ea"), "name" : "John", "age" : 32, "gender" : "male", "amount" : 32} The document is displayed in JSON format. Query documents that belong to a specific customer. We use the find method to query documents from a MongoDB database. If used without any arguments or collections, find method retrieves all documents. We want to see the document belongs to customer John so the name field needs to be specified in the find method. > db.customer.find( {name: "John"} ){ "_id" : ObjectId("600c1806289947de938c68ea"), "name" : "John", "age" : 32, "gender" : "male", "amount" : 32 } We can attach pretty method to make the document seem more appealing. > db.customer.find( {name: "John"} ).pretty(){ "_id" : ObjectId("600c1806289947de938c68ea"), "name" : "John", "age" : 32, "gender" : "male", "amount" : 32} It is easier to read now. Query documents that belong to customers older than 40. The condition is applied to age field using a logical operator. The “$gt” stands for “greater than” and is used as follows. > db.customer.find( {age: {$gt:40}} ).pretty(){ "_id" : ObjectId("600c19d2289947de938c68ee"), "name" : "Jenny", "age" : 42, "gender" : "female", "amount" : 36} Query documents that belong to female customers who are younger than 25. This example is like a combination of the previous two examples. Both conditions must be met so we use “and” logic to combine the conditions. It can be done by writing both conditions separated by comma. > db.customer.find( {gender: "female", age: {$lt:25}} ).pretty(){ "_id" : ObjectId("600c19d2289947de938c68f0"), "name" : "Samantha", "age" : 21, "gender" : "female", "amount" : 41}{ "_id" : ObjectId("600c19d2289947de938c68f1"), "name" : "Laura", "age" : 24, "gender" : "female", "amount" : 51} The “$lt” stands for “less than”. In this example, we will repeat the previous example in a different way. Multiple conditions can also be combined with “and” logic as below. > db.customer.find( {$and :[ {gender: "female", age: {$lt:25}} ]} ).pretty() The logic used for combining the conditions is indicated at the beginning. The remaining part is same as the previous example but we need to put the conditions in a list ( [ ] ). Query customers who are either male or younger than 25. This example requires a compound query with “or” logic. We just need to change “$and” to “$or”. > db.customer.find( { $or: [ {gender: "male"}, {age: {$lt: 22}} ] }){ "_id" : ObjectId("600c1806289947de938c68ea"), "name" : "John", "age" : 32, "gender" : "male", "amount" : 32 }{ "_id" : ObjectId("600c19d2289947de938c68ed"), "name" : "Martin", "age" : 28, "gender" : "male", "amount" : 49 }{ "_id" : ObjectId("600c19d2289947de938c68ef"), "name" : "Mike", "age" : 29, "gender" : "male", "amount" : 22 }{ "_id" : ObjectId("600c19d2289947de938c68f0"), "name" : "Samantha", "age" : 21, "gender" : "female", "amount" : 41 } MongoDB allows for aggregating values while retrieving from the database. For instance, we can calculate the total purchase amount for males and females. The aggregate method is used instead of the find method. > db.customer.aggregate([... { $group: {_id: "$gender", total: {$sum: "$amount"} } }... ]){ "_id" : "female", "total" : 198 }{ "_id" : "male", "total" : 103 } Let’s elaborate on the syntax. We first group the documents by the gender column by selecting “$gender” as id. The next part specifies both the aggregation function which is “$sum” in our case and the column to be aggregated. If you are familiar with Pandas, the syntax is quite similar to the groupby function. Let’s take the previous example one step further and add a condition. Thus, we first select documents that “match” a condition and apply aggregation. The following query is an aggregation pipeline which first selects the customers who are older than 25 and calculates the average purchase amount for males and females. > db.customer.aggregate([... { $match: { age: {$gt:25} } },... { $group: { _id: "$gender", avg: {$avg: "$amount"} } }... ]){ "_id" : "female", "avg" : 35.33 }{ "_id" : "male", "avg" : 34.33 } The query in the previous example contains only two groups so it is not necessary to sort the results. However, we might have queries that return several values. In such cases, sorting the results is a good practice. We can sort the results of the previous query by the average amount in ascending order. > db.customer.aggregate([... { $match: { age: {$gt:25} } },... { $group: { _id: "$gender", avg: {$avg: "$amount"} } },... { $sort: {avg: 1} }... ]){ "_id" : "male", "avg" : 34.33 }{ "_id" : "female", "avg" : 35.33 } We have just added “$sort” in the aggregation pipeline. The field used for sorting is specified along with the sorting behavior. 1 means in ascending order and -1 means in descending order. Both SQL and NoSQL are of crucial importance in data science ecosystem. The fuel of data science is data so everything starts with proper, well maintained and easily accessible data. Both SQL and NoSQL are critical players for these processes. We have covered a brief introduction to querying a MongoDB database. There is, of course, much more to cover. We are likely to write more advanced queries for a typical task. However, once you are comfortable with the basics, you can easily move onto more advanced queries. Stay tuned for more articles on both SQL and NoSQL databases. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 334, "s": 172, "text": "NoSQL refers to non-SQL or non-relational database design. It provides an organized way of storing data but not in tabular form (i.e. labelled rows and columns)." }, { "code": null, "e": 597, "s": 334, "text": "The common structures adapted by NoSQL databases to store data are key-value pairs, wide column, graph, or document. There are several NoSQL databases used in the data science ecosystem. In this article, we will be using one of the popular ones which is MongoDB." }, { "code": null, "e": 953, "s": 597, "text": "MongoDB stores data as documents. A document in MongoDB consists of field-value pairs. Documents are organized in a structure called collection. To make an analogy, document can be considered as a row in a table and collection can be considered as an entire table. If you are new to NoSQL or MongoDB, here is an introductory article that will warm you up:" }, { "code": null, "e": 976, "s": 953, "text": "towardsdatascience.com" }, { "code": null, "e": 1070, "s": 976, "text": "We will go over 10 examples to demonstrate how data can be retrieved from a MongoDB database." }, { "code": null, "e": 1225, "s": 1070, "text": "We have a collection called “customer”. The documents in the customer collection contains customer name, age, gender, and the amount of the last purchase." }, { "code": null, "e": 1272, "s": 1225, "text": "Here is a document in the customer collection:" }, { "code": null, "e": 1383, "s": 1272, "text": "{ \"_id\" : ObjectId(\"600c1806289947de938c68ea\"), \"name\" : \"John\", \"age\" : 32, \"gender\" : \"male\", \"amount\" : 32}" }, { "code": null, "e": 1425, "s": 1383, "text": "The document is displayed in JSON format." }, { "code": null, "e": 1477, "s": 1425, "text": "Query documents that belong to a specific customer." }, { "code": null, "e": 1627, "s": 1477, "text": "We use the find method to query documents from a MongoDB database. If used without any arguments or collections, find method retrieves all documents." }, { "code": null, "e": 1740, "s": 1627, "text": "We want to see the document belongs to customer John so the name field needs to be specified in the find method." }, { "code": null, "e": 1888, "s": 1740, "text": "> db.customer.find( {name: \"John\"} ){ \"_id\" : ObjectId(\"600c1806289947de938c68ea\"), \"name\" : \"John\", \"age\" : 32, \"gender\" : \"male\", \"amount\" : 32 }" }, { "code": null, "e": 1958, "s": 1888, "text": "We can attach pretty method to make the document seem more appealing." }, { "code": null, "e": 2114, "s": 1958, "text": "> db.customer.find( {name: \"John\"} ).pretty(){ \"_id\" : ObjectId(\"600c1806289947de938c68ea\"), \"name\" : \"John\", \"age\" : 32, \"gender\" : \"male\", \"amount\" : 32}" }, { "code": null, "e": 2140, "s": 2114, "text": "It is easier to read now." }, { "code": null, "e": 2196, "s": 2140, "text": "Query documents that belong to customers older than 40." }, { "code": null, "e": 2320, "s": 2196, "text": "The condition is applied to age field using a logical operator. The “$gt” stands for “greater than” and is used as follows." }, { "code": null, "e": 2480, "s": 2320, "text": "> db.customer.find( {age: {$gt:40}} ).pretty(){ \"_id\" : ObjectId(\"600c19d2289947de938c68ee\"), \"name\" : \"Jenny\", \"age\" : 42, \"gender\" : \"female\", \"amount\" : 36}" }, { "code": null, "e": 2553, "s": 2480, "text": "Query documents that belong to female customers who are younger than 25." }, { "code": null, "e": 2757, "s": 2553, "text": "This example is like a combination of the previous two examples. Both conditions must be met so we use “and” logic to combine the conditions. It can be done by writing both conditions separated by comma." }, { "code": null, "e": 3051, "s": 2757, "text": "> db.customer.find( {gender: \"female\", age: {$lt:25}} ).pretty(){ \"_id\" : ObjectId(\"600c19d2289947de938c68f0\"), \"name\" : \"Samantha\", \"age\" : 21, \"gender\" : \"female\", \"amount\" : 41}{ \"_id\" : ObjectId(\"600c19d2289947de938c68f1\"), \"name\" : \"Laura\", \"age\" : 24, \"gender\" : \"female\", \"amount\" : 51}" }, { "code": null, "e": 3085, "s": 3051, "text": "The “$lt” stands for “less than”." }, { "code": null, "e": 3226, "s": 3085, "text": "In this example, we will repeat the previous example in a different way. Multiple conditions can also be combined with “and” logic as below." }, { "code": null, "e": 3303, "s": 3226, "text": "> db.customer.find( {$and :[ {gender: \"female\", age: {$lt:25}} ]} ).pretty()" }, { "code": null, "e": 3482, "s": 3303, "text": "The logic used for combining the conditions is indicated at the beginning. The remaining part is same as the previous example but we need to put the conditions in a list ( [ ] )." }, { "code": null, "e": 3538, "s": 3482, "text": "Query customers who are either male or younger than 25." }, { "code": null, "e": 3634, "s": 3538, "text": "This example requires a compound query with “or” logic. We just need to change “$and” to “$or”." }, { "code": null, "e": 4155, "s": 3634, "text": "> db.customer.find( { $or: [ {gender: \"male\"}, {age: {$lt: 22}} ] }){ \"_id\" : ObjectId(\"600c1806289947de938c68ea\"), \"name\" : \"John\", \"age\" : 32, \"gender\" : \"male\", \"amount\" : 32 }{ \"_id\" : ObjectId(\"600c19d2289947de938c68ed\"), \"name\" : \"Martin\", \"age\" : 28, \"gender\" : \"male\", \"amount\" : 49 }{ \"_id\" : ObjectId(\"600c19d2289947de938c68ef\"), \"name\" : \"Mike\", \"age\" : 29, \"gender\" : \"male\", \"amount\" : 22 }{ \"_id\" : ObjectId(\"600c19d2289947de938c68f0\"), \"name\" : \"Samantha\", \"age\" : 21, \"gender\" : \"female\", \"amount\" : 41 }" }, { "code": null, "e": 4366, "s": 4155, "text": "MongoDB allows for aggregating values while retrieving from the database. For instance, we can calculate the total purchase amount for males and females. The aggregate method is used instead of the find method." }, { "code": null, "e": 4525, "s": 4366, "text": "> db.customer.aggregate([... { $group: {_id: \"$gender\", total: {$sum: \"$amount\"} } }... ]){ \"_id\" : \"female\", \"total\" : 198 }{ \"_id\" : \"male\", \"total\" : 103 }" }, { "code": null, "e": 4751, "s": 4525, "text": "Let’s elaborate on the syntax. We first group the documents by the gender column by selecting “$gender” as id. The next part specifies both the aggregation function which is “$sum” in our case and the column to be aggregated." }, { "code": null, "e": 4837, "s": 4751, "text": "If you are familiar with Pandas, the syntax is quite similar to the groupby function." }, { "code": null, "e": 4987, "s": 4837, "text": "Let’s take the previous example one step further and add a condition. Thus, we first select documents that “match” a condition and apply aggregation." }, { "code": null, "e": 5156, "s": 4987, "text": "The following query is an aggregation pipeline which first selects the customers who are older than 25 and calculates the average purchase amount for males and females." }, { "code": null, "e": 5348, "s": 5156, "text": "> db.customer.aggregate([... { $match: { age: {$gt:25} } },... { $group: { _id: \"$gender\", avg: {$avg: \"$amount\"} } }... ]){ \"_id\" : \"female\", \"avg\" : 35.33 }{ \"_id\" : \"male\", \"avg\" : 34.33 }" }, { "code": null, "e": 5565, "s": 5348, "text": "The query in the previous example contains only two groups so it is not necessary to sort the results. However, we might have queries that return several values. In such cases, sorting the results is a good practice." }, { "code": null, "e": 5653, "s": 5565, "text": "We can sort the results of the previous query by the average amount in ascending order." }, { "code": null, "e": 5869, "s": 5653, "text": "> db.customer.aggregate([... { $match: { age: {$gt:25} } },... { $group: { _id: \"$gender\", avg: {$avg: \"$amount\"} } },... { $sort: {avg: 1} }... ]){ \"_id\" : \"male\", \"avg\" : 34.33 }{ \"_id\" : \"female\", \"avg\" : 35.33 }" }, { "code": null, "e": 6059, "s": 5869, "text": "We have just added “$sort” in the aggregation pipeline. The field used for sorting is specified along with the sorting behavior. 1 means in ascending order and -1 means in descending order." }, { "code": null, "e": 6303, "s": 6059, "text": "Both SQL and NoSQL are of crucial importance in data science ecosystem. The fuel of data science is data so everything starts with proper, well maintained and easily accessible data. Both SQL and NoSQL are critical players for these processes." }, { "code": null, "e": 6577, "s": 6303, "text": "We have covered a brief introduction to querying a MongoDB database. There is, of course, much more to cover. We are likely to write more advanced queries for a typical task. However, once you are comfortable with the basics, you can easily move onto more advanced queries." } ]
Fleury's Algorithm for printing Eulerian Path or Circuit - GeeksforGeeks
04 Feb, 2022 Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex.We strongly recommend to first read the following post on Euler Path and Circuit. https://www.geeksforgeeks.org/eulerian-path-and-circuit/In the above mentioned post, we discussed the problem of finding out whether a given graph is Eulerian or not. In this post, an algorithm to print Eulerian trail or circuit is discussed.Following is Fleury’s Algorithm for printing Eulerian trail or cycle (Source Ref1).1. Make sure the graph has either 0 or 2 odd vertices.2. If there are 0 odd vertices, start anywhere. If there are 2 odd vertices, start at one of them.3. Follow edges one at a time. If you have a choice between a bridge and a non-bridge, always choose the non-bridge.4. Stop when you run out of edges.The idea is, “don’t burn bridges“ so that we can come back to a vertex and traverse remaining edges. For example let us consider the following graph. There are two vertices with odd degree, ‘2’ and ‘3’, we can start path from any of them. Let us start tour from vertex ‘2’. There are three edges going out from vertex ‘2’, which one to pick? We don’t pick the edge ‘2-3’ because that is a bridge (we won’t be able to come back to ‘3’). We can pick any of the remaining two edge. Let us say we pick ‘2-0’. We remove this edge and move to vertex ‘0’. There is only one edge from vertex ‘0’, so we pick it, remove it and move to vertex ‘1’. Euler tour becomes ‘2-0 0-1’. There is only one edge from vertex ‘1’, so we pick it, remove it and move to vertex ‘2’. Euler tour becomes ‘2-0 0-1 1-2’ Again there is only one edge from vertex 2, so we pick it, remove it and move to vertex 3. Euler tour becomes ‘2-0 0-1 1-2 2-3’ There are no more edges left, so we stop here. Final tour is ‘2-0 0-1 1-2 2-3’.See this for and this for more examples.Following is C++ implementation of above algorithm. In the following code, it is assumed that the given graph has an Eulerian trail or Circuit. The main focus is to print an Eulerian trail or circuit. We can use isEulerian() to first check whether there is an Eulerian Trail or Circuit in the given graph. We first find the starting point which must be an odd vertex (if there are odd vertices) and store it in variable ‘u’. If there are zero odd vertices, we start from vertex ‘0’. We call printEulerUtil() to print Euler tour starting with u. We traverse all adjacent vertices of u, if there is only one adjacent vertex, we immediately consider it. If there are more than one adjacent vertices, we consider an adjacent v only if edge u-v is not a bridge. How to find if a given is edge is bridge? We count number of vertices reachable from u. We remove edge u-v and again count number of reachable vertices from u. If number of reachable vertices are reduced, then edge u-v is a bridge. To count reachable vertices, we can either use BFS or DFS, we have used DFS in the above code. The function DFSCount(u) returns number of vertices reachable from u. Once an edge is processed (included in Euler tour), we remove it from the graph. To remove the edge, we replace the vertex entry with -1 in adjacency list. Note that simply deleting the node may not work as the code is recursive and a parent call may be in middle of adjacency list. C++ Java Python3 C# // A C++ program print Eulerian Trail in a given Eulerian or// Semi-Eulerian Graph#include <algorithm>#include <iostream>#include <list>#include <string.h>using namespace std; // A class that represents an undirected graphclass Graph { int V; // No. of vertices list<int>* adj; // A dynamic array of adjacency listspublic: // Constructor and destructor Graph(int V) { this->V = V; adj = new list<int>[V]; } ~Graph() { delete[] adj; } // functions to add and remove edge void addEdge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } void rmvEdge(int u, int v); // Methods to print Eulerian tour void printEulerTour(); void printEulerUtil(int s); // This function returns count of vertices reachable // from v. It does DFS int DFSCount(int v, bool visited[]); // Utility function to check if edge u-v is a valid next // edge in Eulerian trail or circuit bool isValidNextEdge(int u, int v);}; /* The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path */void Graph::printEulerTour(){ // Find a vertex with odd degree int u = 0; for (int i = 0; i < V; i++) if (adj[i].size() & 1) { u = i; break; } // Print tour starting from oddv printEulerUtil(u); cout << endl;} // Print Euler tour starting from vertex uvoid Graph::printEulerUtil(int u){ // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // If edge u-v is not removed and it's a a valid // next edge if (v != -1 && isValidNextEdge(u, v)) { cout << u << "-" << v << " "; rmvEdge(u, v); printEulerUtil(v); } }} // The function to check if edge u-v can be considered as// next edge in Euler Toutbool Graph::isValidNextEdge(int u, int v){ // The edge u-v is valid in one of the following two // cases: // 1) If v is the only adjacent vertex of u int count = 0; // To store count of adjacent vertices list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (*i != -1) count++; if (count == 1) return true; // 2) If there are multiple adjacents, then u-v is not a // bridge Do following steps to check if u-v is a bridge // 2.a) count of vertices reachable from u bool visited[V]; memset(visited, false, V); int count1 = DFSCount(u, visited); // 2.b) Remove edge (u, v) and after removing the edge, // count vertices reachable from u rmvEdge(u, v); memset(visited, false, V); int count2 = DFSCount(u, visited); // 2.c) Add the edge back to the graph addEdge(u, v); // 2.d) If count1 is greater, then edge (u, v) is a // bridge return (count1 > count2) ? false : true;} // This function removes edge u-v from graph. It removes// the edge by replacing adjacent vertex value with -1.void Graph::rmvEdge(int u, int v){ // Find v in adjacency list of u and replace it with -1 list<int>::iterator iv = find(adj[u].begin(), adj[u].end(), v); *iv = -1; // Find u in adjacency list of v and replace it with -1 list<int>::iterator iu = find(adj[v].begin(), adj[v].end(), u); *iu = -1;} // A DFS based function to count reachable vertices from vint Graph::DFSCount(int v, bool visited[]){ // Mark the current node as visited visited[v] = true; int count = 1; // Recur for all vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (*i != -1 && !visited[*i]) count += DFSCount(*i, visited); return count;} // Driver program to test above functionint main(){ // Let us first create and test graphs shown in above // figure Graph g1(4); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.printEulerTour(); Graph g2(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 0); g2.printEulerTour(); Graph g3(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(3, 2); g3.addEdge(3, 1); g3.addEdge(2, 4); g3.printEulerTour(); return 0;} // A Java program print Eulerian Trail// in a given Eulerian or Semi-Eulerian Graphimport java.util.ArrayList; // An Undirected graph using// adjacency list representationpublic class Graph { private int vertices; // No. of vertices private ArrayList<Integer>[] adj; // adjacency list // Constructor Graph(int numOfVertices) { // initialise vertex count this.vertices = numOfVertices; // initialise adjacency list initGraph(); } // utility method to initialise adjacency list @SuppressWarnings("unchecked") private void initGraph() { adj = new ArrayList[vertices]; for (int i = 0; i < vertices; i++) { adj[i] = new ArrayList<>(); } } // add edge u-v private void addEdge(Integer u, Integer v) { adj[u].add(v); adj[v].add(u); } // This function removes edge u-v from graph. private void removeEdge(Integer u, Integer v) { adj[u].remove(v); adj[v].remove(u); } /* The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path */ private void printEulerTour() { // Find a vertex with odd degree Integer u = 0; for (int i = 0; i < vertices; i++) { if (adj[i].size() % 2 == 1) { u = i; break; } } // Print tour starting from oddv printEulerUtil(u); System.out.println(); } // Print Euler tour starting from vertex u private void printEulerUtil(Integer u) { // Recur for all the vertices adjacent to this // vertex for (int i = 0; i < adj[u].size(); i++) { Integer v = adj[u].get(i); // If edge u-v is a valid next edge if (isValidNextEdge(u, v)) { System.out.print(u + "-" + v + " "); // This edge is used so remove it now removeEdge(u, v); printEulerUtil(v); } } } // The function to check if edge u-v can be // considered as next edge in Euler Tout private boolean isValidNextEdge(Integer u, Integer v) { // The edge u-v is valid in one of the // following two cases: // 1) If v is the only adjacent vertex of u // ie size of adjacent vertex list is 1 if (adj[u].size() == 1) { return true; } // 2) If there are multiple adjacents, then // u-v is not a bridge Do following steps // to check if u-v is a bridge // 2.a) count of vertices reachable from u boolean[] isVisited = new boolean[this.vertices]; int count1 = dfsCount(u, isVisited); // 2.b) Remove edge (u, v) and after removing // the edge, count vertices reachable from u removeEdge(u, v); isVisited = new boolean[this.vertices]; int count2 = dfsCount(u, isVisited); // 2.c) Add the edge back to the graph addEdge(u, v); return (count1 > count2) ? false : true; } // A DFS based function to count reachable // vertices from v private int dfsCount(Integer v, boolean[] isVisited) { // Mark the current node as visited isVisited[v] = true; int count = 1; // Recur for all vertices adjacent to this vertex for (int adj : adj[v]) { if (!isVisited[adj]) { count = count + dfsCount(adj, isVisited); } } return count; } // Driver program to test above function public static void main(String a[]) { // Let us first create and test // graphs shown in above figure Graph g1 = new Graph(4); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.printEulerTour(); Graph g2 = new Graph(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 0); g2.printEulerTour(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(3, 2); g3.addEdge(3, 1); g3.addEdge(2, 4); g3.printEulerTour(); }} // This code is contributed by Himanshu Shekhar # Python program print Eulerian Trail in a given Eulerian or Semi-Eulerian Graph from collections import defaultdict #This class represents an undirected graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) # This function removes edge u-v from graph def rmvEdge(self, u, v): for index, key in enumerate(self.graph[u]): if key == v: self.graph[u].pop(index) for index, key in enumerate(self.graph[v]): if key == u: self.graph[v].pop(index) # A DFS based function to count reachable vertices from v def DFSCount(self, v, visited): count = 1 visited[v] = True for i in self.graph[v]: if visited[i] == False: count = count + self.DFSCount(i, visited) return count # The function to check if edge u-v can be considered as next edge in # Euler Tour def isValidNextEdge(self, u, v): # The edge u-v is valid in one of the following two cases: # 1) If v is the only adjacent vertex of u if len(self.graph[u]) == 1: return True else: ''' 2) If there are multiple adjacents, then u-v is not a bridge Do following steps to check if u-v is a bridge 2.a) count of vertices reachable from u''' visited =[False]*(self.V) count1 = self.DFSCount(u, visited) '''2.b) Remove edge (u, v) and after removing the edge, count vertices reachable from u''' self.rmvEdge(u, v) visited =[False]*(self.V) count2 = self.DFSCount(u, visited) #2.c) Add the edge back to the graph self.addEdge(u,v) # 2.d) If count1 is greater, then edge (u, v) is a bridge return False if count1 > count2 else True # Print Euler tour starting from vertex u def printEulerUtil(self, u): #Recur for all the vertices adjacent to this vertex for v in self.graph[u]: #If edge u-v is not removed and it's a a valid next edge if self.isValidNextEdge(u, v): print("%d-%d " %(u,v)), self.rmvEdge(u, v) self.printEulerUtil(v) '''The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path ''' def printEulerTour(self): #Find a vertex with odd degree u = 0 for i in range(self.V): if len(self.graph[i]) %2 != 0 : u = i break # Print tour starting from odd vertex print ("\n") self.printEulerUtil(u) # Create a graph given in the above diagram g1 = Graph(4)g1.addEdge(0, 1)g1.addEdge(0, 2)g1.addEdge(1, 2)g1.addEdge(2, 3)g1.printEulerTour() g2 = Graph(3)g2.addEdge(0, 1)g2.addEdge(1, 2)g2.addEdge(2, 0)g2.printEulerTour() g3 = Graph (5)g3.addEdge(1, 0)g3.addEdge(0, 2)g3.addEdge(2, 1)g3.addEdge(0, 3)g3.addEdge(3, 4)g3.addEdge(3, 2)g3.addEdge(3, 1)g3.addEdge(2, 4)g3.printEulerTour() #This code is contributed by Neelam Yadav // A C# program print Eulerian Trail// in a given Eulerian or Semi-Eulerian Graphusing System;using System.Collections.Generic; // An Undirected graph using// adjacency list representationclass Graph{ private int vertices; // No. of vertices private List<int>[] adj; // adjacency list // Constructor Graph(int numOfVertices) { // initialise vertex count this.vertices = numOfVertices; // initialise adjacency list initGraph(); } // utility method to initialise adjacency list private void initGraph() { adj = new List<int>[vertices]; for (int i = 0; i < vertices; i++) { adj[i] = new List<int>(); } } // add edge u-v private void addEdge(int u, int v) { adj[u].Add(v); adj[v].Add(u); } // This function removes edge u-v from graph. private void removeEdge(int u, int v) { adj[u].Remove(v); adj[v].Remove(u); } /* The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path */ private void printEulerTour() { // Find a vertex with odd degree int u = 0; for (int i = 0; i < vertices; i++) { if (adj[i].Count % 2 == 1) { u = i; break; } } // Print tour starting from oddv printEulerUtil(u); Console.WriteLine(); } // Print Euler tour starting from vertex u private void printEulerUtil(int u) { // Recur for all the vertices // adjacent to this vertex for (int i = 0; i < adj[u].Count; i++) { int v = adj[u][i]; // If edge u-v is a valid next edge if (isValidNextEdge(u, v)) { Console.Write(u + "-" + v + " "); // This edge is used so remove it now removeEdge(u, v); printEulerUtil(v); } } } // The function to check if edge u-v can be // considered as next edge in Euler Tout private bool isValidNextEdge(int u, int v) { // The edge u-v is valid in one of the // following two cases: // 1) If v is the only adjacent vertex of u // ie size of adjacent vertex list is 1 if (adj[u].Count == 1) { return true; } // 2) If there are multiple adjacents, then // u-v is not a bridge Do following steps // to check if u-v is a bridge // 2.a) count of vertices reachable from u bool[] isVisited = new bool[this.vertices]; int count1 = dfsCount(u, isVisited); // 2.b) Remove edge (u, v) and after removing // the edge, count vertices reachable from u removeEdge(u, v); isVisited = new bool[this.vertices]; int count2 = dfsCount(u, isVisited); // 2.c) Add the edge back to the graph addEdge(u, v); return (count1 > count2) ? false : true; } // A DFS based function to count reachable // vertices from v private int dfsCount(int v, bool[] isVisited) { // Mark the current node as visited isVisited[v] = true; int count = 1; // Recur for all vertices adjacent // to this vertex foreach(int i in adj[v]) { if (!isVisited[i]) { count = count + dfsCount(i, isVisited); } } return count; } // Driver Code public static void Main(String []a) { // Let us first create and test // graphs shown in above figure Graph g1 = new Graph(4); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.printEulerTour(); Graph g2 = new Graph(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 0); g2.printEulerTour(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(3, 2); g3.addEdge(3, 1); g3.addEdge(2, 4); g3.printEulerTour(); }} // This code is contributed by PrinciRaj1992 Output: 2-0 0-1 1-2 2-3 0-1 1-2 2-0 0-1 1-2 2-0 0-3 3-4 4-2 2-3 3-1 Note that the above code modifies given graph, we can create a copy of graph if we don’t want the given graph to be modified.Time Complexity: Time complexity of the above implementation is O ((V+E)2). The function printEulerUtil() is like DFS and it calls isValidNextEdge() which also does DFS two times. Time complexity of DFS for adjacency list representation is O(V+E). Therefore overall time complexity is O((V+E)*(V+E)) which can be written as O(E2) for a connected graph. There are better algorithms to print Euler tour, Hierholzer’s Algorithm finds in O(V+E) time.References: http://www.math.ku.edu/~jmartin/courses/math105-F11/Lectures/chapter5-part2.pdf http://en.wikipedia.org/wiki/Eulerian_path#Fleury.27s_algorithmPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above princiraj1992 surinderdawra388 gurukiranx amartyaghoshgfg simmytarika5 Euler-Circuit Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Traveling Salesman Problem (TSP) Implementation Ford-Fulkerson Algorithm for Maximum Flow Problem Detect cycle in an undirected graph Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) m Coloring Problem | Backtracking-5 Shortest path in an unweighted graph
[ { "code": null, "e": 25226, "s": 25198, "text": "\n04 Feb, 2022" }, { "code": null, "e": 26235, "s": 25226, "text": "Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex.We strongly recommend to first read the following post on Euler Path and Circuit. https://www.geeksforgeeks.org/eulerian-path-and-circuit/In the above mentioned post, we discussed the problem of finding out whether a given graph is Eulerian or not. In this post, an algorithm to print Eulerian trail or circuit is discussed.Following is Fleury’s Algorithm for printing Eulerian trail or cycle (Source Ref1).1. Make sure the graph has either 0 or 2 odd vertices.2. If there are 0 odd vertices, start anywhere. If there are 2 odd vertices, start at one of them.3. Follow edges one at a time. If you have a choice between a bridge and a non-bridge, always choose the non-bridge.4. Stop when you run out of edges.The idea is, “don’t burn bridges“ so that we can come back to a vertex and traverse remaining edges. For example let us consider the following graph. " }, { "code": null, "e": 26361, "s": 26235, "text": "There are two vertices with odd degree, ‘2’ and ‘3’, we can start path from any of them. Let us start tour from vertex ‘2’. " }, { "code": null, "e": 26638, "s": 26361, "text": "There are three edges going out from vertex ‘2’, which one to pick? We don’t pick the edge ‘2-3’ because that is a bridge (we won’t be able to come back to ‘3’). We can pick any of the remaining two edge. Let us say we pick ‘2-0’. We remove this edge and move to vertex ‘0’. " }, { "code": null, "e": 26759, "s": 26638, "text": "There is only one edge from vertex ‘0’, so we pick it, remove it and move to vertex ‘1’. Euler tour becomes ‘2-0 0-1’. " }, { "code": null, "e": 26883, "s": 26759, "text": "There is only one edge from vertex ‘1’, so we pick it, remove it and move to vertex ‘2’. Euler tour becomes ‘2-0 0-1 1-2’ " }, { "code": null, "e": 27013, "s": 26883, "text": "Again there is only one edge from vertex 2, so we pick it, remove it and move to vertex 3. Euler tour becomes ‘2-0 0-1 1-2 2-3’ " }, { "code": null, "e": 28570, "s": 27013, "text": "There are no more edges left, so we stop here. Final tour is ‘2-0 0-1 1-2 2-3’.See this for and this for more examples.Following is C++ implementation of above algorithm. In the following code, it is assumed that the given graph has an Eulerian trail or Circuit. The main focus is to print an Eulerian trail or circuit. We can use isEulerian() to first check whether there is an Eulerian Trail or Circuit in the given graph. We first find the starting point which must be an odd vertex (if there are odd vertices) and store it in variable ‘u’. If there are zero odd vertices, we start from vertex ‘0’. We call printEulerUtil() to print Euler tour starting with u. We traverse all adjacent vertices of u, if there is only one adjacent vertex, we immediately consider it. If there are more than one adjacent vertices, we consider an adjacent v only if edge u-v is not a bridge. How to find if a given is edge is bridge? We count number of vertices reachable from u. We remove edge u-v and again count number of reachable vertices from u. If number of reachable vertices are reduced, then edge u-v is a bridge. To count reachable vertices, we can either use BFS or DFS, we have used DFS in the above code. The function DFSCount(u) returns number of vertices reachable from u. Once an edge is processed (included in Euler tour), we remove it from the graph. To remove the edge, we replace the vertex entry with -1 in adjacency list. Note that simply deleting the node may not work as the code is recursive and a parent call may be in middle of adjacency list. " }, { "code": null, "e": 28574, "s": 28570, "text": "C++" }, { "code": null, "e": 28579, "s": 28574, "text": "Java" }, { "code": null, "e": 28587, "s": 28579, "text": "Python3" }, { "code": null, "e": 28590, "s": 28587, "text": "C#" }, { "code": "// A C++ program print Eulerian Trail in a given Eulerian or// Semi-Eulerian Graph#include <algorithm>#include <iostream>#include <list>#include <string.h>using namespace std; // A class that represents an undirected graphclass Graph { int V; // No. of vertices list<int>* adj; // A dynamic array of adjacency listspublic: // Constructor and destructor Graph(int V) { this->V = V; adj = new list<int>[V]; } ~Graph() { delete[] adj; } // functions to add and remove edge void addEdge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } void rmvEdge(int u, int v); // Methods to print Eulerian tour void printEulerTour(); void printEulerUtil(int s); // This function returns count of vertices reachable // from v. It does DFS int DFSCount(int v, bool visited[]); // Utility function to check if edge u-v is a valid next // edge in Eulerian trail or circuit bool isValidNextEdge(int u, int v);}; /* The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path */void Graph::printEulerTour(){ // Find a vertex with odd degree int u = 0; for (int i = 0; i < V; i++) if (adj[i].size() & 1) { u = i; break; } // Print tour starting from oddv printEulerUtil(u); cout << endl;} // Print Euler tour starting from vertex uvoid Graph::printEulerUtil(int u){ // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // If edge u-v is not removed and it's a a valid // next edge if (v != -1 && isValidNextEdge(u, v)) { cout << u << \"-\" << v << \" \"; rmvEdge(u, v); printEulerUtil(v); } }} // The function to check if edge u-v can be considered as// next edge in Euler Toutbool Graph::isValidNextEdge(int u, int v){ // The edge u-v is valid in one of the following two // cases: // 1) If v is the only adjacent vertex of u int count = 0; // To store count of adjacent vertices list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (*i != -1) count++; if (count == 1) return true; // 2) If there are multiple adjacents, then u-v is not a // bridge Do following steps to check if u-v is a bridge // 2.a) count of vertices reachable from u bool visited[V]; memset(visited, false, V); int count1 = DFSCount(u, visited); // 2.b) Remove edge (u, v) and after removing the edge, // count vertices reachable from u rmvEdge(u, v); memset(visited, false, V); int count2 = DFSCount(u, visited); // 2.c) Add the edge back to the graph addEdge(u, v); // 2.d) If count1 is greater, then edge (u, v) is a // bridge return (count1 > count2) ? false : true;} // This function removes edge u-v from graph. It removes// the edge by replacing adjacent vertex value with -1.void Graph::rmvEdge(int u, int v){ // Find v in adjacency list of u and replace it with -1 list<int>::iterator iv = find(adj[u].begin(), adj[u].end(), v); *iv = -1; // Find u in adjacency list of v and replace it with -1 list<int>::iterator iu = find(adj[v].begin(), adj[v].end(), u); *iu = -1;} // A DFS based function to count reachable vertices from vint Graph::DFSCount(int v, bool visited[]){ // Mark the current node as visited visited[v] = true; int count = 1; // Recur for all vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (*i != -1 && !visited[*i]) count += DFSCount(*i, visited); return count;} // Driver program to test above functionint main(){ // Let us first create and test graphs shown in above // figure Graph g1(4); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.printEulerTour(); Graph g2(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 0); g2.printEulerTour(); Graph g3(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(3, 2); g3.addEdge(3, 1); g3.addEdge(2, 4); g3.printEulerTour(); return 0;}", "e": 32979, "s": 28590, "text": null }, { "code": "// A Java program print Eulerian Trail// in a given Eulerian or Semi-Eulerian Graphimport java.util.ArrayList; // An Undirected graph using// adjacency list representationpublic class Graph { private int vertices; // No. of vertices private ArrayList<Integer>[] adj; // adjacency list // Constructor Graph(int numOfVertices) { // initialise vertex count this.vertices = numOfVertices; // initialise adjacency list initGraph(); } // utility method to initialise adjacency list @SuppressWarnings(\"unchecked\") private void initGraph() { adj = new ArrayList[vertices]; for (int i = 0; i < vertices; i++) { adj[i] = new ArrayList<>(); } } // add edge u-v private void addEdge(Integer u, Integer v) { adj[u].add(v); adj[v].add(u); } // This function removes edge u-v from graph. private void removeEdge(Integer u, Integer v) { adj[u].remove(v); adj[v].remove(u); } /* The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path */ private void printEulerTour() { // Find a vertex with odd degree Integer u = 0; for (int i = 0; i < vertices; i++) { if (adj[i].size() % 2 == 1) { u = i; break; } } // Print tour starting from oddv printEulerUtil(u); System.out.println(); } // Print Euler tour starting from vertex u private void printEulerUtil(Integer u) { // Recur for all the vertices adjacent to this // vertex for (int i = 0; i < adj[u].size(); i++) { Integer v = adj[u].get(i); // If edge u-v is a valid next edge if (isValidNextEdge(u, v)) { System.out.print(u + \"-\" + v + \" \"); // This edge is used so remove it now removeEdge(u, v); printEulerUtil(v); } } } // The function to check if edge u-v can be // considered as next edge in Euler Tout private boolean isValidNextEdge(Integer u, Integer v) { // The edge u-v is valid in one of the // following two cases: // 1) If v is the only adjacent vertex of u // ie size of adjacent vertex list is 1 if (adj[u].size() == 1) { return true; } // 2) If there are multiple adjacents, then // u-v is not a bridge Do following steps // to check if u-v is a bridge // 2.a) count of vertices reachable from u boolean[] isVisited = new boolean[this.vertices]; int count1 = dfsCount(u, isVisited); // 2.b) Remove edge (u, v) and after removing // the edge, count vertices reachable from u removeEdge(u, v); isVisited = new boolean[this.vertices]; int count2 = dfsCount(u, isVisited); // 2.c) Add the edge back to the graph addEdge(u, v); return (count1 > count2) ? false : true; } // A DFS based function to count reachable // vertices from v private int dfsCount(Integer v, boolean[] isVisited) { // Mark the current node as visited isVisited[v] = true; int count = 1; // Recur for all vertices adjacent to this vertex for (int adj : adj[v]) { if (!isVisited[adj]) { count = count + dfsCount(adj, isVisited); } } return count; } // Driver program to test above function public static void main(String a[]) { // Let us first create and test // graphs shown in above figure Graph g1 = new Graph(4); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.printEulerTour(); Graph g2 = new Graph(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 0); g2.printEulerTour(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(3, 2); g3.addEdge(3, 1); g3.addEdge(2, 4); g3.printEulerTour(); }} // This code is contributed by Himanshu Shekhar", "e": 37314, "s": 32979, "text": null }, { "code": "# Python program print Eulerian Trail in a given Eulerian or Semi-Eulerian Graph from collections import defaultdict #This class represents an undirected graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) # This function removes edge u-v from graph def rmvEdge(self, u, v): for index, key in enumerate(self.graph[u]): if key == v: self.graph[u].pop(index) for index, key in enumerate(self.graph[v]): if key == u: self.graph[v].pop(index) # A DFS based function to count reachable vertices from v def DFSCount(self, v, visited): count = 1 visited[v] = True for i in self.graph[v]: if visited[i] == False: count = count + self.DFSCount(i, visited) return count # The function to check if edge u-v can be considered as next edge in # Euler Tour def isValidNextEdge(self, u, v): # The edge u-v is valid in one of the following two cases: # 1) If v is the only adjacent vertex of u if len(self.graph[u]) == 1: return True else: ''' 2) If there are multiple adjacents, then u-v is not a bridge Do following steps to check if u-v is a bridge 2.a) count of vertices reachable from u''' visited =[False]*(self.V) count1 = self.DFSCount(u, visited) '''2.b) Remove edge (u, v) and after removing the edge, count vertices reachable from u''' self.rmvEdge(u, v) visited =[False]*(self.V) count2 = self.DFSCount(u, visited) #2.c) Add the edge back to the graph self.addEdge(u,v) # 2.d) If count1 is greater, then edge (u, v) is a bridge return False if count1 > count2 else True # Print Euler tour starting from vertex u def printEulerUtil(self, u): #Recur for all the vertices adjacent to this vertex for v in self.graph[u]: #If edge u-v is not removed and it's a a valid next edge if self.isValidNextEdge(u, v): print(\"%d-%d \" %(u,v)), self.rmvEdge(u, v) self.printEulerUtil(v) '''The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path ''' def printEulerTour(self): #Find a vertex with odd degree u = 0 for i in range(self.V): if len(self.graph[i]) %2 != 0 : u = i break # Print tour starting from odd vertex print (\"\\n\") self.printEulerUtil(u) # Create a graph given in the above diagram g1 = Graph(4)g1.addEdge(0, 1)g1.addEdge(0, 2)g1.addEdge(1, 2)g1.addEdge(2, 3)g1.printEulerTour() g2 = Graph(3)g2.addEdge(0, 1)g2.addEdge(1, 2)g2.addEdge(2, 0)g2.printEulerTour() g3 = Graph (5)g3.addEdge(1, 0)g3.addEdge(0, 2)g3.addEdge(2, 1)g3.addEdge(0, 3)g3.addEdge(3, 4)g3.addEdge(3, 2)g3.addEdge(3, 1)g3.addEdge(2, 4)g3.printEulerTour() #This code is contributed by Neelam Yadav", "e": 40743, "s": 37314, "text": null }, { "code": "// A C# program print Eulerian Trail// in a given Eulerian or Semi-Eulerian Graphusing System;using System.Collections.Generic; // An Undirected graph using// adjacency list representationclass Graph{ private int vertices; // No. of vertices private List<int>[] adj; // adjacency list // Constructor Graph(int numOfVertices) { // initialise vertex count this.vertices = numOfVertices; // initialise adjacency list initGraph(); } // utility method to initialise adjacency list private void initGraph() { adj = new List<int>[vertices]; for (int i = 0; i < vertices; i++) { adj[i] = new List<int>(); } } // add edge u-v private void addEdge(int u, int v) { adj[u].Add(v); adj[v].Add(u); } // This function removes edge u-v from graph. private void removeEdge(int u, int v) { adj[u].Remove(v); adj[v].Remove(u); } /* The main function that print Eulerian Trail. It first finds an odd degree vertex (if there is any) and then calls printEulerUtil() to print the path */ private void printEulerTour() { // Find a vertex with odd degree int u = 0; for (int i = 0; i < vertices; i++) { if (adj[i].Count % 2 == 1) { u = i; break; } } // Print tour starting from oddv printEulerUtil(u); Console.WriteLine(); } // Print Euler tour starting from vertex u private void printEulerUtil(int u) { // Recur for all the vertices // adjacent to this vertex for (int i = 0; i < adj[u].Count; i++) { int v = adj[u][i]; // If edge u-v is a valid next edge if (isValidNextEdge(u, v)) { Console.Write(u + \"-\" + v + \" \"); // This edge is used so remove it now removeEdge(u, v); printEulerUtil(v); } } } // The function to check if edge u-v can be // considered as next edge in Euler Tout private bool isValidNextEdge(int u, int v) { // The edge u-v is valid in one of the // following two cases: // 1) If v is the only adjacent vertex of u // ie size of adjacent vertex list is 1 if (adj[u].Count == 1) { return true; } // 2) If there are multiple adjacents, then // u-v is not a bridge Do following steps // to check if u-v is a bridge // 2.a) count of vertices reachable from u bool[] isVisited = new bool[this.vertices]; int count1 = dfsCount(u, isVisited); // 2.b) Remove edge (u, v) and after removing // the edge, count vertices reachable from u removeEdge(u, v); isVisited = new bool[this.vertices]; int count2 = dfsCount(u, isVisited); // 2.c) Add the edge back to the graph addEdge(u, v); return (count1 > count2) ? false : true; } // A DFS based function to count reachable // vertices from v private int dfsCount(int v, bool[] isVisited) { // Mark the current node as visited isVisited[v] = true; int count = 1; // Recur for all vertices adjacent // to this vertex foreach(int i in adj[v]) { if (!isVisited[i]) { count = count + dfsCount(i, isVisited); } } return count; } // Driver Code public static void Main(String []a) { // Let us first create and test // graphs shown in above figure Graph g1 = new Graph(4); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.printEulerTour(); Graph g2 = new Graph(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 0); g2.printEulerTour(); Graph g3 = new Graph(5); g3.addEdge(1, 0); g3.addEdge(0, 2); g3.addEdge(2, 1); g3.addEdge(0, 3); g3.addEdge(3, 4); g3.addEdge(3, 2); g3.addEdge(3, 1); g3.addEdge(2, 4); g3.printEulerTour(); }} // This code is contributed by PrinciRaj1992", "e": 45061, "s": 40743, "text": null }, { "code": null, "e": 45070, "s": 45061, "text": "Output: " }, { "code": null, "e": 45142, "s": 45070, "text": "2-0 0-1 1-2 2-3\n0-1 1-2 2-0\n0-1 1-2 2-0 0-3 3-4 4-2 2-3 3-1" }, { "code": null, "e": 45993, "s": 45142, "text": "Note that the above code modifies given graph, we can create a copy of graph if we don’t want the given graph to be modified.Time Complexity: Time complexity of the above implementation is O ((V+E)2). The function printEulerUtil() is like DFS and it calls isValidNextEdge() which also does DFS two times. Time complexity of DFS for adjacency list representation is O(V+E). Therefore overall time complexity is O((V+E)*(V+E)) which can be written as O(E2) for a connected graph. There are better algorithms to print Euler tour, Hierholzer’s Algorithm finds in O(V+E) time.References: http://www.math.ku.edu/~jmartin/courses/math105-F11/Lectures/chapter5-part2.pdf http://en.wikipedia.org/wiki/Eulerian_path#Fleury.27s_algorithmPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 46007, "s": 45993, "text": "princiraj1992" }, { "code": null, "e": 46024, "s": 46007, "text": "surinderdawra388" }, { "code": null, "e": 46035, "s": 46024, "text": "gurukiranx" }, { "code": null, "e": 46051, "s": 46035, "text": "amartyaghoshgfg" }, { "code": null, "e": 46064, "s": 46051, "text": "simmytarika5" }, { "code": null, "e": 46078, "s": 46064, "text": "Euler-Circuit" }, { "code": null, "e": 46084, "s": 46078, "text": "Graph" }, { "code": null, "e": 46090, "s": 46084, "text": "Graph" }, { "code": null, "e": 46188, "s": 46090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46197, "s": 46188, "text": "Comments" }, { "code": null, "e": 46210, "s": 46197, "text": "Old Comments" }, { "code": null, "e": 46230, "s": 46210, "text": "Topological Sorting" }, { "code": null, "e": 46263, "s": 46230, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 46331, "s": 46263, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 46406, "s": 46331, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 46454, "s": 46406, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 46504, "s": 46454, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 46540, "s": 46504, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 46606, "s": 46540, "text": "Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)" }, { "code": null, "e": 46642, "s": 46606, "text": "m Coloring Problem | Backtracking-5" } ]
How to set the current working directory in Python?
You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to. >>> import os >>> os.chdir('my_folder')
[ { "code": null, "e": 1209, "s": 1062, "text": "You can change directory or cd in Python using the os module. It takes as input the relative/absolute path of the directory you want to switch to." }, { "code": null, "e": 1249, "s": 1209, "text": ">>> import os\n>>> os.chdir('my_folder')" } ]
Check if a String starts with any of the given prefixes in Java - GeeksforGeeks
11 Dec, 2018 Given a String and an array of prefixes. The task is to check whether the given String starts with any of the given prefixes or not. Example: Input: String = “GeeksforGeeks”, Prefixes = {“Geeks”, “for”, “Gfor”}Output: true Input: String = “GeeksforGeeks”, Prefixes = {“Freaks”, “for”, “Freak”}Output: false Below are the following approaches that can be used to complete the given task: Naive Approach: This method involves the checking the String for each of the prefix array element explicitly.Algorithm:Get the string and the prefixes to be matched with.Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given string String str = "GeeksforGeeks"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String starts with one of the prefixes. Program 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given string String str = "GeeksforGeeks"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String do not starts with one of the prefixes. Using Regular expression:Algorithm:Get the string and the prefixes to be matched with.Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given String String str = "GeeksforGeeks"; // Check for prefixes using Regex if (str.matches("(" + arr[0] + "|" + arr[1] + "|" + arr[2] + ").*")) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String starts with one of the prefixes. Program 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given String String str = "GeeksforGeeks"; // Check for prefixes using Regex if (str.matches("(" + arr[0] + "|" + arr[1] + "|" + arr[2] + ").*")) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String do not starts with one of the prefixes. Using Java 8 Streams API:Algorithm:Get the string and the prefixes to be matched with.Convert the Prefixes into Stream using Stream.of()Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method.If any prefix is matched, then return true else return false.Program 1:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given String String str = "GeeksforGeeks"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String starts with one of the prefixes. Program 2:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given String String str = "GeeksforGeeks"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String do not starts with one of the prefixes. Naive Approach: This method involves the checking the String for each of the prefix array element explicitly.Algorithm:Get the string and the prefixes to be matched with.Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given string String str = "GeeksforGeeks"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String starts with one of the prefixes. Program 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given string String str = "GeeksforGeeks"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String do not starts with one of the prefixes. Algorithm: Get the string and the prefixes to be matched with.Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method.If any prefix is matched, then return true else return false. Get the string and the prefixes to be matched with. Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method. If any prefix is matched, then return true else return false. Program 1: class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given string String str = "GeeksforGeeks"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }} Output: Given String starts with one of the prefixes. Program 2: class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given string String str = "GeeksforGeeks"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }} Output: Given String do not starts with one of the prefixes. Using Regular expression:Algorithm:Get the string and the prefixes to be matched with.Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given String String str = "GeeksforGeeks"; // Check for prefixes using Regex if (str.matches("(" + arr[0] + "|" + arr[1] + "|" + arr[2] + ").*")) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String starts with one of the prefixes. Program 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given String String str = "GeeksforGeeks"; // Check for prefixes using Regex if (str.matches("(" + arr[0] + "|" + arr[1] + "|" + arr[2] + ").*")) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String do not starts with one of the prefixes. Algorithm: Get the string and the prefixes to be matched with.Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method.If any prefix is matched, then return true else return false. Get the string and the prefixes to be matched with. Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method. If any prefix is matched, then return true else return false. Program 1: class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given String String str = "GeeksforGeeks"; // Check for prefixes using Regex if (str.matches("(" + arr[0] + "|" + arr[1] + "|" + arr[2] + ").*")) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }} Output: Given String starts with one of the prefixes. Program 2: class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given String String str = "GeeksforGeeks"; // Check for prefixes using Regex if (str.matches("(" + arr[0] + "|" + arr[1] + "|" + arr[2] + ").*")) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }} Output: Given String do not starts with one of the prefixes. Using Java 8 Streams API:Algorithm:Get the string and the prefixes to be matched with.Convert the Prefixes into Stream using Stream.of()Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method.If any prefix is matched, then return true else return false.Program 1:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given String String str = "GeeksforGeeks"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String starts with one of the prefixes. Program 2:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given String String str = "GeeksforGeeks"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }}Output:Given String do not starts with one of the prefixes. Algorithm: Get the string and the prefixes to be matched with.Convert the Prefixes into Stream using Stream.of()Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method.If any prefix is matched, then return true else return false. Get the string and the prefixes to be matched with. Convert the Prefixes into Stream using Stream.of() Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method. If any prefix is matched, then return true else return false. Program 1: import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Geeks", "for", "Gfor" }; // Given String String str = "GeeksforGeeks"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }} Output: Given String starts with one of the prefixes. Program 2: import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { "Freaks", "for", "Freak" }; // Given String String str = "GeeksforGeeks"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println("Given String " + "starts with one of the prefixes."); else System.out.println("Given String do not " + "starts with one of the prefixes."); }} Output: Given String do not starts with one of the prefixes. Java-String-Programs Java-Strings prefix Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24252, "s": 24224, "text": "\n11 Dec, 2018" }, { "code": null, "e": 24385, "s": 24252, "text": "Given a String and an array of prefixes. The task is to check whether the given String starts with any of the given prefixes or not." }, { "code": null, "e": 24394, "s": 24385, "text": "Example:" }, { "code": null, "e": 24475, "s": 24394, "text": "Input: String = “GeeksforGeeks”, Prefixes = {“Geeks”, “for”, “Gfor”}Output: true" }, { "code": null, "e": 24559, "s": 24475, "text": "Input: String = “GeeksforGeeks”, Prefixes = {“Freaks”, “for”, “Freak”}Output: false" }, { "code": null, "e": 24639, "s": 24559, "text": "Below are the following approaches that can be used to complete the given task:" }, { "code": null, "e": 30110, "s": 24639, "text": "Naive Approach: This method involves the checking the String for each of the prefix array element explicitly.Algorithm:Get the string and the prefixes to be matched with.Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given string String str = \"GeeksforGeeks\"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String starts with one of the prefixes.\nProgram 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given string String str = \"GeeksforGeeks\"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String do not starts with one of the prefixes.\nUsing Regular expression:Algorithm:Get the string and the prefixes to be matched with.Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given String String str = \"GeeksforGeeks\"; // Check for prefixes using Regex if (str.matches(\"(\" + arr[0] + \"|\" + arr[1] + \"|\" + arr[2] + \").*\")) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String starts with one of the prefixes.\nProgram 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given String String str = \"GeeksforGeeks\"; // Check for prefixes using Regex if (str.matches(\"(\" + arr[0] + \"|\" + arr[1] + \"|\" + arr[2] + \").*\")) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String do not starts with one of the prefixes.\nUsing Java 8 Streams API:Algorithm:Get the string and the prefixes to be matched with.Convert the Prefixes into Stream using Stream.of()Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method.If any prefix is matched, then return true else return false.Program 1:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given String String str = \"GeeksforGeeks\"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String starts with one of the prefixes.\nProgram 2:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given String String str = \"GeeksforGeeks\"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String do not starts with one of the prefixes.\n" }, { "code": null, "e": 32059, "s": 30110, "text": "Naive Approach: This method involves the checking the String for each of the prefix array element explicitly.Algorithm:Get the string and the prefixes to be matched with.Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given string String str = \"GeeksforGeeks\"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String starts with one of the prefixes.\nProgram 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given string String str = \"GeeksforGeeks\"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String do not starts with one of the prefixes.\n" }, { "code": null, "e": 32070, "s": 32059, "text": "Algorithm:" }, { "code": null, "e": 32345, "s": 32070, "text": "Get the string and the prefixes to be matched with.Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method.If any prefix is matched, then return true else return false." }, { "code": null, "e": 32397, "s": 32345, "text": "Get the string and the prefixes to be matched with." }, { "code": null, "e": 32560, "s": 32397, "text": "Using loop, iterate through the prefixes and check whether the string starts with the respective prefix. This is done with the help of String.startsWith() method." }, { "code": null, "e": 32622, "s": 32560, "text": "If any prefix is matched, then return true else return false." }, { "code": null, "e": 32633, "s": 32622, "text": "Program 1:" }, { "code": "class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given string String str = \"GeeksforGeeks\"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}", "e": 33344, "s": 32633, "text": null }, { "code": null, "e": 33352, "s": 33344, "text": "Output:" }, { "code": null, "e": 33399, "s": 33352, "text": "Given String starts with one of the prefixes.\n" }, { "code": null, "e": 33410, "s": 33399, "text": "Program 2:" }, { "code": "class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given string String str = \"GeeksforGeeks\"; boolean result = false; // Check for each prefix element for (int i = 0; i < 3; i++) { if (str.startsWith(arr[i])) { result = true; break; } } if (result) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}", "e": 34123, "s": 33410, "text": null }, { "code": null, "e": 34131, "s": 34123, "text": "Output:" }, { "code": null, "e": 34185, "s": 34131, "text": "Given String do not starts with one of the prefixes.\n" }, { "code": null, "e": 35849, "s": 34185, "text": "Using Regular expression:Algorithm:Get the string and the prefixes to be matched with.Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method.If any prefix is matched, then return true else return false.Program 1:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given String String str = \"GeeksforGeeks\"; // Check for prefixes using Regex if (str.matches(\"(\" + arr[0] + \"|\" + arr[1] + \"|\" + arr[2] + \").*\")) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String starts with one of the prefixes.\nProgram 2:class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given String String str = \"GeeksforGeeks\"; // Check for prefixes using Regex if (str.matches(\"(\" + arr[0] + \"|\" + arr[1] + \"|\" + arr[2] + \").*\")) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String do not starts with one of the prefixes.\n" }, { "code": null, "e": 35860, "s": 35849, "text": "Algorithm:" }, { "code": null, "e": 36100, "s": 35860, "text": "Get the string and the prefixes to be matched with.Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method.If any prefix is matched, then return true else return false." }, { "code": null, "e": 36152, "s": 36100, "text": "Get the string and the prefixes to be matched with." }, { "code": null, "e": 36280, "s": 36152, "text": "Form a Regular Expression to check if the string starts with any of the prefix. This can be done using String.matches() method." }, { "code": null, "e": 36342, "s": 36280, "text": "If any prefix is matched, then return true else return false." }, { "code": null, "e": 36353, "s": 36342, "text": "Program 1:" }, { "code": "class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given String String str = \"GeeksforGeeks\"; // Check for prefixes using Regex if (str.matches(\"(\" + arr[0] + \"|\" + arr[1] + \"|\" + arr[2] + \").*\")) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}", "e": 36981, "s": 36353, "text": null }, { "code": null, "e": 36989, "s": 36981, "text": "Output:" }, { "code": null, "e": 37036, "s": 36989, "text": "Given String starts with one of the prefixes.\n" }, { "code": null, "e": 37047, "s": 37036, "text": "Program 2:" }, { "code": "class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given String String str = \"GeeksforGeeks\"; // Check for prefixes using Regex if (str.matches(\"(\" + arr[0] + \"|\" + arr[1] + \"|\" + arr[2] + \").*\")) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}", "e": 37677, "s": 37047, "text": null }, { "code": null, "e": 37685, "s": 37677, "text": "Output:" }, { "code": null, "e": 37739, "s": 37685, "text": "Given String do not starts with one of the prefixes.\n" }, { "code": null, "e": 39599, "s": 37739, "text": "Using Java 8 Streams API:Algorithm:Get the string and the prefixes to be matched with.Convert the Prefixes into Stream using Stream.of()Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method.If any prefix is matched, then return true else return false.Program 1:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given String String str = \"GeeksforGeeks\"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String starts with one of the prefixes.\nProgram 2:import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given String String str = \"GeeksforGeeks\"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}Output:Given String do not starts with one of the prefixes.\n" }, { "code": null, "e": 39610, "s": 39599, "text": "Algorithm:" }, { "code": null, "e": 39878, "s": 39610, "text": "Get the string and the prefixes to be matched with.Convert the Prefixes into Stream using Stream.of()Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method.If any prefix is matched, then return true else return false." }, { "code": null, "e": 39930, "s": 39878, "text": "Get the string and the prefixes to be matched with." }, { "code": null, "e": 39981, "s": 39930, "text": "Convert the Prefixes into Stream using Stream.of()" }, { "code": null, "e": 40087, "s": 39981, "text": "Check if any prefix matches using Predicate str::startsWith. This is done using Stream.anyMatch() method." }, { "code": null, "e": 40149, "s": 40087, "text": "If any prefix is matched, then return true else return false." }, { "code": null, "e": 40160, "s": 40149, "text": "Program 1:" }, { "code": "import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Geeks\", \"for\", \"Gfor\" }; // Given String String str = \"GeeksforGeeks\"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}", "e": 40872, "s": 40160, "text": null }, { "code": null, "e": 40880, "s": 40872, "text": "Output:" }, { "code": null, "e": 40927, "s": 40880, "text": "Given String starts with one of the prefixes.\n" }, { "code": null, "e": 40938, "s": 40927, "text": "Program 2:" }, { "code": "import java.util.stream.Stream; class PrefixSearch { public static void main(String[] args) { // Array of prefixes String[] arr = { \"Freaks\", \"for\", \"Freak\" }; // Given String String str = \"GeeksforGeeks\"; // Convert the Prefixes into Stream using Stream.of() // and check if any prefix matches using Predicate // str::startsWith if (Stream.of(arr) .anyMatch(str::startsWith)) System.out.println(\"Given String \" + \"starts with one of the prefixes.\"); else System.out.println(\"Given String do not \" + \"starts with one of the prefixes.\"); }}", "e": 41652, "s": 40938, "text": null }, { "code": null, "e": 41660, "s": 41652, "text": "Output:" }, { "code": null, "e": 41714, "s": 41660, "text": "Given String do not starts with one of the prefixes.\n" }, { "code": null, "e": 41735, "s": 41714, "text": "Java-String-Programs" }, { "code": null, "e": 41748, "s": 41735, "text": "Java-Strings" }, { "code": null, "e": 41755, "s": 41748, "text": "prefix" }, { "code": null, "e": 41760, "s": 41755, "text": "Java" }, { "code": null, "e": 41774, "s": 41760, "text": "Java Programs" }, { "code": null, "e": 41787, "s": 41774, "text": "Java-Strings" }, { "code": null, "e": 41792, "s": 41787, "text": "Java" }, { "code": null, "e": 41890, "s": 41792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41922, "s": 41890, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 41973, "s": 41922, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 42003, "s": 41973, "text": "HashMap in Java with Examples" }, { "code": null, "e": 42022, "s": 42003, "text": "Interfaces in Java" }, { "code": null, "e": 42053, "s": 42022, "text": "How to iterate any Map in Java" }, { "code": null, "e": 42081, "s": 42053, "text": "Initializing a List in Java" }, { "code": null, "e": 42125, "s": 42081, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 42151, "s": 42125, "text": "Java Programming Examples" }, { "code": null, "e": 42185, "s": 42151, "text": "Convert Double to Integer in Java" } ]
How to convert JSON data into a Python object?
The following code converts a json object(string) into a python object(dictionary). We import the json module and use the json.loads() method to do this. import json json_string = '{"name":"Sonali", "age": 21, "designation":" Software developer"}' print type (json_string) def func(strng): a =json.loads(strng) print type(a) print a func(json_string) <type 'str'> <type 'dict'> {u'age': 21, u'name': u'Sonali', u'designation': u'Software developer'}
[ { "code": null, "e": 1216, "s": 1062, "text": "The following code converts a json object(string) into a python object(dictionary). We import the json module and use the json.loads() method to do this." }, { "code": null, "e": 1425, "s": 1216, "text": "import json\njson_string = '{\"name\":\"Sonali\", \"age\": 21, \"designation\":\" Software developer\"}'\nprint type (json_string)\ndef func(strng):\n a =json.loads(strng)\n print type(a)\n print a\nfunc(json_string)" }, { "code": null, "e": 1524, "s": 1425, "text": "<type 'str'>\n<type 'dict'>\n{u'age': 21, u'name': u'Sonali', u'designation': u'Software developer'}" } ]
How do you sort an array in C# in ascending order?
Firstly, set the unsorted array. int[] list = {98, 23, 97, 36, 77}; Sort the array using the Sort() method. Array.Sort(list); You can try to run the following code to to sort an array in ascending order. Live Demo using System; namespace Demo { public class MyApplication { public static void Main(string[] args) { int[] list = {98, 23, 97, 36, 77}; Console.WriteLine("Original Unsorted List"); foreach (int i in list) { Console.Write(i + " "); } Array.Sort(list); Console.WriteLine("\nSorted List"); for(int i=0; i<list.Length; i++) { Console.Write(list[i] + " "); } } } } Original Unsorted List 98 23 97 36 77 Sorted List 23 36 77 97 98
[ { "code": null, "e": 1095, "s": 1062, "text": "Firstly, set the unsorted array." }, { "code": null, "e": 1130, "s": 1095, "text": "int[] list = {98, 23, 97, 36, 77};" }, { "code": null, "e": 1170, "s": 1130, "text": "Sort the array using the Sort() method." }, { "code": null, "e": 1188, "s": 1170, "text": "Array.Sort(list);" }, { "code": null, "e": 1266, "s": 1188, "text": "You can try to run the following code to to sort an array in ascending order." }, { "code": null, "e": 1277, "s": 1266, "text": " Live Demo" }, { "code": null, "e": 1751, "s": 1277, "text": "using System;\nnamespace Demo {\n public class MyApplication {\n public static void Main(string[] args) {\n int[] list = {98, 23, 97, 36, 77};\n Console.WriteLine(\"Original Unsorted List\");\n foreach (int i in list) {\n Console.Write(i + \" \");\n }\n Array.Sort(list);\n Console.WriteLine(\"\\nSorted List\");\n for(int i=0; i<list.Length; i++) {\n Console.Write(list[i] + \" \");\n }\n }\n }\n}" }, { "code": null, "e": 1816, "s": 1751, "text": "Original Unsorted List\n98 23 97 36 77\nSorted List\n23 36 77 97 98" } ]
How to Convert a String to Hexadecimal and vice versa format in java?
The toHexString() method of the Integer class accepts an integer as a parameter and returns a hexadecimal string. Therefore, to convert a string to a hexadecimal String − Get the desired String. Get the desired String. Create an empty StringBuffer object. Create an empty StringBuffer object. Convert it into a character array using the toCharArray() method of the String class. Convert it into a character array using the toCharArray() method of the String class. Traverse through the contents of the array created above, using a loop. Traverse through the contents of the array created above, using a loop. Within the loop convert each character of the array into an integer and pass it as a parameter to the toHexString() method of the Integer class. Within the loop convert each character of the array into an integer and pass it as a parameter to the toHexString() method of the Integer class. Append the resultant values to the StringBuffer object using the append() method of the StringBuffer class. Append the resultant values to the StringBuffer object using the append() method of the StringBuffer class. Finally, convert the StringBuffer object to a string using the toString() method of the StringBuffer class. Finally, convert the StringBuffer object to a string using the toString() method of the StringBuffer class. import java.util.Scanner; public class StringToHexadecimal { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a String value: "); String str = sc.next(); StringBuffer sb = new StringBuffer(); //Converting string to character array char ch[] = str.toCharArray(); for(int i = 0; i < ch.length; i++) { String hexString = Integer.toHexString(ch[i]); sb.append(hexString); } String result = sb.toString(); System.out.println(result); } } Enter a String value: Tutorialspoint 5475746f7269616c73706f696e74 In the same way to convert a hexadecimal (String) value to a String − Get the hexadecimal value (String). Get the hexadecimal value (String). Convert it into a character array using the toCharArray() method. Convert it into a character array using the toCharArray() method. Read each two characters from the array and convert them into a String. Read each two characters from the array and convert them into a String. Parse above obtained string into base 16 integer, cast it into a character. Parse above obtained string into base 16 integer, cast it into a character. Concat all the characters to a string. Concat all the characters to a string. import java.util.Scanner; public class HexadecimalToString { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a Hexadecimal value: "); String str = sc.next(); String result = new String(); char[] charArray = str.toCharArray(); for(int i = 0; i < charArray.length; i=i+2) { String st = ""+charArray[i]+""+charArray[i+1]; char ch = (char)Integer.parseInt(st, 16); result = result + ch; } System.out.println(result); } } Enter a Hexadecimal value: 5475746f7269616c73706f696e74 Tutorialspoint
[ { "code": null, "e": 1233, "s": 1062, "text": "The toHexString() method of the Integer class accepts an integer as a parameter and returns a hexadecimal string. Therefore, to convert a string to a hexadecimal String −" }, { "code": null, "e": 1257, "s": 1233, "text": "Get the desired String." }, { "code": null, "e": 1281, "s": 1257, "text": "Get the desired String." }, { "code": null, "e": 1318, "s": 1281, "text": "Create an empty StringBuffer object." }, { "code": null, "e": 1355, "s": 1318, "text": "Create an empty StringBuffer object." }, { "code": null, "e": 1441, "s": 1355, "text": "Convert it into a character array using the toCharArray() method of the String class." }, { "code": null, "e": 1527, "s": 1441, "text": "Convert it into a character array using the toCharArray() method of the String class." }, { "code": null, "e": 1599, "s": 1527, "text": "Traverse through the contents of the array created above, using a loop." }, { "code": null, "e": 1671, "s": 1599, "text": "Traverse through the contents of the array created above, using a loop." }, { "code": null, "e": 1816, "s": 1671, "text": "Within the loop convert each character of the array into an integer and pass it as a parameter to the toHexString() method of the Integer class." }, { "code": null, "e": 1961, "s": 1816, "text": "Within the loop convert each character of the array into an integer and pass it as a parameter to the toHexString() method of the Integer class." }, { "code": null, "e": 2069, "s": 1961, "text": "Append the resultant values to the StringBuffer object using the append() method of the StringBuffer class." }, { "code": null, "e": 2177, "s": 2069, "text": "Append the resultant values to the StringBuffer object using the append() method of the StringBuffer class." }, { "code": null, "e": 2285, "s": 2177, "text": "Finally, convert the StringBuffer object to a string using the toString() method of the StringBuffer class." }, { "code": null, "e": 2393, "s": 2285, "text": "Finally, convert the StringBuffer object to a string using the toString() method of the StringBuffer class." }, { "code": null, "e": 2965, "s": 2393, "text": "import java.util.Scanner;\npublic class StringToHexadecimal {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a String value: \");\n String str = sc.next();\n StringBuffer sb = new StringBuffer();\n //Converting string to character array\n char ch[] = str.toCharArray();\n for(int i = 0; i < ch.length; i++) {\n String hexString = Integer.toHexString(ch[i]);\n sb.append(hexString);\n }\n String result = sb.toString();\n System.out.println(result);\n }\n}" }, { "code": null, "e": 3031, "s": 2965, "text": "Enter a String value:\nTutorialspoint\n5475746f7269616c73706f696e74" }, { "code": null, "e": 3101, "s": 3031, "text": "In the same way to convert a hexadecimal (String) value to a String −" }, { "code": null, "e": 3137, "s": 3101, "text": "Get the hexadecimal value (String)." }, { "code": null, "e": 3173, "s": 3137, "text": "Get the hexadecimal value (String)." }, { "code": null, "e": 3239, "s": 3173, "text": "Convert it into a character array using the toCharArray() method." }, { "code": null, "e": 3305, "s": 3239, "text": "Convert it into a character array using the toCharArray() method." }, { "code": null, "e": 3377, "s": 3305, "text": "Read each two characters from the array and convert them into a String." }, { "code": null, "e": 3449, "s": 3377, "text": "Read each two characters from the array and convert them into a String." }, { "code": null, "e": 3525, "s": 3449, "text": "Parse above obtained string into base 16 integer, cast it into a character." }, { "code": null, "e": 3601, "s": 3525, "text": "Parse above obtained string into base 16 integer, cast it into a character." }, { "code": null, "e": 3640, "s": 3601, "text": "Concat all the characters to a string." }, { "code": null, "e": 3679, "s": 3640, "text": "Concat all the characters to a string." }, { "code": null, "e": 4233, "s": 3679, "text": "import java.util.Scanner;\npublic class HexadecimalToString {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a Hexadecimal value: \");\n String str = sc.next();\n String result = new String();\n char[] charArray = str.toCharArray();\n for(int i = 0; i < charArray.length; i=i+2) {\n String st = \"\"+charArray[i]+\"\"+charArray[i+1];\n char ch = (char)Integer.parseInt(st, 16);\n result = result + ch;\n }\n System.out.println(result);\n }\n}" }, { "code": null, "e": 4304, "s": 4233, "text": "Enter a Hexadecimal value:\n5475746f7269616c73706f696e74\nTutorialspoint" } ]
Predictive Maintenance: detect Faults from Sensors with CNN | by Marco Cerliani | Towards Data Science
In Machine Learning the topic of Predictive Maintenance is becoming more popular with the passage of time. The challenges are not easy and very heterogenous: it’s useful to have a good knowledge of the domain or to be in touch with people who know how the underlying system works. For these reasons when a data scientist engages himself in this new field of battle has to follow a linear and rational approach, keeping in mind that the easiest solutions are always the better ones. In this article, we will take a look at a classification problem. We will apply a simple but very powerful model made with CNN in Keras and we will try to give a visual explanation of our results. I decided to take a dataset from the evergreen UCI repository (Condition monitoring of hydraulic systems). The data set was experimentally obtained with a hydraulic test rig. This test rig consists of a primary working and a secondary cooling-filtration circuit which are connected via the oil tank. The system cyclically repeats constant load cycles (duration 60 seconds) and measures process values such as pressures, volume flows and temperatures while the condition of four hydraulic components (cooler, valve, pump and accumulator) is quantitatively varied. We can image to have a hydraulic pipe system which cyclically receives impulse due to e.g. the transition of particular type of liquid in the pipeline. This phenomenon lasts 60 seconds and was measured by different sensors (Sensor Physical quantity Unit Sampling rate, PS1 Pressure bar, PS2 Pressure bar, PS3 Pressure bar, PS4 Pressure bar, PS5 Pressure bar, PS6 Pressure bar, EPS1 Motor power, FS1 Volume flow, FS2 Volume flow, TS1 Temperature, TS2 Temperature, TS3 Temperature, TS4 Temperature, VS1 Vibration, CE Cooling efficiency, CP Cooling power, SE Efficiency factor) with different Hz frequencies. Our purpose is to predict the condition of four hydraulic components which compose the pipeline. These target condition values are annotated in the form of integer values (easy to encode) and say us if a particular component is close to fail for every cycle. The values measured by each sensor are available in a specific txt file, wherein each row represents a cycle in the form of a time series. I’ve decided to take into account the data coming from the Temperature Sensors (TS1, TS2, TS3, TS4) measured with a frequency of 1 Hz (60 observations for every single cycle). label = pd.read_csv(path+'profile.txt', sep='\t', header=None)label.columns = ['Cooler','Valve','Pump','Accumulator','Flag']data = ['TS1.txt','TS2.txt','TS3.txt','TS4.txt']df = pd.DataFrame()for txt in data: read_df = pd.read_csv(path+txt, sep='\t', header=None) df = df.append(read_df) For the first cycle we have these time series from the Temperature Sensors: In order to capture interesting features and not obvious correlations from the series at our disposal, we have decided to adopt a 1D CNN. This kind of model suits very well the analysis of time sequences of sensors and imposes to reshape the data in short fixed-length segments. Developing this workflow, I took inspiration from this post which adopts a very useful approach. I picked the same CNN described on the Keras website and refreshed the parameters. The model was built to classify the status of the Cooler component giving as input only the time series of temperature in array format (t_periods x n_sensor for every single cycle). num_sensors = 4TIME_PERIODS = 60BATCH_SIZE = 16EPOCHS = 10model_m = Sequential()model_m.add(Conv1D(100, 6, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))model_m.add(Conv1D(100, 6, activation='relu'))model_m.add(MaxPooling1D(3))model_m.add(Conv1D(160, 6, activation='relu'))model_m.add(Conv1D(160, 6, activation='relu'))model_m.add(GlobalAveragePooling1D(name='G_A_P_1D'))model_m.add(Dropout(0.5))model_m.add(Dense(3, activation='softmax'))print(model_m.summary())model_m.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])history = model_m.fit(X_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=0.2, verbose=2) In this case, with only 10 epochs we are able to achieve incredible results! Train on 1411 samples, validate on 353 samplesEpoch 1/101411/1411 [==============================] - 2s 2ms/step - loss: 0.2581 - acc: 0.9391 - val_loss: 0.0867 - val_acc: 0.9830Epoch 2/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1111 - acc: 0.9731 - val_loss: 0.0686 - val_acc: 0.9830Epoch 3/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0925 - acc: 0.9759 - val_loss: 0.0674 - val_acc: 0.9802Epoch 4/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1093 - acc: 0.9731 - val_loss: 0.0769 - val_acc: 0.9830Epoch 5/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1022 - acc: 0.9731 - val_loss: 0.0666 - val_acc: 0.9802Epoch 6/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0947 - acc: 0.9773 - val_loss: 0.0792 - val_acc: 0.9830Epoch 7/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0984 - acc: 0.9794 - val_loss: 0.0935 - val_acc: 0.9830Epoch 8/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0976 - acc: 0.9738 - val_loss: 0.0756 - val_acc: 0.9802Epoch 9/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0957 - acc: 0.9780 - val_loss: 0.0752 - val_acc: 0.9830Epoch 10/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1114 - acc: 0.9738 - val_loss: 0.0673 - val_acc: 0.9802 Making the prediction on the test data the model reaches an ACCURACY of 0.9909%. KPIs in each class are awesome! This result is particularly important for class 3 (component Cooler ‘ close to total failure’) because in this way we are able to detect and prevent possible faults in the system. If we want to have a general overview of the system status and see the incredible goodness of our model, might be useful to see a graphic representation. To reach this target we reutilize the CNN that we’ve built above to make a decoder and extract clever features from the time series of every single cycle. With Keras this is possible in one single line of code: emb_model = Model(inputs=model_m.input, outputs=model_m.get_layer('G_A_P_1D').output) The new model is a decoder which receives as input data in the same format as the NN we utilized for the classification task (t_periods x n_sensor for every single cycle) and returns ‘prediction’ in form of embeddings coming from the GlobalAveragePooling1D layer with relative dimension (a row of 160 embedding variables for every single cycle). Computing the prediction with our encoder on the test data, adopting a technique to reduce dimensions (like PCA or T-SNE), and plotting the results we can see this magic: serie_features = emb_model.predict(X_test)tsne = TSNE(n_components=2, random_state=42, n_iter=300, perplexity=5)T = tsne.fit_transform(serie_features)plt.figure(figsize=(16,9))colors = {0:'red', 1:'blue', 2:'yellow'}plt.scatter(T.T[0], T.T[1], c=[colors[i] for i in np.argmax(y_test, axis=1)]) plt.show() WOOW!!! This graph tells the truth! Each dot represents a cycle in the test set and the relative color is the target class of the Cooler condition. It’s possible to see how the distinction among target values of the Cooler component is well defined. This approach is a key indicator of the performance of our model. In this post, we try to solve a problem of Predictive Maintenance, in the form of a classification task for time series with CNN. A strong model with impressive performance was developed. We try to give also a visual representation of the results. It’s important to underline the power of CNN not only in the case of prediction but also as an instrument to detect invisible relations among data. If you are interested in the topic, I suggest: Predictive Maintenance with LSTM Siamese Network Predictive Maintenance: detect Faults from Sensors with CRNN and Spectrograms Predictive Maintenance with ResNet CHECK MY GITHUB REPO Keep in touch: Linkedin
[ { "code": null, "e": 654, "s": 172, "text": "In Machine Learning the topic of Predictive Maintenance is becoming more popular with the passage of time. The challenges are not easy and very heterogenous: it’s useful to have a good knowledge of the domain or to be in touch with people who know how the underlying system works. For these reasons when a data scientist engages himself in this new field of battle has to follow a linear and rational approach, keeping in mind that the easiest solutions are always the better ones." }, { "code": null, "e": 851, "s": 654, "text": "In this article, we will take a look at a classification problem. We will apply a simple but very powerful model made with CNN in Keras and we will try to give a visual explanation of our results." }, { "code": null, "e": 958, "s": 851, "text": "I decided to take a dataset from the evergreen UCI repository (Condition monitoring of hydraulic systems)." }, { "code": null, "e": 1414, "s": 958, "text": "The data set was experimentally obtained with a hydraulic test rig. This test rig consists of a primary working and a secondary cooling-filtration circuit which are connected via the oil tank. The system cyclically repeats constant load cycles (duration 60 seconds) and measures process values such as pressures, volume flows and temperatures while the condition of four hydraulic components (cooler, valve, pump and accumulator) is quantitatively varied." }, { "code": null, "e": 2020, "s": 1414, "text": "We can image to have a hydraulic pipe system which cyclically receives impulse due to e.g. the transition of particular type of liquid in the pipeline. This phenomenon lasts 60 seconds and was measured by different sensors (Sensor Physical quantity Unit Sampling rate, PS1 Pressure bar, PS2 Pressure bar, PS3 Pressure bar, PS4 Pressure bar, PS5 Pressure bar, PS6 Pressure bar, EPS1 Motor power, FS1 Volume flow, FS2 Volume flow, TS1 Temperature, TS2 Temperature, TS3 Temperature, TS4 Temperature, VS1 Vibration, CE Cooling efficiency, CP Cooling power, SE Efficiency factor) with different Hz frequencies." }, { "code": null, "e": 2279, "s": 2020, "text": "Our purpose is to predict the condition of four hydraulic components which compose the pipeline. These target condition values are annotated in the form of integer values (easy to encode) and say us if a particular component is close to fail for every cycle." }, { "code": null, "e": 2418, "s": 2279, "text": "The values measured by each sensor are available in a specific txt file, wherein each row represents a cycle in the form of a time series." }, { "code": null, "e": 2594, "s": 2418, "text": "I’ve decided to take into account the data coming from the Temperature Sensors (TS1, TS2, TS3, TS4) measured with a frequency of 1 Hz (60 observations for every single cycle)." }, { "code": null, "e": 2887, "s": 2594, "text": "label = pd.read_csv(path+'profile.txt', sep='\\t', header=None)label.columns = ['Cooler','Valve','Pump','Accumulator','Flag']data = ['TS1.txt','TS2.txt','TS3.txt','TS4.txt']df = pd.DataFrame()for txt in data: read_df = pd.read_csv(path+txt, sep='\\t', header=None) df = df.append(read_df)" }, { "code": null, "e": 2963, "s": 2887, "text": "For the first cycle we have these time series from the Temperature Sensors:" }, { "code": null, "e": 3242, "s": 2963, "text": "In order to capture interesting features and not obvious correlations from the series at our disposal, we have decided to adopt a 1D CNN. This kind of model suits very well the analysis of time sequences of sensors and imposes to reshape the data in short fixed-length segments." }, { "code": null, "e": 3604, "s": 3242, "text": "Developing this workflow, I took inspiration from this post which adopts a very useful approach. I picked the same CNN described on the Keras website and refreshed the parameters. The model was built to classify the status of the Cooler component giving as input only the time series of temperature in array format (t_periods x n_sensor for every single cycle)." }, { "code": null, "e": 4280, "s": 3604, "text": "num_sensors = 4TIME_PERIODS = 60BATCH_SIZE = 16EPOCHS = 10model_m = Sequential()model_m.add(Conv1D(100, 6, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))model_m.add(Conv1D(100, 6, activation='relu'))model_m.add(MaxPooling1D(3))model_m.add(Conv1D(160, 6, activation='relu'))model_m.add(Conv1D(160, 6, activation='relu'))model_m.add(GlobalAveragePooling1D(name='G_A_P_1D'))model_m.add(Dropout(0.5))model_m.add(Dense(3, activation='softmax'))print(model_m.summary())model_m.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])history = model_m.fit(X_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=0.2, verbose=2)" }, { "code": null, "e": 4357, "s": 4280, "text": "In this case, with only 10 epochs we are able to achieve incredible results!" }, { "code": null, "e": 5725, "s": 4357, "text": "Train on 1411 samples, validate on 353 samplesEpoch 1/101411/1411 [==============================] - 2s 2ms/step - loss: 0.2581 - acc: 0.9391 - val_loss: 0.0867 - val_acc: 0.9830Epoch 2/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1111 - acc: 0.9731 - val_loss: 0.0686 - val_acc: 0.9830Epoch 3/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0925 - acc: 0.9759 - val_loss: 0.0674 - val_acc: 0.9802Epoch 4/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1093 - acc: 0.9731 - val_loss: 0.0769 - val_acc: 0.9830Epoch 5/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1022 - acc: 0.9731 - val_loss: 0.0666 - val_acc: 0.9802Epoch 6/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0947 - acc: 0.9773 - val_loss: 0.0792 - val_acc: 0.9830Epoch 7/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0984 - acc: 0.9794 - val_loss: 0.0935 - val_acc: 0.9830Epoch 8/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0976 - acc: 0.9738 - val_loss: 0.0756 - val_acc: 0.9802Epoch 9/101411/1411 [==============================] - 2s 1ms/step - loss: 0.0957 - acc: 0.9780 - val_loss: 0.0752 - val_acc: 0.9830Epoch 10/101411/1411 [==============================] - 2s 1ms/step - loss: 0.1114 - acc: 0.9738 - val_loss: 0.0673 - val_acc: 0.9802" }, { "code": null, "e": 5806, "s": 5725, "text": "Making the prediction on the test data the model reaches an ACCURACY of 0.9909%." }, { "code": null, "e": 6018, "s": 5806, "text": "KPIs in each class are awesome! This result is particularly important for class 3 (component Cooler ‘ close to total failure’) because in this way we are able to detect and prevent possible faults in the system." }, { "code": null, "e": 6383, "s": 6018, "text": "If we want to have a general overview of the system status and see the incredible goodness of our model, might be useful to see a graphic representation. To reach this target we reutilize the CNN that we’ve built above to make a decoder and extract clever features from the time series of every single cycle. With Keras this is possible in one single line of code:" }, { "code": null, "e": 6469, "s": 6383, "text": "emb_model = Model(inputs=model_m.input, outputs=model_m.get_layer('G_A_P_1D').output)" }, { "code": null, "e": 6815, "s": 6469, "text": "The new model is a decoder which receives as input data in the same format as the NN we utilized for the classification task (t_periods x n_sensor for every single cycle) and returns ‘prediction’ in form of embeddings coming from the GlobalAveragePooling1D layer with relative dimension (a row of 160 embedding variables for every single cycle)." }, { "code": null, "e": 6986, "s": 6815, "text": "Computing the prediction with our encoder on the test data, adopting a technique to reduce dimensions (like PCA or T-SNE), and plotting the results we can see this magic:" }, { "code": null, "e": 7291, "s": 6986, "text": "serie_features = emb_model.predict(X_test)tsne = TSNE(n_components=2, random_state=42, n_iter=300, perplexity=5)T = tsne.fit_transform(serie_features)plt.figure(figsize=(16,9))colors = {0:'red', 1:'blue', 2:'yellow'}plt.scatter(T.T[0], T.T[1], c=[colors[i] for i in np.argmax(y_test, axis=1)]) plt.show()" }, { "code": null, "e": 7607, "s": 7291, "text": "WOOW!!! This graph tells the truth! Each dot represents a cycle in the test set and the relative color is the target class of the Cooler condition. It’s possible to see how the distinction among target values of the Cooler component is well defined. This approach is a key indicator of the performance of our model." }, { "code": null, "e": 8003, "s": 7607, "text": "In this post, we try to solve a problem of Predictive Maintenance, in the form of a classification task for time series with CNN. A strong model with impressive performance was developed. We try to give also a visual representation of the results. It’s important to underline the power of CNN not only in the case of prediction but also as an instrument to detect invisible relations among data." }, { "code": null, "e": 8050, "s": 8003, "text": "If you are interested in the topic, I suggest:" }, { "code": null, "e": 8099, "s": 8050, "text": "Predictive Maintenance with LSTM Siamese Network" }, { "code": null, "e": 8177, "s": 8099, "text": "Predictive Maintenance: detect Faults from Sensors with CRNN and Spectrograms" }, { "code": null, "e": 8212, "s": 8177, "text": "Predictive Maintenance with ResNet" }, { "code": null, "e": 8233, "s": 8212, "text": "CHECK MY GITHUB REPO" } ]
What is the scope of an internal variable of a class in C#?
Internal variable is set using the internal access specifier. internal double length; internal double width; Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined. Live Demo using System; namespace RectangleApplication { class Rectangle { //member variables internal double length; internal double width; double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } //end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5; r.Display(); Console.ReadLine(); } } } Length: 4.5 Width: 3.5 Area: 15.75
[ { "code": null, "e": 1124, "s": 1062, "text": "Internal variable is set using the internal access specifier." }, { "code": null, "e": 1171, "s": 1124, "text": "internal double length;\ninternal double width;" }, { "code": null, "e": 1317, "s": 1171, "text": "Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined." }, { "code": null, "e": 1328, "s": 1317, "text": " Live Demo" }, { "code": null, "e": 1985, "s": 1328, "text": "using System;\nnamespace RectangleApplication {\n class Rectangle {\n //member variables\n internal double length;\n internal double width;\n double GetArea() {\n return length * width;\n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n } //end class Rectangle\n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.length = 4.5;\n r.width = 3.5;\n r.Display();\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2020, "s": 1985, "text": "Length: 4.5\nWidth: 3.5\nArea: 15.75" } ]
Google Guice - Quick Guide
Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google. Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent. Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this − public class TextEditor { private SpellChecker spellChecker; public TextEditor() { spellChecker = new SpellChecker(); } } What we've done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this − public class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } } Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation. Dependency Injection is controlled by the Guice Bindings. Guice uses bindings to map object types to their actual implementations. These bindings are defined a module. A module is a collection of bindings as shown below: public class TextEditorModule extends AbstractModule { @Override protected void configure() { /* * Bind SpellChecker binding to WinWordSpellChecker implementation * whenever spellChecker dependency is used. */ bind(SpellChecker.class).to(WinWordSpellChecker.class); } } The Module is the core building block for an Injector which is Guice's object-graph builder. First step is to create an injector and then we can use the injector to get the objects. public static void main(String[] args) { /* * Guice.createInjector() takes Modules, and returns a new Injector * instance. This method is to be called once during application startup. */ Injector injector = Guice.createInjector(new TextEditorModule()); /* * Build object using injector */ TextEditor textEditor = injector.getInstance(TextEditor.class); } In above example, TextEditor class object graph is constructed by Guice and this graph contains TextEditor object and its dependency as WinWordSpellChecker object. If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment. Java SE is freely available from the link Download Java. So you download a version based on your operating system. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories − We are assuming that you have installed Java in c:\Program Files\java\jdk directory − Right-click on 'My Computer' and select 'Properties'. Right-click on 'My Computer' and select 'Properties'. Click on the 'Environment variables' button under the 'Advanced' tab. Click on the 'Environment variables' button under the 'Advanced' tab. Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. We are assuming that you have installed Java in c:\Program Files\java\jdk directory − Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin' Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin' Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH' To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following − Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html. Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. Download the latest version of Google Guice and related jar files. Google Guice 4.0 Google Guice 4.0 AOP Alliance 1.0 AOP Alliance 1.0 Guava 16.0.1 Guava 16.0.1 javax.inject 1.0 javax.inject 1.0 At the time of writing this tutorial, we have copied them into C:\>Google folder. Set the CLASSPATH environment variable to point to the Guice jar location. Assuming, you have stored Guice and related jars in Google folder on various Operating Systems as follows. Let's create a sample console based application where we'll demonstrate dependency injection using Guice binding mechanism step by step. //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } Compile and run the file, you will see the following output. Inside checkSpelling. In Linked bindings, Guice maps a type to its implementation. In below example, we've mapped SpellChecker interface with its implementation SpellCheckerImpl. bind(SpellChecker.class).to(SpellCheckerImpl.class); We can also mapped the concrete class to its subclass. See the example below: bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class); Here we've chained the bindings. Let's see the result in complete example. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } //subclass of SpellCheckerImpl class WinWordSpellCheckerImpl extends SpellCheckerImpl{ @Override public void checkSpelling() { System.out.println("Inside WinWordSpellCheckerImpl.checkSpelling." ); } } Compile and run the file, you will see the following output. Inside WinWordSpellCheckerImpl.checkSpelling. As we can bind a type with its implementation. In case we want to map a type with multiple implmentations, we can create custom annotation as well. See the below example to understand the concept. @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) @interface WinWord {} @BindingAnnotation - Marks annotation as binding annotation. @BindingAnnotation - Marks annotation as binding annotation. @Target - Marks applicability of annotation. @Target - Marks applicability of annotation. @Retention - Marks availablility of annotation as runtime. @Retention - Marks availablility of annotation as runtime. bind(SpellChecker.class).annotatedWith(WinWord.class).to(WinWordSpellCheckerImpl.class); @Inject public TextEditor(@WinWord SpellChecker spellChecker) { this.spellChecker = spellChecker; } Create a java class named GuiceTester. GuiceTester.java import java.lang.annotation.Target; import com.google.inject.AbstractModule; import com.google.inject.BindingAnnotation; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) @interface WinWord {} public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(@WinWord SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).annotatedWith(WinWord.class) .to(WinWordSpellCheckerImpl.class); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } //subclass of SpellCheckerImpl class WinWordSpellCheckerImpl extends SpellCheckerImpl{ @Override public void checkSpelling() { System.out.println("Inside WinWordSpellCheckerImpl.checkSpelling." ); } } Compile and run the file, you will see the following output. Inside WinWordSpellCheckerImpl.checkSpelling. Guice provides another way also to map bindings without creating a custom annoation. It allows so using @Named annotation. bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice")).to(OpenOfficeWordSpellCheckerImpl.class); @Inject public TextEditor(@Named("OpenOffice") SpellChecker spellChecker) { this.spellChecker = spellChecker; } Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(@Named("OpenOffice") SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice")) .to(OpenOfficeWordSpellCheckerImpl.class); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } //subclass of SpellCheckerImpl class OpenOfficeWordSpellCheckerImpl extends SpellCheckerImpl{ @Override public void checkSpelling() { System.out.println("Inside OpenOfficeWordSpellCheckerImpl.checkSpelling." ); } } Compile and run the file, you will see the following output. Inside OpenOfficeWordSpellCheckerImpl.checkSpelling. Guice provides a way to create bindings with value objects or constants. Consider the case where we want to configure JDBC url. @Inject public void connectDatabase(@Named("JBDC") String dbUrl) { //... } This can be achived using toInstance() method. bind(String.class).annotatedWith(Names.named("JBDC")).toInstance("jdbc:mysql://localhost:5326/emp"); Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeConnection(); } } class TextEditor { private String dbUrl; @Inject public TextEditor(@Named("JDBC") String dbUrl) { this.dbUrl = dbUrl; } public void makeConnection(){ System.out.println(dbUrl); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(String.class) .annotatedWith(Names.named("JDBC")) .toInstance("jdbc:mysql://localhost:5326/emp"); } } Compile and run the file, you will see the following output. jdbc:mysql://localhost:5326/emp Guice provides a way to create bindings with complex objects using @provides method. @Provides public SpellChecker provideSpellChecker(){ String dbUrl = "jdbc:mysql://localhost:5326/emp"; String user = "user"; int timeout = 100; SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout); return SpellChecker; } This methos is being part of Binding Module and provides the complex object to be mapped. See the complete example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provides; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() {} @Provides public SpellChecker provideSpellChecker(){ String dbUrl = "jdbc:mysql://localhost:5326/emp"; String user = "user"; int timeout = 100; SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout); return SpellChecker; } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { private String dbUrl; private String user; private Integer timeout; @Inject public SpellCheckerImpl(String dbUrl, String user, Integer timeout){ this.dbUrl = dbUrl; this.user = user; this.timeout = timeout; } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); System.out.println(user); System.out.println(timeout); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp user 100 As @provides method becomes more complex, these methods can be moved to seperate classes using Provider interface. class SpellCheckerProvider implements Provider<SpellChecker>{ @Override public SpellChecker get() { String dbUrl = "jdbc:mysql://localhost:5326/emp"; String user = "user"; int timeout = 100; SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout); return SpellChecker; } } Next step is to map the provider to type. bind(SpellChecker.class).toProvider(SpellCheckerProvider.class); See the complete example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class) .toProvider(SpellCheckerProvider.class); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { private String dbUrl; private String user; private Integer timeout; @Inject public SpellCheckerImpl(String dbUrl, String user, Integer timeout){ this.dbUrl = dbUrl; this.user = user; this.timeout = timeout; } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); System.out.println(user); System.out.println(timeout); } } class SpellCheckerProvider implements Provider<SpellChecker>{ @Override public SpellChecker get() { String dbUrl = "jdbc:mysql://localhost:5326/emp"; String user = "user"; int timeout = 100; SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout); return SpellChecker; } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp user 100 Guice provides a way to create bindings with specific constructor of an object using toConstructor() method. @Override protected void configure() { try { bind(SpellChecker.class) .toConstructor(SpellCheckerImpl.class.getConstructor(String.class)); } catch (NoSuchMethodException | SecurityException e) { System.out.println("Required constructor missing"); } } See the complete example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { try { bind(SpellChecker.class) .toConstructor(SpellCheckerImpl.class.getConstructor(String.class)); } catch (NoSuchMethodException | SecurityException e) { System.out.println("Required constructor missing"); } bind(String.class) .annotatedWith(Names.named("JDBC")) .toInstance("jdbc:mysql://localhost:5326/emp"); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { private String dbUrl; public SpellCheckerImpl(){} public SpellCheckerImpl(@Named("JDBC") String dbUrl){ this.dbUrl = dbUrl; } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp Guice provides inbuilt binding for java.util.logging.Logger class. Logger's name is automatically set to the name of the class into which the Logger is injected. See the example below. Create a java class named GuiceTester. GuiceTester.java import java.util.logging.Logger; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private Logger logger; @Inject public TextEditor( Logger logger) { this.logger = logger; } public void makeSpellCheck(){ logger.info("In TextEditor.makeSpellCheck() method"); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { } } Compile and run the file, you will see the following output. Dec 20, 2017 12:51:05 PM TextEditor makeSpellCheck INFO: In TextEditor.makeSpellCheck() method As bindings are defined in Binding Module, Guice uses them whenever it needs to inject dependencies. In case bindings are not present, it can attempt to create just-in-time bindings. Bindings present in binding module are called explicit bindings and are of higher precedence whereas just-in-time bindings are called implicit bindings. If both type of bindings are present, explicit bindings are considered for mapping. Following are the examples of three types of Just-in-time bindings. Non-private, No-argument constructors are eligible for just-in-time bindings. Another way is to annotate a constructor with @Inject annotation. See the example: Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); bind(String.class) .annotatedWith(Names.named("JDBC")) .toInstance("jdbc:mysql://localhost:5326/emp"); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Inject @Named("JDBC") private String dbUrl; public SpellCheckerImpl(){} @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp @ImplementatedBy annotation tells the guice about the implementation class. No binding is required in Binding Module in such a case. See the example: Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(String.class) .annotatedWith(Names.named("JDBC")) .toInstance("jdbc:mysql://localhost:5326/emp"); } } @ImplementedBy(SpellCheckerImpl.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Inject @Named("JDBC") private String dbUrl; public SpellCheckerImpl(){} @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp @ProvidedBy annotation tells the guice about the provider of implementation class. No binding is required in Binding Module in such a case. See the example: Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.ProvidedBy; import com.google.inject.Provider; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { } } @ProvidedBy(SpellCheckerProvider.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { private String dbUrl; private String user; private Integer timeout; @Inject public SpellCheckerImpl(String dbUrl, String user, Integer timeout){ this.dbUrl = dbUrl; this.user = user; this.timeout = timeout; } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); System.out.println(user); System.out.println(timeout); } } class SpellCheckerProvider implements Provider<SpellChecker>{ @Override public SpellChecker get() { String dbUrl = "jdbc:mysql://localhost:5326/emp"; String user = "user"; int timeout = 100; SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout); return SpellChecker; } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp user 100 Injection is a process of injecting dependeny into an object. Constructor injection is quite common. In this process, dependency is injected as argument to the constructor. See the example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } Compile and run the file, you will see the following output. Inside checkSpelling. Injection is a process of injecting dependeny into an object. Method injection is used to set value object as dependency to the object. See the example below. Create a java class named GuiceTester. import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(String.class) .annotatedWith(Names.named("JDBC")) .toInstance("jdbc:mysql://localhost:5326/emp"); } } @ImplementedBy(SpellCheckerImpl.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { private String dbUrl; public SpellCheckerImpl(){} @Inject public void setDbUrl(@Named("JDBC") String dbUrl){ this.dbUrl = dbUrl; } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp Injection is a process of injecting dependeny into an object. Field injection is used to set value object as dependency to the field of an object. See the example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(String.class) .annotatedWith(Names.named("JDBC")) .toInstance("jdbc:mysql://localhost:5326/emp"); } } @ImplementedBy(SpellCheckerImpl.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Inject @Named("JDBC") private String dbUrl; public SpellCheckerImpl(){} @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp Injection is a process of injecting dependeny into an object. Optional injection means injecting the dependency if exists. Method and Field injections may be optionally dependent and should have some default value if dependency is not present. See the example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() {} } @ImplementedBy(SpellCheckerImpl.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { private String dbUrl = "jdbc:mysql://localhost:5326/emp"; public SpellCheckerImpl(){} @Inject(optional=true) public void setDbUrl(@Named("JDBC") String dbUrl){ this.dbUrl = dbUrl; } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp Injection is a process of injecting dependeny into an object. Method and field injections can be used to initialize using exiting object using injector.injectMembers() method. See the example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); SpellChecker spellChecker = new SpellCheckerImpl(); injector.injectMembers(spellChecker); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public void setSpellChecker(SpellChecker spellChecker){ this.spellChecker = spellChecker; } public TextEditor() { } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { } } @ImplementedBy(SpellCheckerImpl.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { public SpellCheckerImpl(){} @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } Compile and run the file, you will see the following output. Inside checkSpelling. Guice returns a new instance every time when it supplies a value as its default behaviour. It is configurable via scopes. Following are the scopes that Guice supports: @Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe. @Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe. @SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe. @SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe. @RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe. @RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe. Following are the ways to apply scopes. @Singleton class SpellCheckerImpl implements SpellChecker { public SpellCheckerImpl(){} @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } bind(SpellChecker.class).to(SpellCheckerImpl.class).in(Singleton.class); @Provides @Singleton public SpellChecker provideSpellChecker(){ String dbUrl = "jdbc:mysql://localhost:5326/emp"; String user = "user"; int timeout = 100; SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout); return SpellChecker; } Let's see the Scope at class level in action. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); SpellChecker spellChecker = new SpellCheckerImpl(); injector.injectMembers(spellChecker); TextEditor editor = injector.getInstance(TextEditor.class); System.out.println(editor.getSpellCheckerId()); TextEditor editor1 = injector.getInstance(TextEditor.class); System.out.println(editor1.getSpellCheckerId()); } } class TextEditor { private SpellChecker spellChecker; @Inject public void setSpellChecker(SpellChecker spellChecker){ this.spellChecker = spellChecker; } public TextEditor() { } public void makeSpellCheck(){ spellChecker.checkSpelling(); } public double getSpellCheckerId(){ return spellChecker.getId(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } interface SpellChecker { public double getId(); public void checkSpelling(); } @Singleton class SpellCheckerImpl implements SpellChecker { double id; public SpellCheckerImpl(){ id = Math.random(); } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } @Override public double getId() { return id; } } Compile and run the file, you may see the following output. 0.3055839187063575 0.3055839187063575 Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); SpellChecker spellChecker = new SpellCheckerImpl(); injector.injectMembers(spellChecker); TextEditor editor = injector.getInstance(TextEditor.class); System.out.println(editor.getSpellCheckerId()); TextEditor editor1 = injector.getInstance(TextEditor.class); System.out.println(editor1.getSpellCheckerId()); } } class TextEditor { private SpellChecker spellChecker; @Inject public void setSpellChecker(SpellChecker spellChecker){ this.spellChecker = spellChecker; } public TextEditor() { } public void makeSpellCheck(){ spellChecker.checkSpelling(); } public double getSpellCheckerId(){ return spellChecker.getId(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); } } interface SpellChecker { public double getId(); public void checkSpelling(); } class SpellCheckerImpl implements SpellChecker { double id; public SpellCheckerImpl(){ id = Math.random(); } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); } @Override public double getId() { return id; } } Compile and run the file, you may see the following output. 0.556007079571739 0.22095011760351602 AOP, Aspect oriented programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects like logging, auditing, declarative transactions, security, caching, etc. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other and AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others. Guice provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution. Matcher - Matcher is an interface to either accept or reject a value. In Guice AOP, we need two matchers: one to define which classes participate, and another for the methods of those classes. Matcher - Matcher is an interface to either accept or reject a value. In Guice AOP, we need two matchers: one to define which classes participate, and another for the methods of those classes. MethodInterceptor - MethodInterceptors are executed when a matching method is called. They can inspect the call: the method, its arguments, and the receiving instance. We can perform cross-cutting logic and then delegate to the underlying method. Finally, we may inspect the return value or exception and return. MethodInterceptor - MethodInterceptors are executed when a matching method is called. They can inspect the call: the method, its arguments, and the receiving instance. We can perform cross-cutting logic and then delegate to the underlying method. Finally, we may inspect the return value or exception and return. Create a java class named GuiceTester. GuiceTester.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.matcher.Matchers; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(SpellChecker.class).to(SpellCheckerImpl.class); bindInterceptor(Matchers.any(), Matchers.annotatedWith(CallTracker.class), new CallTrackerService()); } } //spell checker interface interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Override @CallTracker public void checkSpelling() { System.out.println("Inside checkSpelling." ); } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface CallTracker {} class CallTrackerService implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("Before " + invocation.getMethod().getName()); Object result = invocation.proceed(); System.out.println("After " + invocation.getMethod().getName()); return result; } } Compile and run the file, you may see the following output. Before checkSpelling Inside checkSpelling. After checkSpelling 27 Lectures 1.5 hours Lemuel Ogbunude Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 2102, "text": "Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google." }, { "code": null, "e": 2739, "s": 2239, "text": "Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent." }, { "code": null, "e": 2897, "s": 2739, "text": "Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this −" }, { "code": null, "e": 3038, "s": 2897, "text": "public class TextEditor {\n private SpellChecker spellChecker;\n \n public TextEditor() {\n spellChecker = new SpellChecker();\n }\n}" }, { "code": null, "e": 3207, "s": 3038, "text": "What we've done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this −" }, { "code": null, "e": 3383, "s": 3207, "text": "public class TextEditor {\n private SpellChecker spellChecker;\n \n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n}" }, { "code": null, "e": 3588, "s": 3383, "text": "Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation.\n" }, { "code": null, "e": 3810, "s": 3588, "text": "Dependency Injection is controlled by the Guice Bindings. Guice uses bindings to map object types to their actual implementations. These bindings are defined a module. A module is a collection of bindings as shown below:" }, { "code": null, "e": 4121, "s": 3810, "text": "public class TextEditorModule extends AbstractModule {\n @Override \n protected void configure() {\n /*\n * Bind SpellChecker binding to WinWordSpellChecker implementation \n * whenever spellChecker dependency is used.\n */\n bind(SpellChecker.class).to(WinWordSpellChecker.class);\n }\n}" }, { "code": null, "e": 4303, "s": 4121, "text": "The Module is the core building block for an Injector which is Guice's object-graph builder. First step is to create an injector and then we can use the injector to get the objects." }, { "code": null, "e": 4688, "s": 4303, "text": "public static void main(String[] args) {\n /*\n * Guice.createInjector() takes Modules, and returns a new Injector\n * instance. This method is to be called once during application startup.\n */\n Injector injector = Guice.createInjector(new TextEditorModule());\n /*\n * Build object using injector\n */\n TextEditor textEditor = injector.getInstance(TextEditor.class); \n}" }, { "code": null, "e": 4852, "s": 4688, "text": "In above example, TextEditor class object graph is constructed by Guice and this graph contains TextEditor object and its dependency as WinWordSpellChecker object." }, { "code": null, "e": 5083, "s": 4852, "text": "If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment." }, { "code": null, "e": 5198, "s": 5083, "text": "Java SE is freely available from the link Download Java. So you download a version based on your operating system." }, { "code": null, "e": 5426, "s": 5198, "text": "Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories −" }, { "code": null, "e": 5512, "s": 5426, "text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory −" }, { "code": null, "e": 5566, "s": 5512, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 5620, "s": 5566, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 5690, "s": 5620, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 5760, "s": 5690, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 5996, "s": 5760, "text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6232, "s": 5996, "text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6318, "s": 6232, "text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory −" }, { "code": null, "e": 6438, "s": 6318, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'" }, { "code": null, "e": 6558, "s": 6438, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'" }, { "code": null, "e": 6721, "s": 6558, "text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this." }, { "code": null, "e": 6861, "s": 6721, "text": "Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'" }, { "code": null, "e": 7026, "s": 6861, "text": "To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −" }, { "code": null, "e": 7145, "s": 7026, "text": "Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 7264, "s": 7145, "text": "Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 7387, "s": 7264, "text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html." }, { "code": null, "e": 7510, "s": 7387, "text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html." }, { "code": null, "e": 7642, "s": 7510, "text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 7774, "s": 7642, "text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 7841, "s": 7774, "text": "Download the latest version of Google Guice and related jar files." }, { "code": null, "e": 7858, "s": 7841, "text": "Google Guice 4.0" }, { "code": null, "e": 7875, "s": 7858, "text": "Google Guice 4.0" }, { "code": null, "e": 7892, "s": 7875, "text": "AOP Alliance 1.0" }, { "code": null, "e": 7909, "s": 7892, "text": "AOP Alliance 1.0" }, { "code": null, "e": 7922, "s": 7909, "text": "Guava 16.0.1" }, { "code": null, "e": 7935, "s": 7922, "text": "Guava 16.0.1" }, { "code": null, "e": 7952, "s": 7935, "text": "javax.inject 1.0" }, { "code": null, "e": 7969, "s": 7952, "text": "javax.inject 1.0" }, { "code": null, "e": 8051, "s": 7969, "text": "At the time of writing this tutorial, we have copied them into C:\\>Google folder." }, { "code": null, "e": 8233, "s": 8051, "text": "Set the CLASSPATH environment variable to point to the Guice jar location. Assuming, you have stored Guice and related jars in Google folder on various Operating Systems as follows." }, { "code": null, "e": 8370, "s": 8233, "text": "Let's create a sample console based application where we'll demonstrate dependency injection using Guice binding mechanism step by step." }, { "code": null, "e": 8455, "s": 8370, "text": "//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}" }, { "code": null, "e": 8641, "s": 8455, "text": "//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}" }, { "code": null, "e": 8818, "s": 8641, "text": "//Binding Module\nclass TextEditorModule extends AbstractModule {\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}" }, { "code": null, "e": 9057, "s": 8818, "text": "class TextEditor {\n private SpellChecker spellChecker;\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}" }, { "code": null, "e": 9123, "s": 9057, "text": "Injector injector = Guice.createInjector(new TextEditorModule());" }, { "code": null, "e": 9183, "s": 9123, "text": "TextEditor editor = injector.getInstance(TextEditor.class);" }, { "code": null, "e": 9209, "s": 9183, "text": "editor.makeSpellCheck(); " }, { "code": null, "e": 9248, "s": 9209, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 9265, "s": 9248, "text": "GuiceTester.java" }, { "code": null, "e": 10352, "s": 9265, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck(); \n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}" }, { "code": null, "e": 10413, "s": 10352, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 10436, "s": 10413, "text": "Inside checkSpelling.\n" }, { "code": null, "e": 10593, "s": 10436, "text": "In Linked bindings, Guice maps a type to its implementation. In below example, we've mapped SpellChecker interface with its implementation SpellCheckerImpl." }, { "code": null, "e": 10646, "s": 10593, "text": "bind(SpellChecker.class).to(SpellCheckerImpl.class);" }, { "code": null, "e": 10724, "s": 10646, "text": "We can also mapped the concrete class to its subclass. See the example below:" }, { "code": null, "e": 10788, "s": 10724, "text": "bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class);" }, { "code": null, "e": 10863, "s": 10788, "text": "Here we've chained the bindings. Let's see the result in complete example." }, { "code": null, "e": 10902, "s": 10863, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 10919, "s": 10902, "text": "GuiceTester.java" }, { "code": null, "e": 12294, "s": 10919, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck(); \n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class);\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}\n\n//subclass of SpellCheckerImpl\nclass WinWordSpellCheckerImpl extends SpellCheckerImpl{\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside WinWordSpellCheckerImpl.checkSpelling.\" );\n } \n}" }, { "code": null, "e": 12355, "s": 12294, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 12402, "s": 12355, "text": "Inside WinWordSpellCheckerImpl.checkSpelling.\n" }, { "code": null, "e": 12599, "s": 12402, "text": "As we can bind a type with its implementation. In case we want to map a type with multiple implmentations, we can create custom annotation as well. See the below example to understand the concept." }, { "code": null, "e": 12698, "s": 12599, "text": "@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)\n@interface WinWord {}" }, { "code": null, "e": 12760, "s": 12698, "text": "@BindingAnnotation - Marks annotation as binding annotation.\n" }, { "code": null, "e": 12821, "s": 12760, "text": "@BindingAnnotation - Marks annotation as binding annotation." }, { "code": null, "e": 12867, "s": 12821, "text": "@Target - Marks applicability of annotation.\n" }, { "code": null, "e": 12912, "s": 12867, "text": "@Target - Marks applicability of annotation." }, { "code": null, "e": 12972, "s": 12912, "text": "@Retention - Marks availablility of annotation as runtime.\n" }, { "code": null, "e": 13031, "s": 12972, "text": "@Retention - Marks availablility of annotation as runtime." }, { "code": null, "e": 13120, "s": 13031, "text": "bind(SpellChecker.class).annotatedWith(WinWord.class).to(WinWordSpellCheckerImpl.class);" }, { "code": null, "e": 13223, "s": 13120, "text": "@Inject\npublic TextEditor(@WinWord SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n}" }, { "code": null, "e": 13262, "s": 13223, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 13279, "s": 13262, "text": "GuiceTester.java" }, { "code": null, "e": 15100, "s": 13279, "text": "import java.lang.annotation.Target;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.BindingAnnotation;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\nimport java.lang.annotation.Retention;\n\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\n\n@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)\n@interface WinWord {}\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck(); \n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker; \n\n @Inject\n public TextEditor(@WinWord SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling(); \n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).annotatedWith(WinWord.class)\n .to(WinWordSpellCheckerImpl.class); \n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}\n\n//subclass of SpellCheckerImpl\nclass WinWordSpellCheckerImpl extends SpellCheckerImpl{\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside WinWordSpellCheckerImpl.checkSpelling.\" );\n } \n}" }, { "code": null, "e": 15161, "s": 15100, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 15208, "s": 15161, "text": "Inside WinWordSpellCheckerImpl.checkSpelling.\n" }, { "code": null, "e": 15331, "s": 15208, "text": "Guice provides another way also to map bindings without creating a custom annoation. It allows so using @Named annotation." }, { "code": null, "e": 15439, "s": 15331, "text": "bind(SpellChecker.class).annotatedWith(Names.named(\"OpenOffice\")).to(OpenOfficeWordSpellCheckerImpl.class);" }, { "code": null, "e": 15554, "s": 15439, "text": "@Inject\npublic TextEditor(@Named(\"OpenOffice\") SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n}" }, { "code": null, "e": 15593, "s": 15554, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 15610, "s": 15593, "text": "GuiceTester.java" }, { "code": null, "e": 17100, "s": 15610, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n \n\n @Inject\n public TextEditor(@Named(\"OpenOffice\") SpellChecker spellChecker) {\n this.spellChecker = spellChecker; \n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling(); \n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).annotatedWith(Names.named(\"OpenOffice\"))\n .to(OpenOfficeWordSpellCheckerImpl.class);\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}\n\n//subclass of SpellCheckerImpl\nclass OpenOfficeWordSpellCheckerImpl extends SpellCheckerImpl{\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside OpenOfficeWordSpellCheckerImpl.checkSpelling.\" );\n } \n}" }, { "code": null, "e": 17161, "s": 17100, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 17215, "s": 17161, "text": "Inside OpenOfficeWordSpellCheckerImpl.checkSpelling.\n" }, { "code": null, "e": 17343, "s": 17215, "text": "Guice provides a way to create bindings with value objects or constants. Consider the case where we want to configure JDBC url." }, { "code": null, "e": 17421, "s": 17343, "text": "@Inject\npublic void connectDatabase(@Named(\"JBDC\") String dbUrl) {\n //...\n}" }, { "code": null, "e": 17469, "s": 17421, "text": "This can be achived using toInstance() method.\n" }, { "code": null, "e": 17570, "s": 17469, "text": "bind(String.class).annotatedWith(Names.named(\"JBDC\")).toInstance(\"jdbc:mysql://localhost:5326/emp\");" }, { "code": null, "e": 17609, "s": 17570, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 17626, "s": 17609, "text": "GuiceTester.java" }, { "code": null, "e": 18551, "s": 17626, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeConnection();\n } \n}\n\nclass TextEditor {\n private String dbUrl;\n @Inject\n public TextEditor(@Named(\"JDBC\") String dbUrl) {\n this.dbUrl = dbUrl;\n }\n\n public void makeConnection(){\n System.out.println(dbUrl);\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}" }, { "code": null, "e": 18612, "s": 18551, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 18645, "s": 18612, "text": "jdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 18731, "s": 18645, "text": "Guice provides a way to create bindings with complex objects using @provides method. " }, { "code": null, "e": 18985, "s": 18731, "text": "@Provides\npublic SpellChecker provideSpellChecker(){\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n}" }, { "code": null, "e": 19107, "s": 18985, "text": "This methos is being part of Binding Module and provides the complex object to be mapped. See the complete example below." }, { "code": null, "e": 19146, "s": 19107, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 19163, "s": 19146, "text": "GuiceTester.java" }, { "code": null, "e": 20860, "s": 19163, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {} \n\n @Provides\n public SpellChecker provideSpellChecker(){\n\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n }\n}\n\n//spell checker interface\ninterface SpellChecker {\npublic void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n private String dbUrl;\n private String user;\n private Integer timeout;\n\n @Inject\n public SpellCheckerImpl(String dbUrl, \n String user, \n Integer timeout){\n this.dbUrl = dbUrl;\n this.user = user;\n this.timeout = timeout;\n } \n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl);\n System.out.println(user);\n System.out.println(timeout);\n }\n}" }, { "code": null, "e": 20921, "s": 20860, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 20985, "s": 20921, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\nuser\n100\n" }, { "code": null, "e": 21101, "s": 20985, "text": "As @provides method becomes more complex, these methods can be moved to seperate classes using Provider interface. " }, { "code": null, "e": 21429, "s": 21101, "text": "class SpellCheckerProvider implements Provider<SpellChecker>{\n @Override\n public SpellChecker get() {\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n } \n}" }, { "code": null, "e": 21471, "s": 21429, "text": "Next step is to map the provider to type." }, { "code": null, "e": 21536, "s": 21471, "text": "bind(SpellChecker.class).toProvider(SpellCheckerProvider.class);" }, { "code": null, "e": 21568, "s": 21536, "text": "See the complete example below." }, { "code": null, "e": 21607, "s": 21568, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 21624, "s": 21607, "text": "GuiceTester.java" }, { "code": null, "e": 23459, "s": 21624, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Provider;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class)\n .toProvider(SpellCheckerProvider.class);\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n private String dbUrl;\n private String user;\n private Integer timeout;\n\n @Inject\n public SpellCheckerImpl(String dbUrl, \n String user, \n Integer timeout){\n this.dbUrl = dbUrl;\n this.user = user;\n this.timeout = timeout;\n } \n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl);\n System.out.println(user);\n System.out.println(timeout);\n }\n}\n\nclass SpellCheckerProvider implements Provider<SpellChecker>{\n\n @Override\n public SpellChecker get() {\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n }\n}" }, { "code": null, "e": 23520, "s": 23459, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 23584, "s": 23520, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\nuser\n100\n" }, { "code": null, "e": 23693, "s": 23584, "text": "Guice provides a way to create bindings with specific constructor of an object using toConstructor() method." }, { "code": null, "e": 23979, "s": 23693, "text": "@Override\nprotected void configure() {\n try {\n bind(SpellChecker.class)\n .toConstructor(SpellCheckerImpl.class.getConstructor(String.class));\n } catch (NoSuchMethodException | SecurityException e) {\n System.out.println(\"Required constructor missing\");\n } \n} " }, { "code": null, "e": 24011, "s": 23979, "text": "See the complete example below." }, { "code": null, "e": 24050, "s": 24011, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 24067, "s": 24050, "text": "GuiceTester.java" }, { "code": null, "e": 25736, "s": 24067, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n try {\n bind(SpellChecker.class)\n .toConstructor(SpellCheckerImpl.class.getConstructor(String.class));\n } catch (NoSuchMethodException | SecurityException e) {\n System.out.println(\"Required constructor missing\");\n } \n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n private String dbUrl;\n\n public SpellCheckerImpl(){}\n\n public SpellCheckerImpl(@Named(\"JDBC\") String dbUrl){\n this.dbUrl = dbUrl;\n } \n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 25797, "s": 25736, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 25852, "s": 25797, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 26037, "s": 25852, "text": "Guice provides inbuilt binding for java.util.logging.Logger class. Logger's name is automatically set to the name of the class into which the Logger is injected. See the example below." }, { "code": null, "e": 26076, "s": 26037, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 26093, "s": 26076, "text": "GuiceTester.java" }, { "code": null, "e": 26869, "s": 26093, "text": "import java.util.logging.Logger;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private Logger logger;\n\n @Inject\n public TextEditor( Logger logger) {\n this.logger = logger;\n }\n\n public void makeSpellCheck(){\n logger.info(\"In TextEditor.makeSpellCheck() method\");\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n } \n}" }, { "code": null, "e": 26930, "s": 26869, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 27026, "s": 26930, "text": "Dec 20, 2017 12:51:05 PM TextEditor makeSpellCheck\nINFO: In TextEditor.makeSpellCheck() method\n" }, { "code": null, "e": 27446, "s": 27026, "text": "As bindings are defined in Binding Module, Guice uses them whenever it needs to inject dependencies. In case bindings are not present, it can attempt to create just-in-time bindings. Bindings present in binding module are called explicit bindings and are of higher precedence whereas just-in-time bindings are called implicit bindings. If both type of bindings are present, explicit bindings are considered for mapping." }, { "code": null, "e": 27514, "s": 27446, "text": "Following are the examples of three types of Just-in-time bindings." }, { "code": null, "e": 27675, "s": 27514, "text": "Non-private, No-argument constructors are eligible for just-in-time bindings. Another way is to annotate a constructor with @Inject annotation. See the example:" }, { "code": null, "e": 27714, "s": 27675, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 27731, "s": 27714, "text": "GuiceTester.java" }, { "code": null, "e": 29138, "s": 27731, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Inject @Named(\"JDBC\")\n private String dbUrl;\n\n public SpellCheckerImpl(){}\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 29199, "s": 29138, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 29254, "s": 29199, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 29404, "s": 29254, "text": "@ImplementatedBy annotation tells the guice about the implementation class. No binding is required in Binding Module in such a case. See the example:" }, { "code": null, "e": 29443, "s": 29404, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 29460, "s": 29443, "text": "GuiceTester.java" }, { "code": null, "e": 30861, "s": 29460, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Inject @Named(\"JDBC\")\n private String dbUrl;\n\n public SpellCheckerImpl(){}\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 30922, "s": 30861, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 30977, "s": 30922, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 31134, "s": 30977, "text": "@ProvidedBy annotation tells the guice about the provider of implementation class. No binding is required in Binding Module in such a case. See the example:" }, { "code": null, "e": 31173, "s": 31134, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 31190, "s": 31173, "text": "GuiceTester.java" }, { "code": null, "e": 33000, "s": 31190, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.ProvidedBy;\nimport com.google.inject.Provider;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n } \n}\n\n@ProvidedBy(SpellCheckerProvider.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n private String dbUrl;\n private String user;\n private Integer timeout;\n\n @Inject\n public SpellCheckerImpl(String dbUrl, \n String user, \n Integer timeout){\n this.dbUrl = dbUrl;\n this.user = user;\n this.timeout = timeout;\n } \n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl);\n System.out.println(user);\n System.out.println(timeout);\n }\n}\n\nclass SpellCheckerProvider implements Provider<SpellChecker>{\n\n @Override\n public SpellChecker get() {\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n }\n}" }, { "code": null, "e": 33061, "s": 33000, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 33125, "s": 33061, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\nuser\n100\n" }, { "code": null, "e": 33321, "s": 33125, "text": "Injection is a process of injecting dependeny into an object. Constructor injection is quite common. In this process, dependency is injected as argument to the constructor. See the example below." }, { "code": null, "e": 33360, "s": 33321, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 33377, "s": 33360, "text": "GuiceTester.java" }, { "code": null, "e": 34464, "s": 33377, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck(); \n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}" }, { "code": null, "e": 34525, "s": 34464, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 34548, "s": 34525, "text": "Inside checkSpelling.\n" }, { "code": null, "e": 34707, "s": 34548, "text": "Injection is a process of injecting dependeny into an object. Method injection is used to set value object as dependency to the object. See the example below." }, { "code": null, "e": 34746, "s": 34707, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 36223, "s": 34746, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n \n private String dbUrl;\n\n public SpellCheckerImpl(){}\n \n @Inject \n public void setDbUrl(@Named(\"JDBC\") String dbUrl){\n this.dbUrl = dbUrl;\n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 36284, "s": 36223, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 36339, "s": 36284, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 36509, "s": 36339, "text": "Injection is a process of injecting dependeny into an object. Field injection is used to set value object as dependency to the field of an object. See the example below." }, { "code": null, "e": 36548, "s": 36509, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 36565, "s": 36548, "text": "GuiceTester.java" }, { "code": null, "e": 37966, "s": 36565, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Inject @Named(\"JDBC\")\n private String dbUrl;\n\n public SpellCheckerImpl(){}\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 38027, "s": 37966, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 38082, "s": 38027, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 38349, "s": 38082, "text": "Injection is a process of injecting dependeny into an object. Optional injection means injecting the dependency if exists. Method and Field injections may be optionally dependent and should have some default value if dependency is not present. See the example below." }, { "code": null, "e": 38388, "s": 38349, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 38405, "s": 38388, "text": "GuiceTester.java" }, { "code": null, "e": 39762, "s": 38405, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {} \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n private String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n\n public SpellCheckerImpl(){}\n \n @Inject(optional=true)\n public void setDbUrl(@Named(\"JDBC\") String dbUrl){\n this.dbUrl = dbUrl;\n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 39823, "s": 39762, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 39878, "s": 39823, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 40077, "s": 39878, "text": "Injection is a process of injecting dependeny into an object. Method and field injections can be used to initialize using exiting object using injector.injectMembers() method. See the example below." }, { "code": null, "e": 40116, "s": 40077, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 40133, "s": 40116, "text": "GuiceTester.java" }, { "code": null, "e": 41401, "s": 40133, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n SpellChecker spellChecker = new SpellCheckerImpl();\n injector.injectMembers(spellChecker);\n \n TextEditor editor = injector.getInstance(TextEditor.class); \n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public void setSpellChecker(SpellChecker spellChecker){\n this.spellChecker = spellChecker;\n }\n public TextEditor() { }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n } \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n public SpellCheckerImpl(){}\n \n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n }\n}" }, { "code": null, "e": 41462, "s": 41401, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 41485, "s": 41462, "text": "Inside checkSpelling.\n" }, { "code": null, "e": 41653, "s": 41485, "text": "Guice returns a new instance every time when it supplies a value as its default behaviour. It is configurable via scopes. Following are the scopes that Guice supports:" }, { "code": null, "e": 41758, "s": 41653, "text": "@Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe.\n" }, { "code": null, "e": 41862, "s": 41758, "text": "@Singleton - Single instance for lifetime of the application. @Singleton object needs to be threadsafe." }, { "code": null, "e": 41991, "s": 41862, "text": "@SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe.\n" }, { "code": null, "e": 42119, "s": 41991, "text": "@SessionScoped - Single instance for a particular session of the web application. @SessionScoped object needs to be threadsafe." }, { "code": null, "e": 42256, "s": 42119, "text": "@RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe.\n" }, { "code": null, "e": 42392, "s": 42256, "text": "@RequestScoped - Single instance for a particular request of the web application. @RequestScoped object does not need to be threadsafe." }, { "code": null, "e": 42432, "s": 42392, "text": "Following are the ways to apply scopes." }, { "code": null, "e": 42634, "s": 42432, "text": "@Singleton\nclass SpellCheckerImpl implements SpellChecker {\n\n public SpellCheckerImpl(){}\n \n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n }\n}" }, { "code": null, "e": 42710, "s": 42634, "text": " bind(SpellChecker.class).to(SpellCheckerImpl.class).in(Singleton.class);" }, { "code": null, "e": 42977, "s": 42710, "text": "@Provides @Singleton\npublic SpellChecker provideSpellChecker(){\n\n String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n String user = \"user\";\n int timeout = 100;\n\n SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);\n return SpellChecker;\n}" }, { "code": null, "e": 43023, "s": 42977, "text": "Let's see the Scope at class level in action." }, { "code": null, "e": 43062, "s": 43023, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 43079, "s": 43062, "text": "GuiceTester.java" }, { "code": null, "e": 44703, "s": 43079, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Singleton;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n SpellChecker spellChecker = new SpellCheckerImpl();\n injector.injectMembers(spellChecker);\n\n TextEditor editor = injector.getInstance(TextEditor.class); \n System.out.println(editor.getSpellCheckerId());\n\n TextEditor editor1 = injector.getInstance(TextEditor.class); \n System.out.println(editor1.getSpellCheckerId());\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public void setSpellChecker(SpellChecker spellChecker){\n this.spellChecker = spellChecker;\n }\n public TextEditor() { }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n\n public double getSpellCheckerId(){\n return spellChecker.getId();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\ninterface SpellChecker {\n public double getId();\n public void checkSpelling();\n}\n\n@Singleton\nclass SpellCheckerImpl implements SpellChecker {\n\n double id; \n public SpellCheckerImpl(){\n id = Math.random(); \n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n }\n\n @Override\n public double getId() { \n return id;\n }\n}" }, { "code": null, "e": 44763, "s": 44703, "text": "Compile and run the file, you may see the following output." }, { "code": null, "e": 44802, "s": 44763, "text": "0.3055839187063575\n0.3055839187063575\n" }, { "code": null, "e": 44841, "s": 44802, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 44858, "s": 44841, "text": "GuiceTester.java" }, { "code": null, "e": 46435, "s": 44858, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n SpellChecker spellChecker = new SpellCheckerImpl();\n injector.injectMembers(spellChecker);\n\n TextEditor editor = injector.getInstance(TextEditor.class); \n System.out.println(editor.getSpellCheckerId());\n\n TextEditor editor1 = injector.getInstance(TextEditor.class); \n System.out.println(editor1.getSpellCheckerId());\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public void setSpellChecker(SpellChecker spellChecker){\n this.spellChecker = spellChecker;\n }\n public TextEditor() { }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n\n public double getSpellCheckerId(){\n return spellChecker.getId();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n } \n}\n\ninterface SpellChecker {\n public double getId();\n public void checkSpelling();\n}\n\nclass SpellCheckerImpl implements SpellChecker {\n\n double id; \n public SpellCheckerImpl(){\n id = Math.random(); \n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n }\n\n @Override\n public double getId() { \n return id;\n }\n}" }, { "code": null, "e": 46495, "s": 46435, "text": "Compile and run the file, you may see the following output." }, { "code": null, "e": 46534, "s": 46495, "text": "0.556007079571739\n0.22095011760351602\n" }, { "code": null, "e": 46964, "s": 46534, "text": "AOP, Aspect oriented programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects like logging, auditing, declarative transactions, security, caching, etc." }, { "code": null, "e": 47482, "s": 46964, "text": "The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other and AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others. Guice provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution." }, { "code": null, "e": 47677, "s": 47482, "text": "Matcher - Matcher is an interface to either accept or reject a value. In Guice AOP, we need two matchers: one to define which classes participate, and another for the methods of those classes. \n" }, { "code": null, "e": 47871, "s": 47677, "text": "Matcher - Matcher is an interface to either accept or reject a value. In Guice AOP, we need two matchers: one to define which classes participate, and another for the methods of those classes. " }, { "code": null, "e": 48186, "s": 47871, "text": "MethodInterceptor - MethodInterceptors are executed when a matching method is called. They can inspect the call: the method, its arguments, and the receiving instance. We can perform cross-cutting logic and then delegate to the underlying method. Finally, we may inspect the return value or exception and return. \n" }, { "code": null, "e": 48500, "s": 48186, "text": "MethodInterceptor - MethodInterceptors are executed when a matching method is called. They can inspect the call: the method, its arguments, and the receiving instance. We can perform cross-cutting logic and then delegate to the underlying method. Finally, we may inspect the return value or exception and return. " }, { "code": null, "e": 48539, "s": 48500, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 48556, "s": 48539, "text": "GuiceTester.java" }, { "code": null, "e": 50542, "s": 48556, "text": "import java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport org.aopalliance.intercept.MethodInterceptor;\nimport org.aopalliance.intercept.MethodInvocation;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.matcher.Matchers;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck(); \n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor(SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n }\n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(SpellChecker.class).to(SpellCheckerImpl.class);\n bindInterceptor(Matchers.any(), \n Matchers.annotatedWith(CallTracker.class), \n new CallTrackerService());\n } \n}\n\n//spell checker interface\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Override @CallTracker\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n } \n}\n\n@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)\n@interface CallTracker {}\n\nclass CallTrackerService implements MethodInterceptor {\n\n @Override\n public Object invoke(MethodInvocation invocation) throws Throwable {\n System.out.println(\"Before \" + invocation.getMethod().getName());\n Object result = invocation.proceed();\n System.out.println(\"After \" + invocation.getMethod().getName());\n return result;\n }\n}" }, { "code": null, "e": 50602, "s": 50542, "text": "Compile and run the file, you may see the following output." }, { "code": null, "e": 50666, "s": 50602, "text": "Before checkSpelling\nInside checkSpelling.\nAfter checkSpelling\n" }, { "code": null, "e": 50701, "s": 50666, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 50718, "s": 50701, "text": " Lemuel Ogbunude" }, { "code": null, "e": 50725, "s": 50718, "text": " Print" }, { "code": null, "e": 50736, "s": 50725, "text": " Add Notes" } ]
TF-IDF Explained And Python Sklearn Implementation | by Marius Borcan | Towards Data Science
What is TF-IDF and how you can implement it in Python and Scikit-Learn. TF-IDF is an information retrieval and information extraction subtask which aims to express the importance of a word to a document which is part of a colection of documents which we usually name a corpus. It is usually used by some search engines to help them obtain better results which are more relevant to a specific query. In this article we are going to discuss what exactly is TF-IDF, explain the math behind it and then we will see how we can implement it in Python by using the Scikit-Learn library. This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind. Thank you so much for reading this! Interested in more stories like this? Follow me on Twitter at @b_dmarius and I’ll post there every new article. What is TF-IDF TF-IDF formula explained TF-IDF sklearn python implementation TfIdfVectorizer vs TfIdfTransformer — what is the difference TF-IDF Applications Conclusions TF-IDF stands for Term Frequency — Inverse Document Frequency and is a statistic that aims to better define how important a word is for a document, while also taking into account the relation to other documents from the same corpus. This is performed by looking at how many times a word appears into a document while also paying attention to how many times the same word appears in other documents in the corpus. The rationale behind this is the following: a word that frequently appears in a document has more relevancy for that document, meaning that there is higher probability that the document is about or in relation to that specific word a word that frequently appears in more documents may prevent us from finding the right document in a collection; the word is relevant either for all documents or for none. Either way, it will not help us filter out a single document or a small subset of documents from the whole set. So then TF-IDF is a score which is applied to every word in every document in our dataset. And for every word, the TF-IDF value increases with every appearance of the word in a document, but is gradually decreased with every appearance in other documents. And the maths for that is in the next section. Now let’s take a look at the simple formula behind the TF-IDF statistical measure. First let’s define some notations: N is the number of documents we have in our dataset d is a given document from our dataset D is the collection of all documents w is a given word in a document First step is to calculate the term frequency, our first measure if the score. Here f(w,d) is the frequency of word w in document d. Second step is to calculate the inverse term frequency. With N documents in the dataset and f(w, D) the frequency of word w in the whole dataset, this number will be lower with more appearances of the word in the whole dataset. Final step is to compute the TF-IDF score by the following formula: With such awesome libraries like scikit-learn implementing TD-IDF is a breeze. First off we need to install 2 dependencies for our project, so let’s do that now. pip3 install scikit-learnpip3 install pandas In order to see the full power of TF-IDF we would actually require a proper, larger dataset. But for the purpose of our article, we only want to focus on implementation, so let’s import our dependencies into our project and build our mini-dataset. import pandas as pdfrom sklearn.feature_extraction.text import TfidfTransformerdataset = [ "I enjoy reading about Machine Learning and Machine Learning is my PhD subject", "I would enjoy a walk in the park", "I was reading in the library"] Let’s now calculate the TF-IDF score and print out our results. tfIdfVectorizer=TfidfVectorizer(use_idf=True)tfIdf = tfIdfVectorizer.fit_transform(dataset)df = pd.DataFrame(tfIdf[0].T.todense(), index=tfIdfVectorizer.get_feature_names(), columns=["TF-IDF"])df = df.sort_values('TF-IDF', ascending=False)print (df.head(25)) Let’s see our results now. TF-IDFmachine 0.513720learning 0.513720about 0.256860subject 0.256860phd 0.256860and 0.256860my 0.256860is 0.256860reading 0.195349enjoy 0.195349library 0.000000park 0.000000in 0.000000the 0.000000walk 0.000000was 0.000000would 0.000000 If you’ve ever seen other implementations of TF-IDF you may have seen that there are 2 different ways of implementing TF-IDF using Scikit-Learn. One is using the TfidfVectorizer class(like we just did) and the other one is by using the TfidfTransformer class. You may have wondered what’s the difference between the 2 of them, so let’s discuss that. Theoretically speaking, there is actually no difference between the 2 implementations. Practically speaking, we need to write some more code if we want to use TfidfTransformer. The main difference between the 2 implementations is that TfidfVectorizer performs both term frequency and inverse document frequency for you, while using TfidfTransformer will require you to use the CountVectorizer class from Scikit-Learn to perform Term Frequency. So let’s see an alternative TF-IDF implementation and validate the results are the same. We will first need to import 2 additional dependencies to our project. from sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.feature_extraction.text import CountVectorizer We will use the same mini-dataset we used with the other implementation. Let’s write the alternative implementation and print out the results. tfIdfTransformer = TfidfTransformer(use_idf=True)countVectorizer = CountVectorizer()wordCount = countVectorizer.fit_transform(dataset)newTfIdf = tfIdfTransformer.fit_transform(wordCount)df = pd.DataFrame(newTfIdf[0].T.todense(), index=countVectorizer.get_feature_names(), columns=["TF-IDF"])df = df.sort_values('TF-IDF', ascending=False)print (df.head(25)) You can look at the results and see they are the same as the above. TF-IDFmachine 0.513720learning 0.513720about 0.256860subject 0.256860phd 0.256860and 0.256860my 0.256860is 0.256860reading 0.195349enjoy 0.195349library 0.000000park 0.000000in 0.000000the 0.000000walk 0.000000was 0.000000would 0.000000 So we’ve seen that implementing TF-IDF using the right tools is very easy, yet the applications of this algorithm are very powerful. The 2 most common use cases for TF-IDF are: Information retrieval: by calculating the TF-IDF score of a user query against the whole document set we can figure out how relevant a document is to that given query. Rumour has it that most search engines around use some sort of TF-IDF implementation, but I couldn’t verify that information myself, so take this with a grain of salt. Keywords extraction: The highest ranking words for a document in terms of TF-IDF score can very well represent the keywords of that document(as they make that document stand out from the other documents). So we can very easily use some sort of TF-IDF score computation to extract the keywords from a text. So in this article we’ve seen an explanation of what is TF-IDF and how we can explain it mathematically. Then we’ve seen two alternative implementations using the Scikit-Learn Python library. We’ve then discussed some possible applications of this algorithm. I hope you enjoyed this! Thank you so much for reading this article! Interested in more? Follow me on Twitter at @b_dmarius and I’ll post there every new article.
[ { "code": null, "e": 243, "s": 171, "text": "What is TF-IDF and how you can implement it in Python and Scikit-Learn." }, { "code": null, "e": 751, "s": 243, "text": "TF-IDF is an information retrieval and information extraction subtask which aims to express the importance of a word to a document which is part of a colection of documents which we usually name a corpus. It is usually used by some search engines to help them obtain better results which are more relevant to a specific query. In this article we are going to discuss what exactly is TF-IDF, explain the math behind it and then we will see how we can implement it in Python by using the Scikit-Learn library." }, { "code": null, "e": 898, "s": 751, "text": "This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind." }, { "code": null, "e": 1046, "s": 898, "text": "Thank you so much for reading this! Interested in more stories like this? Follow me on Twitter at @b_dmarius and I’ll post there every new article." }, { "code": null, "e": 1061, "s": 1046, "text": "What is TF-IDF" }, { "code": null, "e": 1086, "s": 1061, "text": "TF-IDF formula explained" }, { "code": null, "e": 1123, "s": 1086, "text": "TF-IDF sklearn python implementation" }, { "code": null, "e": 1184, "s": 1123, "text": "TfIdfVectorizer vs TfIdfTransformer — what is the difference" }, { "code": null, "e": 1204, "s": 1184, "text": "TF-IDF Applications" }, { "code": null, "e": 1216, "s": 1204, "text": "Conclusions" }, { "code": null, "e": 1449, "s": 1216, "text": "TF-IDF stands for Term Frequency — Inverse Document Frequency and is a statistic that aims to better define how important a word is for a document, while also taking into account the relation to other documents from the same corpus." }, { "code": null, "e": 1629, "s": 1449, "text": "This is performed by looking at how many times a word appears into a document while also paying attention to how many times the same word appears in other documents in the corpus." }, { "code": null, "e": 1673, "s": 1629, "text": "The rationale behind this is the following:" }, { "code": null, "e": 1861, "s": 1673, "text": "a word that frequently appears in a document has more relevancy for that document, meaning that there is higher probability that the document is about or in relation to that specific word" }, { "code": null, "e": 2145, "s": 1861, "text": "a word that frequently appears in more documents may prevent us from finding the right document in a collection; the word is relevant either for all documents or for none. Either way, it will not help us filter out a single document or a small subset of documents from the whole set." }, { "code": null, "e": 2448, "s": 2145, "text": "So then TF-IDF is a score which is applied to every word in every document in our dataset. And for every word, the TF-IDF value increases with every appearance of the word in a document, but is gradually decreased with every appearance in other documents. And the maths for that is in the next section." }, { "code": null, "e": 2566, "s": 2448, "text": "Now let’s take a look at the simple formula behind the TF-IDF statistical measure. First let’s define some notations:" }, { "code": null, "e": 2618, "s": 2566, "text": "N is the number of documents we have in our dataset" }, { "code": null, "e": 2657, "s": 2618, "text": "d is a given document from our dataset" }, { "code": null, "e": 2694, "s": 2657, "text": "D is the collection of all documents" }, { "code": null, "e": 2726, "s": 2694, "text": "w is a given word in a document" }, { "code": null, "e": 2805, "s": 2726, "text": "First step is to calculate the term frequency, our first measure if the score." }, { "code": null, "e": 2859, "s": 2805, "text": "Here f(w,d) is the frequency of word w in document d." }, { "code": null, "e": 2915, "s": 2859, "text": "Second step is to calculate the inverse term frequency." }, { "code": null, "e": 3087, "s": 2915, "text": "With N documents in the dataset and f(w, D) the frequency of word w in the whole dataset, this number will be lower with more appearances of the word in the whole dataset." }, { "code": null, "e": 3155, "s": 3087, "text": "Final step is to compute the TF-IDF score by the following formula:" }, { "code": null, "e": 3317, "s": 3155, "text": "With such awesome libraries like scikit-learn implementing TD-IDF is a breeze. First off we need to install 2 dependencies for our project, so let’s do that now." }, { "code": null, "e": 3362, "s": 3317, "text": "pip3 install scikit-learnpip3 install pandas" }, { "code": null, "e": 3610, "s": 3362, "text": "In order to see the full power of TF-IDF we would actually require a proper, larger dataset. But for the purpose of our article, we only want to focus on implementation, so let’s import our dependencies into our project and build our mini-dataset." }, { "code": null, "e": 3859, "s": 3610, "text": "import pandas as pdfrom sklearn.feature_extraction.text import TfidfTransformerdataset = [ \"I enjoy reading about Machine Learning and Machine Learning is my PhD subject\", \"I would enjoy a walk in the park\", \"I was reading in the library\"]" }, { "code": null, "e": 3923, "s": 3859, "text": "Let’s now calculate the TF-IDF score and print out our results." }, { "code": null, "e": 4182, "s": 3923, "text": "tfIdfVectorizer=TfidfVectorizer(use_idf=True)tfIdf = tfIdfVectorizer.fit_transform(dataset)df = pd.DataFrame(tfIdf[0].T.todense(), index=tfIdfVectorizer.get_feature_names(), columns=[\"TF-IDF\"])df = df.sort_values('TF-IDF', ascending=False)print (df.head(25))" }, { "code": null, "e": 4209, "s": 4182, "text": "Let’s see our results now." }, { "code": null, "e": 4522, "s": 4209, "text": "TF-IDFmachine 0.513720learning 0.513720about 0.256860subject 0.256860phd 0.256860and 0.256860my 0.256860is 0.256860reading 0.195349enjoy 0.195349library 0.000000park 0.000000in 0.000000the 0.000000walk 0.000000was 0.000000would 0.000000" }, { "code": null, "e": 4872, "s": 4522, "text": "If you’ve ever seen other implementations of TF-IDF you may have seen that there are 2 different ways of implementing TF-IDF using Scikit-Learn. One is using the TfidfVectorizer class(like we just did) and the other one is by using the TfidfTransformer class. You may have wondered what’s the difference between the 2 of them, so let’s discuss that." }, { "code": null, "e": 5316, "s": 4872, "text": "Theoretically speaking, there is actually no difference between the 2 implementations. Practically speaking, we need to write some more code if we want to use TfidfTransformer. The main difference between the 2 implementations is that TfidfVectorizer performs both term frequency and inverse document frequency for you, while using TfidfTransformer will require you to use the CountVectorizer class from Scikit-Learn to perform Term Frequency." }, { "code": null, "e": 5476, "s": 5316, "text": "So let’s see an alternative TF-IDF implementation and validate the results are the same. We will first need to import 2 additional dependencies to our project." }, { "code": null, "e": 5596, "s": 5476, "text": "from sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.feature_extraction.text import CountVectorizer" }, { "code": null, "e": 5739, "s": 5596, "text": "We will use the same mini-dataset we used with the other implementation. Let’s write the alternative implementation and print out the results." }, { "code": null, "e": 6096, "s": 5739, "text": "tfIdfTransformer = TfidfTransformer(use_idf=True)countVectorizer = CountVectorizer()wordCount = countVectorizer.fit_transform(dataset)newTfIdf = tfIdfTransformer.fit_transform(wordCount)df = pd.DataFrame(newTfIdf[0].T.todense(), index=countVectorizer.get_feature_names(), columns=[\"TF-IDF\"])df = df.sort_values('TF-IDF', ascending=False)print (df.head(25))" }, { "code": null, "e": 6164, "s": 6096, "text": "You can look at the results and see they are the same as the above." }, { "code": null, "e": 6477, "s": 6164, "text": "TF-IDFmachine 0.513720learning 0.513720about 0.256860subject 0.256860phd 0.256860and 0.256860my 0.256860is 0.256860reading 0.195349enjoy 0.195349library 0.000000park 0.000000in 0.000000the 0.000000walk 0.000000was 0.000000would 0.000000" }, { "code": null, "e": 6654, "s": 6477, "text": "So we’ve seen that implementing TF-IDF using the right tools is very easy, yet the applications of this algorithm are very powerful. The 2 most common use cases for TF-IDF are:" }, { "code": null, "e": 6990, "s": 6654, "text": "Information retrieval: by calculating the TF-IDF score of a user query against the whole document set we can figure out how relevant a document is to that given query. Rumour has it that most search engines around use some sort of TF-IDF implementation, but I couldn’t verify that information myself, so take this with a grain of salt." }, { "code": null, "e": 7296, "s": 6990, "text": "Keywords extraction: The highest ranking words for a document in terms of TF-IDF score can very well represent the keywords of that document(as they make that document stand out from the other documents). So we can very easily use some sort of TF-IDF score computation to extract the keywords from a text." }, { "code": null, "e": 7580, "s": 7296, "text": "So in this article we’ve seen an explanation of what is TF-IDF and how we can explain it mathematically. Then we’ve seen two alternative implementations using the Scikit-Learn Python library. We’ve then discussed some possible applications of this algorithm. I hope you enjoyed this!" } ]
Binary Tree Preorder Traversal in Python
Suppose we have a binary tree. We have to return the preorder traversal of that tree. So if the tree is like − Then the preorder traversal will be: [3,9,20,15,7] To solve this, we will follow these steps − make empty lists called res and st. node := root while node or st is not emptywhile node is not null, theninsert val of node into res, insert node into st and set node := left of nodetemp := last element of st, and delete last element of stif right of temp is available, thennode := right of temp while node is not null, theninsert val of node into res, insert node into st and set node := left of node insert val of node into res, insert node into st and set node := left of node temp := last element of st, and delete last element of st if right of temp is available, thennode := right of temp node := right of temp return res Let us see the following implementation to get better understanding − Live Demo class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): temp.left = TreeNode(data) break else: que.append(temp.left) if (not temp.right): temp.right = TreeNode(data) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def preorderTraversal(self, root): res = [] st = [] node = root while node or st: while node: if node.data != None: res.append(node.data) st.append(node) node = node.left temp = st[-1] st.pop() if temp.right: node = temp.right return res ob1 = Solution() head = make_tree([3,9,20,None,None,15,7]) print(ob1.preorderTraversal(head)) [3,9,20,null,null,15,7] [3, 9, 20, 15, 7]
[ { "code": null, "e": 1173, "s": 1062, "text": "Suppose we have a binary tree. We have to return the preorder traversal of that tree. So if the tree is like −" }, { "code": null, "e": 1224, "s": 1173, "text": "Then the preorder traversal will be: [3,9,20,15,7]" }, { "code": null, "e": 1268, "s": 1224, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1304, "s": 1268, "text": "make empty lists called res and st." }, { "code": null, "e": 1317, "s": 1304, "text": "node := root" }, { "code": null, "e": 1565, "s": 1317, "text": "while node or st is not emptywhile node is not null, theninsert val of node into res, insert node into st and set node := left of nodetemp := last element of st, and delete last element of stif right of temp is available, thennode := right of temp" }, { "code": null, "e": 1671, "s": 1565, "text": "while node is not null, theninsert val of node into res, insert node into st and set node := left of node" }, { "code": null, "e": 1749, "s": 1671, "text": "insert val of node into res, insert node into st and set node := left of node" }, { "code": null, "e": 1807, "s": 1749, "text": "temp := last element of st, and delete last element of st" }, { "code": null, "e": 1864, "s": 1807, "text": "if right of temp is available, thennode := right of temp" }, { "code": null, "e": 1886, "s": 1864, "text": "node := right of temp" }, { "code": null, "e": 1897, "s": 1886, "text": "return res" }, { "code": null, "e": 1967, "s": 1897, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1978, "s": 1967, "text": " Live Demo" }, { "code": null, "e": 3091, "s": 1978, "text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef insert(temp,data):\n que = []\n que.append(temp)\n while (len(que)):\n temp = que[0]\n que.pop(0)\n if (not temp.left):\n temp.left = TreeNode(data)\n break\n else:\n que.append(temp.left)\n if (not temp.right):\n temp.right = TreeNode(data)\n break\n else:\n que.append(temp.right)\ndef make_tree(elements):\n Tree = TreeNode(elements[0])\n for element in elements[1:]:\n insert(Tree, element)\n return Tree\nclass Solution(object):\n def preorderTraversal(self, root):\n res = []\n st = []\n node = root\n while node or st:\n while node:\n if node.data != None:\n res.append(node.data)\n st.append(node)\n node = node.left\n temp = st[-1]\n st.pop()\n if temp.right:\n node = temp.right\n return res\nob1 = Solution()\nhead = make_tree([3,9,20,None,None,15,7])\nprint(ob1.preorderTraversal(head))" }, { "code": null, "e": 3115, "s": 3091, "text": "[3,9,20,null,null,15,7]" }, { "code": null, "e": 3133, "s": 3115, "text": "[3, 9, 20, 15, 7]" } ]
How to use internal CSS (Style Sheet) in HTML?
CSS can be used in various ways in HTML. One of them is by using Internal CSS i.e. using a <style> tag. The <style> tag is used in the <head>...</head> tag. It defines CSS style for a single page. You can try to run the following code to use internal CSS in HTML − <!DOCTYPE html> <html> <head> <style> h1 {color: red;} p {font-size: 12px;} </style> </head> <body> <h1>Tutorials</h1> <p>We provide free tutorials for engineers and professional.</p> </body> </html>
[ { "code": null, "e": 1259, "s": 1062, "text": "CSS can be used in various ways in HTML. One of them is by using Internal CSS i.e. using a <style> tag. The <style> tag is used in the <head>...</head> tag. It defines CSS style for a single page." }, { "code": null, "e": 1327, "s": 1259, "text": "You can try to run the following code to use internal CSS in HTML −" }, { "code": null, "e": 1585, "s": 1327, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n h1 {color: red;}\n p {font-size: 12px;}\n </style>\n </head>\n \n <body>\n <h1>Tutorials</h1>\n <p>We provide free tutorials for engineers and professional.</p>\n </body>\n</html>" } ]
Bitwise Right Shift Operators in Java - GeeksforGeeks
24 Dec, 2021 In C/C++ there is only one right shift operator ‘>>’ which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators. Here we will be discussing both of right shift operators as listed: Signed right shift “>>” Unsigned right shift “>>>” In Java, the operator ‘>>’ is signed right shift operator. All integers are signed in Java, and it is fine to use >> for negative numbers. The operator ‘>>’ uses the sign bit (leftmost bit) to fill the trailing positions after the shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler. For example, if the binary representation of a number is 10....100, then right shifting it by 2 using >> will make it 11.......1. Example: Java // Java Program to Illustrate Signed Right Shift Operator // Main classclass GFG { // Main driver method public static void main(String args[]) { int x = -4; System.out.println(x >> 1); int y = 4; System.out.println(y >> 1); }} -2 2 In Java, the operator ‘>>>’ denotes unsigned right shift operator and always fill 0 irrespective of the sign of the number. Example: Java // Java Program to Illustrate Unsigned Right Shift Operator // Main classclass GFG { // main driver method public static void main(String args[]) { // x is stored using 32 bit 2's complement form. // Binary representation of -1 is all 1s (111..1) int x = -1; // The value of 'x>>>29' is 00...0111 System.out.println(x >>> 29); // The value of 'x>>>30' is 00...0011 System.out.println(x >>> 30); // The value of 'x>>>31' is 00...0001 System.out.println(x >>> 31); }} 7 3 1 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nagen010 solankimayank Java-Operators Bit Magic Java Java-Operators Bit Magic Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Add two numbers without using arithmetic operators Binary representation of a given number Program to find whether a given number is power of 2 For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 24533, "s": 24505, "text": "\n24 Dec, 2021" }, { "code": null, "e": 24871, "s": 24533, "text": "In C/C++ there is only one right shift operator ‘>>’ which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators." }, { "code": null, "e": 24939, "s": 24871, "text": "Here we will be discussing both of right shift operators as listed:" }, { "code": null, "e": 24963, "s": 24939, "text": "Signed right shift “>>”" }, { "code": null, "e": 24990, "s": 24963, "text": "Unsigned right shift “>>>”" }, { "code": null, "e": 25471, "s": 24990, "text": "In Java, the operator ‘>>’ is signed right shift operator. All integers are signed in Java, and it is fine to use >> for negative numbers. The operator ‘>>’ uses the sign bit (leftmost bit) to fill the trailing positions after the shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler. For example, if the binary representation of a number is 10....100, then right shifting it by 2 using >> will make it 11.......1." }, { "code": null, "e": 25480, "s": 25471, "text": "Example:" }, { "code": null, "e": 25485, "s": 25480, "text": "Java" }, { "code": "// Java Program to Illustrate Signed Right Shift Operator // Main classclass GFG { // Main driver method public static void main(String args[]) { int x = -4; System.out.println(x >> 1); int y = 4; System.out.println(y >> 1); }}", "e": 25756, "s": 25485, "text": null }, { "code": null, "e": 25761, "s": 25756, "text": "-2\n2" }, { "code": null, "e": 25885, "s": 25761, "text": "In Java, the operator ‘>>>’ denotes unsigned right shift operator and always fill 0 irrespective of the sign of the number." }, { "code": null, "e": 25894, "s": 25885, "text": "Example:" }, { "code": null, "e": 25899, "s": 25894, "text": "Java" }, { "code": "// Java Program to Illustrate Unsigned Right Shift Operator // Main classclass GFG { // main driver method public static void main(String args[]) { // x is stored using 32 bit 2's complement form. // Binary representation of -1 is all 1s (111..1) int x = -1; // The value of 'x>>>29' is 00...0111 System.out.println(x >>> 29); // The value of 'x>>>30' is 00...0011 System.out.println(x >>> 30); // The value of 'x>>>31' is 00...0001 System.out.println(x >>> 31); }}", "e": 26445, "s": 25899, "text": null }, { "code": null, "e": 26451, "s": 26445, "text": "7\n3\n1" }, { "code": null, "e": 26576, "s": 26451, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26585, "s": 26576, "text": "nagen010" }, { "code": null, "e": 26599, "s": 26585, "text": "solankimayank" }, { "code": null, "e": 26614, "s": 26599, "text": "Java-Operators" }, { "code": null, "e": 26624, "s": 26614, "text": "Bit Magic" }, { "code": null, "e": 26629, "s": 26624, "text": "Java" }, { "code": null, "e": 26644, "s": 26629, "text": "Java-Operators" }, { "code": null, "e": 26654, "s": 26644, "text": "Bit Magic" }, { "code": null, "e": 26659, "s": 26654, "text": "Java" }, { "code": null, "e": 26757, "s": 26659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26766, "s": 26757, "text": "Comments" }, { "code": null, "e": 26779, "s": 26766, "text": "Old Comments" }, { "code": null, "e": 26825, "s": 26779, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 26855, "s": 26825, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 26906, "s": 26855, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 26946, "s": 26906, "text": "Binary representation of a given number" }, { "code": null, "e": 26999, "s": 26946, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 27021, "s": 26999, "text": "For-each loop in Java" }, { "code": null, "e": 27046, "s": 27021, "text": "Reverse a string in Java" }, { "code": null, "e": 27082, "s": 27046, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27133, "s": 27082, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to install Angry IP Scanner from PPA in Ubuntu/Linux Mint
Angry IP Scanner is an open-source and cross-platform network scanner. It is very faster and simple to use platform which scans IP addresses and ports. TCP/IP(Angry IP) network scanner allows users to easily scan IP addresses within any range of your choice via a user-friendly interface. Once Angry IP Scanner detects an active IP address, then it resolves MAC address, hostname, and port/s. The gathered data information can be saved as TXT, CSV, XML or IP-Port list files. This article describes” How to install and use IP scanner in Linux” To install Angry IP Scanner in Ubuntu/Linux Mint, open the terminal and access PPA repository using the following command – $ sudo add-apt-repository ppa:upubuntu-com/network The sample output should be like this – More info: https://launchpad.net/~upubuntu-com/+archive/ubuntu/network Press [ENTER] to continue or ctrl-c to cancel adding it gpg: keyring `/tmp/tmpaj4fxqym/secring.gpg' created gpg: keyring `/tmp/tmpaj4fxqym/pubring.gpg' created gpg: requesting key E06E6293 from hkp server keyserver.ubuntu.com gpg: /tmp/tmpaj4fxqym/trustdb.gpg: trustdb created gpg: key E06E6293: public key "Launchpad PPA for upubuntu.com" imported gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1) OK Now update the Linux package index by using the following command – $ sudo apt-get update The sample output should be like this – Ign http://dl.google.com stable InRelease Get:1 http://dl.google.com stable Release.gpg [181 B] Get:2 http://dl.google.com stable Release [782 B] Get:3 http://security.ubuntu.com trusty-security InRelease [65.9 kB] Ign http://extras.ubuntu.com trusty InRelease Ign http://in.archive.ubuntu.com trusty InRelease Hit http://ppa.launchpad.net trusty InRelease Get:4 http://dl.google.com stable/main amd64 Packages [1,215 B] Get:5 http://extras.ubuntu.com trusty Release.gpg [72 B] Get:6 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB] Hit http://ppa.launchpad.net trusty InRelease Hit http://extras.ubuntu.com trusty Release Get:7 http://ppa.launchpad.net trusty InRelease [20.9 kB] Hit http://extras.ubuntu.com trusty/main Sources Get:8 http://security.ubuntu.com trusty-security/main Sources [108 kB] Hit http://extras.ubuntu.com trusty/main amd64 Packages Get:9 http://in.archive.ubuntu.com trusty-backports InRelease [65.9 kB] Ign http://ppa.launchpad.net trusty InRelease Hit http://extras.ubuntu.com trusty/main i386 Packages Get:10 http://security.ubuntu.com trusty-security/restricted Sources [4,035 B] Ign http://ppa.launchpad.net trusty InRelease Get:11 http://security.ubuntu.com trusty-security/universe Sources [34.0 kB] Hit http://in.archive.ubuntu.com trusty Release.gpg Hit http://ppa.launchpad.net trusty/main amd64 Packages Get:12 http://security.ubuntu.com trusty-security/multiverse Sources [2,750 B] Get:13 http://in.archive.ubuntu.com trusty-updates/main Sources [264 kB] Hit http://ppa.launchpad.net trusty/main i386 Packages Get:14 http://security.ubuntu.com trusty-security/main amd64 Packages [444 kB] Hit http://ppa.launchpad.net trusty/main Translation-en Hit http://ppa.launchpad.net trusty/main amd64 Packages Hit http://ppa.launchpad.net trusty/main i386 Packages Hit http://ppa.launchpad.net trusty/main Translation-en Get:15 http://ppa.launchpad.net trusty/main amd64 Packages [27.9 kB] ............................................................. To install IP scanner, use the following command – $ sudo apt-get install ipscan The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic Use 'apt-get autoremove' to remove them. The following extra packages will be installed: ca-certificates-java fonts-dejavu-extra java-common libatk-wrapper-java libatk-wrapper-java-jni libgconf2-4 libsctp1 lksctp-tools openjdk-7-jre openjdk-7-jre-headless tzdata-java Suggested packages: default-jre equivs icedtea-7-plugin icedtea-7-jre-jamvm sun-java6-fonts fonts-ipafont-gothic fonts-ipafont-mincho ttf-wqy-microhei ttf-wqy-zenhei ttf-telugu-fonts ttf-oriya-fonts ttf-kannada-fonts ttf-bengali-fonts The following NEW packages will be installed: ca-certificates-java fonts-dejavu-extra ipscan java-common .......................................................... To open IP scanner, use the following command – $ ipscan The output should be like this – To remove angryIP scanner, use the following command – $ sudo apt-get remove ipscan The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic Use 'apt-get autoremove' to remove them. The following packages will be REMOVED: ipscan 0 upgraded, 0 newly installed, 1 to remove and 12 not upgraded. After this operation, 3,358 kB disk space will be freed. Do you want to continue? [Y/n] y (Reading database ... 251656 files and directories currently installed.) Removing ipscan (3.3.3) ... Processing triggers for gnome-menus (3.10.1-0ubuntu2) ... Processing triggers for desktop-file-utils (0.22-1ubuntu1) ... Processing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ... ............................................... Now remove added PPA, use the following command – $ sudo add-apt-repository --remove ppa:upubuntu-com/network The sample output should be like this – More info: https://launchpad.net/~upubuntu-com/+archive/ubuntu/network Press [ENTER] to continue or ctrl-c to cancel removing it Now update Linux package index, by using the following command – $ sudo apt-get update The sample output should be like this – Ign http://dl.google.com stable InRelease Hit http://dl.google.com stable Release.gpg Hit http://dl.google.com stable Release Hit http://dl.google.com stable/main amd64 Packages Ign http://extras.ubuntu.com trusty InRelease Hit http://ppa.launchpad.net trusty InRelease Get:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB] Hit http://extras.ubuntu.com trusty Release.gpg Ign http://in.archive.ubuntu.com trusty InRelease Hit http://ppa.launchpad.net trusty InRelease Hit http://extras.ubuntu.com trusty Release Hit http://ppa.launchpad.net trusty InRelease Get:2 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB] Hit http://extras.ubuntu.com trusty/main Sources Ign http://ppa.launchpad.net trusty InRelease Get:3 http://security.ubuntu.com trusty-security/main Sources [108 kB] Hit http://extras.ubuntu.com trusty/main amd64 Packages Hit http://ppa.launchpad.net trusty/main amd64 Packages Hit http://extras.ubuntu.com trusty/main i386 Packages Hit http://ppa.launchpad.net trusty/main i386 Packages Get:4 http://security.ubuntu.com trusty-security/restricted Sources [4,035 B] Hit http://ppa.launchpad.net trusty/main Translation-en Get:5 http://security.ubuntu.com trusty-security/universe Sources [34.0 kB] Hit http://ppa.launchpad.net trusty/main amd64 Packages Get:6 http://in.archive.ubuntu.com trusty-backports InRelease [65.9 kB] ............................. Congratulations! Now, you know “How to install Angry IP Scanner from PPA in Ubuntu/Linux Mint”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1606, "s": 1062, "text": "Angry IP Scanner is an open-source and cross-platform network scanner. It is very faster and simple to use platform which scans IP addresses and ports. TCP/IP(Angry IP) network scanner allows users to easily scan IP addresses within any range of your choice via a user-friendly interface. Once Angry IP Scanner detects an active IP address, then it resolves MAC address, hostname, and port/s. The gathered data information can be saved as TXT, CSV, XML or IP-Port list files. This article describes” How to install and use IP scanner in Linux”" }, { "code": null, "e": 1730, "s": 1606, "text": "To install Angry IP Scanner in Ubuntu/Linux Mint, open the terminal and access PPA repository using the following command –" }, { "code": null, "e": 1781, "s": 1730, "text": "$ sudo add-apt-repository ppa:upubuntu-com/network" }, { "code": null, "e": 1821, "s": 1781, "text": "The sample output should be like this –" }, { "code": null, "e": 2315, "s": 1821, "text": "More info: https://launchpad.net/~upubuntu-com/+archive/ubuntu/network\nPress [ENTER] to continue or ctrl-c to cancel adding it\n\ngpg: keyring `/tmp/tmpaj4fxqym/secring.gpg' created\ngpg: keyring `/tmp/tmpaj4fxqym/pubring.gpg' created\ngpg: requesting key E06E6293 from hkp server keyserver.ubuntu.com\n\ngpg: /tmp/tmpaj4fxqym/trustdb.gpg: trustdb created\ngpg: key E06E6293: public key \"Launchpad PPA for upubuntu.com\" imported\ngpg: Total number processed: 1\ngpg: imported: 1 (RSA: 1)\nOK" }, { "code": null, "e": 2383, "s": 2315, "text": "Now update the Linux package index by using the following command –" }, { "code": null, "e": 2405, "s": 2383, "text": "$ sudo apt-get update" }, { "code": null, "e": 2445, "s": 2405, "text": "The sample output should be like this –" }, { "code": null, "e": 4440, "s": 2445, "text": "Ign http://dl.google.com stable InRelease\nGet:1 http://dl.google.com stable Release.gpg [181 B]\nGet:2 http://dl.google.com stable Release [782 B]\nGet:3 http://security.ubuntu.com trusty-security InRelease [65.9 kB]\nIgn http://extras.ubuntu.com trusty InRelease\nIgn http://in.archive.ubuntu.com trusty InRelease\nHit http://ppa.launchpad.net trusty InRelease\nGet:4 http://dl.google.com stable/main amd64 Packages [1,215 B]\nGet:5 http://extras.ubuntu.com trusty Release.gpg [72 B]\nGet:6 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB]\nHit http://ppa.launchpad.net trusty InRelease\nHit http://extras.ubuntu.com trusty Release\nGet:7 http://ppa.launchpad.net trusty InRelease [20.9 kB]\nHit http://extras.ubuntu.com trusty/main Sources\nGet:8 http://security.ubuntu.com trusty-security/main Sources [108 kB]\nHit http://extras.ubuntu.com trusty/main amd64 Packages\nGet:9 http://in.archive.ubuntu.com trusty-backports InRelease [65.9 kB]\nIgn http://ppa.launchpad.net trusty InRelease\nHit http://extras.ubuntu.com trusty/main i386 Packages\nGet:10 http://security.ubuntu.com trusty-security/restricted Sources [4,035 B]\nIgn http://ppa.launchpad.net trusty InRelease\nGet:11 http://security.ubuntu.com trusty-security/universe Sources [34.0 kB]\nHit http://in.archive.ubuntu.com trusty Release.gpg\nHit http://ppa.launchpad.net trusty/main amd64 Packages\nGet:12 http://security.ubuntu.com trusty-security/multiverse Sources [2,750 B]\nGet:13 http://in.archive.ubuntu.com trusty-updates/main Sources [264 kB]\nHit http://ppa.launchpad.net trusty/main i386 Packages\nGet:14 http://security.ubuntu.com trusty-security/main amd64 Packages [444 kB]\nHit http://ppa.launchpad.net trusty/main Translation-en\nHit http://ppa.launchpad.net trusty/main amd64 Packages\nHit http://ppa.launchpad.net trusty/main i386 Packages\nHit http://ppa.launchpad.net trusty/main Translation-en\nGet:15 http://ppa.launchpad.net trusty/main amd64 Packages [27.9 kB]\n............................................................." }, { "code": null, "e": 4491, "s": 4440, "text": "To install IP scanner, use the following command –" }, { "code": null, "e": 4521, "s": 4491, "text": "$ sudo apt-get install ipscan" }, { "code": null, "e": 4561, "s": 4521, "text": "The sample output should be like this –" }, { "code": null, "e": 5601, "s": 4561, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic\n linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic\n linux-signed-image-4.2.0-27-generic\nUse 'apt-get autoremove' to remove them.\nThe following extra packages will be installed:\n ca-certificates-java fonts-dejavu-extra java-common libatk-wrapper-java\n libatk-wrapper-java-jni libgconf2-4 libsctp1 lksctp-tools openjdk-7-jre\n openjdk-7-jre-headless tzdata-java\nSuggested packages:\n default-jre equivs icedtea-7-plugin icedtea-7-jre-jamvm sun-java6-fonts\n fonts-ipafont-gothic fonts-ipafont-mincho ttf-wqy-microhei ttf-wqy-zenhei\n ttf-telugu-fonts ttf-oriya-fonts ttf-kannada-fonts ttf-bengali-fonts\nThe following NEW packages will be installed:\n ca-certificates-java fonts-dejavu-extra ipscan java-common\n.........................................................." }, { "code": null, "e": 5649, "s": 5601, "text": "To open IP scanner, use the following command –" }, { "code": null, "e": 5658, "s": 5649, "text": "$ ipscan" }, { "code": null, "e": 5691, "s": 5658, "text": "The output should be like this –" }, { "code": null, "e": 5746, "s": 5691, "text": "To remove angryIP scanner, use the following command –" }, { "code": null, "e": 5775, "s": 5746, "text": "$ sudo apt-get remove ipscan" }, { "code": null, "e": 5815, "s": 5775, "text": "The sample output should be like this –" }, { "code": null, "e": 6753, "s": 5815, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n libapache2-mod-php5 linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic\n linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic\n linux-signed-image-4.2.0-27-generic\nUse 'apt-get autoremove' to remove them.\nThe following packages will be REMOVED:\n ipscan\n0 upgraded, 0 newly installed, 1 to remove and 12 not upgraded.\nAfter this operation, 3,358 kB disk space will be freed.\nDo you want to continue? [Y/n] y\n(Reading database ... 251656 files and directories currently installed.)\nRemoving ipscan (3.3.3) ...\nProcessing triggers for gnome-menus (3.10.1-0ubuntu2) ...\nProcessing triggers for desktop-file-utils (0.22-1ubuntu1) ...\nProcessing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ...\n..............................................." }, { "code": null, "e": 6803, "s": 6753, "text": "Now remove added PPA, use the following command –" }, { "code": null, "e": 6863, "s": 6803, "text": "$ sudo add-apt-repository --remove ppa:upubuntu-com/network" }, { "code": null, "e": 6903, "s": 6863, "text": "The sample output should be like this –" }, { "code": null, "e": 7032, "s": 6903, "text": "More info: https://launchpad.net/~upubuntu-com/+archive/ubuntu/network\nPress [ENTER] to continue or ctrl-c to cancel removing it" }, { "code": null, "e": 7097, "s": 7032, "text": "Now update Linux package index, by using the following command –" }, { "code": null, "e": 7119, "s": 7097, "text": "$ sudo apt-get update" }, { "code": null, "e": 7159, "s": 7119, "text": "The sample output should be like this –" }, { "code": null, "e": 8558, "s": 7159, "text": "Ign http://dl.google.com stable InRelease\nHit http://dl.google.com stable Release.gpg\nHit http://dl.google.com stable Release\nHit http://dl.google.com stable/main amd64 Packages\nIgn http://extras.ubuntu.com trusty InRelease\nHit http://ppa.launchpad.net trusty InRelease\nGet:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB]\nHit http://extras.ubuntu.com trusty Release.gpg\nIgn http://in.archive.ubuntu.com trusty InRelease\nHit http://ppa.launchpad.net trusty InRelease\nHit http://extras.ubuntu.com trusty Release\nHit http://ppa.launchpad.net trusty InRelease\nGet:2 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB]\nHit http://extras.ubuntu.com trusty/main Sources\nIgn http://ppa.launchpad.net trusty InRelease\nGet:3 http://security.ubuntu.com trusty-security/main Sources [108 kB]\nHit http://extras.ubuntu.com trusty/main amd64 Packages\nHit http://ppa.launchpad.net trusty/main amd64 Packages\nHit http://extras.ubuntu.com trusty/main i386 Packages\nHit http://ppa.launchpad.net trusty/main i386 Packages\nGet:4 http://security.ubuntu.com trusty-security/restricted Sources [4,035 B]\nHit http://ppa.launchpad.net trusty/main Translation-en\nGet:5 http://security.ubuntu.com trusty-security/universe Sources [34.0 kB]\nHit http://ppa.launchpad.net trusty/main amd64 Packages\nGet:6 http://in.archive.ubuntu.com trusty-backports InRelease [65.9 kB]\n............................." }, { "code": null, "e": 8739, "s": 8558, "text": "Congratulations! Now, you know “How to install Angry IP Scanner from PPA in Ubuntu/Linux Mint”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
VBA - Hour Function
The Hour Function returns a number between 0 and 23 that represents the hour of the day for the specified time stamp. Hour(time) Add a button and add the following function. Private Sub Constant_demo_Click() msgbox("Line 1: " & Hour("3:13:45 PM")) msgbox("Line 2: " & Hour("23:13:45")) msgbox("Line 3: " & Hour("2:20 PM")) End Sub When you execute the above function, it produces the following output. Line 1: 15 Line 2: 23 Line 3: 14 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2053, "s": 1935, "text": "The Hour Function returns a number between 0 and 23 that represents the hour of the day for the specified time stamp." }, { "code": null, "e": 2066, "s": 2053, "text": "Hour(time) \n" }, { "code": null, "e": 2111, "s": 2066, "text": "Add a button and add the following function." }, { "code": null, "e": 2277, "s": 2111, "text": "Private Sub Constant_demo_Click()\n msgbox(\"Line 1: \" & Hour(\"3:13:45 PM\"))\n msgbox(\"Line 2: \" & Hour(\"23:13:45\"))\n msgbox(\"Line 3: \" & Hour(\"2:20 PM\"))\nEnd Sub" }, { "code": null, "e": 2348, "s": 2277, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 2383, "s": 2348, "text": "Line 1: 15\nLine 2: 23\nLine 3: 14 \n" }, { "code": null, "e": 2417, "s": 2383, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 2432, "s": 2417, "text": " Pavan Lalwani" }, { "code": null, "e": 2465, "s": 2432, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 2480, "s": 2465, "text": " Arnold Higuit" }, { "code": null, "e": 2515, "s": 2480, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2533, "s": 2515, "text": " Prashant Panchal" }, { "code": null, "e": 2566, "s": 2533, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 2584, "s": 2566, "text": " Prashant Panchal" }, { "code": null, "e": 2617, "s": 2584, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 2632, "s": 2617, "text": " Arnold Higuit" }, { "code": null, "e": 2668, "s": 2632, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 2696, "s": 2668, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 2703, "s": 2696, "text": " Print" }, { "code": null, "e": 2714, "s": 2703, "text": " Add Notes" } ]
Doctor.ai, an AI-Powered Virtual Voice Assistant for Health Care | by Sixing Huang | Towards Data Science
By Sixing Huang, Derek Ding, Emil Pastor, Irwan Butar Butar, Shiny Zhu. Supported by Maruthi Prithivirajan, Joshua Yu and Daniel Ng from Neo4j. I think a pinnacle of the future of health-care will be building the virtual medical coach to promote self-driving healthy humans. Acknowledging there’s no shortage of obstacles, I remain confident it will be built and fully clinically validated someday. The futuristic statement above was written by Eric Topol in his book Deep Medicine. According to the context, what Topol meant by a virtual medical coach was in fact a voice AI assistant. This assistant manages and learns from a vast amount of data, including personal medical records, health statuses, and scientific literature. On the one hand, it can make health recommendations, explain medical concepts and create alerts for the patients. On the other hand, it can assist the doctors in making better decisions. The COVID-19 global pandemic makes it clear that we need to make health care accessible to more people. In this regard, a voice assistant provides some nice advantages over smartphone or computer apps. Firstly, it is hands-free. A doctor in a surgery room is not going to tap a phone or type a keyboard. Secondly, a substantial proportion of the global population can neither write nor code. And let’s not forget that many are visually impaired. Thirdly, voice input is faster than typing. For languages such as Chinese, voice can be twice as fast as typing. Last but not least, a smart voice assistant can trigger an emergency alert when the patient is alone and incapacitated. This last point is especially important for single senior citizens. In my opinion, because the natural language understanding and meta-learning are still in their infancy, a virtual voice agent with bona fide artificial general intelligence will be far in the future. But that does not mean that we cannot build a voice agent with lots of practical functions today. In fact, many software building blocks are already available. We just need to put the pieces together. For example, with AWS Lex we can quickly build a chatbot that understands natural languages. Between 3 and 5 December 2021, four Neo4j fellow engineers and I — with the support of Neo4j — have participated in the Singapore Healthcare AI Datathon & EXPO 2021. We have built a virtual voice assistant called Doctor.ai. Doctor.ai was built on top of the eICU dataset. We ran Neo4j on AWS as our backend database. Lex served as our voice agent and it was connected to Neo4j via Lambda. Finally, we put together a frontend based on the React Simple Chatbot by Lucas Bassetti. Doctor.ai can serve both the patients and the doctors in English conversations. On the one hand, patients can query their own medical records but not someone else’s. On the other hand, doctors can ask for patients’ medical histories, such as their past ICU visits, diagnoses and received treatments. In addition, Doctor.ai can do rudimentary treatment recommendations for certain patients via the Neo4j Graph Data Science Library. When combined with AWS Kendra, Doctor.ai can even explain medical terms and fetch answers from medical literature. In this article, I am going to walk you through the setup of Doctor.ai and explain some of its functions, so that you can also have your own clone of Doctor.ai. I did strip some advanced features such as user authentification in this demo though. The code is hosted in my Github repository here: github.com Doctor.ai is built on the eICU dataset. According to the official documentation, this dataset is “populated with data from a combination of many critical care units throughout the continental United States. The data in the collaborative database covers patients who were admitted to critical care units in 2014 and 2015”. It contains lab results, demographic information, diagnoses, treatments and other pertinent information over 200,000 ICU visits of more than 139,000 patients. We used the full dataset as our stand-in medical records to develop Doctor.ai. You can also get a preview out of the demo dataset. If you want to use the full dataset, you should first apply for the credentialed access to it (follow the instruction here). You need to complete the CITI “Data or Specimens Only Research” course and obtain the completion report. Afterwards, fill out the form in PhysioNet and they will examine and approve your application within days. Finally, you will be able to request access to the data stored in Big Query from the Google Cloud Platform. For this project, we only need to download six tables from the eicu_crd and eicu_crd_derived databases: eicu_crd_derived diagnosis_categories icustay_detail pivoted_labeicu_crd diagnosis microlab treatment The download needs to go through Google Cloud Storage (GCS). Select each table, click EXPORT and Export to GCS, use the gz format and select one of your buckets as destination. Then you can download the data to your local machine from your bucket. Doctor.ai consists of a backend Neo4j database on an EC2 instance, the natural language understanding engine Lex and a frontend web application hosted by Amplify (Figure 4). In the datathon, we used the Neo4j Enterprise because it allowed us to regulate doctor/patient privileges via its Role-Based Access Control (RBAC) feature. We included Kendra as our FAQ engine there, too. After the datathon, I have codified most of the infrastructure into an AWS Serverless Application Model (SAM) project. Clone the project from my Github link above. Create a key pair called cloudformation.pem for your EC2, chmod 400 it and place it into the project folder. With the SAM CLI, now you just need the following three commands to manipulate the infrastructure: ## build sam build ​ ## deployment sam deploy --guided --capabilities CAPABILITY_NAMED_IAM ​ ## destruction sam delete --stack-name sam-app Choose a region such as us-east-1 where Lex is available. The deployment will be swift. It will output the ID of the Lex, the IP address and domain name of our Neo4j for the steps ahead. Unfortunately, AWS SAM has some bugs here and there. For example, it cannot set up a Lex Alias (read here). When defined in SAM, Amplify cannot be built automatically, and it also has problems with environment variables. When Kendra FAQ is used, the imported bot errors out at the KendraSearchIntent. So we need to manually configure Neo4j, Lex and Amplify before Doctor.ai can go online. First, log in your EC2 as the user “ubuntu” with your key pair: ssh -i "cloudformation.pem" ubuntu@[your neo4j EC2 public domain name] You need to import the six tables into Neo4j. Although other options may exist, I recommend that you first transfer the six files into the /var/lib/neo4j/import folder in the EC2. And then log into Neo4j in your browser via this URL: http://[your Neo4j EC IP address]:7474/browser/ Enter the initial username “neo4j” and password “s00pers3cret” and you will be greeted with the familiar Neo4j Browser interface. Run the commands in neo4j_command.txt from my repository to import the data (adjust the file names if needed). After the import, we can move on to Lex. First, make sure you are in the Lex V2 console (as long as Return to the V1 console is visible in the left panel). Click LexForDoctorai➡️ Aliases➡️ TestBotAlias ➡️ English (US) to reach the Lambda function page. Select LambdaForLex and $LATEST and click the Save button. Finally, let’s build LexForDoctorai to test whether the bot is functional. Click Intents and click the Build button. After the build, you can test LexForDoctorai by using the test console. Here, you can see that Doctor.ai could already hold a nice conversation. The test console from Lex is nice and powerful. It can both listen to and speak back to the user. However, we need a frontend so that we can deploy Doctor.ai as a web or smartphone application. We have put together a simple React frontend by Lucas Bassetti and hosted it on Amplify. I attempted to deploy the frontend in SAM but I encountered bugs. So let’s just manually deploy Amplify. First, fork this repository to your Github account because Amplify can only retrieve codes from your own account. github.com Once done, head over to the AWS Amplify page and click New app➡️ Host web app. Then select Github and Amplify will fetch all the repositories under your account. Choose doctorai-ui under your account. Click Next to the Configure build settings page, click open the Advanced settings and add five key pair environment variables: REACT_APP_AWS_ACCESS_KEY, REACT_APP_AWS_SECRET, REACT_APP_AWS_USERID, REACT_APP_LEX_botId and REACT_APP_AWS_REGION. They are your AWS access key, AWS secret access key, your AWS user id, the BotID (you can get this value from the sam deploy output) and your AWS region. Then clickNext and Save and deploy. Before we move on to test Doctor.ai, let me explain a bit how Doctor.ai works. In essence, Doctor.ai is an information retrieval system. Even though it has a grasp of natural language and can understand contexts, it is not exactly a general conversationalist. It only understands a predefined set of inquiries. Therefore, we need to speak purposefully to Doctor.ai. For example, we can ask how many times a patient visited the ICU, whether he or she was ever infected with Staphylococcus aureus, and what kind of treatment he or she received. These “purposes” are called “intents” in Lex’s jargon. Currently, Doctor.ai can fulfill the following intents: it checks whether this is the first ICU visit; it counts how many times a patient was admitted; it shows the past diagnoses, the lab results, and the isolated microorganisms; it can even recommend treatments. Augmented with some courtesy, command and test intents, Doctor.ai can hold a short conversation much like a human receptionist. Doctor.ai can also understand pronouns thanks to context understanding. We have trained Lex with sample utterances for each intent so that it can understand similar utterances in production. So when Doctor.ai is spoken to, it tries to classify the user inputs into one of the twelve intents. If the classification fails, Doctor.ai will fall back to a FallbackIntent. It is interesting to know the difference between AWS Kendra and Lex. Kendra can give answers in the form of text excerpts out of its digested text corpus. In essence, it is much like a search engine for internal private data. But it cannot aggregate numeric data. For example, we cannot ask how many times a patient has been to the ICU, what was his average blood sugar level, or what were the last two diagnoses for a certain patient. In contrast, Lex can fulfill these inquiries with the help of Lambda functions. These functions query the backend Neo4j database through Neo4j driver. We used the graph database Neo4j because it can model those many intricate eICU dimensions intuitively and easily. It gives Lex the power to aggregate data across many aspects of the patients’ health histories. Lex can even recommend treatment with the help of GDS. The treatment recommendation in Doctor.ai is based on user similarities. In principle, it works in the same way as those product recommendations in e-commerce sites. In details, Doctor.ai calculates pairwise cosine similarity between all the patients. Patients of the same gender, with age differences less than ten and with similarity scores higher than 0.9 are qualified as similar. We set these strict criteria because we want to avoid false positives. When a patient is in need of treatment recommendation, Doctor.ai first returns the treatments that his similar patients have received, and takes into account whether or not the suggested treatments are compatible with patient’s current diagnosis. If the treatments satisfy the constraints, Doctor.ai will recommend them to the doctor. But because of the stringent criteria and the scarcity of diagnosis and treatment data, currently only a small amount of patients will receive treatment recommendations. To protect privacy, we can control whose records are visible to the patients and the doctors through user authentication and authorization. With Neo4j Enterprise, we can even use role-based access control (RBAC) to make some dimensions confidential. For example, we can make the dimension “ethnicity” inaccessible to the doctors but accessible to the patients themselves. After all the theories and hard work, let’s test Doctor.ai. Use Chrome to open the Production branch URL in Amplify. Because the eICU data was anonymized, we used the pid as the patient’s name. We can read or type the following inquiries one by one and see how Doctor.ai replies. Are you online?This is patient 002-43934How many times did he visit the ICU?What was the diagnosis? As you can see from the screenshot above or from your own test, Doctor.ai is able to tell us that the patient 002–43934 has visited the ICU twice because of cardiac arrest. Let’s say patient 002–33870 is in front of us and we want to know his glucose and hemoglobin levels: Are you onlineThis is patient 002–33870What was his glucose level?What was his Hemoglobin level? Doctor.ai quickly retrieves the glucose and hemoglobin readings from his last two ICU visits. Finally, let’s try to see which treatments Doctor.ai will recommend for patient 003–2482. This is patient 003–2482What was the diagnosis?treatment recommendation Interestingly, Doctor.ai recommends consulation to this patient who suffered from drug overdose in his last ICU visit. This recommendation looks odd at first glance. But drug overdose may impair brain functions so neurological consultation may be necessary for his full recovery. In this project, we have put together Neo4j, AWS and the eICU dataset to build a small virtual voice assistant. Although Doctor.ai can fulfill only a limited set of inquiries in its current form, it is not hard to see its enormous potentials in health care: we can use it in ICU, psychiatric clinics and dentists. By changing the underlying data, we can even make it into a general purpose Q&A chatbot for other industries. Doctor.ai still needs some more polishing to become a full-fledged product. Firstly, its voice recognition is powered by the Chrome browser, which is not always precise. Secondly, it often gets confused in the conversation. This is partially due to the fact that its context memory lasts only five minutes. But it is more likely that some of its configurations need optimizations. Thirdly, although eICU is a large dataset, many patients have incomplete records. And this makes information retrieval and machine learning difficult. We can also train it to understand more intents and improve its situational awareness. Also, you can add Kendra to the mix. Finally, although the Neo4j Community version is very powerful and can handle this demo effectively, it is not for production. So you should consider the Enterprise version or AuraDB instead. So please try Doctor.ai and give us your feedbacks. Updates: A second article about Doctor.ai has been published on Neo4j’s official blog. It dives into the implementation of Lambda and Lex. The third article is about the transfer of three knowledge graphs into Doctor.ai. They make Doctor.ai into a more knowledgeable chatbot. The fourth article is based on the knowledge graphs from the third article. Doctor.ai can now make simple diagnoses based on symptoms or mutated genes thanks to the data from the knowledge graphs. The fifth article is an attempt to distribute the graph to a P2P network. The sixth article uses GPT-3 as NLU to improve performance, reduce development time and shrink code. The seventh article Can Doctor.ai understand German, Chinese and Japanese? GPT-3 Answers: Ja, 一点点 and できます! shows that Doctor.ai can understand German, Chinese and Japanese thanks to GPT-3. The eighth article improves Doctor.ai’s voice recognition with Alan AI. The ninth article uses Synthea as the new stand-in data. The tenth article uses GPT-3 to extract subject-verb-object from raw texts.
[ { "code": null, "e": 316, "s": 172, "text": "By Sixing Huang, Derek Ding, Emil Pastor, Irwan Butar Butar, Shiny Zhu. Supported by Maruthi Prithivirajan, Joshua Yu and Daniel Ng from Neo4j." }, { "code": null, "e": 571, "s": 316, "text": "I think a pinnacle of the future of health-care will be building the virtual medical coach to promote self-driving healthy humans. Acknowledging there’s no shortage of obstacles, I remain confident it will be built and fully clinically validated someday." }, { "code": null, "e": 1088, "s": 571, "text": "The futuristic statement above was written by Eric Topol in his book Deep Medicine. According to the context, what Topol meant by a virtual medical coach was in fact a voice AI assistant. This assistant manages and learns from a vast amount of data, including personal medical records, health statuses, and scientific literature. On the one hand, it can make health recommendations, explain medical concepts and create alerts for the patients. On the other hand, it can assist the doctors in making better decisions." }, { "code": null, "e": 1835, "s": 1088, "text": "The COVID-19 global pandemic makes it clear that we need to make health care accessible to more people. In this regard, a voice assistant provides some nice advantages over smartphone or computer apps. Firstly, it is hands-free. A doctor in a surgery room is not going to tap a phone or type a keyboard. Secondly, a substantial proportion of the global population can neither write nor code. And let’s not forget that many are visually impaired. Thirdly, voice input is faster than typing. For languages such as Chinese, voice can be twice as fast as typing. Last but not least, a smart voice assistant can trigger an emergency alert when the patient is alone and incapacitated. This last point is especially important for single senior citizens." }, { "code": null, "e": 2329, "s": 1835, "text": "In my opinion, because the natural language understanding and meta-learning are still in their infancy, a virtual voice agent with bona fide artificial general intelligence will be far in the future. But that does not mean that we cannot build a voice agent with lots of practical functions today. In fact, many software building blocks are already available. We just need to put the pieces together. For example, with AWS Lex we can quickly build a chatbot that understands natural languages." }, { "code": null, "e": 2807, "s": 2329, "text": "Between 3 and 5 December 2021, four Neo4j fellow engineers and I — with the support of Neo4j — have participated in the Singapore Healthcare AI Datathon & EXPO 2021. We have built a virtual voice assistant called Doctor.ai. Doctor.ai was built on top of the eICU dataset. We ran Neo4j on AWS as our backend database. Lex served as our voice agent and it was connected to Neo4j via Lambda. Finally, we put together a frontend based on the React Simple Chatbot by Lucas Bassetti." }, { "code": null, "e": 3353, "s": 2807, "text": "Doctor.ai can serve both the patients and the doctors in English conversations. On the one hand, patients can query their own medical records but not someone else’s. On the other hand, doctors can ask for patients’ medical histories, such as their past ICU visits, diagnoses and received treatments. In addition, Doctor.ai can do rudimentary treatment recommendations for certain patients via the Neo4j Graph Data Science Library. When combined with AWS Kendra, Doctor.ai can even explain medical terms and fetch answers from medical literature." }, { "code": null, "e": 3649, "s": 3353, "text": "In this article, I am going to walk you through the setup of Doctor.ai and explain some of its functions, so that you can also have your own clone of Doctor.ai. I did strip some advanced features such as user authentification in this demo though. The code is hosted in my Github repository here:" }, { "code": null, "e": 3660, "s": 3649, "text": "github.com" }, { "code": null, "e": 4272, "s": 3660, "text": "Doctor.ai is built on the eICU dataset. According to the official documentation, this dataset is “populated with data from a combination of many critical care units throughout the continental United States. The data in the collaborative database covers patients who were admitted to critical care units in 2014 and 2015”. It contains lab results, demographic information, diagnoses, treatments and other pertinent information over 200,000 ICU visits of more than 139,000 patients. We used the full dataset as our stand-in medical records to develop Doctor.ai. You can also get a preview out of the demo dataset." }, { "code": null, "e": 4717, "s": 4272, "text": "If you want to use the full dataset, you should first apply for the credentialed access to it (follow the instruction here). You need to complete the CITI “Data or Specimens Only Research” course and obtain the completion report. Afterwards, fill out the form in PhysioNet and they will examine and approve your application within days. Finally, you will be able to request access to the data stored in Big Query from the Google Cloud Platform." }, { "code": null, "e": 4821, "s": 4717, "text": "For this project, we only need to download six tables from the eicu_crd and eicu_crd_derived databases:" }, { "code": null, "e": 4941, "s": 4821, "text": "eicu_crd_derived diagnosis_categories icustay_detail pivoted_labeicu_crd diagnosis microlab treatment" }, { "code": null, "e": 5189, "s": 4941, "text": "The download needs to go through Google Cloud Storage (GCS). Select each table, click EXPORT and Export to GCS, use the gz format and select one of your buckets as destination. Then you can download the data to your local machine from your bucket." }, { "code": null, "e": 5568, "s": 5189, "text": "Doctor.ai consists of a backend Neo4j database on an EC2 instance, the natural language understanding engine Lex and a frontend web application hosted by Amplify (Figure 4). In the datathon, we used the Neo4j Enterprise because it allowed us to regulate doctor/patient privileges via its Role-Based Access Control (RBAC) feature. We included Kendra as our FAQ engine there, too." }, { "code": null, "e": 5940, "s": 5568, "text": "After the datathon, I have codified most of the infrastructure into an AWS Serverless Application Model (SAM) project. Clone the project from my Github link above. Create a key pair called cloudformation.pem for your EC2, chmod 400 it and place it into the project folder. With the SAM CLI, now you just need the following three commands to manipulate the infrastructure:" }, { "code": null, "e": 5949, "s": 5940, "text": "## build" }, { "code": null, "e": 5959, "s": 5949, "text": "sam build" }, { "code": null, "e": 5961, "s": 5959, "text": "​" }, { "code": null, "e": 5975, "s": 5961, "text": "## deployment" }, { "code": null, "e": 6031, "s": 5975, "text": "sam deploy --guided --capabilities CAPABILITY_NAMED_IAM" }, { "code": null, "e": 6033, "s": 6031, "text": "​" }, { "code": null, "e": 6048, "s": 6033, "text": "## destruction" }, { "code": null, "e": 6080, "s": 6048, "text": "sam delete --stack-name sam-app" }, { "code": null, "e": 6267, "s": 6080, "text": "Choose a region such as us-east-1 where Lex is available. The deployment will be swift. It will output the ID of the Lex, the IP address and domain name of our Neo4j for the steps ahead." }, { "code": null, "e": 6656, "s": 6267, "text": "Unfortunately, AWS SAM has some bugs here and there. For example, it cannot set up a Lex Alias (read here). When defined in SAM, Amplify cannot be built automatically, and it also has problems with environment variables. When Kendra FAQ is used, the imported bot errors out at the KendraSearchIntent. So we need to manually configure Neo4j, Lex and Amplify before Doctor.ai can go online." }, { "code": null, "e": 6720, "s": 6656, "text": "First, log in your EC2 as the user “ubuntu” with your key pair:" }, { "code": null, "e": 6791, "s": 6720, "text": "ssh -i \"cloudformation.pem\" ubuntu@[your neo4j EC2 public domain name]" }, { "code": null, "e": 7025, "s": 6791, "text": "You need to import the six tables into Neo4j. Although other options may exist, I recommend that you first transfer the six files into the /var/lib/neo4j/import folder in the EC2. And then log into Neo4j in your browser via this URL:" }, { "code": null, "e": 7073, "s": 7025, "text": "http://[your Neo4j EC IP address]:7474/browser/" }, { "code": null, "e": 7314, "s": 7073, "text": "Enter the initial username “neo4j” and password “s00pers3cret” and you will be greeted with the familiar Neo4j Browser interface. Run the commands in neo4j_command.txt from my repository to import the data (adjust the file names if needed)." }, { "code": null, "e": 7470, "s": 7314, "text": "After the import, we can move on to Lex. First, make sure you are in the Lex V2 console (as long as Return to the V1 console is visible in the left panel)." }, { "code": null, "e": 7626, "s": 7470, "text": "Click LexForDoctorai➡️ Aliases➡️ TestBotAlias ➡️ English (US) to reach the Lambda function page. Select LambdaForLex and $LATEST and click the Save button." }, { "code": null, "e": 7743, "s": 7626, "text": "Finally, let’s build LexForDoctorai to test whether the bot is functional. Click Intents and click the Build button." }, { "code": null, "e": 7888, "s": 7743, "text": "After the build, you can test LexForDoctorai by using the test console. Here, you can see that Doctor.ai could already hold a nice conversation." }, { "code": null, "e": 8276, "s": 7888, "text": "The test console from Lex is nice and powerful. It can both listen to and speak back to the user. However, we need a frontend so that we can deploy Doctor.ai as a web or smartphone application. We have put together a simple React frontend by Lucas Bassetti and hosted it on Amplify. I attempted to deploy the frontend in SAM but I encountered bugs. So let’s just manually deploy Amplify." }, { "code": null, "e": 8390, "s": 8276, "text": "First, fork this repository to your Github account because Amplify can only retrieve codes from your own account." }, { "code": null, "e": 8401, "s": 8390, "text": "github.com" }, { "code": null, "e": 8999, "s": 8401, "text": "Once done, head over to the AWS Amplify page and click New app➡️ Host web app. Then select Github and Amplify will fetch all the repositories under your account. Choose doctorai-ui under your account. Click Next to the Configure build settings page, click open the Advanced settings and add five key pair environment variables: REACT_APP_AWS_ACCESS_KEY, REACT_APP_AWS_SECRET, REACT_APP_AWS_USERID, REACT_APP_LEX_botId and REACT_APP_AWS_REGION. They are your AWS access key, AWS secret access key, your AWS user id, the BotID (you can get this value from the sam deploy output) and your AWS region." }, { "code": null, "e": 9035, "s": 8999, "text": "Then clickNext and Save and deploy." }, { "code": null, "e": 9633, "s": 9035, "text": "Before we move on to test Doctor.ai, let me explain a bit how Doctor.ai works. In essence, Doctor.ai is an information retrieval system. Even though it has a grasp of natural language and can understand contexts, it is not exactly a general conversationalist. It only understands a predefined set of inquiries. Therefore, we need to speak purposefully to Doctor.ai. For example, we can ask how many times a patient visited the ICU, whether he or she was ever infected with Staphylococcus aureus, and what kind of treatment he or she received. These “purposes” are called “intents” in Lex’s jargon." }, { "code": null, "e": 10393, "s": 9633, "text": "Currently, Doctor.ai can fulfill the following intents: it checks whether this is the first ICU visit; it counts how many times a patient was admitted; it shows the past diagnoses, the lab results, and the isolated microorganisms; it can even recommend treatments. Augmented with some courtesy, command and test intents, Doctor.ai can hold a short conversation much like a human receptionist. Doctor.ai can also understand pronouns thanks to context understanding. We have trained Lex with sample utterances for each intent so that it can understand similar utterances in production. So when Doctor.ai is spoken to, it tries to classify the user inputs into one of the twelve intents. If the classification fails, Doctor.ai will fall back to a FallbackIntent." }, { "code": null, "e": 11246, "s": 10393, "text": "It is interesting to know the difference between AWS Kendra and Lex. Kendra can give answers in the form of text excerpts out of its digested text corpus. In essence, it is much like a search engine for internal private data. But it cannot aggregate numeric data. For example, we cannot ask how many times a patient has been to the ICU, what was his average blood sugar level, or what were the last two diagnoses for a certain patient. In contrast, Lex can fulfill these inquiries with the help of Lambda functions. These functions query the backend Neo4j database through Neo4j driver. We used the graph database Neo4j because it can model those many intricate eICU dimensions intuitively and easily. It gives Lex the power to aggregate data across many aspects of the patients’ health histories. Lex can even recommend treatment with the help of GDS." }, { "code": null, "e": 12207, "s": 11246, "text": "The treatment recommendation in Doctor.ai is based on user similarities. In principle, it works in the same way as those product recommendations in e-commerce sites. In details, Doctor.ai calculates pairwise cosine similarity between all the patients. Patients of the same gender, with age differences less than ten and with similarity scores higher than 0.9 are qualified as similar. We set these strict criteria because we want to avoid false positives. When a patient is in need of treatment recommendation, Doctor.ai first returns the treatments that his similar patients have received, and takes into account whether or not the suggested treatments are compatible with patient’s current diagnosis. If the treatments satisfy the constraints, Doctor.ai will recommend them to the doctor. But because of the stringent criteria and the scarcity of diagnosis and treatment data, currently only a small amount of patients will receive treatment recommendations." }, { "code": null, "e": 12579, "s": 12207, "text": "To protect privacy, we can control whose records are visible to the patients and the doctors through user authentication and authorization. With Neo4j Enterprise, we can even use role-based access control (RBAC) to make some dimensions confidential. For example, we can make the dimension “ethnicity” inaccessible to the doctors but accessible to the patients themselves." }, { "code": null, "e": 12773, "s": 12579, "text": "After all the theories and hard work, let’s test Doctor.ai. Use Chrome to open the Production branch URL in Amplify. Because the eICU data was anonymized, we used the pid as the patient’s name." }, { "code": null, "e": 12859, "s": 12773, "text": "We can read or type the following inquiries one by one and see how Doctor.ai replies." }, { "code": null, "e": 12959, "s": 12859, "text": "Are you online?This is patient 002-43934How many times did he visit the ICU?What was the diagnosis?" }, { "code": null, "e": 13132, "s": 12959, "text": "As you can see from the screenshot above or from your own test, Doctor.ai is able to tell us that the patient 002–43934 has visited the ICU twice because of cardiac arrest." }, { "code": null, "e": 13233, "s": 13132, "text": "Let’s say patient 002–33870 is in front of us and we want to know his glucose and hemoglobin levels:" }, { "code": null, "e": 13330, "s": 13233, "text": "Are you onlineThis is patient 002–33870What was his glucose level?What was his Hemoglobin level?" }, { "code": null, "e": 13424, "s": 13330, "text": "Doctor.ai quickly retrieves the glucose and hemoglobin readings from his last two ICU visits." }, { "code": null, "e": 13514, "s": 13424, "text": "Finally, let’s try to see which treatments Doctor.ai will recommend for patient 003–2482." }, { "code": null, "e": 13586, "s": 13514, "text": "This is patient 003–2482What was the diagnosis?treatment recommendation" }, { "code": null, "e": 13866, "s": 13586, "text": "Interestingly, Doctor.ai recommends consulation to this patient who suffered from drug overdose in his last ICU visit. This recommendation looks odd at first glance. But drug overdose may impair brain functions so neurological consultation may be necessary for his full recovery." }, { "code": null, "e": 14290, "s": 13866, "text": "In this project, we have put together Neo4j, AWS and the eICU dataset to build a small virtual voice assistant. Although Doctor.ai can fulfill only a limited set of inquiries in its current form, it is not hard to see its enormous potentials in health care: we can use it in ICU, psychiatric clinics and dentists. By changing the underlying data, we can even make it into a general purpose Q&A chatbot for other industries." }, { "code": null, "e": 15138, "s": 14290, "text": "Doctor.ai still needs some more polishing to become a full-fledged product. Firstly, its voice recognition is powered by the Chrome browser, which is not always precise. Secondly, it often gets confused in the conversation. This is partially due to the fact that its context memory lasts only five minutes. But it is more likely that some of its configurations need optimizations. Thirdly, although eICU is a large dataset, many patients have incomplete records. And this makes information retrieval and machine learning difficult. We can also train it to understand more intents and improve its situational awareness. Also, you can add Kendra to the mix. Finally, although the Neo4j Community version is very powerful and can handle this demo effectively, it is not for production. So you should consider the Enterprise version or AuraDB instead." }, { "code": null, "e": 15190, "s": 15138, "text": "So please try Doctor.ai and give us your feedbacks." }, { "code": null, "e": 15199, "s": 15190, "text": "Updates:" }, { "code": null, "e": 15329, "s": 15199, "text": "A second article about Doctor.ai has been published on Neo4j’s official blog. It dives into the implementation of Lambda and Lex." }, { "code": null, "e": 15466, "s": 15329, "text": "The third article is about the transfer of three knowledge graphs into Doctor.ai. They make Doctor.ai into a more knowledgeable chatbot." }, { "code": null, "e": 15663, "s": 15466, "text": "The fourth article is based on the knowledge graphs from the third article. Doctor.ai can now make simple diagnoses based on symptoms or mutated genes thanks to the data from the knowledge graphs." }, { "code": null, "e": 15737, "s": 15663, "text": "The fifth article is an attempt to distribute the graph to a P2P network." }, { "code": null, "e": 15838, "s": 15737, "text": "The sixth article uses GPT-3 as NLU to improve performance, reduce development time and shrink code." }, { "code": null, "e": 16029, "s": 15838, "text": "The seventh article Can Doctor.ai understand German, Chinese and Japanese? GPT-3 Answers: Ja, 一点点 and できます! shows that Doctor.ai can understand German, Chinese and Japanese thanks to GPT-3." }, { "code": null, "e": 16101, "s": 16029, "text": "The eighth article improves Doctor.ai’s voice recognition with Alan AI." }, { "code": null, "e": 16158, "s": 16101, "text": "The ninth article uses Synthea as the new stand-in data." } ]
How to check if a string contains a certain word in C#?
Use the Contains() method to check if a string contains a word or not. Set the string − string s = "Together we can do so much!"; Now let’s say you need to find the word “much” if (s.Contains("much") == true) { Console.WriteLine("Word found!"); } Let us see the complete code − Live Demo using System; public class Demo { public static void Main() { string s = "Together we can do so much!"; if (s.Contains("much") == true) { Console.WriteLine("Word found!"); } else { Console.WriteLine("Word not found!"); } } } Word found!
[ { "code": null, "e": 1133, "s": 1062, "text": "Use the Contains() method to check if a string contains a word or not." }, { "code": null, "e": 1150, "s": 1133, "text": "Set the string −" }, { "code": null, "e": 1192, "s": 1150, "text": "string s = \"Together we can do so much!\";" }, { "code": null, "e": 1239, "s": 1192, "text": "Now let’s say you need to find the word “much”" }, { "code": null, "e": 1312, "s": 1239, "text": "if (s.Contains(\"much\") == true) {\n Console.WriteLine(\"Word found!\");\n}" }, { "code": null, "e": 1343, "s": 1312, "text": "Let us see the complete code −" }, { "code": null, "e": 1354, "s": 1343, "text": " Live Demo" }, { "code": null, "e": 1628, "s": 1354, "text": "using System;\n\npublic class Demo {\n public static void Main() {\n string s = \"Together we can do so much!\";\n if (s.Contains(\"much\") == true) {\n Console.WriteLine(\"Word found!\");\n } else {\n Console.WriteLine(\"Word not found!\");\n }\n }\n}" }, { "code": null, "e": 1640, "s": 1628, "text": "Word found!" } ]
How to initialize a string to an empty string in C#?
To initialize a string to an empty list − string myStr = null; Now, use the built-in method IsNullOrEmpty() to check whether the list is empty or not − if (string.IsNullOrEmpty(myStr)) { Console.WriteLine("String is empty or null!"); } Let us see the complete code − Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { string myStr = null; if (string.IsNullOrEmpty(myStr)) { Console.WriteLine("String is empty or null!"); } Console.ReadKey(); } } } String is empty or null! Another way to initialize a string to an empty string, try the following code. Here, we have used string.Empty − Live Demo using System; namespace Demo { public class Program { public static void Main(string[] args) { string myStr = string.Empty; if (string.IsNullOrEmpty(myStr)) { Console.WriteLine("String is empty or null!"); } else { Console.WriteLine("String isn't empty or null!"); } } } } String is empty or null!
[ { "code": null, "e": 1104, "s": 1062, "text": "To initialize a string to an empty list −" }, { "code": null, "e": 1125, "s": 1104, "text": "string myStr = null;" }, { "code": null, "e": 1214, "s": 1125, "text": "Now, use the built-in method IsNullOrEmpty() to check whether the list is empty or not −" }, { "code": null, "e": 1301, "s": 1214, "text": "if (string.IsNullOrEmpty(myStr)) {\n Console.WriteLine(\"String is empty or null!\");\n}" }, { "code": null, "e": 1332, "s": 1301, "text": "Let us see the complete code −" }, { "code": null, "e": 1343, "s": 1332, "text": " Live Demo" }, { "code": null, "e": 1622, "s": 1343, "text": "using System;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n string myStr = null;\n\n if (string.IsNullOrEmpty(myStr)) {\n Console.WriteLine(\"String is empty or null!\");\n }\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 1647, "s": 1622, "text": "String is empty or null!" }, { "code": null, "e": 1760, "s": 1647, "text": "Another way to initialize a string to an empty string, try the following code. Here, we have used string.Empty −" }, { "code": null, "e": 1771, "s": 1760, "text": " Live Demo" }, { "code": null, "e": 2124, "s": 1771, "text": "using System;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n string myStr = string.Empty;\n\n if (string.IsNullOrEmpty(myStr)) {\n Console.WriteLine(\"String is empty or null!\");\n } else {\n Console.WriteLine(\"String isn't empty or null!\");\n }\n }\n }\n}" }, { "code": null, "e": 2149, "s": 2124, "text": "String is empty or null!" } ]
Complex Demodulation Phase and Amplitude Plot - GeeksforGeeks
14 Aug, 2021 In the frequency analysis of time series models, a common model is a sinusoidal wave: where, ∝ is the amplitude, phi is the phase shift and omega is the dominant frequency. The goal of the complex demodulation plot is to improve the frequency estimate. The complex demodulation plots formed by two components: Vertical axis: Phase Horizontal axis: Time The non-linear fitting for the sinusoidal waves The above equation is sensitive to good initial values. The initial value of frequency omega can be obtained by the spectral plot. The complex demodulation phase plot is used to assess whether this estimate is adequate. If the estimate is not adequate then whether it should be increased and decreased. In the frequency analysis of time series models, a common model is a sinusoidal wave: where, ∝ is the amplitude, phi is the phase shift and omega is the dominant frequency. If the slope of the complex demodulation amplitude plot is not zero, then the above equation is finally replaced by the model. where, ai is some type of linear model fit with standard least squares. The most common case is linear fit, that is the model becomes as follows: The complex demodulation amplitude plot is formed by Vertical axis: Amplitude Horizontal axis: Time The complex amplitude demodulation plot answers the following questions: Does amplitude change over time? Is there any start-up effect that led to the amplitude being unstable at the start? Is there any outliers in amplitude? python3 # codeimport numpy as npimport matplotlib.pyplot as plt def gen_test_data(periods, noise=0, rotary=False, npts=1000, dt=1.0/24): """ Generate a simple time series for testing complex demodulation. *periods* is a sequence with the periods of one or more harmonics that will be added to make the test signal. They can be positive or negative. *noise* is the amplitude of independent Gaussian noise. *rotary* is Boolean; if True, the test signal is complex. *npts* is the length of the series. *dt* is the time interval (default is 1.0/24) Returns t, x: ndarrays with the test times and test data values.. """ t = np.arange(npts, dtype=float) * dt if rotary: x = noise * (np.random.randn(npts) + 1j * np.random.randn(npts)) else: x = noise * np.random.randn(npts) for p in periods: if rotary: x += np.exp(2j * np.pi * t / p) else: x += np.cos(2 * np.pi * t / p) return t, x def complex_demodulation(t, x, central_period, hwidth = 2): """ Complex demodulation of a real or complex series, *x* of samples at times *t*, assumed to be uniformly spaced. *central_period* is the period of the central frequency for the demodulation. It should be positive for real signals. For complex signals, a positive value will return the CCW rotary component, and a negative value will return the CW component (negative frequency). Period is in the same time units as are used for *t*. *hwidth* is the Blackman filter half-width in units of the *central_period*. For example, the default value of 2 makes the Blackman half-width equal to twice the central period. Returns a dictionary. """ rotary = x.dtype.kind == 'c' # complex input # Make the complex exponential for demodulation: c = np.exp(-1j * 2 * np.pi * t / central_period) product = x * c # filter half-width number of points dt = t[1] - t[0] hwpts = int(round(hwidth * abs(central_period) / dt)) nf = hwpts * 2 + 1 x1 = np.linspace(-1, 1, nf, endpoint=True) x1 = x1[1:-1] # chop off the useless endpoints with zero weight w1 = 0.42 + 0.5 * np.cos(x1 * np.pi) + 0.08 * np.cos(x1 * 2 * np.pi) ytop = np.convolve(product, w1, mode='same') ybot = np.convolve(np.ones_like(product), w1, mode='same') demod = ytop/ybot if not rotary: # The factor of 2 below comes from fact that the # mean value of a squared unit sinusoid is 0.5. demod *= 2 reconstructed = (demod * np.conj(c)) if not rotary: reconstructed = reconstructed.real if np.sign(central_period) < 0: demod = np.conj(demod) # This is to make the phase increase in time # for both positive and negative demod frequency # when the frequency of the signal exceeds the # frequency of the demodulation. d = {'t':t,'signal' : x,'hwpts' : hwpts,'demod': demod,'reconstructed' : reconstructed} return d def plot_demodulation(dm): fig, axs = plt.subplots(3, sharex=True) resid = dm.get('signal') - dm.get('reconstructed') if dm.get('signal').dtype.kind == 'c': axs[0].plot(dm.get('t'), dm.get('signal').real, label='signal.real') axs[0].plot(dm.get('t'), dm.get('signal').imag, label='signal.imag') axs[0].plot(dm.get('t'), resid.real, label='difference real') axs[0].plot(dm.get('t'), resid.imag, label='difference imag') else: axs[0].plot(dm.get('t'), dm.get('signal'), label='signal') axs[0].plot(dm.get('t'), dm.get('reconstructed'), label='reconstructed') axs[0].plot(dm.get('t'), dm.get('signal') - dm.get('reconstructed'), label='difference') axs[0].legend(loc='upper right', fontsize='small') axs[1].plot(dm.get('t'), np.abs(dm.get('demod')), label='amplitude', color='C3') axs[1].legend(loc='upper right', fontsize='small') axs[2].plot(dm.get('t'), np.angle(dm.get('demod'), deg=True), '.', label='phase', color='C4') axs[2].set_ylim(-180, 180) axs[2].legend(loc='upper right', fontsize='small') for ax in axs: ax.locator_params(axis='y', nbins=5) return fig, axs def test_demodulation(periods, central_period, noise=0, rotary=False, hwidth = 1, npts=1000, dt=1.0/24): t, x = gen_test_data(periods, noise=noise, rotary=rotary, npts=npts, dt=dt) dm = complex_demodulation(t, x, central_period, hwidth=hwidth) fig, axs = plot_demodulation(dm) return fig, axs, dm# Example 1test_demodulation([12.0/24], 12.0/24);# Example 2test_demodulation([11.0/24], 12.0/24) Example 1: Signal, amplitude demodulation, and phase demodulation Example 2: Signal, amplitude demodulation, and phase demodulation gulshankumarar231 Data Visualization ML-EDA ML-plots Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Intuition of Adam Optimizer ML | Logistic Regression using Python Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24344, "s": 24316, "text": "\n14 Aug, 2021" }, { "code": null, "e": 24430, "s": 24344, "text": "In the frequency analysis of time series models, a common model is a sinusoidal wave:" }, { "code": null, "e": 24597, "s": 24430, "text": "where, ∝ is the amplitude, phi is the phase shift and omega is the dominant frequency. The goal of the complex demodulation plot is to improve the frequency estimate." }, { "code": null, "e": 24655, "s": 24597, "text": " The complex demodulation plots formed by two components:" }, { "code": null, "e": 24676, "s": 24655, "text": "Vertical axis: Phase" }, { "code": null, "e": 24698, "s": 24676, "text": "Horizontal axis: Time" }, { "code": null, "e": 24746, "s": 24698, "text": "The non-linear fitting for the sinusoidal waves" }, { "code": null, "e": 25051, "s": 24748, "text": "The above equation is sensitive to good initial values. The initial value of frequency omega can be obtained by the spectral plot. The complex demodulation phase plot is used to assess whether this estimate is adequate. If the estimate is not adequate then whether it should be increased and decreased." }, { "code": null, "e": 25137, "s": 25051, "text": "In the frequency analysis of time series models, a common model is a sinusoidal wave:" }, { "code": null, "e": 25226, "s": 25139, "text": "where, ∝ is the amplitude, phi is the phase shift and omega is the dominant frequency." }, { "code": null, "e": 25353, "s": 25226, "text": "If the slope of the complex demodulation amplitude plot is not zero, then the above equation is finally replaced by the model." }, { "code": null, "e": 25499, "s": 25353, "text": "where, ai is some type of linear model fit with standard least squares. The most common case is linear fit, that is the model becomes as follows:" }, { "code": null, "e": 25552, "s": 25499, "text": "The complex demodulation amplitude plot is formed by" }, { "code": null, "e": 25577, "s": 25552, "text": "Vertical axis: Amplitude" }, { "code": null, "e": 25599, "s": 25577, "text": "Horizontal axis: Time" }, { "code": null, "e": 25673, "s": 25599, "text": " The complex amplitude demodulation plot answers the following questions:" }, { "code": null, "e": 25706, "s": 25673, "text": "Does amplitude change over time?" }, { "code": null, "e": 25790, "s": 25706, "text": "Is there any start-up effect that led to the amplitude being unstable at the start?" }, { "code": null, "e": 25826, "s": 25790, "text": "Is there any outliers in amplitude?" }, { "code": null, "e": 25834, "s": 25826, "text": "python3" }, { "code": "# codeimport numpy as npimport matplotlib.pyplot as plt def gen_test_data(periods, noise=0, rotary=False, npts=1000, dt=1.0/24): \"\"\" Generate a simple time series for testing complex demodulation. *periods* is a sequence with the periods of one or more harmonics that will be added to make the test signal. They can be positive or negative. *noise* is the amplitude of independent Gaussian noise. *rotary* is Boolean; if True, the test signal is complex. *npts* is the length of the series. *dt* is the time interval (default is 1.0/24) Returns t, x: ndarrays with the test times and test data values.. \"\"\" t = np.arange(npts, dtype=float) * dt if rotary: x = noise * (np.random.randn(npts) + 1j * np.random.randn(npts)) else: x = noise * np.random.randn(npts) for p in periods: if rotary: x += np.exp(2j * np.pi * t / p) else: x += np.cos(2 * np.pi * t / p) return t, x def complex_demodulation(t, x, central_period, hwidth = 2): \"\"\" Complex demodulation of a real or complex series, *x* of samples at times *t*, assumed to be uniformly spaced. *central_period* is the period of the central frequency for the demodulation. It should be positive for real signals. For complex signals, a positive value will return the CCW rotary component, and a negative value will return the CW component (negative frequency). Period is in the same time units as are used for *t*. *hwidth* is the Blackman filter half-width in units of the *central_period*. For example, the default value of 2 makes the Blackman half-width equal to twice the central period. Returns a dictionary. \"\"\" rotary = x.dtype.kind == 'c' # complex input # Make the complex exponential for demodulation: c = np.exp(-1j * 2 * np.pi * t / central_period) product = x * c # filter half-width number of points dt = t[1] - t[0] hwpts = int(round(hwidth * abs(central_period) / dt)) nf = hwpts * 2 + 1 x1 = np.linspace(-1, 1, nf, endpoint=True) x1 = x1[1:-1] # chop off the useless endpoints with zero weight w1 = 0.42 + 0.5 * np.cos(x1 * np.pi) + 0.08 * np.cos(x1 * 2 * np.pi) ytop = np.convolve(product, w1, mode='same') ybot = np.convolve(np.ones_like(product), w1, mode='same') demod = ytop/ybot if not rotary: # The factor of 2 below comes from fact that the # mean value of a squared unit sinusoid is 0.5. demod *= 2 reconstructed = (demod * np.conj(c)) if not rotary: reconstructed = reconstructed.real if np.sign(central_period) < 0: demod = np.conj(demod) # This is to make the phase increase in time # for both positive and negative demod frequency # when the frequency of the signal exceeds the # frequency of the demodulation. d = {'t':t,'signal' : x,'hwpts' : hwpts,'demod': demod,'reconstructed' : reconstructed} return d def plot_demodulation(dm): fig, axs = plt.subplots(3, sharex=True) resid = dm.get('signal') - dm.get('reconstructed') if dm.get('signal').dtype.kind == 'c': axs[0].plot(dm.get('t'), dm.get('signal').real, label='signal.real') axs[0].plot(dm.get('t'), dm.get('signal').imag, label='signal.imag') axs[0].plot(dm.get('t'), resid.real, label='difference real') axs[0].plot(dm.get('t'), resid.imag, label='difference imag') else: axs[0].plot(dm.get('t'), dm.get('signal'), label='signal') axs[0].plot(dm.get('t'), dm.get('reconstructed'), label='reconstructed') axs[0].plot(dm.get('t'), dm.get('signal') - dm.get('reconstructed'), label='difference') axs[0].legend(loc='upper right', fontsize='small') axs[1].plot(dm.get('t'), np.abs(dm.get('demod')), label='amplitude', color='C3') axs[1].legend(loc='upper right', fontsize='small') axs[2].plot(dm.get('t'), np.angle(dm.get('demod'), deg=True), '.', label='phase', color='C4') axs[2].set_ylim(-180, 180) axs[2].legend(loc='upper right', fontsize='small') for ax in axs: ax.locator_params(axis='y', nbins=5) return fig, axs def test_demodulation(periods, central_period, noise=0, rotary=False, hwidth = 1, npts=1000, dt=1.0/24): t, x = gen_test_data(periods, noise=noise, rotary=rotary, npts=npts, dt=dt) dm = complex_demodulation(t, x, central_period, hwidth=hwidth) fig, axs = plot_demodulation(dm) return fig, axs, dm# Example 1test_demodulation([12.0/24], 12.0/24);# Example 2test_demodulation([11.0/24], 12.0/24)", "e": 30643, "s": 25834, "text": null }, { "code": null, "e": 30709, "s": 30643, "text": "Example 1: Signal, amplitude demodulation, and phase demodulation" }, { "code": null, "e": 30775, "s": 30709, "text": "Example 2: Signal, amplitude demodulation, and phase demodulation" }, { "code": null, "e": 30793, "s": 30775, "text": "gulshankumarar231" }, { "code": null, "e": 30812, "s": 30793, "text": "Data Visualization" }, { "code": null, "e": 30819, "s": 30812, "text": "ML-EDA" }, { "code": null, "e": 30828, "s": 30819, "text": "ML-plots" }, { "code": null, "e": 30845, "s": 30828, "text": "Machine Learning" }, { "code": null, "e": 30852, "s": 30845, "text": "Python" }, { "code": null, "e": 30869, "s": 30852, "text": "Machine Learning" }, { "code": null, "e": 30967, "s": 30869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31000, "s": 30967, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 31039, "s": 31000, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 31074, "s": 31039, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 31102, "s": 31074, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 31140, "s": 31102, "text": "ML | Logistic Regression using Python" }, { "code": null, "e": 31168, "s": 31140, "text": "Read JSON file using Python" }, { "code": null, "e": 31218, "s": 31168, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31240, "s": 31218, "text": "Python map() function" } ]
Domino and Tromino Tiling in C++
Suppose we have two types of shapes, Domino and Tromino. They can be rotated like below − In a tiling, every square must be covered by a tile. Here two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. Given N, then we have to find in how many ways we can tile 2xN board? So if the input is 3, then the output will be 5. So the arrangements can be [XYZ XXZ XYY XXY XYY] and [XYZ YYZ XZZ XYY XXY], here different letters are used for different tiles. To solve this, we will follow these steps − Make an array called dp of size N + 5, set dp[1] := 1, dp[2] := 2 and dp[3] := 5 Make an array called dp of size N + 5, set dp[1] := 1, dp[2] := 2 and dp[3] := 5 for i in range 4 to Ndp[i] := 2*dp[i – 1] + dp[i – 3] for i in range 4 to N dp[i] := 2*dp[i – 1] + dp[i – 3] dp[i] := 2*dp[i – 1] + dp[i – 3] return dp[N] return dp[N] Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; int add(int a, int b){ return ((a % MOD) + (b % MOD)) % MOD; } class Solution { public: int numTilings(int N) { vector <int> dp(N + 5); dp[1] = 1; dp[2] = 2; dp[3] = 5; for(int i = 4; i <= N; i++){ dp[i] = add(2 * dp[i - 1], dp[i - 3]); } return dp[N]; } }; main(){ Solution ob; cout << (ob.numTilings(3)); } 3 5
[ { "code": null, "e": 1152, "s": 1062, "text": "Suppose we have two types of shapes, Domino and Tromino. They can be rotated like below −" }, { "code": null, "e": 1383, "s": 1152, "text": "In a tiling, every square must be covered by a tile. Here two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile." }, { "code": null, "e": 1631, "s": 1383, "text": "Given N, then we have to find in how many ways we can tile 2xN board? So if the input is 3, then the output will be 5. So the arrangements can be [XYZ XXZ XYY XXY XYY] and [XYZ YYZ XZZ XYY XXY], here different letters are used for different tiles." }, { "code": null, "e": 1675, "s": 1631, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1756, "s": 1675, "text": "Make an array called dp of size N + 5, set dp[1] := 1, dp[2] := 2 and dp[3] := 5" }, { "code": null, "e": 1837, "s": 1756, "text": "Make an array called dp of size N + 5, set dp[1] := 1, dp[2] := 2 and dp[3] := 5" }, { "code": null, "e": 1891, "s": 1837, "text": "for i in range 4 to Ndp[i] := 2*dp[i – 1] + dp[i – 3]" }, { "code": null, "e": 1913, "s": 1891, "text": "for i in range 4 to N" }, { "code": null, "e": 1946, "s": 1913, "text": "dp[i] := 2*dp[i – 1] + dp[i – 3]" }, { "code": null, "e": 1979, "s": 1946, "text": "dp[i] := 2*dp[i – 1] + dp[i – 3]" }, { "code": null, "e": 1992, "s": 1979, "text": "return dp[N]" }, { "code": null, "e": 2005, "s": 1992, "text": "return dp[N]" }, { "code": null, "e": 2077, "s": 2005, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2088, "s": 2077, "text": " Live Demo" }, { "code": null, "e": 2537, "s": 2088, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MOD = 1e9 + 7;\nint add(int a, int b){\n return ((a % MOD) + (b % MOD)) % MOD;\n}\nclass Solution {\n public:\n int numTilings(int N) {\n vector <int> dp(N + 5);\n dp[1] = 1;\n dp[2] = 2;\n dp[3] = 5;\n for(int i = 4; i <= N; i++){\n dp[i] = add(2 * dp[i - 1], dp[i - 3]);\n }\n return dp[N];\n }\n};\nmain(){\n Solution ob;\n cout << (ob.numTilings(3));\n}" }, { "code": null, "e": 2539, "s": 2537, "text": "3" }, { "code": null, "e": 2541, "s": 2539, "text": "5" } ]
Shell Scripts to Find How Many Users are Logged In - GeeksforGeeks
11 May, 2021 Every operating system provides a feature of multiple user accounts. Linux-based operating systems have some commands or functionalities to check user accounts’ details and change them. This ability is mainly used by the admin account user that is the root user, to provide permissions and access to different users. The admin can also check how many users are currently logged in, how many are logged out, and the login time. Here in this article, we will explore all these ways and also write a shell script to complete these tasks efficiently. 1. id: The id command is used to print the user and group information for the specified USER. -a ignore, for compatibility with other versions -Z, --context print only the security context of the process -g, --group print only the effective group ID -G, --groups print all group IDs -n, --name print a name instead of a number, for -ugG -r, --real print the real ID instead of the effective ID, with -ugG -u, --user print only the effective user ID -z, --zero delimit entries with NUL characters, not whitespace This id command has produced all the user identifiers, group identifiers, and groups. If you want only a group identifier, use the below command. id -G 2. groups: This will print the group to which the specified user belongs. If no specific username is given, it will search for the current users. Use the below command for the current user. 3. getent: This command displays entries from the databases. -i, --no-idn disable IDN encoding -s, --service=CONFIG Service configuration to be used -?, --help Give this help list --usage Give a short usage message -V, --version Print program version Let us see the version of getent program present on our system. getent -V 4. lslogins: To see all the username and user ids. This provides a list of several features like UID, USER, LAST-LOGIN, etc. -a, --acc-expiration display info about passwords expiration -c, --colon-separate display data in a format similar to /etc/passwd -e, --export display in an export-able output format -f, --failed display data about the users' last failed logins -G, --supp-groups display information about groups -g, --groups=<groups> display users belonging to a group in <groups> -L, --last show info about the users' last login sessions -l, --logins=<logins> display only users from <logins> -n, --newline display each piece of information on a new line --noheadings don't print headings --notruncate don't truncate output 5. users: This command will print the usernames of logged-in to the current host. users This is the only user logged in currently. 6. who: To show who is logged-on. This lists the users with id and the time and date of user login. -a, --all same as –b, -d, --login, -p, -r, -t, -T, -u -b, --boot time of last system boot -d, --dead print dead processes -H, --heading print line of column headings -l, --login print system login processes --lookup attempt to canonicalize hostnames via DNS -m only hostname and user associated with stdin -p, --process print active processes spawned by init -q, --count all login names and number of users logged on 7. w: w command shows the logged-on user accounts and also shows what they are doing. -h, --no-header do not print header -u, --no-current ignore current process username -s, --short short format -f, --from show remote hostname field -o, --old-style old style output -i, --ip-addr display IP address instead of hostname (if possible) This has some more features and columns than who, to give more detailed information about users. w 8. last or lastb: The commands last and lastb shows a listing of last logged in users -<number> how many lines to show -a, --hostlast display hostnames in the last column -d, --dns translate the IP number back into a hostname -f, --file <file> use a specific file instead of /var/log/wtmp -F, --fulltimes print full login and logout times and dates -i, --ip display IP numbers in numbers-and-dots notation -n, --limit <number> how many lines to show -R, --nohostname don't display the hostname field -s, --since <time> display the lines since the specified time -t, --until <time> display the lines until the specified time -p, --present <time> display who were present at the specified time This provides all the login details of several users according to date and time. last 9. lastlog: This will produce a report of all the recent login users. This can also create a single-user report if specified. -b, --before DAYS print only lastlog records older than DAYS -C, --clear clear lastlog record of a user (usable only with -u) -h, --help display this help message and exit -R, --root CHROOT_DIR directory to chroot into -S, --set set lastlog record to the current time (usable only with -u) -t, --time DAYS print only lastlog records more recent than DAYS -u, --user LOGIN print lastlog record of the specified LOGIN This tells about the latest log of the users. lastlog Now we will create a shell script using some above-mentioned commands to get user details. We are approaching the solution in a way that the user is asked for input by given suggestions. That input will be then used to check against the available cases, and then the matched case will be allowed to run. Open any editor according to your preferences, we have used gedit editor because of its simple user interface and the color combination present. gedit userAccounts.sh Here in the userAccounts.sh we will write our code, and use switch cases to compare the user input. We have used commands like lslogins, who, groups, etc. which will help us to satisfy the user requirements. You could find the use of these commands more extended above. So, let us begin the script. #!/bin/bash #here we are you going to develope a script for various options on user accounts echo -e "\n [ 1 ] for listing all the user accounts name \n [ 2 ] for counting the number of logged-in user accounts \n [ 3 ] for listing the names of currently logged-in users\n [ 4 ] for checking the groups to which the current user belong \n" #Now take user input read userInput #Now we will use switch cases for various input operations case $userInput in 1) #syntax lslogins <option[=output field]> lslogins -o USER ;; 2) #syntax who <option> <user optional> #grep used to filter who --count | grep users ;; 3) #-q option is to count the number of users and print the logged-in users. # instead of -q, --count can also be used. # -v is used to exclude any pattern who -q | grep -v users ;; 4) #syntax groups <option> [USERNAME] groups ;; *) echo -e "Please Enter Correct Input \n" ;; esac Executable permissions must be granted to the files to make them run or execute on the system. We could also use “777” instead of “+x” in the chmod command. Also please run the script as root to # chmod +x userAccounts.sh ./userAccounts.sh Example 1: ./userAccounts.sh 1 Example 2: ./userAccounts.sh 2 Example 3: ./userAccounts.sh 3 Hence, we were able to find out various login-related results using our shell script. Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n11 May, 2021" }, { "code": null, "e": 24562, "s": 24015, "text": "Every operating system provides a feature of multiple user accounts. Linux-based operating systems have some commands or functionalities to check user accounts’ details and change them. This ability is mainly used by the admin account user that is the root user, to provide permissions and access to different users. The admin can also check how many users are currently logged in, how many are logged out, and the login time. Here in this article, we will explore all these ways and also write a shell script to complete these tasks efficiently." }, { "code": null, "e": 24656, "s": 24562, "text": "1. id: The id command is used to print the user and group information for the specified USER." }, { "code": null, "e": 25116, "s": 24656, "text": "-a ignore, for compatibility with other versions\n-Z, --context print only the security context of the process\n-g, --group print only the effective group ID\n-G, --groups print all group IDs\n-n, --name print a name instead of a number, for -ugG\n-r, --real print the real ID instead of the effective ID, with -ugG\n-u, --user print only the effective user ID\n-z, --zero delimit entries with NUL characters, not whitespace" }, { "code": null, "e": 25262, "s": 25116, "text": "This id command has produced all the user identifiers, group identifiers, and groups. If you want only a group identifier, use the below command." }, { "code": null, "e": 25268, "s": 25262, "text": "id -G" }, { "code": null, "e": 25458, "s": 25268, "text": "2. groups: This will print the group to which the specified user belongs. If no specific username is given, it will search for the current users. Use the below command for the current user." }, { "code": null, "e": 25519, "s": 25458, "text": "3. getent: This command displays entries from the databases." }, { "code": null, "e": 25762, "s": 25519, "text": "-i, --no-idn disable IDN encoding\n-s, --service=CONFIG Service configuration to be used\n-?, --help Give this help list\n--usage Give a short usage message\n-V, --version Print program version" }, { "code": null, "e": 25826, "s": 25762, "text": "Let us see the version of getent program present on our system." }, { "code": null, "e": 25836, "s": 25826, "text": "getent -V" }, { "code": null, "e": 25961, "s": 25836, "text": "4. lslogins: To see all the username and user ids. This provides a list of several features like UID, USER, LAST-LOGIN, etc." }, { "code": null, "e": 26675, "s": 25961, "text": "-a, --acc-expiration display info about passwords expiration\n-c, --colon-separate display data in a format similar to /etc/passwd\n-e, --export display in an export-able output format\n-f, --failed display data about the users' last failed logins\n-G, --supp-groups display information about groups\n-g, --groups=<groups> display users belonging to a group in <groups>\n-L, --last show info about the users' last login sessions\n-l, --logins=<logins> display only users from <logins>\n-n, --newline display each piece of information on a new line\n--noheadings don't print headings\n--notruncate don't truncate output" }, { "code": null, "e": 26757, "s": 26675, "text": "5. users: This command will print the usernames of logged-in to the current host." }, { "code": null, "e": 26763, "s": 26757, "text": "users" }, { "code": null, "e": 26806, "s": 26763, "text": "This is the only user logged in currently." }, { "code": null, "e": 26906, "s": 26806, "text": "6. who: To show who is logged-on. This lists the users with id and the time and date of user login." }, { "code": null, "e": 27398, "s": 26906, "text": "-a, --all same as –b, -d, --login, -p, -r, -t, -T, -u\n-b, --boot time of last system boot\n-d, --dead print dead processes\n-H, --heading print line of column headings\n-l, --login print system login processes\n--lookup attempt to canonicalize hostnames via DNS\n-m only hostname and user associated with stdin\n-p, --process print active processes spawned by init\n-q, --count all login names and number of users logged on" }, { "code": null, "e": 27484, "s": 27398, "text": "7. w: w command shows the logged-on user accounts and also shows what they are doing." }, { "code": null, "e": 27754, "s": 27484, "text": "-h, --no-header do not print header\n-u, --no-current ignore current process username\n-s, --short short format\n-f, --from show remote hostname field\n-o, --old-style old style output\n-i, --ip-addr display IP address instead of hostname (if possible)" }, { "code": null, "e": 27851, "s": 27754, "text": "This has some more features and columns than who, to give more detailed information about users." }, { "code": null, "e": 27853, "s": 27851, "text": "w" }, { "code": null, "e": 27939, "s": 27853, "text": "8. last or lastb: The commands last and lastb shows a listing of last logged in users" }, { "code": null, "e": 28612, "s": 27939, "text": "-<number> how many lines to show\n-a, --hostlast display hostnames in the last column\n-d, --dns translate the IP number back into a hostname\n-f, --file <file> use a specific file instead of /var/log/wtmp\n-F, --fulltimes print full login and logout times and dates\n-i, --ip display IP numbers in numbers-and-dots notation\n-n, --limit <number> how many lines to show\n-R, --nohostname don't display the hostname field\n-s, --since <time> display the lines since the specified time\n-t, --until <time> display the lines until the specified time\n-p, --present <time> display who were present at the specified time" }, { "code": null, "e": 28693, "s": 28612, "text": "This provides all the login details of several users according to date and time." }, { "code": null, "e": 28698, "s": 28693, "text": "last" }, { "code": null, "e": 28824, "s": 28698, "text": "9. lastlog: This will produce a report of all the recent login users. This can also create a single-user report if specified." }, { "code": null, "e": 29351, "s": 28824, "text": "-b, --before DAYS print only lastlog records older than DAYS\n-C, --clear clear lastlog record of a user (usable only with -u)\n-h, --help display this help message and exit\n-R, --root CHROOT_DIR directory to chroot into\n-S, --set set lastlog record to the current time (usable only with -u)\n-t, --time DAYS print only lastlog records more recent than DAYS\n-u, --user LOGIN print lastlog record of the specified LOGIN" }, { "code": null, "e": 29397, "s": 29351, "text": "This tells about the latest log of the users." }, { "code": null, "e": 29405, "s": 29397, "text": "lastlog" }, { "code": null, "e": 29709, "s": 29405, "text": "Now we will create a shell script using some above-mentioned commands to get user details. We are approaching the solution in a way that the user is asked for input by given suggestions. That input will be then used to check against the available cases, and then the matched case will be allowed to run." }, { "code": null, "e": 29854, "s": 29709, "text": "Open any editor according to your preferences, we have used gedit editor because of its simple user interface and the color combination present." }, { "code": null, "e": 29876, "s": 29854, "text": "gedit userAccounts.sh" }, { "code": null, "e": 30175, "s": 29876, "text": "Here in the userAccounts.sh we will write our code, and use switch cases to compare the user input. We have used commands like lslogins, who, groups, etc. which will help us to satisfy the user requirements. You could find the use of these commands more extended above. So, let us begin the script." }, { "code": null, "e": 31157, "s": 30175, "text": "#!/bin/bash\n#here we are you going to develope a script for various options on user accounts\necho -e \"\\n\n[ 1 ] for listing all the user accounts name \\n\n[ 2 ] for counting the number of logged-in user accounts \\n\n[ 3 ] for listing the names of currently logged-in users\\n\n[ 4 ] for checking the groups to which the current user belong \\n\"\n\n#Now take user input\nread userInput\n\n#Now we will use switch cases for various input operations\ncase $userInput in\n 1)\n #syntax lslogins <option[=output field]>\n lslogins -o USER\n ;;\n 2)\n #syntax who <option> <user optional>\n #grep used to filter\n who --count | grep users\n ;;\n 3)\n #-q option is to count the number of users and print the logged-in users.\n # instead of -q, --count can also be used.\n # -v is used to exclude any pattern\n who -q | grep -v users\n ;;\n 4)\n #syntax groups <option> [USERNAME]\n groups\n ;;\n *)\n echo -e \"Please Enter Correct Input \\n\"\n ;; \nesac" }, { "code": null, "e": 31353, "s": 31157, "text": "Executable permissions must be granted to the files to make them run or execute on the system. We could also use “777” instead of “+x” in the chmod command. Also please run the script as root to " }, { "code": null, "e": 31380, "s": 31353, "text": "# chmod +x userAccounts.sh" }, { "code": null, "e": 31398, "s": 31380, "text": "./userAccounts.sh" }, { "code": null, "e": 31410, "s": 31398, "text": "Example 1: " }, { "code": null, "e": 31430, "s": 31410, "text": "./userAccounts.sh\n1" }, { "code": null, "e": 31442, "s": 31430, "text": "Example 2: " }, { "code": null, "e": 31462, "s": 31442, "text": "./userAccounts.sh\n2" }, { "code": null, "e": 31473, "s": 31462, "text": "Example 3:" }, { "code": null, "e": 31493, "s": 31473, "text": "./userAccounts.sh\n3" }, { "code": null, "e": 31579, "s": 31493, "text": "Hence, we were able to find out various login-related results using our shell script." }, { "code": null, "e": 31586, "s": 31579, "text": "Picked" }, { "code": null, "e": 31599, "s": 31586, "text": "Shell Script" }, { "code": null, "e": 31610, "s": 31599, "text": "Linux-Unix" }, { "code": null, "e": 31708, "s": 31610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31717, "s": 31708, "text": "Comments" }, { "code": null, "e": 31730, "s": 31717, "text": "Old Comments" }, { "code": null, "e": 31756, "s": 31730, "text": "Thread functions in C/C++" }, { "code": null, "e": 31793, "s": 31756, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 31827, "s": 31793, "text": "mv command in Linux with examples" }, { "code": null, "e": 31862, "s": 31827, "text": "scp command in Linux with Examples" }, { "code": null, "e": 31888, "s": 31862, "text": "Docker - COPY Instruction" }, { "code": null, "e": 31925, "s": 31888, "text": "chown command in Linux with Examples" }, { "code": null, "e": 31965, "s": 31925, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 31994, "s": 31965, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 32036, "s": 31994, "text": "Named Pipe or FIFO with example C program" } ]
Hacking RSA Cipher
Hacking RSA cipher is possible with small prime numbers, but it is considered impossible if it is used with large numbers. The reasons which specify why it is difficult to hack RSA cipher are as follows − Brute force attack would not work as there are too many possible keys to work through. Also, this consumes a lot of time. Brute force attack would not work as there are too many possible keys to work through. Also, this consumes a lot of time. Dictionary attack will not work in RSA algorithm as the keys are numeric and does not include any characters in it. Dictionary attack will not work in RSA algorithm as the keys are numeric and does not include any characters in it. Frequency analysis of the characters is very difficult to follow as a single encrypted block represents various characters. Frequency analysis of the characters is very difficult to follow as a single encrypted block represents various characters. There are no specific mathematical tricks to hack RSA cipher. There are no specific mathematical tricks to hack RSA cipher. The RSA decryption equation is − M = C^d mod n With the help of small prime numbers, we can try hacking RSA cipher and the sample code for the same is mentioned below − def p_and_q(n): data = [] for i in range(2, n): if n % i == 0: data.append(i) return tuple(data) def euler(p, q): return (p - 1) * (q - 1) def private_index(e, euler_v): for i in range(2, euler_v): if i * e % euler_v == 1: return i def decipher(d, n, c): return c ** d % n def main(): e = int(input("input e: ")) n = int(input("input n: ")) c = int(input("input c: ")) # t = 123 # private key = (103, 143) p_and_q_v = p_and_q(n) # print("[p_and_q]: ", p_and_q_v) euler_v = euler(p_and_q_v[0], p_and_q_v[1]) # print("[euler]: ", euler_v) d = private_index(e, euler_v) plain = decipher(d, n, c) print("plain: ", plain) if __name__ == "__main__": main() The above code produces the following output − 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2497, "s": 2292, "text": "Hacking RSA cipher is possible with small prime numbers, but it is considered impossible if it is used with large numbers. The reasons which specify why it is difficult to hack RSA cipher are as follows −" }, { "code": null, "e": 2619, "s": 2497, "text": "Brute force attack would not work as there are too many possible keys to work through. Also, this consumes a lot of time." }, { "code": null, "e": 2741, "s": 2619, "text": "Brute force attack would not work as there are too many possible keys to work through. Also, this consumes a lot of time." }, { "code": null, "e": 2857, "s": 2741, "text": "Dictionary attack will not work in RSA algorithm as the keys are numeric and does not include any characters in it." }, { "code": null, "e": 2973, "s": 2857, "text": "Dictionary attack will not work in RSA algorithm as the keys are numeric and does not include any characters in it." }, { "code": null, "e": 3097, "s": 2973, "text": "Frequency analysis of the characters is very difficult to follow as a single encrypted block represents various characters." }, { "code": null, "e": 3221, "s": 3097, "text": "Frequency analysis of the characters is very difficult to follow as a single encrypted block represents various characters." }, { "code": null, "e": 3283, "s": 3221, "text": "There are no specific mathematical tricks to hack RSA cipher." }, { "code": null, "e": 3345, "s": 3283, "text": "There are no specific mathematical tricks to hack RSA cipher." }, { "code": null, "e": 3378, "s": 3345, "text": "The RSA decryption equation is −" }, { "code": null, "e": 3393, "s": 3378, "text": "M = C^d mod n\n" }, { "code": null, "e": 3515, "s": 3393, "text": "With the help of small prime numbers, we can try hacking RSA cipher and the sample code for the same is mentioned below −" }, { "code": null, "e": 4307, "s": 3515, "text": "def p_and_q(n):\n data = []\n for i in range(2, n):\n if n % i == 0:\n data.append(i)\n return tuple(data)\n\ndef euler(p, q):\n return (p - 1) * (q - 1)\n\ndef private_index(e, euler_v):\n for i in range(2, euler_v):\n if i * e % euler_v == 1:\n return i\n\ndef decipher(d, n, c):\n return c ** d % n\n\tdef main():\n e = int(input(\"input e: \"))\n n = int(input(\"input n: \"))\n c = int(input(\"input c: \"))\n \n # t = 123\n # private key = (103, 143)\n p_and_q_v = p_and_q(n)\n # print(\"[p_and_q]: \", p_and_q_v)\n euler_v = euler(p_and_q_v[0], p_and_q_v[1])\n \n # print(\"[euler]: \", euler_v)\n d = private_index(e, euler_v)\n plain = decipher(d, n, c)\n print(\"plain: \", plain)\nif __name__ == \"__main__\":\n main()" }, { "code": null, "e": 4354, "s": 4307, "text": "The above code produces the following output −" }, { "code": null, "e": 4387, "s": 4354, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4403, "s": 4387, "text": " Total Seminars" }, { "code": null, "e": 4436, "s": 4403, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4459, "s": 4436, "text": " Stone River ELearning" }, { "code": null, "e": 4466, "s": 4459, "text": " Print" }, { "code": null, "e": 4477, "s": 4466, "text": " Add Notes" } ]
How to Encode and Decode Image in Base64 in Android? - GeeksforGeeks
13 Jul, 2021 Here, we are going to make an application of the “Encoding-Decoding” of an image. By making this application we will be able to learn that how we can encode an image in Base64. We will also be decoding our image with help of a button. Prerequisite: Before proceeding with this application you should be aware of Base64 in java. If you are not aware of it, use Basic Type Base64 Encoding and Decoding in Java. In this application, we will be using two buttons Encode and Decode to perform their respective operations. Moreover, we will be using a textView to display encoded text and finally an imageView to display the decoded image. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article. Step 1: Creating a new project Open a new project. We will be working on Empty Activity with language as Java. Leave all other options unchanged. You can change the name of the project at your convenience. There will be two default files named activity_main.xml and MainActivity.java. If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Step 2: Navigate to app > Manifests > AndroidManifest.xml file and add the following permission to it <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> Step 3: Working with the activity_main.xml file Here we will design the user interface of our application. We will be using the following components for their respective works: TextView – to show the encoded text ImageView – to show the decoded image. Button – to encode or decode the image on click. Navigate to the app > res > layout > activity_main.xml and add the below code to that file. XML <?xml version="1.0" encoding="utf-8"?><!-- Parent Linear layout --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#EFA1A1" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <!-- Layout to display buttons for encoding and decoding--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <!-- Button for encoding of image--> <Button android:id="@+id/btn_encode" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginEnd="4dp" android:layout_marginRight="4dp" android:layout_weight="1" android:text="Encode Image" app:backgroundTint="#511C1C" /> <!--Button for decoding of image--> <Button android:id="@+id/btn_decode" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="4dp" android:layout_marginLeft="4dp" android:layout_weight="1" android:text="DEcode Image" app:backgroundTint="#511C1C" /> </LinearLayout> <!-- Textview to display encoded text--> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:ellipsize="end" android:maxLines="5" /> <!-- Imageview to display decoded image--> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="8dp" android:adjustViewBounds="true" android:scaleType="centerCrop" /> </LinearLayout> After implementing the above code, the design of the activity_main.xml file looks like this. Step 4: Working with MainActivity.java file Here we write code for the onClickListeners for the Encoding and Decoding buttons, so that they can perform their function. Use the below code in the MainActvity.java file. Java import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.util.Base64;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import java.io.ByteArrayOutputStream;import java.io.IOException; public class MainActivity extends AppCompatActivity { // Initialize variable Button btnEncode,btnDecode; TextView textView; ImageView imageView; String sImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnEncode=findViewById(R.id.btn_encode); btnDecode=findViewById(R.id.btn_decode); textView=findViewById(R.id.textView); imageView= findViewById(R.id.imageView); // Code for Encode button btnEncode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // check condition if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) { // when permission is nor granted // request permission ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100); } else { // when permission // is granted // create method selectImage(); } } }); // Code for Decode button btnDecode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // decode base64 string byte[] bytes=Base64.decode(sImage,Base64.DEFAULT); // Initialize bitmap Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length); // set bitmap on imageView imageView.setImageBitmap(bitmap); } }); } private void selectImage() { // clear previous data textView.setText(""); imageView.setImageBitmap(null); // Initialize intent Intent intent=new Intent(Intent.ACTION_PICK); // set type intent.setType("image/*"); // start activity result startActivityForResult(Intent.createChooser(intent,"Select Image"),100); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // check condition if (requestCode==100 && grantResults[0]==PackageManager.PERMISSION_GRANTED) { // when permission // is granted // call method selectImage(); } else { // when permission is denied Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // check condition if (requestCode==100 && resultCode==RESULT_OK && data!=null) { // when result is ok // initialize uri Uri uri=data.getData(); // Initialize bitmap try { Bitmap bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),uri); // initialize byte stream ByteArrayOutputStream stream=new ByteArrayOutputStream(); // compress Bitmap bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream); // Initialize byte array byte[] bytes=stream.toByteArray(); // get base64 encoded string sImage= Base64.encodeToString(bytes,Base64.DEFAULT); // set encoded text on textview textView.setText(sImage); } catch (IOException e) { e.printStackTrace(); } } }} Output: anikakapoor Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Change the Background Color After Clicking the Button in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25116, "s": 25088, "text": "\n13 Jul, 2021" }, { "code": null, "e": 25351, "s": 25116, "text": "Here, we are going to make an application of the “Encoding-Decoding” of an image. By making this application we will be able to learn that how we can encode an image in Base64. We will also be decoding our image with help of a button." }, { "code": null, "e": 25365, "s": 25351, "text": "Prerequisite:" }, { "code": null, "e": 25525, "s": 25365, "text": "Before proceeding with this application you should be aware of Base64 in java. If you are not aware of it, use Basic Type Base64 Encoding and Decoding in Java." }, { "code": null, "e": 25916, "s": 25525, "text": "In this application, we will be using two buttons Encode and Decode to perform their respective operations. Moreover, we will be using a textView to display encoded text and finally an imageView to display the decoded image. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 25947, "s": 25916, "text": "Step 1: Creating a new project" }, { "code": null, "e": 25967, "s": 25947, "text": "Open a new project." }, { "code": null, "e": 26062, "s": 25967, "text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged." }, { "code": null, "e": 26122, "s": 26062, "text": "You can change the name of the project at your convenience." }, { "code": null, "e": 26201, "s": 26122, "text": "There will be two default files named activity_main.xml and MainActivity.java." }, { "code": null, "e": 26341, "s": 26201, "text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? " }, { "code": null, "e": 26443, "s": 26341, "text": "Step 2: Navigate to app > Manifests > AndroidManifest.xml file and add the following permission to it" }, { "code": null, "e": 26518, "s": 26443, "text": "<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/>" }, { "code": null, "e": 26567, "s": 26518, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26696, "s": 26567, "text": "Here we will design the user interface of our application. We will be using the following components for their respective works:" }, { "code": null, "e": 26732, "s": 26696, "text": "TextView – to show the encoded text" }, { "code": null, "e": 26771, "s": 26732, "text": "ImageView – to show the decoded image." }, { "code": null, "e": 26820, "s": 26771, "text": "Button – to encode or decode the image on click." }, { "code": null, "e": 26912, "s": 26820, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file." }, { "code": null, "e": 26916, "s": 26912, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- Parent Linear layout --><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#EFA1A1\" android:orientation=\"vertical\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <!-- Layout to display buttons for encoding and decoding--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <!-- Button for encoding of image--> <Button android:id=\"@+id/btn_encode\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginEnd=\"4dp\" android:layout_marginRight=\"4dp\" android:layout_weight=\"1\" android:text=\"Encode Image\" app:backgroundTint=\"#511C1C\" /> <!--Button for decoding of image--> <Button android:id=\"@+id/btn_decode\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"4dp\" android:layout_marginLeft=\"4dp\" android:layout_weight=\"1\" android:text=\"DEcode Image\" app:backgroundTint=\"#511C1C\" /> </LinearLayout> <!-- Textview to display encoded text--> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"8dp\" android:ellipsize=\"end\" android:maxLines=\"5\" /> <!-- Imageview to display decoded image--> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"8dp\" android:adjustViewBounds=\"true\" android:scaleType=\"centerCrop\" /> </LinearLayout>", "e": 28986, "s": 26916, "text": null }, { "code": null, "e": 29083, "s": 28990, "text": "After implementing the above code, the design of the activity_main.xml file looks like this." }, { "code": null, "e": 29131, "s": 29087, "text": "Step 4: Working with MainActivity.java file" }, { "code": null, "e": 29306, "s": 29133, "text": "Here we write code for the onClickListeners for the Encoding and Decoding buttons, so that they can perform their function. Use the below code in the MainActvity.java file." }, { "code": null, "e": 29313, "s": 29308, "text": "Java" }, { "code": "import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.util.Base64;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import java.io.ByteArrayOutputStream;import java.io.IOException; public class MainActivity extends AppCompatActivity { // Initialize variable Button btnEncode,btnDecode; TextView textView; ImageView imageView; String sImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnEncode=findViewById(R.id.btn_encode); btnDecode=findViewById(R.id.btn_decode); textView=findViewById(R.id.textView); imageView= findViewById(R.id.imageView); // Code for Encode button btnEncode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // check condition if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) { // when permission is nor granted // request permission ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100); } else { // when permission // is granted // create method selectImage(); } } }); // Code for Decode button btnDecode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // decode base64 string byte[] bytes=Base64.decode(sImage,Base64.DEFAULT); // Initialize bitmap Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length); // set bitmap on imageView imageView.setImageBitmap(bitmap); } }); } private void selectImage() { // clear previous data textView.setText(\"\"); imageView.setImageBitmap(null); // Initialize intent Intent intent=new Intent(Intent.ACTION_PICK); // set type intent.setType(\"image/*\"); // start activity result startActivityForResult(Intent.createChooser(intent,\"Select Image\"),100); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // check condition if (requestCode==100 && grantResults[0]==PackageManager.PERMISSION_GRANTED) { // when permission // is granted // call method selectImage(); } else { // when permission is denied Toast.makeText(this, \"Permission Denied\", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // check condition if (requestCode==100 && resultCode==RESULT_OK && data!=null) { // when result is ok // initialize uri Uri uri=data.getData(); // Initialize bitmap try { Bitmap bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),uri); // initialize byte stream ByteArrayOutputStream stream=new ByteArrayOutputStream(); // compress Bitmap bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream); // Initialize byte array byte[] bytes=stream.toByteArray(); // get base64 encoded string sImage= Base64.encodeToString(bytes,Base64.DEFAULT); // set encoded text on textview textView.setText(sImage); } catch (IOException e) { e.printStackTrace(); } } }}", "e": 34027, "s": 29313, "text": null }, { "code": null, "e": 34039, "s": 34031, "text": "Output:" }, { "code": null, "e": 34055, "s": 34043, "text": "anikakapoor" }, { "code": null, "e": 34063, "s": 34055, "text": "Android" }, { "code": null, "e": 34068, "s": 34063, "text": "Java" }, { "code": null, "e": 34073, "s": 34068, "text": "Java" }, { "code": null, "e": 34081, "s": 34073, "text": "Android" }, { "code": null, "e": 34179, "s": 34081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34218, "s": 34179, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34268, "s": 34218, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 34310, "s": 34268, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 34348, "s": 34310, "text": "Android Listview in Java with Example" }, { "code": null, "e": 34421, "s": 34348, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 34436, "s": 34421, "text": "Arrays in Java" }, { "code": null, "e": 34480, "s": 34436, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34502, "s": 34480, "text": "For-each loop in Java" }, { "code": null, "e": 34538, "s": 34502, "text": "Arrays.sort() in Java with examples" } ]
Visualizing House Price Distributions | by Anthony Agnone | Towards Data Science
I’m in the process of closing on my first home in Atlanta, GA, and have been heavily using various real estate websites like Zillow, Redfin, and Trulia. I’ve also been toying with Zillow’s API, although somewhat spotty in functionality and documentation. Despite its shortcomings, I was fully inspired once I read the post by Lukas Frei on using the library to seamlessly create geography-based visualizations. A few days and some quick fun later, I’ve combined Zillow and Folium to make some cool visualizations of housing prices both within Atlanta and across the U.S. API integration Graph traversal Visualization Let’s start simple by using some pre-aggregated data I downloaded from the Zillow website. This data set shows the median price by square foot for every state in the U.S. for each month from April 1996 to May 2019. Naturally, one could build a rich visualization on the progression of these prices over time; however, let’s stick with the most recent prices for now, which are in the last column of the file. Having a look at the top-10 states, there aren’t many surprises. To be clear, I was initially caught off guard by the ordering of some of these, notably D.C. and Hawaii topping the chart. However, recall the normalization of “per square foot” in the metric. By that token, I’m maybe more surprised now that California still hits #3, given its size. Anyways, onto the show! Since this is a visualization article, I’ll avoid throwing too many lines of code in your face, and link it all to you to it at the end of the article. In short, I downloaded a GeoJSON file of the U.S. states from the folium repo. This was a great find, because it immediately gave me the schema of the data that I needed to give to folium for a seamless process; the only information I needed to add was the pricing data (to generate coloring in the final map). After providing that, a mere 5 lines of code got me the following plot: Now that I’d dipped my toes into the waters of Zillow and Folium, I was ready to be immersed. I decided to create a heat map of Metro Atlanta housing prices. One of the drawbacks of the Zillow API is that it’s rather limited in search functionality — I couldn’t find any way to perform a search based on lat/long coordinates, which would have been quite convenient for creating a granular heat map. Nevertheless, I took it as an opportunity to brush up on some crawler-style code; I used the results of an initial search by a city’s name as seeds for future calls to get the comps (via the GetComps endpoint) of those homes. It’s worth noting that Zillow does have plenty of URL-based search filters that one could use to e.g. search by lat/long (see below). Obtaining the homes from the web page then becomes a scraping job, though, and you are subject to any sudden changes in Zillow’s web page structure. That being said, scraping projects can be a lot of fun; if you’d like to build this into what I made, let me know! # an example of a Zillow search URL, with plenty of specificationshttps://www.zillow.com/atlanta-ga/houses/2-_beds/2.0-_baths/?searchQueryState={%22pagination%22:{},%22mapBounds%22:{%22west%22:-84.88217862207034,%22east%22:-84.07880337792972,%22south%22:33.53377471775447,%22north%22:33.999556422130006},%22usersSearchTerm%22:%22Atlanta,%20GA%22,%22regionSelection%22:[{%22regionId%22:37211,%22regionType%22:6}],%22isMapVisible%22:true,%22mapZoom%22:11,%22filterState%22:{%22price%22:{%22min%22:300000,%22max%22:600000},%22monthlyPayment%22:{%22min%22:1119,%22max%22:2237},%22hoa%22:{%22max%22:200},%22beds%22:{%22min%22:2},%22baths%22:{%22min%22:2},%22sqft%22:{%22min%22:1300},%22isAuction%22:{%22value%22:false},%22isMakeMeMove%22:{%22value%22:false},%22isMultiFamily%22:{%22value%22:false},%22isManufactured%22:{%22value%22:false},%22isLotLand%22:{%22value%22:false},%22isPreMarketForeclosure%22:{%22value%22:false},%22isPreMarketPreForeclosure%22:{%22value%22:false}},%22isListVisible%22:true} Returning to the chosen path, I mentioned that I used initial results as entry points into the web of homes in a given city. With those entry points, I kept recursing into calls for each homes comps. An important assumption here is that Zillow’s definition of similarity between houses includes location proximity in addition to other factors. Without location proximity, the comp-based traversal of homes will be very non-smooth with respect to location. So, what algorithms are at our disposal for traversing through a network of nodes in different ways? Of course, breadth-first search (BFS) and depth-first search (DFS) quickly come to mind. For the curious, have a look at the basic logic flow of it below. Besides a set membership guard, new homes are only added to the collection when they satisfy the constraints asserted in the meets_criteria function. For now, I do a simple L2 distance check between a pre-defined root lat/long location and the current home's location. This criterion encouraged the search to stay local to the root, for the purposes of a well-connected and granular heat map. The implementation below uses DFS by popping off the end of the list (line 5) and adding to the end of the list (14), but BFS can be quickly achieved by changing either line (but not both) to instead use the front of the list. Letting this algorithm run for 10,000 iterations on Atlanta homes produces the following map in just a few minutes! What’s more, the generated web page by folium is interactive, allowing common map navigation tools like zooming and panning. To prove out its modularity, I generated some smaller-scale maps of prices for Boston, MA and Seattle, WA as well. As promised, here’s the project. It has a Make+Docker setup for ease of use and reproducibility. If you’d like to get an intro to how these two tools come together nicely for reproducible data science, keep reading here. Either way, the README will get you up and running in no time, either via script or Jupyter notebook. Happy viz! github.com There are numerous different directions in which we could take this logic next. I’ve detailed a few below for stimulation, but I’d prefer to move in the direction that has the most support, impact, and collaboration. What do you think? Originally published at https://anthonyagnone.com.
[ { "code": null, "e": 743, "s": 172, "text": "I’m in the process of closing on my first home in Atlanta, GA, and have been heavily using various real estate websites like Zillow, Redfin, and Trulia. I’ve also been toying with Zillow’s API, although somewhat spotty in functionality and documentation. Despite its shortcomings, I was fully inspired once I read the post by Lukas Frei on using the library to seamlessly create geography-based visualizations. A few days and some quick fun later, I’ve combined Zillow and Folium to make some cool visualizations of housing prices both within Atlanta and across the U.S." }, { "code": null, "e": 759, "s": 743, "text": "API integration" }, { "code": null, "e": 775, "s": 759, "text": "Graph traversal" }, { "code": null, "e": 789, "s": 775, "text": "Visualization" }, { "code": null, "e": 1198, "s": 789, "text": "Let’s start simple by using some pre-aggregated data I downloaded from the Zillow website. This data set shows the median price by square foot for every state in the U.S. for each month from April 1996 to May 2019. Naturally, one could build a rich visualization on the progression of these prices over time; however, let’s stick with the most recent prices for now, which are in the last column of the file." }, { "code": null, "e": 1547, "s": 1198, "text": "Having a look at the top-10 states, there aren’t many surprises. To be clear, I was initially caught off guard by the ordering of some of these, notably D.C. and Hawaii topping the chart. However, recall the normalization of “per square foot” in the metric. By that token, I’m maybe more surprised now that California still hits #3, given its size." }, { "code": null, "e": 2106, "s": 1547, "text": "Anyways, onto the show! Since this is a visualization article, I’ll avoid throwing too many lines of code in your face, and link it all to you to it at the end of the article. In short, I downloaded a GeoJSON file of the U.S. states from the folium repo. This was a great find, because it immediately gave me the schema of the data that I needed to give to folium for a seamless process; the only information I needed to add was the pricing data (to generate coloring in the final map). After providing that, a mere 5 lines of code got me the following plot:" }, { "code": null, "e": 2731, "s": 2106, "text": "Now that I’d dipped my toes into the waters of Zillow and Folium, I was ready to be immersed. I decided to create a heat map of Metro Atlanta housing prices. One of the drawbacks of the Zillow API is that it’s rather limited in search functionality — I couldn’t find any way to perform a search based on lat/long coordinates, which would have been quite convenient for creating a granular heat map. Nevertheless, I took it as an opportunity to brush up on some crawler-style code; I used the results of an initial search by a city’s name as seeds for future calls to get the comps (via the GetComps endpoint) of those homes." }, { "code": null, "e": 3129, "s": 2731, "text": "It’s worth noting that Zillow does have plenty of URL-based search filters that one could use to e.g. search by lat/long (see below). Obtaining the homes from the web page then becomes a scraping job, though, and you are subject to any sudden changes in Zillow’s web page structure. That being said, scraping projects can be a lot of fun; if you’d like to build this into what I made, let me know!" }, { "code": null, "e": 4127, "s": 3129, "text": "# an example of a Zillow search URL, with plenty of specificationshttps://www.zillow.com/atlanta-ga/houses/2-_beds/2.0-_baths/?searchQueryState={%22pagination%22:{},%22mapBounds%22:{%22west%22:-84.88217862207034,%22east%22:-84.07880337792972,%22south%22:33.53377471775447,%22north%22:33.999556422130006},%22usersSearchTerm%22:%22Atlanta,%20GA%22,%22regionSelection%22:[{%22regionId%22:37211,%22regionType%22:6}],%22isMapVisible%22:true,%22mapZoom%22:11,%22filterState%22:{%22price%22:{%22min%22:300000,%22max%22:600000},%22monthlyPayment%22:{%22min%22:1119,%22max%22:2237},%22hoa%22:{%22max%22:200},%22beds%22:{%22min%22:2},%22baths%22:{%22min%22:2},%22sqft%22:{%22min%22:1300},%22isAuction%22:{%22value%22:false},%22isMakeMeMove%22:{%22value%22:false},%22isMultiFamily%22:{%22value%22:false},%22isManufactured%22:{%22value%22:false},%22isLotLand%22:{%22value%22:false},%22isPreMarketForeclosure%22:{%22value%22:false},%22isPreMarketPreForeclosure%22:{%22value%22:false}},%22isListVisible%22:true}" }, { "code": null, "e": 4583, "s": 4127, "text": "Returning to the chosen path, I mentioned that I used initial results as entry points into the web of homes in a given city. With those entry points, I kept recursing into calls for each homes comps. An important assumption here is that Zillow’s definition of similarity between houses includes location proximity in addition to other factors. Without location proximity, the comp-based traversal of homes will be very non-smooth with respect to location." }, { "code": null, "e": 5459, "s": 4583, "text": "So, what algorithms are at our disposal for traversing through a network of nodes in different ways? Of course, breadth-first search (BFS) and depth-first search (DFS) quickly come to mind. For the curious, have a look at the basic logic flow of it below. Besides a set membership guard, new homes are only added to the collection when they satisfy the constraints asserted in the meets_criteria function. For now, I do a simple L2 distance check between a pre-defined root lat/long location and the current home's location. This criterion encouraged the search to stay local to the root, for the purposes of a well-connected and granular heat map. The implementation below uses DFS by popping off the end of the list (line 5) and adding to the end of the list (14), but BFS can be quickly achieved by changing either line (but not both) to instead use the front of the list." }, { "code": null, "e": 5815, "s": 5459, "text": "Letting this algorithm run for 10,000 iterations on Atlanta homes produces the following map in just a few minutes! What’s more, the generated web page by folium is interactive, allowing common map navigation tools like zooming and panning. To prove out its modularity, I generated some smaller-scale maps of prices for Boston, MA and Seattle, WA as well." }, { "code": null, "e": 6149, "s": 5815, "text": "As promised, here’s the project. It has a Make+Docker setup for ease of use and reproducibility. If you’d like to get an intro to how these two tools come together nicely for reproducible data science, keep reading here. Either way, the README will get you up and running in no time, either via script or Jupyter notebook. Happy viz!" }, { "code": null, "e": 6160, "s": 6149, "text": "github.com" }, { "code": null, "e": 6396, "s": 6160, "text": "There are numerous different directions in which we could take this logic next. I’ve detailed a few below for stimulation, but I’d prefer to move in the direction that has the most support, impact, and collaboration. What do you think?" } ]
Command line arguments in C/C++ - GeeksforGeeks
28 Jun, 2021 The most important function of C/C++ is main() function. It is mostly defined with a return type of int and without parameters : int main() { /* ... */ } We can also give command-line arguments in C and C++. Command-line arguments are given after the name of the program in command-line shell of Operating Systems.To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. int main(int argc, char *argv[]) { /* ... */ } or int main(int argc, char **argv) { /* ... */ } argc (ARGument Count) is int and stores number of command-line arguments passed by the user including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for argument and one for program name) The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments. If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings. Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line arguments. For better understanding run this code on your linux machine. // Name of program mainreturn.cpp#include <iostream>using namespace std; int main(int argc, char** argv){ cout << "You have entered " << argc << " arguments:" << "\n"; for (int i = 0; i < argc; ++i) cout << argv[i] << "\n"; return 0;} Input: $ g++ mainreturn.cpp -o main $ ./main geeks for geeks Output: You have entered 4 arguments: ./main geeks for geeks Note : Other platform-dependent formats are also allowed by the C and C++ standards; for example, Unix (though not POSIX.1) and Microsoft Visual C++ have a third argument giving the program’s environment, otherwise accessible through getenv in stdlib.h: Refer C program to print environment variables for details. Properties of Command Line Arguments: They are passed to main() function.They are parameters/arguments supplied to the program when it is invoked.They are used to control program from outside instead of hard coding those values inside the code.argv[argc] is a NULL pointer.argv[0] holds the name of the program.argv[1] points to the first command line argument and argv[n] points last argument. They are passed to main() function. They are parameters/arguments supplied to the program when it is invoked. They are used to control program from outside instead of hard coding those values inside the code. argv[argc] is a NULL pointer. argv[0] holds the name of the program. argv[1] points to the first command line argument and argv[n] points last argument. Note : You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes “” or single quotes ”. // C program to illustrate// command line arguments#include<stdio.h> int main(int argc,char* argv[]){ int counter; printf("Program Name Is: %s",argv[0]); if(argc==1) printf("\nNo Extra Command Line Argument Passed Other Than Program Name"); if(argc>=2) { printf("\nNumber Of Arguments Passed: %d",argc); printf("\n----Following Are The Command Line Arguments Passed----"); for(counter=0;counter<argc;counter++) printf("\nargv[%d]: %s",counter,argv[counter]); } return 0;} Output in different scenarios: Without argument: When the above code is compiled and executed without passing any argument, it produces following output.$ ./a.out Program Name Is: ./a.out No Extra Command Line Argument Passed Other Than Program Name Three arguments : When the above code is compiled and executed with a three arguments, it produces the following output.$ ./a.out First Second Third Program Name Is: ./a.out Number Of Arguments Passed: 4 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First argv[2]: Second argv[3]: Third Single Argument : When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following output.$ ./a.out "First Second Third" Program Name Is: ./a.out Number Of Arguments Passed: 2 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First Second Third Single argument in quotes separated by space : When the above code is compiled and executed with a single argument separated by space but inside single quotes, it produces the following output.$ ./a.out 'First Second Third' Program Name Is: ./a.out Number Of Arguments Passed: 2 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First Second Third Without argument: When the above code is compiled and executed without passing any argument, it produces following output.$ ./a.out Program Name Is: ./a.out No Extra Command Line Argument Passed Other Than Program Name $ ./a.out Program Name Is: ./a.out No Extra Command Line Argument Passed Other Than Program Name Three arguments : When the above code is compiled and executed with a three arguments, it produces the following output.$ ./a.out First Second Third Program Name Is: ./a.out Number Of Arguments Passed: 4 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First argv[2]: Second argv[3]: Third $ ./a.out First Second Third Program Name Is: ./a.out Number Of Arguments Passed: 4 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First argv[2]: Second argv[3]: Third Single Argument : When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following output.$ ./a.out "First Second Third" Program Name Is: ./a.out Number Of Arguments Passed: 2 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First Second Third $ ./a.out "First Second Third" Program Name Is: ./a.out Number Of Arguments Passed: 2 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First Second Third Single argument in quotes separated by space : When the above code is compiled and executed with a single argument separated by space but inside single quotes, it produces the following output.$ ./a.out 'First Second Third' Program Name Is: ./a.out Number Of Arguments Passed: 2 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First Second Third $ ./a.out 'First Second Third' Program Name Is: ./a.out Number Of Arguments Passed: 2 ----Following Are The Command Line Arguments Passed---- argv[0]: ./a.out argv[1]: First Second Third References:http://www.cprogramming.com/tutorial/lesson14.htmlhttp://c0x.coding-guidelines.com/5.1.2.2.1.html TCS C Language C++ TCS CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Core Dump (Segmentation fault) in C/C++ fork() in C Function Pointer in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24558, "s": 24530, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24687, "s": 24558, "text": "The most important function of C/C++ is main() function. It is mostly defined with a return type of int and without parameters :" }, { "code": null, "e": 24714, "s": 24687, "text": "int main() { /* ... */ } \n" }, { "code": null, "e": 25055, "s": 24714, "text": "We can also give command-line arguments in C and C++. Command-line arguments are given after the name of the program in command-line shell of Operating Systems.To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments." }, { "code": null, "e": 25103, "s": 25055, "text": "int main(int argc, char *argv[]) { /* ... */ }\n" }, { "code": null, "e": 25106, "s": 25103, "text": "or" }, { "code": null, "e": 25153, "s": 25106, "text": "int main(int argc, char **argv) { /* ... */ }\n" }, { "code": null, "e": 25385, "s": 25153, "text": "argc (ARGument Count) is int and stores number of command-line arguments passed by the user including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for argument and one for program name)" }, { "code": null, "e": 25427, "s": 25385, "text": "The value of argc should be non negative." }, { "code": null, "e": 25507, "s": 25427, "text": "argv(ARGument Vector) is array of character pointers listing all the arguments." }, { "code": null, "e": 25618, "s": 25507, "text": "If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings." }, { "code": null, "e": 25726, "s": 25618, "text": "Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line arguments." }, { "code": null, "e": 25788, "s": 25726, "text": "For better understanding run this code on your linux machine." }, { "code": "// Name of program mainreturn.cpp#include <iostream>using namespace std; int main(int argc, char** argv){ cout << \"You have entered \" << argc << \" arguments:\" << \"\\n\"; for (int i = 0; i < argc; ++i) cout << argv[i] << \"\\n\"; return 0;}", "e": 26052, "s": 25788, "text": null }, { "code": null, "e": 26059, "s": 26052, "text": "Input:" }, { "code": null, "e": 26115, "s": 26059, "text": "$ g++ mainreturn.cpp -o main \n$ ./main geeks for geeks\n" }, { "code": null, "e": 26123, "s": 26115, "text": "Output:" }, { "code": null, "e": 26177, "s": 26123, "text": "You have entered 4 arguments:\n./main\ngeeks\nfor\ngeeks\n" }, { "code": null, "e": 26491, "s": 26177, "text": "Note : Other platform-dependent formats are also allowed by the C and C++ standards; for example, Unix (though not POSIX.1) and Microsoft Visual C++ have a third argument giving the program’s environment, otherwise accessible through getenv in stdlib.h: Refer C program to print environment variables for details." }, { "code": null, "e": 26529, "s": 26491, "text": "Properties of Command Line Arguments:" }, { "code": null, "e": 26886, "s": 26529, "text": "They are passed to main() function.They are parameters/arguments supplied to the program when it is invoked.They are used to control program from outside instead of hard coding those values inside the code.argv[argc] is a NULL pointer.argv[0] holds the name of the program.argv[1] points to the first command line argument and argv[n] points last argument." }, { "code": null, "e": 26922, "s": 26886, "text": "They are passed to main() function." }, { "code": null, "e": 26996, "s": 26922, "text": "They are parameters/arguments supplied to the program when it is invoked." }, { "code": null, "e": 27095, "s": 26996, "text": "They are used to control program from outside instead of hard coding those values inside the code." }, { "code": null, "e": 27125, "s": 27095, "text": "argv[argc] is a NULL pointer." }, { "code": null, "e": 27164, "s": 27125, "text": "argv[0] holds the name of the program." }, { "code": null, "e": 27248, "s": 27164, "text": "argv[1] points to the first command line argument and argv[n] points last argument." }, { "code": null, "e": 27445, "s": 27248, "text": "Note : You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes “” or single quotes ”." }, { "code": "// C program to illustrate// command line arguments#include<stdio.h> int main(int argc,char* argv[]){ int counter; printf(\"Program Name Is: %s\",argv[0]); if(argc==1) printf(\"\\nNo Extra Command Line Argument Passed Other Than Program Name\"); if(argc>=2) { printf(\"\\nNumber Of Arguments Passed: %d\",argc); printf(\"\\n----Following Are The Command Line Arguments Passed----\"); for(counter=0;counter<argc;counter++) printf(\"\\nargv[%d]: %s\",counter,argv[counter]); } return 0;}", "e": 27978, "s": 27445, "text": null }, { "code": null, "e": 28009, "s": 27978, "text": "Output in different scenarios:" }, { "code": null, "e": 29283, "s": 28009, "text": "Without argument: When the above code is compiled and executed without passing any argument, it produces following output.$ ./a.out\nProgram Name Is: ./a.out\nNo Extra Command Line Argument Passed Other Than Program Name\nThree arguments : When the above code is compiled and executed with a three arguments, it produces the following output.$ ./a.out First Second Third\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 4\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First\nargv[2]: Second\nargv[3]: Third\nSingle Argument : When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following output.$ ./a.out \"First Second Third\"\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 2\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First Second Third\nSingle argument in quotes separated by space : When the above code is compiled and executed with a single argument separated by space but inside single quotes, it produces the following output.$ ./a.out 'First Second Third'\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 2\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First Second Third\n" }, { "code": null, "e": 29503, "s": 29283, "text": "Without argument: When the above code is compiled and executed without passing any argument, it produces following output.$ ./a.out\nProgram Name Is: ./a.out\nNo Extra Command Line Argument Passed Other Than Program Name\n" }, { "code": null, "e": 29601, "s": 29503, "text": "$ ./a.out\nProgram Name Is: ./a.out\nNo Extra Command Line Argument Passed Other Than Program Name\n" }, { "code": null, "e": 29925, "s": 29601, "text": "Three arguments : When the above code is compiled and executed with a three arguments, it produces the following output.$ ./a.out First Second Third\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 4\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First\nargv[2]: Second\nargv[3]: Third\n" }, { "code": null, "e": 30129, "s": 29925, "text": "$ ./a.out First Second Third\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 4\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First\nargv[2]: Second\nargv[3]: Third\n" }, { "code": null, "e": 30481, "s": 30129, "text": "Single Argument : When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following output.$ ./a.out \"First Second Third\"\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 2\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First Second Third\n" }, { "code": null, "e": 30669, "s": 30481, "text": "$ ./a.out \"First Second Third\"\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 2\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First Second Third\n" }, { "code": null, "e": 31050, "s": 30669, "text": "Single argument in quotes separated by space : When the above code is compiled and executed with a single argument separated by space but inside single quotes, it produces the following output.$ ./a.out 'First Second Third'\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 2\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First Second Third\n" }, { "code": null, "e": 31238, "s": 31050, "text": "$ ./a.out 'First Second Third'\nProgram Name Is: ./a.out\nNumber Of Arguments Passed: 2\n----Following Are The Command Line Arguments Passed----\nargv[0]: ./a.out\nargv[1]: First Second Third\n" }, { "code": null, "e": 31347, "s": 31238, "text": "References:http://www.cprogramming.com/tutorial/lesson14.htmlhttp://c0x.coding-guidelines.com/5.1.2.2.1.html" }, { "code": null, "e": 31351, "s": 31347, "text": "TCS" }, { "code": null, "e": 31362, "s": 31351, "text": "C Language" }, { "code": null, "e": 31366, "s": 31362, "text": "C++" }, { "code": null, "e": 31370, "s": 31366, "text": "TCS" }, { "code": null, "e": 31374, "s": 31370, "text": "CPP" }, { "code": null, "e": 31472, "s": 31374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31500, "s": 31472, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 31546, "s": 31500, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31586, "s": 31546, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 31598, "s": 31586, "text": "fork() in C" }, { "code": null, "e": 31620, "s": 31598, "text": "Function Pointer in C" }, { "code": null, "e": 31638, "s": 31620, "text": "Vector in C++ STL" }, { "code": null, "e": 31684, "s": 31638, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 31703, "s": 31684, "text": "Inheritance in C++" }, { "code": null, "e": 31746, "s": 31703, "text": "Map in C++ Standard Template Library (STL)" } ]
How to use prepared statement for select query in Java with MySQL?
You need to use executeQuery() for this. The syntax is as follows − yourPreparedStatementObject=yourConnectionObject.prepareStatement(yourQueryName); yourresultSetObject=yourPreparedStatementObject.executeQuery(); Create a table in the database ‘sample’. The query to create a table is as follows − mysql> create table JavaPreparedStatement -> ( -> Id int, -> Name varchar(10), -> Age int -> ); Query OK, 0 rows affected (0.89 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into JavaPreparedStatement values(1,'Larry',23); Query OK, 1 row affected (0.16 sec) mysql> insert into JavaPreparedStatement values(2,'Sam',25); Query OK, 1 row affected (0.21 sec) mysql> insert into JavaPreparedStatement values(3,'Mike',26); Query OK, 1 row affected (0.12 sec) Now you can display all records of the table using Java PreparedStatement. You need to use the executeQuery() method. Here is the Java code − import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class PreparedStatementSelectQueryDemo { public static void main(String[] args) { String JdbcURL = "jdbc:mysql://localhost:3306/sample?useSSL=false"; String Username = "root"; String password = "123456"; Connection con = null; PreparedStatement pstmt = null; ResultSet rst = null; String myQuery = "select Id,Name,Age from JavaPreparedStatement"; try { con = DriverManager.getConnection(JdbcURL, Username, password); pstmt = con.prepareStatement(myQuery); rst = pstmt.executeQuery(); System.out.println("Id\t\tName\t\tAge\n"); while(rst.next()) { System.out.print(rst.getInt(1)); System.out.print("\t\t"+rst.getString(2)); System.out.print("\t\t"+rst.getInt(3)); System.out.println(); } } catch(Exception exec) { exec.printStackTrace(); } } } Here is the snapshot of Java code − Here is the snapshot of sample output −
[ { "code": null, "e": 1130, "s": 1062, "text": "You need to use executeQuery() for this. The syntax is as follows −" }, { "code": null, "e": 1276, "s": 1130, "text": "yourPreparedStatementObject=yourConnectionObject.prepareStatement(yourQueryName);\nyourresultSetObject=yourPreparedStatementObject.executeQuery();" }, { "code": null, "e": 1361, "s": 1276, "text": "Create a table in the database ‘sample’. The query to create a table is as follows −" }, { "code": null, "e": 1509, "s": 1361, "text": "mysql> create table JavaPreparedStatement\n -> (\n -> Id int,\n -> Name varchar(10),\n -> Age int\n -> );\nQuery OK, 0 rows affected (0.89 sec)" }, { "code": null, "e": 1590, "s": 1509, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1884, "s": 1590, "text": "mysql> insert into JavaPreparedStatement values(1,'Larry',23);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into JavaPreparedStatement values(2,'Sam',25);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into JavaPreparedStatement values(3,'Mike',26);\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2002, "s": 1884, "text": "Now you can display all records of the table using Java PreparedStatement. You need to use the executeQuery() method." }, { "code": null, "e": 2026, "s": 2002, "text": "Here is the Java code −" }, { "code": null, "e": 3074, "s": 2026, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\npublic class PreparedStatementSelectQueryDemo {\n public static void main(String[] args) {\n String JdbcURL = \"jdbc:mysql://localhost:3306/sample?useSSL=false\";\n String Username = \"root\";\n String password = \"123456\";\n Connection con = null;\n PreparedStatement pstmt = null;\n ResultSet rst = null;\n String myQuery = \"select Id,Name,Age from JavaPreparedStatement\";\n try {\n con = DriverManager.getConnection(JdbcURL, Username, password);\n pstmt = con.prepareStatement(myQuery);\n rst = pstmt.executeQuery();\n System.out.println(\"Id\\t\\tName\\t\\tAge\\n\");\n while(rst.next()) {\n System.out.print(rst.getInt(1));\n System.out.print(\"\\t\\t\"+rst.getString(2));\n System.out.print(\"\\t\\t\"+rst.getInt(3));\n System.out.println();\n }\n } catch(Exception exec) {\n exec.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 3110, "s": 3074, "text": "Here is the snapshot of Java code −" }, { "code": null, "e": 3150, "s": 3110, "text": "Here is the snapshot of sample output −" } ]
Find time taken to execute the tasks in A based on the order of execution in B - GeeksforGeeks
11 Jun, 2021 Given two queues A and B, each of size N, the task is to find the minimum time taken to execute the tasks in A based on the order of execution in B where: If the task found at the front of queue B is at the front of queue A, then pop this task and execute it.If the task found at the front of queue B is not found at the front of queue A, then pop the current task from queue A and push it at the end.Push and Pop operation in a queue costs one unit of time and the execution of a task is done in constant time. If the task found at the front of queue B is at the front of queue A, then pop this task and execute it. If the task found at the front of queue B is not found at the front of queue A, then pop the current task from queue A and push it at the end. Push and Pop operation in a queue costs one unit of time and the execution of a task is done in constant time. Example Input: A = { 3, 2, 1 }, B = { 1, 3, 2 } Output: 7 Explanation: For A = 3 and B = 1 => Since the front of queue A does not match with the front of queue B. Pop and Push 3 at the back of Queue. Then, A becomes { 2, 1, 3 } and time consumed = 2 ( 1 unit of time for each push and pop operation) For A = 2 and B = 1 => Since the front of queue A does not match with the front of queue B. Pop and Push 2 at the back of Queue. Then, A becomes { 1, 3, 2 } and time = 2 + 2 = 4 For A = 1 and B = 1 => Since the front of queue, A equals to front of queue B. Pop 1 from both the queue and execute it, Then A becomes { 3, 2 } and B becomes { 3, 2 } and time = 4 + 1 = 5 For A = 3 and B = 3 => Since the front of queue, A equals to front of queue B. Pop 3 from both the queue and execute it, Then A becomes { 2 } and B becomes { 2 } and time = 5 + 1 = 6 For A = 2 and B = 2 => Since the front of the queue, A equals to front of queue B. Pop 2 from both the queue and execute it. All the tasks are executed. time = 6 + 1 = 7 Therefore the total time is 7. Input: A = { 3, 2, 1, 4 }, B = { 4, 1, 3, 2 } Output: 14 Approach: For each task in queue A: If the front task of queue A is the same as the front task of queue B. Pop the task from both the queues and execute it. Increment the total time by one unit.If the front task of queue A is not the same as the front task of queue B. Pop the task from queue A and push it at the back of queue A and increment the total time by two units. (1 for pop operation and 1 for push operation)Repeat the above steps till all the task in queue A is executed. If the front task of queue A is the same as the front task of queue B. Pop the task from both the queues and execute it. Increment the total time by one unit. If the front task of queue A is not the same as the front task of queue B. Pop the task from queue A and push it at the back of queue A and increment the total time by two units. (1 for pop operation and 1 for push operation) Repeat the above steps till all the task in queue A is executed. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the total// time taken to execute the task// in given order #include "bits/stdc++.h"using namespace std; // Function to calculate the// total time taken to execute// the given task in original orderint run_tasks(queue<int>& A, queue<int>& B){ // To find the total time // taken for executing // the task int total_time = 0; // While A is not empty while (!A.empty()) { // Store the front element of queue A and B int x = A.front(); int y = B.front(); // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.pop(); B.pop(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.pop(); A.push(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver Codeint main(){ // Given task to be executed queue<int> A; A.push(3); A.push(2); A.push(1); A.push(4); // Order in which task need to be // executed queue<int> B; B.push(4); B.push(1); B.push(3); B.push(2); // Function the returns the total // time taken to execute all the task cout << run_tasks(A, B); return 0;} // Java program to find the total// time taken to execute the task// in given orderimport java.util.*; class GFG{ // Function to calculate the// total time taken to execute// the given task in original orderstatic int run_tasks(Queue<Integer> A, Queue<Integer> B){ // To find the total time // taken for executing // the task int total_time = 0; // While A is not empty while (!A.isEmpty()) { // Store the front element of queue A and B int x = A.peek(); int y = B.peek(); // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.remove(); B.remove(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.remove(); A.add(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver Codepublic static void main(String[] args){ // Given task to be executed Queue<Integer> A = new LinkedList<Integer>(); A.add(3); A.add(2); A.add(1); A.add(4); // Order in which task need to be // executed Queue<Integer> B = new LinkedList<Integer>(); B.add(4); B.add(1); B.add(3); B.add(2); // Function the returns the total // time taken to execute all the task System.out.print(run_tasks(A, B)); }} // This code is contributed by PrinciRaj1992 # Python3 program to find the total# time taken to execute the task# in given orderfrom collections import deque # Function to calculate the# total time taken to execute# the given task in original orderdef run_tasks(A, B): # To find the total time # taken for executing # the task total_time = 0 # While A is not empty while (len(A) > 0): # Store the front element of queue A and B x = A.popleft() y = B.popleft() # If the front element of the queue A # is equal to the front element of queue B # then pop the element from both # the queues and execute the task # Increment total_time by 1 if (x == y): total_time += 1 # If front element of queue A is not equal # to front element of queue B then # pop the element from queue A & # append it at the back of queue A # Increment the total_time by 2 #(1 for append operation and # 1 for pop operation) else: B.appendleft(y) A.append(x) total_time += 2 # Return the total time taken return total_time # Driver Codeif __name__ == '__main__': # Given task to be executed A = deque() A.append(3) A.append(2) A.append(1) A.append(4) # Order in which task need to be # executed B = deque() B.append(4) B.append(1) B.append(3) B.append(2) # Function the returns the total # time taken to execute all the task print(run_tasks(A, B)) # This code is contributed by mohit kumar 29 // C# program to find the total// time taken to execute the task// in given orderusing System;using System.Collections.Generic; class GFG{ // Function to calculate the// total time taken to execute// the given task in original orderstatic int run_tasks(Queue<int> A, Queue<int> B){ // To find the total time // taken for executing // the task int total_time = 0; // While A is not empty while (A.Count != 0) { // Store the front element of queue A and B int x = A.Peek(); int y = B.Peek(); // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.Dequeue(); B.Dequeue(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.Dequeue(); A.Enqueue(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver Codepublic static void Main(String[] args){ // Given task to be executed Queue<int> A = new Queue<int>(); A.Enqueue(3); A.Enqueue(2); A.Enqueue(1); A.Enqueue(4); // Order in which task need to be // executed Queue<int> B = new Queue<int>(); B.Enqueue(4); B.Enqueue(1); B.Enqueue(3); B.Enqueue(2); // Function the returns the total // time taken to execute all the task Console.Write(run_tasks(A, B));}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find the total// time taken to execute the task// in given order // Function to calculate the// total time taken to execute// the given task in original orderfunction run_tasks(A, B){ // To find the total time // taken for executing // the task let total_time = 0; // While A is not empty while (A.length != 0) { // Store the front element of // queue A and B let x = A[0]; let y = B[0]; // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.shift(); B.shift(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.shift(); A.push(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver code // Given task to be executedlet A = [ 3, 2, 1, 4 ]; // Order in which task need to be// executedlet B = [ 4, 1, 3, 2 ]; // Function the returns the total// time taken to execute all the taskdocument.write(run_tasks(A, B)); // This code is contributed by patel2127 </script> 14 Time Complexity: O(N2), where N is the number of tasks. princiraj1992 mohit kumar 29 patel2127 Technical Scripter 2019 Arrays Operating Systems Queue Technical Scripter Operating Systems Arrays Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Banker's Algorithm in Operating System Types of Operating Systems Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Program for Round Robin scheduling | Set 1
[ { "code": null, "e": 24405, "s": 24377, "text": "\n11 Jun, 2021" }, { "code": null, "e": 24561, "s": 24405, "text": "Given two queues A and B, each of size N, the task is to find the minimum time taken to execute the tasks in A based on the order of execution in B where: " }, { "code": null, "e": 24918, "s": 24561, "text": "If the task found at the front of queue B is at the front of queue A, then pop this task and execute it.If the task found at the front of queue B is not found at the front of queue A, then pop the current task from queue A and push it at the end.Push and Pop operation in a queue costs one unit of time and the execution of a task is done in constant time." }, { "code": null, "e": 25023, "s": 24918, "text": "If the task found at the front of queue B is at the front of queue A, then pop this task and execute it." }, { "code": null, "e": 25166, "s": 25023, "text": "If the task found at the front of queue B is not found at the front of queue A, then pop the current task from queue A and push it at the end." }, { "code": null, "e": 25277, "s": 25166, "text": "Push and Pop operation in a queue costs one unit of time and the execution of a task is done in constant time." }, { "code": null, "e": 25286, "s": 25277, "text": "Example " }, { "code": null, "e": 26329, "s": 25286, "text": "Input: A = { 3, 2, 1 }, B = { 1, 3, 2 } Output: 7 Explanation: For A = 3 and B = 1 => Since the front of queue A does not match with the front of queue B. Pop and Push 3 at the back of Queue. Then, A becomes { 2, 1, 3 } and time consumed = 2 ( 1 unit of time for each push and pop operation) For A = 2 and B = 1 => Since the front of queue A does not match with the front of queue B. Pop and Push 2 at the back of Queue. Then, A becomes { 1, 3, 2 } and time = 2 + 2 = 4 For A = 1 and B = 1 => Since the front of queue, A equals to front of queue B. Pop 1 from both the queue and execute it, Then A becomes { 3, 2 } and B becomes { 3, 2 } and time = 4 + 1 = 5 For A = 3 and B = 3 => Since the front of queue, A equals to front of queue B. Pop 3 from both the queue and execute it, Then A becomes { 2 } and B becomes { 2 } and time = 5 + 1 = 6 For A = 2 and B = 2 => Since the front of the queue, A equals to front of queue B. Pop 2 from both the queue and execute it. All the tasks are executed. time = 6 + 1 = 7 Therefore the total time is 7." }, { "code": null, "e": 26388, "s": 26329, "text": "Input: A = { 3, 2, 1, 4 }, B = { 4, 1, 3, 2 } Output: 14 " }, { "code": null, "e": 26426, "s": 26388, "text": "Approach: For each task in queue A: " }, { "code": null, "e": 26874, "s": 26426, "text": "If the front task of queue A is the same as the front task of queue B. Pop the task from both the queues and execute it. Increment the total time by one unit.If the front task of queue A is not the same as the front task of queue B. Pop the task from queue A and push it at the back of queue A and increment the total time by two units. (1 for pop operation and 1 for push operation)Repeat the above steps till all the task in queue A is executed." }, { "code": null, "e": 27033, "s": 26874, "text": "If the front task of queue A is the same as the front task of queue B. Pop the task from both the queues and execute it. Increment the total time by one unit." }, { "code": null, "e": 27259, "s": 27033, "text": "If the front task of queue A is not the same as the front task of queue B. Pop the task from queue A and push it at the back of queue A and increment the total time by two units. (1 for pop operation and 1 for push operation)" }, { "code": null, "e": 27324, "s": 27259, "text": "Repeat the above steps till all the task in queue A is executed." }, { "code": null, "e": 27377, "s": 27324, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27381, "s": 27377, "text": "C++" }, { "code": null, "e": 27386, "s": 27381, "text": "Java" }, { "code": null, "e": 27394, "s": 27386, "text": "Python3" }, { "code": null, "e": 27397, "s": 27394, "text": "C#" }, { "code": null, "e": 27408, "s": 27397, "text": "Javascript" }, { "code": "// C++ program to find the total// time taken to execute the task// in given order #include \"bits/stdc++.h\"using namespace std; // Function to calculate the// total time taken to execute// the given task in original orderint run_tasks(queue<int>& A, queue<int>& B){ // To find the total time // taken for executing // the task int total_time = 0; // While A is not empty while (!A.empty()) { // Store the front element of queue A and B int x = A.front(); int y = B.front(); // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.pop(); B.pop(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.pop(); A.push(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver Codeint main(){ // Given task to be executed queue<int> A; A.push(3); A.push(2); A.push(1); A.push(4); // Order in which task need to be // executed queue<int> B; B.push(4); B.push(1); B.push(3); B.push(2); // Function the returns the total // time taken to execute all the task cout << run_tasks(A, B); return 0;}", "e": 29067, "s": 27408, "text": null }, { "code": "// Java program to find the total// time taken to execute the task// in given orderimport java.util.*; class GFG{ // Function to calculate the// total time taken to execute// the given task in original orderstatic int run_tasks(Queue<Integer> A, Queue<Integer> B){ // To find the total time // taken for executing // the task int total_time = 0; // While A is not empty while (!A.isEmpty()) { // Store the front element of queue A and B int x = A.peek(); int y = B.peek(); // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.remove(); B.remove(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.remove(); A.add(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver Codepublic static void main(String[] args){ // Given task to be executed Queue<Integer> A = new LinkedList<Integer>(); A.add(3); A.add(2); A.add(1); A.add(4); // Order in which task need to be // executed Queue<Integer> B = new LinkedList<Integer>(); B.add(4); B.add(1); B.add(3); B.add(2); // Function the returns the total // time taken to execute all the task System.out.print(run_tasks(A, B)); }} // This code is contributed by PrinciRaj1992", "e": 30883, "s": 29067, "text": null }, { "code": "# Python3 program to find the total# time taken to execute the task# in given orderfrom collections import deque # Function to calculate the# total time taken to execute# the given task in original orderdef run_tasks(A, B): # To find the total time # taken for executing # the task total_time = 0 # While A is not empty while (len(A) > 0): # Store the front element of queue A and B x = A.popleft() y = B.popleft() # If the front element of the queue A # is equal to the front element of queue B # then pop the element from both # the queues and execute the task # Increment total_time by 1 if (x == y): total_time += 1 # If front element of queue A is not equal # to front element of queue B then # pop the element from queue A & # append it at the back of queue A # Increment the total_time by 2 #(1 for append operation and # 1 for pop operation) else: B.appendleft(y) A.append(x) total_time += 2 # Return the total time taken return total_time # Driver Codeif __name__ == '__main__': # Given task to be executed A = deque() A.append(3) A.append(2) A.append(1) A.append(4) # Order in which task need to be # executed B = deque() B.append(4) B.append(1) B.append(3) B.append(2) # Function the returns the total # time taken to execute all the task print(run_tasks(A, B)) # This code is contributed by mohit kumar 29", "e": 32445, "s": 30883, "text": null }, { "code": "// C# program to find the total// time taken to execute the task// in given orderusing System;using System.Collections.Generic; class GFG{ // Function to calculate the// total time taken to execute// the given task in original orderstatic int run_tasks(Queue<int> A, Queue<int> B){ // To find the total time // taken for executing // the task int total_time = 0; // While A is not empty while (A.Count != 0) { // Store the front element of queue A and B int x = A.Peek(); int y = B.Peek(); // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.Dequeue(); B.Dequeue(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.Dequeue(); A.Enqueue(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver Codepublic static void Main(String[] args){ // Given task to be executed Queue<int> A = new Queue<int>(); A.Enqueue(3); A.Enqueue(2); A.Enqueue(1); A.Enqueue(4); // Order in which task need to be // executed Queue<int> B = new Queue<int>(); B.Enqueue(4); B.Enqueue(1); B.Enqueue(3); B.Enqueue(2); // Function the returns the total // time taken to execute all the task Console.Write(run_tasks(A, B));}} // This code is contributed by PrinciRaj1992", "e": 34287, "s": 32445, "text": null }, { "code": "<script> // Javascript program to find the total// time taken to execute the task// in given order // Function to calculate the// total time taken to execute// the given task in original orderfunction run_tasks(A, B){ // To find the total time // taken for executing // the task let total_time = 0; // While A is not empty while (A.length != 0) { // Store the front element of // queue A and B let x = A[0]; let y = B[0]; // If the front element of the queue A // is equal to the front element of queue B // then pop the element from both // the queues and execute the task // Increment total_time by 1 if (x == y) { A.shift(); B.shift(); total_time++; } // If front element of queue A is not equal // to front element of queue B then // pop the element from queue A & // push it at the back of queue A // Increment the total_time by 2 //(1 for push operation and // 1 for pop operation) else { A.shift(); A.push(x); total_time += 2; } } // Return the total time taken return total_time;} // Driver code // Given task to be executedlet A = [ 3, 2, 1, 4 ]; // Order in which task need to be// executedlet B = [ 4, 1, 3, 2 ]; // Function the returns the total// time taken to execute all the taskdocument.write(run_tasks(A, B)); // This code is contributed by patel2127 </script>", "e": 35835, "s": 34287, "text": null }, { "code": null, "e": 35838, "s": 35835, "text": "14" }, { "code": null, "e": 35897, "s": 35840, "text": "Time Complexity: O(N2), where N is the number of tasks. " }, { "code": null, "e": 35911, "s": 35897, "text": "princiraj1992" }, { "code": null, "e": 35926, "s": 35911, "text": "mohit kumar 29" }, { "code": null, "e": 35936, "s": 35926, "text": "patel2127" }, { "code": null, "e": 35960, "s": 35936, "text": "Technical Scripter 2019" }, { "code": null, "e": 35967, "s": 35960, "text": "Arrays" }, { "code": null, "e": 35985, "s": 35967, "text": "Operating Systems" }, { "code": null, "e": 35991, "s": 35985, "text": "Queue" }, { "code": null, "e": 36010, "s": 35991, "text": "Technical Scripter" }, { "code": null, "e": 36028, "s": 36010, "text": "Operating Systems" }, { "code": null, "e": 36035, "s": 36028, "text": "Arrays" }, { "code": null, "e": 36041, "s": 36035, "text": "Queue" }, { "code": null, "e": 36139, "s": 36041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36148, "s": 36139, "text": "Comments" }, { "code": null, "e": 36161, "s": 36148, "text": "Old Comments" }, { "code": null, "e": 36182, "s": 36161, "text": "Next Greater Element" }, { "code": null, "e": 36207, "s": 36182, "text": "Window Sliding Technique" }, { "code": null, "e": 36234, "s": 36207, "text": "Count pairs with given sum" }, { "code": null, "e": 36283, "s": 36234, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 36321, "s": 36283, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36360, "s": 36321, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 36387, "s": 36360, "text": "Types of Operating Systems" }, { "code": null, "e": 36436, "s": 36387, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 36476, "s": 36436, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
A Layman’s Guide to Building Your First Image Classification Model in R Using Keras | by Abhibhav Sharma | Towards Data Science
Applications of machine learning (ML) are now almost an integral part of our everyday life. From a speech-recognition based virtual assistant in our smartphones to super-intelligent automated drones, ML and artificial intelligence (AI) is revolutionizing the dynamics of human-machine interactions. AI algorithms, especially the convolution neural networks (CNN) have made computer vision extremely powerful than ever. While the applications of it are breathtakingly awesome, it could be very intimidating to build one’s own CNN model, especially for a non-programmer or a beginner in data science, in general. As an R lover, it was not difficult for me to assert that it gets even more enigmatic for a novice R programmer. The plausible reason for this imbalance could be that the standard neural network and ML libraries (like Keras and Tensorflow) are primarily compatible with Python and naturally gravitate the masses to roll with Python itself, leading to a severe lack of novice’s guide and documentation to facilitate the implementation of these sophisticated frameworks in R. Nevertheless, APIs of Keras and Tensorflow is now available on CRAN. Herein, we are going to make a CNN based vanilla image-classification model using Keras and Tensorflow framework in R. With this article, my goal is to enable you to conceptualize and build your own CNN models in R using Keras and, sequentially help to boost your confidence through hands-on coding to build even more complex models in the future using this profound API. Apart from the scripting of the model, I will also try as much to concisely elaborate on the necessary components while plunging the hardcore underlying mathematics. Now let’s start. As a prelude to the scripting of CNN, let’s understand the formalisms of it in brief. Just like a human eye registers the information only in the confined receptive frame and learns the specific patterns and spatial features, which subsequently trigger specific neural responses, a CNN model operates in the same fashion. We will try to probe the CNN architecture and understand its key components (Figure 1). Instead of amalgamating the entire image pixels at a time, a subset of pixels is convoluted into a single datum Figure 2. Convolution is carried out by sliding a frame of a smaller size across the entire image acting as a receptive field that accounts for the temporal-spatial features. This frame is called a Kernel/Filter. Imagine scanning a building wall with a flashlight, the filter works in the same fashion. Now, if you have a variety of filters, you are likely to extract or observe more discriminative spatial features and frequently recurring adjacent values. This scheme empowers the learning by not only preserving the spatial characteristics with the least information loss but also significantly reduces the required number of weights, enabling the image classification practically feasible and scalable. For example, consider a 2D black and white (b&w) image as the input to CNN. The model initiates to convolute the image by employing a filter which then slides across the image with a given step size, also called strides. The filter values are analogous to the weights in the neural network. The linear combination of these filter values and the image’s foregrounding pixel values at an instance, generate a single feature output. A set of these values generated produces a new layer called a feature map. Intuitively, a feature map is a condensed form of the input image that preserves all the dominating features and patterns into a smaller dimension for efficient learning. Elucidating this in Figure 3, the filter of size 4x4 is employed over a b&w image of dimension 10X10. The filter slides across the image with a stride of 1 unit, thus generating a convoluted layer of dimension (10–4+1)X(10–4+1) i.e 7X7. Note that the bias/intercept for this example is assumed to be 0. Similarly, n number of filters would generate n feature maps. For a b&w image, the depth is 1 and so of the filters. However, a colored image is an ensemble of Red, Blue, and Green (RBG) channels. precisely, a stack of three 2D layers, where each layer represents the intensity of a particular color channel. So for a colored image of depth 3, you will need a filter of dimension (4X4)X3 (Figure 4). Once the feature maps are generated, an activation function is applied over each of them. For this purpose, the Rectified Linear Unit (ReLU) activation function comes in handy. If the input to ReLU is a negative value, it simply transforms it to zero else it will spit out the very same input value (Figure 4). Mathematically, f(x)= max(0,x). After the activation layer, another scheme is employed to smartly reduce the dimensions of the feature map without losing vital information. This technique is called Max-pooling. Quite similar to the convolution scheme, here only the highest value from the max-pooling window is picked. This window slides in the same fashion as of the filter but with a step-size equal to the dimension of the pooling window (Figure 5). Max-pooling significantly reduces the dimension of the feature map while also preserving the important/dominating features. The final max-pooled layer is then squashed and flatten into the neuron layer that connects to a fully connected neural network to perform the classification task. Mind you CNN is not limited to a single convolution or a single set of the aforementioned schemes. Backed with a sufficient number of filters, The deeper your network is, the higher performance it will achieve. Intuitively, the initial convolutions would capture the low-level recurring features such as edges and colors. Sequentially, the deep layers tend to capture high-level features like recurring clusters pixels say eyes or noses in a portrait. So, in conclusion, based on your image complexity and computation power, you should choose a sufficient and efficient number of layers and filters. Now let’s jump into the making of our toy model 🤓!! I believe that to understand any statistical concept nothing comes handier than a deck of playing cards. Here I will exploit a deck of playing cards but in a slightly unorthodox form. Yes, you guessed it!! I will make a prediction model that should be able to accurately classify and predict the suit of a given image of any arbitrary non-faced playing card. This dataset contains a set of 43 card images for each suit viz Clubs ♣, Hearts ♥️ , Diamonds ♦️, and Spades ♠️ . Note that the symbols of each suit follow a standard shape however the designing and arrangement of these symbols vary from card to card. We will incorporate this dataset to train and test our model. (To follow the script conveniently, I recommend you to download the images and keep all the files in a parent file as they appear in the Github repository) For this task, you would require Keras and EBImage packages. The former is available on the cran repository. The later is used to deal with the images efficiently and can be called from an open-source software called Bioconductor. These can be installed on Windows OS as: install.packages(“keras”) # Install the package from CRANlibrary(keras)install_keras() #to setup the Keras library and TensorFlow backendif (!requireNamespace(“BiocManager”, quietly = TRUE))install.packages(“BiocManager”)BiocManager::install(“EBImage”)library(EBImage) This installs the CPU version of Keras API, which is recommended for the novice for now. Note: The Keras API will require Python support and R tools plug-in. So make sure you have anaconda and R tools installed on your machine with properly added to your system path. Next, we will convert the images of each suit into a tensor (numbered matrix). readImage() function from EBImage library does this robustly. Let’s try reading an image from our dataset. setwd(“C:/parent/spade”) # To access the images of Spades suit. # The path should be modified as per your # machinecard<-readImage(“ace_of_spades (2).png”) # Reading an imgae from the # datasetprint(card) # Print the details of image This gives the output as: Image colorMode : Color storage.mode : double dim : 500 726 4 frames.total : 4 frames.render: 1imageData(object)[1:5,1:6,1][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1 This indicates that the image is colored with dimension 500 X 726 X 4. Notice, as we have discussed earlier, here the image depth is 4 and so we will need a filter of depth 4. To unmask these four matrixes we use: getFrames(card, type=”total”) This will give the details of the four channels separately. [[1]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1[[2]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1[[3]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1[[4]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 0 0 0 0 0 0[2,] 0 0 0 0 0 0[3,] 0 0 0 0 0 0[4,] 0 0 0 0 0 0[5,] 0 0 0 0 0 0 And oh yeah! to elucidate our selected card we do: display(card) Although the depth is the same for each card in the data set, the pixel dimensions are varying and so we have to resize each of the cards to 100x100x4 dimensions and combine them all in a stack that is compatible to Keras. This stack then directly goes into the architecture as input. setwd(“C:/parent/club”) # To access the images of Clubs suit. # The path should be modified as per your # machineimg.card<- sample(dir()); #-------shuffle the ordercards<-list(NULL); for(i in 1:length(img.card)){ cards[[i]]<- readImage(img.card[i]) cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100club<- cards # Storing stack of the Clubs cards in # matrix form in a list#-----------------------------------------------------------setwd(“C:/parent/heart”)# To access the images of Hearts suit. # The path should be modified as per your # machineimg.card<- sample(dir());cards<-list(NULL);for(i in 1:length(img.card)) { cards[[i]]<- readImage(img.card[i])cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100heart<- cards # Storing stack of the Hearts cards in # matrix form in a list#------------------------------------------------------------setwd(“C:/parent/spade”)# To access the images of Spades suit. # The path should be modified as per your # machineimg.card<- sample(dir());cards<-list(NULL);for(i in 1:length(img.card)){ cards[[i]]<- readImage(img.card[i])cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100spade<- cards # Storing stack of the Spades cards in # matrix form in a list#------------------------------------------------------------setwd(“C:/parent/diamond”) # To access the images of Diamonds suit. #The path should be modified as per your # machineimg.card<- sample(dir());cards<-list(NULL);for(i in 1:length(img.card)){ cards[[i]]<- readImage(img.card[i])cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100diamond<- cards # Storing stack of the Diamonds cards in # matrix form in a list#-------------------------------------------------------------train_pool<-c(club[1:40], heart[1:40], spade[1:40], diamond[1:40]) # Vector of all the training images. # The first 40 images from each suit # are included in the train settrain<-aperm(combine(train_pool), c(4,1,2,3)) # Combine and stackedtest_pool<-c(club[41:43], heart[41:43], spade[41:43], diamond[41:43]) # Vector of all test images. The last # 3 images from each suit is included # in test settest<-aperm(combine(test_pool), c(4,1,2,3)) # Combined and stacked To see what images are included in the test set, we do this: par(mfrow=c(3,4)) # To contain all images in single framefor(i in 1:12){ plot(test_pool[[i]]) }par(mfrow=c(1,1)) # Reset the default I got the cards as shown in figure 8. It could be a different set of cards for you. One Hot encoding is necessary to create the categorical vectors corresponding to the input data. #one hot encodingtrain_y<-c(rep(0,40),rep(1,40),rep(2,40),rep(3,40))test_y<-c(rep(0,3),rep(1,3),rep(2,3),rep(3,3))train_lab<-to_categorical(train_y) #Catagorical vector for training #classestest_lab<-to_categorical(test_y)#Catagorical vector for test classes Below is the R script to build the CNN model. I am also giving a comprehensive animation along with it that illustrates what’s what as the script proceeds (Figure 9). # Model Buildingmodel.card<- keras_model_sequential() #-Keras Model composed of a #-----linear stack of layersmodel.card %>% #---------Initiate and connect to #----------------------------(A)-----------------------------------#layer_conv_2d(filters = 40, #----------First convoluted layer kernel_size = c(4,4), #---40 Filters with dimension 4x4 activation = ‘relu’, #-with a ReLu activation function input_shape = c(100,100,4)) %>% #----------------------------(B)-----------------------------------#layer_conv_2d(filters = 40, #---------Second convoluted layer kernel_size = c(4,4), #---40 Filters with dimension 4x4 activation = ‘relu’) %>% #-with a ReLu activation function#---------------------------(C)-----------------------------------#layer_max_pooling_2d(pool_size = c(4,4) )%>% #--------Max Pooling#-----------------------------------------------------------------#layer_dropout(rate = 0.25) %>% #-------------------Drop out layer#----------------------------(D)-----------------------------------#layer_conv_2d(filters = 80, #-----------Third convoluted layer kernel_size = c(4,4), #----80 Filters with dimension 4x4 activation = ‘relu’) %>% #--with a ReLu activation function#-----------------------------(E)----------------------------------#layer_conv_2d(filters = 80, #----------Fourth convoluted layer kernel_size = c(4,4), #----80 Filters with dimension 4x4 activation = ‘relu’) %>% #--with a ReLu activation function#-----------------------------(F)----------------------------------#layer_max_pooling_2d(pool_size = c(4,4)) %>% #---------Max Pooling#-----------------------------------------------------------------#layer_dropout(rate = 0.35) %>% #-------------------Drop out layer#------------------------------(G)---------------------------------#layer_flatten()%>% #---Flattening the final stack of feature maps#------------------------------(H)---------------------------------#layer_dense(units = 256, activation = ‘relu’)%>% #-----Hidden layer#---------------------------(I)-----------------------------------#layer_dropout(rate= 0.25)%>% #-------------------Drop-out layer#-----------------------------------------------------------------#layer_dense(units = 4, activation = “softmax”)%>% #-----Final Layer#----------------------------(J)-----------------------------------#compile(loss = 'categorical_crossentropy', optimizer = optimizer_adam(), metrics = c("accuracy")) # Compiling the architecture We can get a summary of this model using summary(model.card). The output of this will be a neat and concise summary of the model. Model: “sequential”____________________________________________________________________Layer (type) Output Shape Param # ====================================================================conv2d (Conv2D) (None, 97, 97, 40) 2600 ____________________________________________________________________conv2d_1 (Conv2D) (None, 94, 94, 40) 25640 ____________________________________________________________________max_pooling2d (MaxPooling2D) (None, 23, 23, 40) 0 ____________________________________________________________________dropout (Dropout) (None, 23, 23, 40) 0 ____________________________________________________________________conv2d_2 (Conv2D) (None, 20, 20, 80) 51280 ____________________________________________________________________conv2d_3 (Conv2D) (None, 17, 17, 80) 102480 ____________________________________________________________________max_pooling2d_1 (MaxPooling2D) (None, 4, 4, 80) 0 ____________________________________________________________________dropout_1 (Dropout) (None, 4, 4, 80) 0____________________________________________________________________flatten (Flatten) (None, 1280) 0 ____________________________________________________________________dense (Dense) (None, 256) 327936 ____________________________________________________________________dropout_2 (Dropout) (None, 256) 0 ____________________________________________________________________dense_1 (Dense) (None, 4) 1028 ====================================================================Total params: 510,964Trainable params: 510,964Non-trainable params: 0____________________________________________________________________ Once the architecture is built, its time to fit our dataset for the training of the model. The fitting is done as: #fit modelhistory<- model.card %>% fit(train, train_lab, epochs = 100, batch_size = 40, validation_split = 0.2 ) On fitting, each epoch (forward feed-backpropagation) will appear in the console area. The processing time may vary from machine to machine. While the epochs are running you should see a graphic in the Rstudio viewer (Figure 9). These are the juxtaposed curves of loss and accuracy for training and validation sets. The running epochs appearing in the console looks something like this: Train on 128 samples, validate on 32 samplesEpoch 1/100128/128 [==============================] — 10s 78ms/sample — loss: 1.3648 — accuracy: 0.3281 — val_loss: 2.0009 — val_accuracy: 0.0000e+00Epoch 2/100128/128 [==============================] — 8s 59ms/sample — loss: 1.3098 — accuracy: 0.3359 — val_loss: 1.9864 — val_accuracy: 0.0000e+00Epoch 3/100128/128 [==============================] — 8s 61ms/sample — loss: 1.2686 — accuracy: 0.3516 — val_loss: 2.5289 — val_accuracy: 0.0000e+00 A summary of the whole training process can be plotted using plot(history). Once the training is completed. Its time to evaluate our freshly trained model. First, we will look at the performance of moel over the trained data set, and then we will finally test and evaluate our trained model over our test set. #Model Evaluationmodel.card %>% evaluate(train,train_lab) #Evaluation of training set pred<- model.card %>% predict_classes(train) #-----ClassificationTrain_Result<-table(Predicted = pred, Actual = train_y) #----Resultsmodel.card %>% evaluate(test, test_lab) #-----Evaluation of test setpred1<- model.card %>% predict_classes(test) #-----ClassificationTest_Result<-table(Predicted = pred1, Actual = test_y) #-----Resultsrownames(Train_Result)<-rownames(Test_Result)<-colnames(Train_Result)<-colnames(Test_Result)<-c("Clubs", "Hearts", "Spades", "Diamonds")print(Train_Result)print(Test_Result) This will spit: The 100% accuracy over the train set can be a sign of overfitting but notice that our model has achieved a 100% accuracy over the test set as well. That means we have successfully made a convolution neural network model to correctly classify a given card image into its true suit. If you are here then congratulations!! You have successfully made your Convolution neural network model. Hope you enjoyed the ride. Please feel free to reach out to me in case you find anything fallible or incorrect. I am also open to all suggestions that can improve the quality of this document. Thank you for reading and Happy R-ing 😀 Where Is Artificial Intelligence Used: Areas Where AI Can Be Used Illustrated: 10 CNN Architectures Gentle Dive into Math Behind Convolutional Neural Networks A Comprehensive Guide to Convolutional Neural Networks — the ELI5 way Keras for R Introduction to EBImage
[ { "code": null, "e": 1881, "s": 172, "text": "Applications of machine learning (ML) are now almost an integral part of our everyday life. From a speech-recognition based virtual assistant in our smartphones to super-intelligent automated drones, ML and artificial intelligence (AI) is revolutionizing the dynamics of human-machine interactions. AI algorithms, especially the convolution neural networks (CNN) have made computer vision extremely powerful than ever. While the applications of it are breathtakingly awesome, it could be very intimidating to build one’s own CNN model, especially for a non-programmer or a beginner in data science, in general. As an R lover, it was not difficult for me to assert that it gets even more enigmatic for a novice R programmer. The plausible reason for this imbalance could be that the standard neural network and ML libraries (like Keras and Tensorflow) are primarily compatible with Python and naturally gravitate the masses to roll with Python itself, leading to a severe lack of novice’s guide and documentation to facilitate the implementation of these sophisticated frameworks in R. Nevertheless, APIs of Keras and Tensorflow is now available on CRAN. Herein, we are going to make a CNN based vanilla image-classification model using Keras and Tensorflow framework in R. With this article, my goal is to enable you to conceptualize and build your own CNN models in R using Keras and, sequentially help to boost your confidence through hands-on coding to build even more complex models in the future using this profound API. Apart from the scripting of the model, I will also try as much to concisely elaborate on the necessary components while plunging the hardcore underlying mathematics. Now let’s start." }, { "code": null, "e": 2291, "s": 1881, "text": "As a prelude to the scripting of CNN, let’s understand the formalisms of it in brief. Just like a human eye registers the information only in the confined receptive frame and learns the specific patterns and spatial features, which subsequently trigger specific neural responses, a CNN model operates in the same fashion. We will try to probe the CNN architecture and understand its key components (Figure 1)." }, { "code": null, "e": 3786, "s": 2291, "text": "Instead of amalgamating the entire image pixels at a time, a subset of pixels is convoluted into a single datum Figure 2. Convolution is carried out by sliding a frame of a smaller size across the entire image acting as a receptive field that accounts for the temporal-spatial features. This frame is called a Kernel/Filter. Imagine scanning a building wall with a flashlight, the filter works in the same fashion. Now, if you have a variety of filters, you are likely to extract or observe more discriminative spatial features and frequently recurring adjacent values. This scheme empowers the learning by not only preserving the spatial characteristics with the least information loss but also significantly reduces the required number of weights, enabling the image classification practically feasible and scalable. For example, consider a 2D black and white (b&w) image as the input to CNN. The model initiates to convolute the image by employing a filter which then slides across the image with a given step size, also called strides. The filter values are analogous to the weights in the neural network. The linear combination of these filter values and the image’s foregrounding pixel values at an instance, generate a single feature output. A set of these values generated produces a new layer called a feature map. Intuitively, a feature map is a condensed form of the input image that preserves all the dominating features and patterns into a smaller dimension for efficient learning." }, { "code": null, "e": 4151, "s": 3786, "text": "Elucidating this in Figure 3, the filter of size 4x4 is employed over a b&w image of dimension 10X10. The filter slides across the image with a stride of 1 unit, thus generating a convoluted layer of dimension (10–4+1)X(10–4+1) i.e 7X7. Note that the bias/intercept for this example is assumed to be 0. Similarly, n number of filters would generate n feature maps." }, { "code": null, "e": 4489, "s": 4151, "text": "For a b&w image, the depth is 1 and so of the filters. However, a colored image is an ensemble of Red, Blue, and Green (RBG) channels. precisely, a stack of three 2D layers, where each layer represents the intensity of a particular color channel. So for a colored image of depth 3, you will need a filter of dimension (4X4)X3 (Figure 4)." }, { "code": null, "e": 4832, "s": 4489, "text": "Once the feature maps are generated, an activation function is applied over each of them. For this purpose, the Rectified Linear Unit (ReLU) activation function comes in handy. If the input to ReLU is a negative value, it simply transforms it to zero else it will spit out the very same input value (Figure 4). Mathematically, f(x)= max(0,x)." }, { "code": null, "e": 5541, "s": 4832, "text": "After the activation layer, another scheme is employed to smartly reduce the dimensions of the feature map without losing vital information. This technique is called Max-pooling. Quite similar to the convolution scheme, here only the highest value from the max-pooling window is picked. This window slides in the same fashion as of the filter but with a step-size equal to the dimension of the pooling window (Figure 5). Max-pooling significantly reduces the dimension of the feature map while also preserving the important/dominating features. The final max-pooled layer is then squashed and flatten into the neuron layer that connects to a fully connected neural network to perform the classification task." }, { "code": null, "e": 6141, "s": 5541, "text": "Mind you CNN is not limited to a single convolution or a single set of the aforementioned schemes. Backed with a sufficient number of filters, The deeper your network is, the higher performance it will achieve. Intuitively, the initial convolutions would capture the low-level recurring features such as edges and colors. Sequentially, the deep layers tend to capture high-level features like recurring clusters pixels say eyes or noses in a portrait. So, in conclusion, based on your image complexity and computation power, you should choose a sufficient and efficient number of layers and filters." }, { "code": null, "e": 6193, "s": 6141, "text": "Now let’s jump into the making of our toy model 🤓!!" }, { "code": null, "e": 6552, "s": 6193, "text": "I believe that to understand any statistical concept nothing comes handier than a deck of playing cards. Here I will exploit a deck of playing cards but in a slightly unorthodox form. Yes, you guessed it!! I will make a prediction model that should be able to accurately classify and predict the suit of a given image of any arbitrary non-faced playing card." }, { "code": null, "e": 7022, "s": 6552, "text": "This dataset contains a set of 43 card images for each suit viz Clubs ♣, Hearts ♥️ , Diamonds ♦️, and Spades ♠️ . Note that the symbols of each suit follow a standard shape however the designing and arrangement of these symbols vary from card to card. We will incorporate this dataset to train and test our model. (To follow the script conveniently, I recommend you to download the images and keep all the files in a parent file as they appear in the Github repository)" }, { "code": null, "e": 7294, "s": 7022, "text": "For this task, you would require Keras and EBImage packages. The former is available on the cran repository. The later is used to deal with the images efficiently and can be called from an open-source software called Bioconductor. These can be installed on Windows OS as:" }, { "code": null, "e": 7563, "s": 7294, "text": "install.packages(“keras”) # Install the package from CRANlibrary(keras)install_keras() #to setup the Keras library and TensorFlow backendif (!requireNamespace(“BiocManager”, quietly = TRUE))install.packages(“BiocManager”)BiocManager::install(“EBImage”)library(EBImage)" }, { "code": null, "e": 7652, "s": 7563, "text": "This installs the CPU version of Keras API, which is recommended for the novice for now." }, { "code": null, "e": 7831, "s": 7652, "text": "Note: The Keras API will require Python support and R tools plug-in. So make sure you have anaconda and R tools installed on your machine with properly added to your system path." }, { "code": null, "e": 8017, "s": 7831, "text": "Next, we will convert the images of each suit into a tensor (numbered matrix). readImage() function from EBImage library does this robustly. Let’s try reading an image from our dataset." }, { "code": null, "e": 8340, "s": 8017, "text": "setwd(“C:/parent/spade”) # To access the images of Spades suit. # The path should be modified as per your # machinecard<-readImage(“ace_of_spades (2).png”) # Reading an imgae from the # datasetprint(card) # Print the details of image" }, { "code": null, "e": 8366, "s": 8340, "text": "This gives the output as:" }, { "code": null, "e": 8599, "s": 8366, "text": "Image colorMode : Color storage.mode : double dim : 500 726 4 frames.total : 4 frames.render: 1imageData(object)[1:5,1:6,1][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1" }, { "code": null, "e": 8813, "s": 8599, "text": "This indicates that the image is colored with dimension 500 X 726 X 4. Notice, as we have discussed earlier, here the image depth is 4 and so we will need a filter of depth 4. To unmask these four matrixes we use:" }, { "code": null, "e": 8843, "s": 8813, "text": "getFrames(card, type=”total”)" }, { "code": null, "e": 8903, "s": 8843, "text": "This will give the details of the four channels separately." }, { "code": null, "e": 9852, "s": 8903, "text": "[[1]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1[[2]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1[[3]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 1 1 1 1 1 1[2,] 1 1 1 1 1 1[3,] 1 1 1 1 1 1[4,] 1 1 1 1 1 1[5,] 1 1 1 1 1 1[[4]]Image colorMode : Grayscale storage.mode : double dim : 500 726 frames.total : 1 frames.render: 1imageData(object)[1:5,1:6][,1] [,2] [,3] [,4] [,5] [,6][1,] 0 0 0 0 0 0[2,] 0 0 0 0 0 0[3,] 0 0 0 0 0 0[4,] 0 0 0 0 0 0[5,] 0 0 0 0 0 0" }, { "code": null, "e": 9903, "s": 9852, "text": "And oh yeah! to elucidate our selected card we do:" }, { "code": null, "e": 9917, "s": 9903, "text": "display(card)" }, { "code": null, "e": 10202, "s": 9917, "text": "Although the depth is the same for each card in the data set, the pixel dimensions are varying and so we have to resize each of the cards to 100x100x4 dimensions and combine them all in a stack that is compatible to Keras. This stack then directly goes into the architecture as input." }, { "code": null, "e": 12932, "s": 10202, "text": "setwd(“C:/parent/club”) # To access the images of Clubs suit. # The path should be modified as per your # machineimg.card<- sample(dir()); #-------shuffle the ordercards<-list(NULL); for(i in 1:length(img.card)){ cards[[i]]<- readImage(img.card[i]) cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100club<- cards # Storing stack of the Clubs cards in # matrix form in a list#-----------------------------------------------------------setwd(“C:/parent/heart”)# To access the images of Hearts suit. # The path should be modified as per your # machineimg.card<- sample(dir());cards<-list(NULL);for(i in 1:length(img.card)) { cards[[i]]<- readImage(img.card[i])cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100heart<- cards # Storing stack of the Hearts cards in # matrix form in a list#------------------------------------------------------------setwd(“C:/parent/spade”)# To access the images of Spades suit. # The path should be modified as per your # machineimg.card<- sample(dir());cards<-list(NULL);for(i in 1:length(img.card)){ cards[[i]]<- readImage(img.card[i])cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100spade<- cards # Storing stack of the Spades cards in # matrix form in a list#------------------------------------------------------------setwd(“C:/parent/diamond”) # To access the images of Diamonds suit. #The path should be modified as per your # machineimg.card<- sample(dir());cards<-list(NULL);for(i in 1:length(img.card)){ cards[[i]]<- readImage(img.card[i])cards[[i]]<- resize(cards[[i]], 100, 100)} #resizing to 100x100diamond<- cards # Storing stack of the Diamonds cards in # matrix form in a list#-------------------------------------------------------------train_pool<-c(club[1:40], heart[1:40], spade[1:40], diamond[1:40]) # Vector of all the training images. # The first 40 images from each suit # are included in the train settrain<-aperm(combine(train_pool), c(4,1,2,3)) # Combine and stackedtest_pool<-c(club[41:43], heart[41:43], spade[41:43], diamond[41:43]) # Vector of all test images. The last # 3 images from each suit is included # in test settest<-aperm(combine(test_pool), c(4,1,2,3)) # Combined and stacked" }, { "code": null, "e": 12993, "s": 12932, "text": "To see what images are included in the test set, we do this:" }, { "code": null, "e": 13128, "s": 12993, "text": "par(mfrow=c(3,4)) # To contain all images in single framefor(i in 1:12){ plot(test_pool[[i]]) }par(mfrow=c(1,1)) # Reset the default" }, { "code": null, "e": 13212, "s": 13128, "text": "I got the cards as shown in figure 8. It could be a different set of cards for you." }, { "code": null, "e": 13309, "s": 13212, "text": "One Hot encoding is necessary to create the categorical vectors corresponding to the input data." }, { "code": null, "e": 13603, "s": 13309, "text": "#one hot encodingtrain_y<-c(rep(0,40),rep(1,40),rep(2,40),rep(3,40))test_y<-c(rep(0,3),rep(1,3),rep(2,3),rep(3,3))train_lab<-to_categorical(train_y) #Catagorical vector for training #classestest_lab<-to_categorical(test_y)#Catagorical vector for test classes" }, { "code": null, "e": 13770, "s": 13603, "text": "Below is the R script to build the CNN model. I am also giving a comprehensive animation along with it that illustrates what’s what as the script proceeds (Figure 9)." }, { "code": null, "e": 16394, "s": 13770, "text": "# Model Buildingmodel.card<- keras_model_sequential() #-Keras Model composed of a #-----linear stack of layersmodel.card %>% #---------Initiate and connect to #----------------------------(A)-----------------------------------#layer_conv_2d(filters = 40, #----------First convoluted layer kernel_size = c(4,4), #---40 Filters with dimension 4x4 activation = ‘relu’, #-with a ReLu activation function input_shape = c(100,100,4)) %>% #----------------------------(B)-----------------------------------#layer_conv_2d(filters = 40, #---------Second convoluted layer kernel_size = c(4,4), #---40 Filters with dimension 4x4 activation = ‘relu’) %>% #-with a ReLu activation function#---------------------------(C)-----------------------------------#layer_max_pooling_2d(pool_size = c(4,4) )%>% #--------Max Pooling#-----------------------------------------------------------------#layer_dropout(rate = 0.25) %>% #-------------------Drop out layer#----------------------------(D)-----------------------------------#layer_conv_2d(filters = 80, #-----------Third convoluted layer kernel_size = c(4,4), #----80 Filters with dimension 4x4 activation = ‘relu’) %>% #--with a ReLu activation function#-----------------------------(E)----------------------------------#layer_conv_2d(filters = 80, #----------Fourth convoluted layer kernel_size = c(4,4), #----80 Filters with dimension 4x4 activation = ‘relu’) %>% #--with a ReLu activation function#-----------------------------(F)----------------------------------#layer_max_pooling_2d(pool_size = c(4,4)) %>% #---------Max Pooling#-----------------------------------------------------------------#layer_dropout(rate = 0.35) %>% #-------------------Drop out layer#------------------------------(G)---------------------------------#layer_flatten()%>% #---Flattening the final stack of feature maps#------------------------------(H)---------------------------------#layer_dense(units = 256, activation = ‘relu’)%>% #-----Hidden layer#---------------------------(I)-----------------------------------#layer_dropout(rate= 0.25)%>% #-------------------Drop-out layer#-----------------------------------------------------------------#layer_dense(units = 4, activation = “softmax”)%>% #-----Final Layer#----------------------------(J)-----------------------------------#compile(loss = 'categorical_crossentropy', optimizer = optimizer_adam(), metrics = c(\"accuracy\")) # Compiling the architecture" }, { "code": null, "e": 16524, "s": 16394, "text": "We can get a summary of this model using summary(model.card). The output of this will be a neat and concise summary of the model." }, { "code": null, "e": 18145, "s": 16524, "text": "Model: “sequential”____________________________________________________________________Layer (type) Output Shape Param # ====================================================================conv2d (Conv2D) (None, 97, 97, 40) 2600 ____________________________________________________________________conv2d_1 (Conv2D) (None, 94, 94, 40) 25640 ____________________________________________________________________max_pooling2d (MaxPooling2D) (None, 23, 23, 40) 0 ____________________________________________________________________dropout (Dropout) (None, 23, 23, 40) 0 ____________________________________________________________________conv2d_2 (Conv2D) (None, 20, 20, 80) 51280 ____________________________________________________________________conv2d_3 (Conv2D) (None, 17, 17, 80) 102480 ____________________________________________________________________max_pooling2d_1 (MaxPooling2D) (None, 4, 4, 80) 0 ____________________________________________________________________dropout_1 (Dropout) (None, 4, 4, 80) 0____________________________________________________________________flatten (Flatten) (None, 1280) 0 ____________________________________________________________________dense (Dense) (None, 256) 327936 ____________________________________________________________________dropout_2 (Dropout) (None, 256) 0 ____________________________________________________________________dense_1 (Dense) (None, 4) 1028 ====================================================================Total params: 510,964Trainable params: 510,964Non-trainable params: 0____________________________________________________________________" }, { "code": null, "e": 18260, "s": 18145, "text": "Once the architecture is built, its time to fit our dataset for the training of the model. The fitting is done as:" }, { "code": null, "e": 18375, "s": 18260, "text": "#fit modelhistory<- model.card %>% fit(train, train_lab, epochs = 100, batch_size = 40, validation_split = 0.2 )" }, { "code": null, "e": 18691, "s": 18375, "text": "On fitting, each epoch (forward feed-backpropagation) will appear in the console area. The processing time may vary from machine to machine. While the epochs are running you should see a graphic in the Rstudio viewer (Figure 9). These are the juxtaposed curves of loss and accuracy for training and validation sets." }, { "code": null, "e": 18762, "s": 18691, "text": "The running epochs appearing in the console looks something like this:" }, { "code": null, "e": 19252, "s": 18762, "text": "Train on 128 samples, validate on 32 samplesEpoch 1/100128/128 [==============================] — 10s 78ms/sample — loss: 1.3648 — accuracy: 0.3281 — val_loss: 2.0009 — val_accuracy: 0.0000e+00Epoch 2/100128/128 [==============================] — 8s 59ms/sample — loss: 1.3098 — accuracy: 0.3359 — val_loss: 1.9864 — val_accuracy: 0.0000e+00Epoch 3/100128/128 [==============================] — 8s 61ms/sample — loss: 1.2686 — accuracy: 0.3516 — val_loss: 2.5289 — val_accuracy: 0.0000e+00" }, { "code": null, "e": 19328, "s": 19252, "text": "A summary of the whole training process can be plotted using plot(history)." }, { "code": null, "e": 19562, "s": 19328, "text": "Once the training is completed. Its time to evaluate our freshly trained model. First, we will look at the performance of moel over the trained data set, and then we will finally test and evaluate our trained model over our test set." }, { "code": null, "e": 20159, "s": 19562, "text": "#Model Evaluationmodel.card %>% evaluate(train,train_lab) #Evaluation of training set pred<- model.card %>% predict_classes(train) #-----ClassificationTrain_Result<-table(Predicted = pred, Actual = train_y) #----Resultsmodel.card %>% evaluate(test, test_lab) #-----Evaluation of test setpred1<- model.card %>% predict_classes(test) #-----ClassificationTest_Result<-table(Predicted = pred1, Actual = test_y) #-----Resultsrownames(Train_Result)<-rownames(Test_Result)<-colnames(Train_Result)<-colnames(Test_Result)<-c(\"Clubs\", \"Hearts\", \"Spades\", \"Diamonds\")print(Train_Result)print(Test_Result)" }, { "code": null, "e": 20175, "s": 20159, "text": "This will spit:" }, { "code": null, "e": 20456, "s": 20175, "text": "The 100% accuracy over the train set can be a sign of overfitting but notice that our model has achieved a 100% accuracy over the test set as well. That means we have successfully made a convolution neural network model to correctly classify a given card image into its true suit." }, { "code": null, "e": 20754, "s": 20456, "text": "If you are here then congratulations!! You have successfully made your Convolution neural network model. Hope you enjoyed the ride. Please feel free to reach out to me in case you find anything fallible or incorrect. I am also open to all suggestions that can improve the quality of this document." }, { "code": null, "e": 20794, "s": 20754, "text": "Thank you for reading and Happy R-ing 😀" }, { "code": null, "e": 20860, "s": 20794, "text": "Where Is Artificial Intelligence Used: Areas Where AI Can Be Used" }, { "code": null, "e": 20894, "s": 20860, "text": "Illustrated: 10 CNN Architectures" }, { "code": null, "e": 20953, "s": 20894, "text": "Gentle Dive into Math Behind Convolutional Neural Networks" }, { "code": null, "e": 21023, "s": 20953, "text": "A Comprehensive Guide to Convolutional Neural Networks — the ELI5 way" }, { "code": null, "e": 21035, "s": 21023, "text": "Keras for R" } ]
How to Connect Python with SQL Database? - GeeksforGeeks
30 Sep, 2021 Python is a high-level, general-purpose, and very popular programming language. Basically, it was designed with an emphasis on code readability, and programmers can express their concepts in fewer lines of code. We can also use Python with SQL. In this article, we will learn how to connect SQL with Python using the ‘MySQL Connector Python‘ module. The diagram given below illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data. SQL connection with Python To create a connection between the MySQL database and Python, the connect() method of mysql.connector module is used. We pass the database details like HostName, username, and the password in the method call, and then the method returns the connection object. The following steps are required to connect SQL with Python: Step 1: Download and Install the free MySQL database from here. Step 2: After installing the MySQL database, open your Command prompt. Step 3: Navigate your Command prompt to the location of PIP. Click here to see, How to install PIP? Step 4: Now run the commands given below to download and install “MySQL Connector”. Here, mysql.connector statement will help you to communicate with the MySQL database. pip install mysql-connector-python Step 5: To check if the installation was successful, or if you already installed “MySQL Connector”, go to your IDE and run the given below code : import mysql.connector If the above code gets executed with no errors, “MySQL Connector” is ready to be used. Step 6: Now to connect SQL with Python, run the code given below in your IDE. Python3 # Importing moduleimport mysql.connector # Creating connection objectmydb = mysql.connector.connect( host = "localhost", user = "yourusername", password = "your_password") # Printing the connection objectprint(mydb) Output: Here, in the above code: Code Info To create a database, we will use CREATE DATABASE database_name statement and we will execute this statement by creating an instance of the ‘cursor’ class. Python3 import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "yourusername", password = "your_password") # Creating an instance of 'cursor' class# which is used to execute the 'SQL'# statements in 'Python'cursor = mydb.cursor() # Creating a database with a name# 'geeksforgeeks' execute() method# is used to compile a SQL statement# below statement is used to create# the 'geeksforgeeks' databasecursor.execute("CREATE DATABASE geeksforgeeks") Output: If the database with the name ‘geeksforgeeks’ already exists then you will get an error, otherwise no error. So make sure that the new database that you are creating does not have the same name as the database already you created or exists previously. Now to check the databases that you created, use “SHOW DATABASES” – SQL statement i.e. cursor.execute(“SHOW DATABASES”) Python3 import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "root", password = "1234") # Creating an instance of 'cursor' class# which is used to execute the 'SQL'# statements in 'Python'cursor = mydb.cursor() # Show databasecursor.execute("SHOW DATABASE") for x in cursor: print(x) Output: Now to create tables in a database, first, we have to select a database and for that, we will pass database = “NameofDatabase” as your fourth parameter in connect() function. Since we have created a database with the name ‘geekforgeeks’ above, so we will use that and create our tables. We will use CREATE TABLE gfg (variableName1 datatype, variableName2 datatype) statement to create our table with the name ‘gfg’. Python3 import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "yourusername", password = "your_password", database = "geeksforgeeks") cursor = mydb.cursor() # Creating a table called 'gfg' in the# 'geeksforgeeks' databasecursor.execute("CREATE TABLE gfg (name VARCHAR(255), user_name VARCHAR(255))") Output: If the table with the name ‘gfg’ already exists, you will get an error, otherwise no error. So make sure that the new table that you are creating does not have the same name as the table already you created or exists previously. Now to check tables that you created, use “SHOW TABLES” – SQL statement i.e. cursor.execute(“SHOW TABLES”). Python3 import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "root password = "1234", database = "geeksforgeeks") cursor = mydb.cursor() # Show existing tablescursor.execute("SHOW TABLES") for x in cursor: print(x) Output: Notes: mysql.connector allows Python programs to access MySQL databases. connect() method of the MySQL Connector class with the arguments will connect to MySQL and would return a MySQLConnection object if the connection is established successfully. user = “yourusername”, here “yourusername” should be the same username as you set during MySQL installation. password = “your_password”, here “your_password” should be the same password as you set during MySQL installation. cursor() is used to execute the SQL statements in Python. execute() method is used to compile a SQL statement. saurabh1990aror Blogathon-2021 Picked Blogathon Class 12 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? Banking Transaction System using Java How to build a basic CRUD app with Node.js and ReactJS ? Changing CSS styling with React onClick() Event Python - Gaussian fit Libraries in Python Reading Rows from a CSV File in Python GeeksforGeeks School Data Communication - Definition, Components, Types, Channels What is an IP Address?
[ { "code": null, "e": 25741, "s": 25713, "text": "\n30 Sep, 2021" }, { "code": null, "e": 26275, "s": 25741, "text": "Python is a high-level, general-purpose, and very popular programming language. Basically, it was designed with an emphasis on code readability, and programmers can express their concepts in fewer lines of code. We can also use Python with SQL. In this article, we will learn how to connect SQL with Python using the ‘MySQL Connector Python‘ module. The diagram given below illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data." }, { "code": null, "e": 26302, "s": 26275, "text": "SQL connection with Python" }, { "code": null, "e": 26562, "s": 26302, "text": "To create a connection between the MySQL database and Python, the connect() method of mysql.connector module is used. We pass the database details like HostName, username, and the password in the method call, and then the method returns the connection object." }, { "code": null, "e": 26623, "s": 26562, "text": "The following steps are required to connect SQL with Python:" }, { "code": null, "e": 26687, "s": 26623, "text": "Step 1: Download and Install the free MySQL database from here." }, { "code": null, "e": 26758, "s": 26687, "text": "Step 2: After installing the MySQL database, open your Command prompt." }, { "code": null, "e": 26858, "s": 26758, "text": "Step 3: Navigate your Command prompt to the location of PIP. Click here to see, How to install PIP?" }, { "code": null, "e": 27028, "s": 26858, "text": "Step 4: Now run the commands given below to download and install “MySQL Connector”. Here, mysql.connector statement will help you to communicate with the MySQL database." }, { "code": null, "e": 27064, "s": 27028, "text": "pip install mysql-connector-python " }, { "code": null, "e": 27210, "s": 27064, "text": "Step 5: To check if the installation was successful, or if you already installed “MySQL Connector”, go to your IDE and run the given below code :" }, { "code": null, "e": 27233, "s": 27210, "text": "import mysql.connector" }, { "code": null, "e": 27320, "s": 27233, "text": "If the above code gets executed with no errors, “MySQL Connector” is ready to be used." }, { "code": null, "e": 27398, "s": 27320, "text": "Step 6: Now to connect SQL with Python, run the code given below in your IDE." }, { "code": null, "e": 27406, "s": 27398, "text": "Python3" }, { "code": "# Importing moduleimport mysql.connector # Creating connection objectmydb = mysql.connector.connect( host = \"localhost\", user = \"yourusername\", password = \"your_password\") # Printing the connection objectprint(mydb)", "e": 27631, "s": 27406, "text": null }, { "code": null, "e": 27639, "s": 27631, "text": "Output:" }, { "code": null, "e": 27664, "s": 27639, "text": "Here, in the above code:" }, { "code": null, "e": 27674, "s": 27664, "text": "Code Info" }, { "code": null, "e": 27830, "s": 27674, "text": "To create a database, we will use CREATE DATABASE database_name statement and we will execute this statement by creating an instance of the ‘cursor’ class." }, { "code": null, "e": 27838, "s": 27830, "text": "Python3" }, { "code": "import mysql.connector mydb = mysql.connector.connect( host = \"localhost\", user = \"yourusername\", password = \"your_password\") # Creating an instance of 'cursor' class# which is used to execute the 'SQL'# statements in 'Python'cursor = mydb.cursor() # Creating a database with a name# 'geeksforgeeks' execute() method# is used to compile a SQL statement# below statement is used to create# the 'geeksforgeeks' databasecursor.execute(\"CREATE DATABASE geeksforgeeks\")", "e": 28312, "s": 27838, "text": null }, { "code": null, "e": 28320, "s": 28312, "text": "Output:" }, { "code": null, "e": 28692, "s": 28320, "text": "If the database with the name ‘geeksforgeeks’ already exists then you will get an error, otherwise no error. So make sure that the new database that you are creating does not have the same name as the database already you created or exists previously. Now to check the databases that you created, use “SHOW DATABASES” – SQL statement i.e. cursor.execute(“SHOW DATABASES”)" }, { "code": null, "e": 28700, "s": 28692, "text": "Python3" }, { "code": "import mysql.connector mydb = mysql.connector.connect( host = \"localhost\", user = \"root\", password = \"1234\") # Creating an instance of 'cursor' class# which is used to execute the 'SQL'# statements in 'Python'cursor = mydb.cursor() # Show databasecursor.execute(\"SHOW DATABASE\") for x in cursor: print(x)", "e": 29015, "s": 28700, "text": null }, { "code": null, "e": 29023, "s": 29015, "text": "Output:" }, { "code": null, "e": 29439, "s": 29023, "text": "Now to create tables in a database, first, we have to select a database and for that, we will pass database = “NameofDatabase” as your fourth parameter in connect() function. Since we have created a database with the name ‘geekforgeeks’ above, so we will use that and create our tables. We will use CREATE TABLE gfg (variableName1 datatype, variableName2 datatype) statement to create our table with the name ‘gfg’." }, { "code": null, "e": 29447, "s": 29439, "text": "Python3" }, { "code": "import mysql.connector mydb = mysql.connector.connect( host = \"localhost\", user = \"yourusername\", password = \"your_password\", database = \"geeksforgeeks\") cursor = mydb.cursor() # Creating a table called 'gfg' in the# 'geeksforgeeks' databasecursor.execute(\"CREATE TABLE gfg (name VARCHAR(255), user_name VARCHAR(255))\")", "e": 29779, "s": 29447, "text": null }, { "code": null, "e": 29787, "s": 29779, "text": "Output:" }, { "code": null, "e": 30124, "s": 29787, "text": "If the table with the name ‘gfg’ already exists, you will get an error, otherwise no error. So make sure that the new table that you are creating does not have the same name as the table already you created or exists previously. Now to check tables that you created, use “SHOW TABLES” – SQL statement i.e. cursor.execute(“SHOW TABLES”)." }, { "code": null, "e": 30132, "s": 30124, "text": "Python3" }, { "code": "import mysql.connector mydb = mysql.connector.connect( host = \"localhost\", user = \"root password = \"1234\", database = \"geeksforgeeks\") cursor = mydb.cursor() # Show existing tablescursor.execute(\"SHOW TABLES\") for x in cursor: print(x)", "e": 30381, "s": 30132, "text": null }, { "code": null, "e": 30389, "s": 30381, "text": "Output:" }, { "code": null, "e": 30396, "s": 30389, "text": "Notes:" }, { "code": null, "e": 30462, "s": 30396, "text": "mysql.connector allows Python programs to access MySQL databases." }, { "code": null, "e": 30638, "s": 30462, "text": "connect() method of the MySQL Connector class with the arguments will connect to MySQL and would return a MySQLConnection object if the connection is established successfully." }, { "code": null, "e": 30747, "s": 30638, "text": "user = “yourusername”, here “yourusername” should be the same username as you set during MySQL installation." }, { "code": null, "e": 30862, "s": 30747, "text": "password = “your_password”, here “your_password” should be the same password as you set during MySQL installation." }, { "code": null, "e": 30920, "s": 30862, "text": "cursor() is used to execute the SQL statements in Python." }, { "code": null, "e": 30973, "s": 30920, "text": "execute() method is used to compile a SQL statement." }, { "code": null, "e": 30989, "s": 30973, "text": "saurabh1990aror" }, { "code": null, "e": 31004, "s": 30989, "text": "Blogathon-2021" }, { "code": null, "e": 31011, "s": 31004, "text": "Picked" }, { "code": null, "e": 31021, "s": 31011, "text": "Blogathon" }, { "code": null, "e": 31030, "s": 31021, "text": "Class 12" }, { "code": null, "e": 31046, "s": 31030, "text": "School Learning" }, { "code": null, "e": 31065, "s": 31046, "text": "School Programming" }, { "code": null, "e": 31163, "s": 31065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31220, "s": 31163, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 31258, "s": 31220, "text": "Banking Transaction System using Java" }, { "code": null, "e": 31315, "s": 31258, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 31363, "s": 31315, "text": "Changing CSS styling with React onClick() Event" }, { "code": null, "e": 31385, "s": 31363, "text": "Python - Gaussian fit" }, { "code": null, "e": 31405, "s": 31385, "text": "Libraries in Python" }, { "code": null, "e": 31444, "s": 31405, "text": "Reading Rows from a CSV File in Python" }, { "code": null, "e": 31465, "s": 31444, "text": "GeeksforGeeks School" }, { "code": null, "e": 31526, "s": 31465, "text": "Data Communication - Definition, Components, Types, Channels" } ]
C++ Program to Find Largest Number Among Three Numbers
The largest number among three numbers can be found using if statement multiple times. This is given in a program as follows − Live Demo #include <iostream> using namespace std; int main() { int a = 5 ,b = 1 ,c = 9; if(a>b) { if(a>c) cout<<a<<" is largest number"; else cout<<c<<" is largest number"; }else { if(b>c) cout<<b<<" is largest number"; else cout<<c<<" is largest number"; } return 0; } 9 is largest number In the above program, firstly, a is compared to b. If a is greater than b, then it is compared to c. If it is greater than c as well, that means a is the largest number and if not, then c is the largest number. if(a>b) { if(a>c) cout<<a<<" is largest number"; else cout<<c<<" is largest number"; } If a is not greater than b, that means b is greater than a. Then b is compared to c. If it is greater than c, that means b is the largest number and if not, then c is the largest number. else { if(b>c) cout<<b<<" is largest number"; else cout<<c<<" is largest number"; }
[ { "code": null, "e": 1189, "s": 1062, "text": "The largest number among three numbers can be found using if statement multiple times. This is given in a program as follows −" }, { "code": null, "e": 1200, "s": 1189, "text": " Live Demo" }, { "code": null, "e": 1524, "s": 1200, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int a = 5 ,b = 1 ,c = 9;\n if(a>b) {\n if(a>c)\n cout<<a<<\" is largest number\";\n else\n cout<<c<<\" is largest number\";\n }else {\n if(b>c)\n cout<<b<<\" is largest number\";\n else\n cout<<c<<\" is largest number\";\n }\n return 0;\n}" }, { "code": null, "e": 1544, "s": 1524, "text": "9 is largest number" }, { "code": null, "e": 1755, "s": 1544, "text": "In the above program, firstly, a is compared to b. If a is greater than b, then it is compared to c. If it is greater than c as well, that means a is the largest number and if not, then c is the largest number." }, { "code": null, "e": 1854, "s": 1755, "text": "if(a>b) {\n if(a>c)\n cout<<a<<\" is largest number\";\n else\n cout<<c<<\" is largest number\";\n}" }, { "code": null, "e": 2041, "s": 1854, "text": "If a is not greater than b, that means b is greater than a. Then b is compared to c. If it is greater than c, that means b is the largest number and if not, then c is the largest number." }, { "code": null, "e": 2137, "s": 2041, "text": "else {\n if(b>c)\n cout<<b<<\" is largest number\";\n else\n cout<<c<<\" is largest number\";\n}" } ]
Generate Parentheses | Practice | GeeksforGeeks
Given an integer N representing the number of pairs of parentheses, the task is to generate all combinations of well-formed(balanced) parentheses. Example 1: Input: N = 3 Output: ((())) (()()) (())() ()(()) ()()() Input: N = 1 Output: () 0 sarthakpandey200218 hours ago SIMPLE C++ SOLUTION void solve(string out,vector<string>&ans,int open,int close){ //int open=n; //int close=n; if(open==0 && close==0){ ans.push_back(out); return; } if(open!=0){ string op1=out; op1.push_back('('); solve(op1,ans,open-1,close); } if(close>open){ string op2=out; op2.push_back(')'); solve(op2,ans,open,close-1); } return; } vector<string> AllParenthesis(int n) { // Your code goes here vector<string>ans; int open=n; int close=n; solve("",ans,open,close); return ans; }}; 0 rounakdiptaghosh19992 weeks ago void solve(int open , int close,vector<string>&ans,string op) { if(open==0 and close==0){ ans.push_back(op); return ; } if(open!=0){ string op1 = op ; op1.push_back('('); solve(open-1,close,ans,op1); } if(close>open){ string op2=op; op2.push_back(')'); solve(open,close-1,ans,op2); } return ; } vector<string> AllParenthesis(int n) { // Your code goes here vector<string> ans; int open=n; int close=n; string op=""; solve(open , close , ans ,op); return ans; +1 shourya17agarwal3 weeks ago There us an error with python compiler. IT shows wrong output while submitting. but correct while testing. 0 bokonist3 weeks ago Simple C++ recursive solution with comments. TC: O(2^N * N) . . . void paran(int n, int open, int close, string s, vector<string> &ans) { //try to picture the recursion tree, at every point, there are two choices, add an opening or a closing // when opening and closing reaches n, we have one of our ans strings if(open==n && close==n) { ans.push_back(s); return; } if(open<n) paran(n, open+1, close, s+"(", ans); if(close<open) paran(n, open, close+1, s+")", ans); } vector<string> AllParenthesis(int n) { // Your code goes here vector<string> ans; paran(n, 0,0,"",ans); return ans; } 0 aanandhub4 weeks ago List<String> str = new ArrayList<String>(); public List<String> AllParenthesis(int n) { // Write your code here return Paranthesis("",0,0,n); } public List<String> Paranthesis(String temp, int start, int close, int n) { if(close > start) { return str; } if(start + close == n*2) { if(start == close) { str.add(String.valueOf(temp)); return str; } else { return str; } } Paranthesis(temp+"(", start+1, close, n); Paranthesis(temp+")", start, close+1, n); return str; } +1 adarshgupta4014 weeks ago Easy Java Recursive Soln→ class Solution { public List<String> AllParenthesis(int n) { List<String> list = new ArrayList<>(); int open= n, close= n; String op= ""; helper(open, close, op, list); return list; } public void helper(int open, int close, String op, List<String> list) { //base if(open == 0 && close == 0) { list.add(op); return; } if(open > 0 ){ String op1 = op; op1 += '('; helper(open-1, close, op1, list); } if(close > open){ String op2 = op; op2 += ')'; helper(open, close-1, op2, list); } return; } } +1 scien-terrific1 month ago C++ BackTracking Solution class Solution { vector<string>res; private: void helper(string &s,int open,int close){ if(!open and !close){ res.push_back(s); return; } if(open){ s+="("; helper(s,open-1,close); s.pop_back(); } if(close and close>open){ s+=")"; helper(s,open,close-1); s.pop_back(); } } public: vector<string> AllParenthesis(int n) { if(!n)return {}; string s=""; helper(s,n,n); return res; } }; +1 abytespaceneeded1 month ago // upvote if you like the solution. class Solution { public: vector<string> ans; void solve(string temp, int open, int close) { if(open == 0 && close == 0) { ans.push_back(temp); return ; } if(open == close) solve(temp+'(',open-1,close); else if(open == 0 && close != 0) solve(temp+')',open,close-1); else { solve(temp+'(',open-1,close); solve(temp+')',open,close-1); } } vector<string> AllParenthesis(int n) { solve("",n,n); return ans; } }; 0 aloksinghbais021 month ago C++ solution having time complexity as O((2^N)*N) and space complexity as O((2^N)*X) is as follows :- Execution Time :- 0.9 / 1.5 sec vector<string> ans; bool isValid(string str,int cnt1,int cnt2){ if(cnt1 != cnt2) return (false); stack<char> stk; for(auto &ch: str){ if(ch == '(') stk.push(ch); else{ if(stk.empty()) return (false); if(stk.top() != '(') return (false); stk.pop(); } } if(!stk.empty()) return (false); return (true); } void helper(int i,string output,int cnt1,int cnt2,int n){ if(i == 2*n){ if(isValid(output,cnt1,cnt2)){ ans.push_back(output); } return; } if(cnt1 <= n) helper(i+1,output+'(',cnt1+1,cnt2,n); if(cnt2 <= n && cnt1 > cnt2) helper(i+1,output+')',cnt1,cnt2+1,n); } vector<string> AllParenthesis(int n) { string output{}; helper(0,output,0,0,n); return (ans); } 0 kashyapjhon2 months ago C++ Solution Input Output Approach Time=(0.3/1.5) MEDIUM: void help(vector<string> &u,int l,int r,string out){ if(l==0 && r==0){ u.push_back(out); return; } if(l!=0){ string out1=out; out1.push_back('('); help(u,l-1,r,out1); } if(l<r){ string out2=out; out2.push_back(')'); help(u,l,r-1,out2); } return; } vector<string> AllParenthesis(int n) { // Your code goes here vector<string> u; int l=n; int r=n; string out=""; help(u,l,r,out); return u; } 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": 385, "s": 238, "text": "Given an integer N representing the number of pairs of parentheses, the task is to generate all combinations of well-formed(balanced) parentheses." }, { "code": null, "e": 397, "s": 385, "text": "\nExample 1:" }, { "code": null, "e": 454, "s": 397, "text": "Input:\nN = 3\nOutput:\n((()))\n(()())\n(())()\n()(())\n()()()\n" }, { "code": null, "e": 479, "s": 454, "text": "Input:\nN = 1\nOutput:\n()\n" }, { "code": null, "e": 481, "s": 479, "text": "0" }, { "code": null, "e": 511, "s": 481, "text": "sarthakpandey200218 hours ago" }, { "code": null, "e": 532, "s": 511, "text": "SIMPLE C++ SOLUTION " }, { "code": null, "e": 1180, "s": 532, "text": "void solve(string out,vector<string>&ans,int open,int close){ //int open=n; //int close=n; if(open==0 && close==0){ ans.push_back(out); return; } if(open!=0){ string op1=out; op1.push_back('('); solve(op1,ans,open-1,close); } if(close>open){ string op2=out; op2.push_back(')'); solve(op2,ans,open,close-1); } return; } vector<string> AllParenthesis(int n) { // Your code goes here vector<string>ans; int open=n; int close=n; solve(\"\",ans,open,close); return ans; }}; " }, { "code": null, "e": 1182, "s": 1180, "text": "0" }, { "code": null, "e": 1214, "s": 1182, "text": "rounakdiptaghosh19992 weeks ago" }, { "code": null, "e": 1910, "s": 1214, "text": "void solve(int open , int close,vector<string>&ans,string op)\n {\n if(open==0 and close==0){\n ans.push_back(op);\n return ;\n }\n \n if(open!=0){\n string op1 = op ;\n op1.push_back('(');\n solve(open-1,close,ans,op1);\n }\n if(close>open){\n string op2=op;\n op2.push_back(')');\n solve(open,close-1,ans,op2);\n }\n return ;\n }\n \n vector<string> AllParenthesis(int n) \n {\n // Your code goes here \n vector<string> ans;\n int open=n;\n int close=n;\n string op=\"\";\n solve(open , close , ans ,op);\n return ans;\n " }, { "code": null, "e": 1913, "s": 1910, "text": "+1" }, { "code": null, "e": 1941, "s": 1913, "text": "shourya17agarwal3 weeks ago" }, { "code": null, "e": 2048, "s": 1941, "text": "There us an error with python compiler. IT shows wrong output while submitting. but correct while testing." }, { "code": null, "e": 2050, "s": 2048, "text": "0" }, { "code": null, "e": 2070, "s": 2050, "text": "bokonist3 weeks ago" }, { "code": null, "e": 2115, "s": 2070, "text": "Simple C++ recursive solution with comments." }, { "code": null, "e": 2130, "s": 2115, "text": "TC: O(2^N * N)" }, { "code": null, "e": 2132, "s": 2130, "text": "." }, { "code": null, "e": 2134, "s": 2132, "text": "." }, { "code": null, "e": 2136, "s": 2134, "text": "." }, { "code": null, "e": 2744, "s": 2136, "text": "void paran(int n, int open, int close, string s, vector<string> &ans)\n{\n //try to picture the recursion tree, at every point, there are two choices, add an opening or a closing\n // when opening and closing reaches n, we have one of our ans strings\n if(open==n && close==n)\n {\n ans.push_back(s);\n return;\n } \n if(open<n)\n paran(n, open+1, close, s+\"(\", ans);\n if(close<open)\n paran(n, open, close+1, s+\")\", ans);\n}\nvector<string> AllParenthesis(int n) \n{\n // Your code goes here \n vector<string> ans;\n paran(n, 0,0,\"\",ans);\n return ans;\n \n}" }, { "code": null, "e": 2746, "s": 2744, "text": "0" }, { "code": null, "e": 2767, "s": 2746, "text": "aanandhub4 weeks ago" }, { "code": null, "e": 3016, "s": 2767, "text": "List<String> str = new ArrayList<String>(); public List<String> AllParenthesis(int n) { // Write your code here return Paranthesis(\"\",0,0,n); } public List<String> Paranthesis(String temp, int start, int close, int n) {" }, { "code": null, "e": 3452, "s": 3016, "text": " if(close > start) { return str; } if(start + close == n*2) { if(start == close) { str.add(String.valueOf(temp)); return str; } else { return str; } } Paranthesis(temp+\"(\", start+1, close, n); Paranthesis(temp+\")\", start, close+1, n); return str; }" }, { "code": null, "e": 3455, "s": 3452, "text": "+1" }, { "code": null, "e": 3481, "s": 3455, "text": "adarshgupta4014 weeks ago" }, { "code": null, "e": 3507, "s": 3481, "text": "Easy Java Recursive Soln→" }, { "code": null, "e": 4228, "s": 3507, "text": "class Solution {\n \n public List<String> AllParenthesis(int n) \n {\n List<String> list = new ArrayList<>();\n\n int open= n, close= n;\n String op= \"\";\n helper(open, close, op, list);\n return list;\n }\n public void helper(int open, int close, String op, List<String> list) {\n //base\n if(open == 0 && close == 0) {\n list.add(op);\n return;\n }\n if(open > 0 ){\n String op1 = op;\n op1 += '(';\n helper(open-1, close, op1, list);\n }\n if(close > open){\n String op2 = op;\n op2 += ')';\n helper(open, close-1, op2, list);\n }\n return;\n }\n}\n" }, { "code": null, "e": 4231, "s": 4228, "text": "+1" }, { "code": null, "e": 4257, "s": 4231, "text": "scien-terrific1 month ago" }, { "code": null, "e": 4283, "s": 4257, "text": "C++ BackTracking Solution" }, { "code": null, "e": 4873, "s": 4283, "text": "class Solution\n{\n vector<string>res;\n private:\n void helper(string &s,int open,int close){\n if(!open and !close){\n res.push_back(s);\n return;\n }\n if(open){\n s+=\"(\";\n helper(s,open-1,close);\n s.pop_back();\n }\n if(close and close>open){\n s+=\")\";\n helper(s,open,close-1);\n s.pop_back();\n }\n }\n public:\n vector<string> AllParenthesis(int n) \n {\n if(!n)return {};\n string s=\"\";\n helper(s,n,n);\n return res;\n }\n};" }, { "code": null, "e": 4876, "s": 4873, "text": "+1" }, { "code": null, "e": 4904, "s": 4876, "text": "abytespaceneeded1 month ago" }, { "code": null, "e": 5561, "s": 4904, "text": "// upvote if you like the solution.\n\nclass Solution\n{\n public:\n vector<string> ans;\n \n void solve(string temp, int open, int close)\n {\n if(open == 0 && close == 0)\n {\n ans.push_back(temp);\n return ;\n }\n \n if(open == close)\n solve(temp+'(',open-1,close);\n else if(open == 0 && close != 0)\n solve(temp+')',open,close-1);\n else\n {\n solve(temp+'(',open-1,close);\n solve(temp+')',open,close-1);\n }\n }\n \n vector<string> AllParenthesis(int n) \n {\n solve(\"\",n,n);\n \n return ans;\n }\n};" }, { "code": null, "e": 5563, "s": 5561, "text": "0" }, { "code": null, "e": 5590, "s": 5563, "text": "aloksinghbais021 month ago" }, { "code": null, "e": 5693, "s": 5590, "text": "C++ solution having time complexity as O((2^N)*N) and space complexity as O((2^N)*X) is as follows :- " }, { "code": null, "e": 5727, "s": 5695, "text": "Execution Time :- 0.9 / 1.5 sec" }, { "code": null, "e": 6608, "s": 5729, "text": "vector<string> ans; bool isValid(string str,int cnt1,int cnt2){ if(cnt1 != cnt2) return (false); stack<char> stk; for(auto &ch: str){ if(ch == '(') stk.push(ch); else{ if(stk.empty()) return (false); if(stk.top() != '(') return (false); stk.pop(); } } if(!stk.empty()) return (false); return (true); } void helper(int i,string output,int cnt1,int cnt2,int n){ if(i == 2*n){ if(isValid(output,cnt1,cnt2)){ ans.push_back(output); } return; } if(cnt1 <= n) helper(i+1,output+'(',cnt1+1,cnt2,n); if(cnt2 <= n && cnt1 > cnt2) helper(i+1,output+')',cnt1,cnt2+1,n); } vector<string> AllParenthesis(int n) { string output{}; helper(0,output,0,0,n); return (ans); }" }, { "code": null, "e": 6610, "s": 6608, "text": "0" }, { "code": null, "e": 6634, "s": 6610, "text": "kashyapjhon2 months ago" }, { "code": null, "e": 6669, "s": 6634, "text": "C++ Solution Input Output Approach" }, { "code": null, "e": 6692, "s": 6669, "text": "Time=(0.3/1.5) MEDIUM:" }, { "code": null, "e": 7255, "s": 6692, "text": "void help(vector<string> &u,int l,int r,string out){ if(l==0 && r==0){ u.push_back(out); return; } if(l!=0){ string out1=out; out1.push_back('('); help(u,l-1,r,out1); } if(l<r){ string out2=out; out2.push_back(')'); help(u,l,r-1,out2); } return; } vector<string> AllParenthesis(int n) { // Your code goes here vector<string> u; int l=n; int r=n; string out=\"\"; help(u,l,r,out); return u; }" }, { "code": null, "e": 7401, "s": 7255, "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": 7437, "s": 7401, "text": " Login to access your submissions. " }, { "code": null, "e": 7447, "s": 7437, "text": "\nProblem\n" }, { "code": null, "e": 7457, "s": 7447, "text": "\nContest\n" }, { "code": null, "e": 7520, "s": 7457, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7668, "s": 7520, "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": 7876, "s": 7668, "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": 7982, "s": 7876, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Gantt charts with Python’s Matplotlib | by Thiago Carvalho | Towards Data Science
With more than 100 years of history, this visualization continues to be very useful for project management. Henry Gantt initially created the graph for analyzing completed projects. More specifically, he designed this visualization to measure productivity and identify underperforming employees. Through the years, it became a tool for planning and tracking, often discarded once the project is over. It’s undeniable that Gantt charts have changed a lot since their first design. Analysts introduced many encodings to display distinctions between departments, tasks completeness, dependencies, deadlines, and much more. This article will explore how to create Gantt charts using Python, Pandas, and Matplotlib. import pandas as pdimport matplotlib.pyplot as pltimport numpy as np For this example, we’ll need some dummy data; the dataset we’ll use has columns for the task’s name, department, a start and end date, and completion. df = pd.read_excel('../data/plan.xlsx')df To make our plotting easier, we’ll need to derive some measures. We’ll start with a variable for the project’s start date. Then, we’ll add a column with the number of days from the start of the project to the beginning of each task; this will help position the bars on the x-axis. Same for the task’s end; This facilitates calculating the total days needed to complete the task, the bar’s length, and helps position the texts later on. # project start dateproj_start = df.Start.min()# number of days from project start to task startdf['start_num'] = (df.Start-proj_start).dt.days# number of days from project start to end of tasksdf['end_num'] = (df.End-proj_start).dt.days# days between start and end of each taskdf['days_start_to_end'] = df.end_num - df.start_num Now we can plot a bar chart. Y will be the task name, the width is the number of days between the start and end of the task, and the left is the number of days between the project start to the task start. fig, ax = plt.subplots(1, figsize=(16,6))ax.barh(df.Task, df.days_start_to_end, left=df.start_num)plt.show() Cool, we got the simplest of the Gantt charts. There are lots of details we can add to make our chart more insightful. We’ll start with the most essential, a proper x-axis with dates and colors to distinguish the departments. # create a column with the color for each departmentdef color(row): c_dict = {'MKT':'#E64646', 'FIN':'#E69646', 'ENG':'#34D05C', 'PROD':'#34D0C3', 'IT':'#3475D0'} return c_dict[row['Department']]df['color'] = df.apply(color, axis=1) For the x-axis, we’ll add a label every three days, and we’ll also add minor ticks for each day. from matplotlib.patches import Patchfig, ax = plt.subplots(1, figsize=(16,6))ax.barh(df.Task, df.days_start_to_end, left=df.start_num, color=df.color)##### LEGENDS #####c_dict = {'MKT':'#E64646', 'FIN':'#E69646', 'ENG':'#34D05C', 'PROD':'#34D0C3', 'IT':'#3475D0'}legend_elements = [Patch(facecolor=c_dict[i], label=i) for i in c_dict]plt.legend(handles=legend_elements)##### TICKS #####xticks = np.arange(0, df.end_num.max()+1, 3)xticks_labels = pd.date_range(proj_start, end=df.End.max()).strftime("%m/%d")xticks_minor = np.arange(0, df.end_num.max()+1, 1)ax.set_xticks(xticks)ax.set_xticks(xticks_minor, minor=True)ax.set_xticklabels(xticks_labels[::3])plt.show() Great! This graph is way more insightful than our previous version. Now let’s encode the completeness of the project to our visualization. # days between start and current progression of each taskdf['current_num'] = (df.days_start_to_end * df.Completion) We’ll add another bar to our plot and use the measure we just created as the width. To increase the precision, we’ll write the percentage of completeness at the end of the bars. And to distinguish the completed from uncompleted, we can play with the alpha parameter of the bars. from matplotlib.patches import Patchfig, ax = plt.subplots(1, figsize=(16,6))# barsax.barh(df.Task, df.current_num, left=df.start_num, color=df.color)ax.barh(df.Task, df.days_start_to_end, left=df.start_num, color=df.color, alpha=0.5)# textsfor idx, row in df.iterrows(): ax.text(row.end_num+0.1, idx, f"{int(row.Completion*100)}%", va='center', alpha=0.8)##### LEGENDS #####c_dict = {'MKT':'#E64646', 'FIN':'#E69646', 'ENG':'#34D05C', 'PROD':'#34D0C3', 'IT':'#3475D0'}legend_elements = [Patch(facecolor=c_dict[i], label=i) for i in c_dict]plt.legend(handles=legend_elements)##### TICKS #####xticks = np.arange(0, df.end_num.max()+1, 3)xticks_labels = pd.date_range(proj_start, end=df.End.max()).strftime("%m/%d")xticks_minor = np.arange(0, df.end_num.max()+1, 1)ax.set_xticks(xticks)ax.set_xticks(xticks_minor, minor=True)ax.set_xticklabels(xticks_labels[::3])plt.show() And that’s it! We can improve this visualization, make it more appealing, add more information with another axis, draw gridlines, add a title, and so much more. Overall this is an excellent way of visualizing projects, even though it might not fit with the most current project management approaches. Gantt charts are flexible in the sense of — They can have many functionalities. You can break down tasks, track performance measures, dependencies, milestones, deadlines, and much more. Adding more information to Gantt charts is easily achieved with more encodings, tooltips, drill-downs, and texts. All that information can just as easily make our chart hard to understand and even tougher to maintain. With agile approaches, plans are constantly changing. Spending that much time collecting and maintaining this information to follow up on a project requires too many resources and often becomes counterproductive. All that said, they excel in visualizing completed projects and can be way more insightful than flowcharts, tables, or Kanban/ Scrum boards, especially for scrutinizing a single process or project. Thanks for reading my article! — Here you can find more Python dataviz tutorials.
[ { "code": null, "e": 280, "s": 172, "text": "With more than 100 years of history, this visualization continues to be very useful for project management." }, { "code": null, "e": 573, "s": 280, "text": "Henry Gantt initially created the graph for analyzing completed projects. More specifically, he designed this visualization to measure productivity and identify underperforming employees. Through the years, it became a tool for planning and tracking, often discarded once the project is over." }, { "code": null, "e": 792, "s": 573, "text": "It’s undeniable that Gantt charts have changed a lot since their first design. Analysts introduced many encodings to display distinctions between departments, tasks completeness, dependencies, deadlines, and much more." }, { "code": null, "e": 883, "s": 792, "text": "This article will explore how to create Gantt charts using Python, Pandas, and Matplotlib." }, { "code": null, "e": 952, "s": 883, "text": "import pandas as pdimport matplotlib.pyplot as pltimport numpy as np" }, { "code": null, "e": 1103, "s": 952, "text": "For this example, we’ll need some dummy data; the dataset we’ll use has columns for the task’s name, department, a start and end date, and completion." }, { "code": null, "e": 1145, "s": 1103, "text": "df = pd.read_excel('../data/plan.xlsx')df" }, { "code": null, "e": 1210, "s": 1145, "text": "To make our plotting easier, we’ll need to derive some measures." }, { "code": null, "e": 1268, "s": 1210, "text": "We’ll start with a variable for the project’s start date." }, { "code": null, "e": 1426, "s": 1268, "text": "Then, we’ll add a column with the number of days from the start of the project to the beginning of each task; this will help position the bars on the x-axis." }, { "code": null, "e": 1581, "s": 1426, "text": "Same for the task’s end; This facilitates calculating the total days needed to complete the task, the bar’s length, and helps position the texts later on." }, { "code": null, "e": 1911, "s": 1581, "text": "# project start dateproj_start = df.Start.min()# number of days from project start to task startdf['start_num'] = (df.Start-proj_start).dt.days# number of days from project start to end of tasksdf['end_num'] = (df.End-proj_start).dt.days# days between start and end of each taskdf['days_start_to_end'] = df.end_num - df.start_num" }, { "code": null, "e": 2116, "s": 1911, "text": "Now we can plot a bar chart. Y will be the task name, the width is the number of days between the start and end of the task, and the left is the number of days between the project start to the task start." }, { "code": null, "e": 2225, "s": 2116, "text": "fig, ax = plt.subplots(1, figsize=(16,6))ax.barh(df.Task, df.days_start_to_end, left=df.start_num)plt.show()" }, { "code": null, "e": 2272, "s": 2225, "text": "Cool, we got the simplest of the Gantt charts." }, { "code": null, "e": 2451, "s": 2272, "text": "There are lots of details we can add to make our chart more insightful. We’ll start with the most essential, a proper x-axis with dates and colors to distinguish the departments." }, { "code": null, "e": 2690, "s": 2451, "text": "# create a column with the color for each departmentdef color(row): c_dict = {'MKT':'#E64646', 'FIN':'#E69646', 'ENG':'#34D05C', 'PROD':'#34D0C3', 'IT':'#3475D0'} return c_dict[row['Department']]df['color'] = df.apply(color, axis=1)" }, { "code": null, "e": 2787, "s": 2690, "text": "For the x-axis, we’ll add a label every three days, and we’ll also add minor ticks for each day." }, { "code": null, "e": 3463, "s": 2787, "text": "from matplotlib.patches import Patchfig, ax = plt.subplots(1, figsize=(16,6))ax.barh(df.Task, df.days_start_to_end, left=df.start_num, color=df.color)##### LEGENDS #####c_dict = {'MKT':'#E64646', 'FIN':'#E69646', 'ENG':'#34D05C', 'PROD':'#34D0C3', 'IT':'#3475D0'}legend_elements = [Patch(facecolor=c_dict[i], label=i) for i in c_dict]plt.legend(handles=legend_elements)##### TICKS #####xticks = np.arange(0, df.end_num.max()+1, 3)xticks_labels = pd.date_range(proj_start, end=df.End.max()).strftime(\"%m/%d\")xticks_minor = np.arange(0, df.end_num.max()+1, 1)ax.set_xticks(xticks)ax.set_xticks(xticks_minor, minor=True)ax.set_xticklabels(xticks_labels[::3])plt.show()" }, { "code": null, "e": 3531, "s": 3463, "text": "Great! This graph is way more insightful than our previous version." }, { "code": null, "e": 3602, "s": 3531, "text": "Now let’s encode the completeness of the project to our visualization." }, { "code": null, "e": 3718, "s": 3602, "text": "# days between start and current progression of each taskdf['current_num'] = (df.days_start_to_end * df.Completion)" }, { "code": null, "e": 3802, "s": 3718, "text": "We’ll add another bar to our plot and use the measure we just created as the width." }, { "code": null, "e": 3997, "s": 3802, "text": "To increase the precision, we’ll write the percentage of completeness at the end of the bars. And to distinguish the completed from uncompleted, we can play with the alpha parameter of the bars." }, { "code": null, "e": 4897, "s": 3997, "text": "from matplotlib.patches import Patchfig, ax = plt.subplots(1, figsize=(16,6))# barsax.barh(df.Task, df.current_num, left=df.start_num, color=df.color)ax.barh(df.Task, df.days_start_to_end, left=df.start_num, color=df.color, alpha=0.5)# textsfor idx, row in df.iterrows(): ax.text(row.end_num+0.1, idx, f\"{int(row.Completion*100)}%\", va='center', alpha=0.8)##### LEGENDS #####c_dict = {'MKT':'#E64646', 'FIN':'#E69646', 'ENG':'#34D05C', 'PROD':'#34D0C3', 'IT':'#3475D0'}legend_elements = [Patch(facecolor=c_dict[i], label=i) for i in c_dict]plt.legend(handles=legend_elements)##### TICKS #####xticks = np.arange(0, df.end_num.max()+1, 3)xticks_labels = pd.date_range(proj_start, end=df.End.max()).strftime(\"%m/%d\")xticks_minor = np.arange(0, df.end_num.max()+1, 1)ax.set_xticks(xticks)ax.set_xticks(xticks_minor, minor=True)ax.set_xticklabels(xticks_labels[::3])plt.show()" }, { "code": null, "e": 4912, "s": 4897, "text": "And that’s it!" }, { "code": null, "e": 5058, "s": 4912, "text": "We can improve this visualization, make it more appealing, add more information with another axis, draw gridlines, add a title, and so much more." }, { "code": null, "e": 5198, "s": 5058, "text": "Overall this is an excellent way of visualizing projects, even though it might not fit with the most current project management approaches." }, { "code": null, "e": 5278, "s": 5198, "text": "Gantt charts are flexible in the sense of — They can have many functionalities." }, { "code": null, "e": 5498, "s": 5278, "text": "You can break down tasks, track performance measures, dependencies, milestones, deadlines, and much more. Adding more information to Gantt charts is easily achieved with more encodings, tooltips, drill-downs, and texts." }, { "code": null, "e": 5602, "s": 5498, "text": "All that information can just as easily make our chart hard to understand and even tougher to maintain." }, { "code": null, "e": 5815, "s": 5602, "text": "With agile approaches, plans are constantly changing. Spending that much time collecting and maintaining this information to follow up on a project requires too many resources and often becomes counterproductive." }, { "code": null, "e": 6013, "s": 5815, "text": "All that said, they excel in visualizing completed projects and can be way more insightful than flowcharts, tables, or Kanban/ Scrum boards, especially for scrutinizing a single process or project." } ]
Count frequencies of all elements in array in Python
In this tutorial, we are going to write a program that finds the frequency of all the elements in an array. We can find it in different ways let's explore two of them. Initialize the array. Initialize the array. Initialize an empty dict. Initialize an empty dict. Iterate over the list.If the element is not in dict, then set the value to 1.Else increment the value by 1. Iterate over the list. If the element is not in dict, then set the value to 1. If the element is not in dict, then set the value to 1. Else increment the value by 1. Else increment the value by 1. Print the element and frequencies by iterating over the dict. Print the element and frequencies by iterating over the dict. Let's see the code. # intializing the list arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3] # initializing dict to store frequency of each element elements_count = {} # iterating over the elements for frequency for element in arr: # checking whether it is in the dict or not if element in elements_count: # incerementing the count by 1 elements_count[element] += 1 else: # setting the count to 1 elements_count[element] = 1 # printing the elements frequencies for key, value in elements_count.items(): print(f"{key}: {value}") If you run the above program, you will get the following results. 1: 3 2: 4 3: 5 Let's see the second approach using Counter class of the collections module. Import the collections module. Import the collections module. Initialize the array. Initialize the array. Pass the list to the Counter class. And store the result in a variable. Pass the list to the Counter class. And store the result in a variable. Print the element and the frequencies by iterating over the result. Print the element and the frequencies by iterating over the result. See the code below. # importing the collections module import collections # intializing the arr arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3] # getting the elements frequencies using Counter class elements_count = collections.Counter(arr) # printing the element and the frequency for key, value in elements_count.items(): print(f"{key}: {value}") If you run the above code, you will get the same output as previous one. 1: 3 2: 4 3: 5 If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1230, "s": 1062, "text": "In this tutorial, we are going to write a program that finds the frequency of all the elements in an array. We can find it in different ways let's explore two of them." }, { "code": null, "e": 1252, "s": 1230, "text": "Initialize the array." }, { "code": null, "e": 1274, "s": 1252, "text": "Initialize the array." }, { "code": null, "e": 1300, "s": 1274, "text": "Initialize an empty dict." }, { "code": null, "e": 1326, "s": 1300, "text": "Initialize an empty dict." }, { "code": null, "e": 1434, "s": 1326, "text": "Iterate over the list.If the element is not in dict, then set the value to 1.Else increment the value by 1." }, { "code": null, "e": 1457, "s": 1434, "text": "Iterate over the list." }, { "code": null, "e": 1513, "s": 1457, "text": "If the element is not in dict, then set the value to 1." }, { "code": null, "e": 1569, "s": 1513, "text": "If the element is not in dict, then set the value to 1." }, { "code": null, "e": 1600, "s": 1569, "text": "Else increment the value by 1." }, { "code": null, "e": 1631, "s": 1600, "text": "Else increment the value by 1." }, { "code": null, "e": 1693, "s": 1631, "text": "Print the element and frequencies by iterating over the dict." }, { "code": null, "e": 1755, "s": 1693, "text": "Print the element and frequencies by iterating over the dict." }, { "code": null, "e": 1775, "s": 1755, "text": "Let's see the code." }, { "code": null, "e": 2312, "s": 1775, "text": "# intializing the list\narr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]\n# initializing dict to store frequency of each element\nelements_count = {}\n# iterating over the elements for frequency\nfor element in arr:\n # checking whether it is in the dict or not\n if element in elements_count:\n # incerementing the count by 1\n elements_count[element] += 1\n else:\n # setting the count to 1\n elements_count[element] = 1\n# printing the elements frequencies\nfor key, value in elements_count.items():\n print(f\"{key}: {value}\")" }, { "code": null, "e": 2378, "s": 2312, "text": "If you run the above program, you will get the following results." }, { "code": null, "e": 2393, "s": 2378, "text": "1: 3\n2: 4\n3: 5" }, { "code": null, "e": 2470, "s": 2393, "text": "Let's see the second approach using Counter class of the collections module." }, { "code": null, "e": 2501, "s": 2470, "text": "Import the collections module." }, { "code": null, "e": 2532, "s": 2501, "text": "Import the collections module." }, { "code": null, "e": 2554, "s": 2532, "text": "Initialize the array." }, { "code": null, "e": 2576, "s": 2554, "text": "Initialize the array." }, { "code": null, "e": 2648, "s": 2576, "text": "Pass the list to the Counter class. And store the result in a variable." }, { "code": null, "e": 2720, "s": 2648, "text": "Pass the list to the Counter class. And store the result in a variable." }, { "code": null, "e": 2788, "s": 2720, "text": "Print the element and the frequencies by iterating over the result." }, { "code": null, "e": 2856, "s": 2788, "text": "Print the element and the frequencies by iterating over the result." }, { "code": null, "e": 2876, "s": 2856, "text": "See the code below." }, { "code": null, "e": 3203, "s": 2876, "text": "# importing the collections module\nimport collections\n# intializing the arr\narr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]\n# getting the elements frequencies using Counter class\nelements_count = collections.Counter(arr)\n# printing the element and the frequency\nfor key, value in elements_count.items():\n print(f\"{key}: {value}\")" }, { "code": null, "e": 3276, "s": 3203, "text": "If you run the above code, you will get the same output as previous one." }, { "code": null, "e": 3291, "s": 3276, "text": "1: 3\n2: 4\n3: 5" }, { "code": null, "e": 3368, "s": 3291, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
Delete Row From Pandas DataFrames Based on Column Value | Towards Data Science
Deleting rows from pandas DataFrames based on specific conditions relevant to column values is among the most commonly performed tasks. In today’s short guide we are going to explore how to perform row deletion when a row contains (i.e. is equal to) specific column value(s) a particular column value of a row is not equal to another value a row has null value(s) in a specific column a row has non-null column values multiple conditions (combination of the above) need to be met First, let’s create an example DataFrame that we’ll reference across this article in order to demonstrate a few concepts that will help us understand how to delete rows from pandas DataFrames. import pandas as pddf = pd.DataFrame({ 'colA': [1, 2, 3, 4, None], 'colB': [True, True, False, False, True], 'colC': ['a', None, 'c', None, 'e'], 'colD': [0.1, None, None, None, 0.5],})print(df) colA colB colC colD0 1.0 True a 0.11 2.0 True None NaN2 3.0 False c NaN3 4.0 False None NaN4 NaN True e 0.5 If you want to delete rows based on the values of a specific column, you can do so by slicing the original DataFrame. For instance, in order to drop all the rows where the colA is equal to 1.0, you can do so as shown below: df = df.drop(df.index[df['colA'] == 1.0])print(df) colA colB colC colD1 2.0 True None NaN2 3.0 False c NaN3 4.0 False None NaN4 NaN True e 0.5 Another approach is to reverse the condition so that you can keep all the rows where colA is not equal to 1.0. For example, df = df[df.colA != 1.0] Alternatively, if you want to drop rows where a column value is equal with any other value appearing in -say- a list of numbers, then you can make use of the isin() method. For instance, in order to drop all the rows where the column value of colA is 1.0, 2.0 or 3.0 then the following will do the trick: df = df.drop(df.index[df['colA'].isin([1.0, 2.0, 3.0])])print(df) colA colB colC colD3 4.0 False None NaN4 NaN True e 0.5 In the same way, you can revert the condition in order to keep only the records that don’t satisfy the condition. For instance, df = df[~df.colA.isin([1.0, 2.0, 3.0])] which is equivalent to the previous expression. In the same way, you can simply drop rows whose column value is not equal to a specific value. For instance, the following expression will drop all records not having the colA equal to 1.0: df = df.drop(df.index[df['colA']!=1.0])print(df) colA colB colC colD0 1.0 True a 0.1 Now if you want to drop rows having null values in a specific column you can make use of the isnull() method. For instance, in order to drop all the rows with null values in column colC you can do the following: df = df.drop(df.index[df['colC'].isnull()])print(df) colA colB colC colD0 1.0 True a 0.12 3.0 False c NaN4 NaN True e 0.5 Alternatively, you can reverse the condition and keep all non-null values: df = df[df.colC.notnull()]print(df) colA colB colC colD0 1.0 True a 0.12 3.0 False c NaN4 NaN True e 0.5 On the other hand, if you want to drop rows having non-null values in a specific column, you can make use of the notnull() method. For instance, to drop all rows with non-null values in column colC you need to run df = df.drop(df.index[df['colC'].notnull()])print(df) colA colB colC colD1 2.0 True None NaN3 4.0 False None NaN Once again, you can reverse the condition and keep only null values by using isnull method as shown below: df = df[df.colC.isnull()] Now let’s assume that you want to drop rows by combining multiple conditions. For example, say you want to drop all the rows where both colC and colD are null. You can combine multiple expressions using the & operator as shown below. df = df.drop(df[df['colC'].isnull() & df['colD'].isnull()].index)print(df) colA colB colC colD0 1.0 True a 0.12 3.0 False c NaN4 NaN True e 0.5 If you want either of the conditions to be met, then you can use the | operator. In this case, all the rows that have null values in either colC or colD will be dropped from the returned DataFrame. df = df.drop(df[df['colC'].isnull() | df['colD'].isnull()].index)print(df) colA colB colC colD0 1.0 True a 0.14 NaN True e 0.5 In today’s guide, we explored how to delete rows from pandas DataFrames based on specific conditions. Specifically, we discussed how to perform row deletion when specific column value(s) of rows are equal (or not equal) to other value(s). Additionally, we discussed how to drop rows containing null or non-null values in specific columns. Finally, we explored how to combine multiple conditions when deleting rows from DataFrames. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You may also like
[ { "code": null, "e": 388, "s": 172, "text": "Deleting rows from pandas DataFrames based on specific conditions relevant to column values is among the most commonly performed tasks. In today’s short guide we are going to explore how to perform row deletion when" }, { "code": null, "e": 447, "s": 388, "text": "a row contains (i.e. is equal to) specific column value(s)" }, { "code": null, "e": 512, "s": 447, "text": "a particular column value of a row is not equal to another value" }, { "code": null, "e": 557, "s": 512, "text": "a row has null value(s) in a specific column" }, { "code": null, "e": 590, "s": 557, "text": "a row has non-null column values" }, { "code": null, "e": 652, "s": 590, "text": "multiple conditions (combination of the above) need to be met" }, { "code": null, "e": 845, "s": 652, "text": "First, let’s create an example DataFrame that we’ll reference across this article in order to demonstrate a few concepts that will help us understand how to delete rows from pandas DataFrames." }, { "code": null, "e": 1208, "s": 845, "text": "import pandas as pddf = pd.DataFrame({ 'colA': [1, 2, 3, 4, None], 'colB': [True, True, False, False, True], 'colC': ['a', None, 'c', None, 'e'], 'colD': [0.1, None, None, None, 0.5],})print(df) colA colB colC colD0 1.0 True a 0.11 2.0 True None NaN2 3.0 False c NaN3 4.0 False None NaN4 NaN True e 0.5" }, { "code": null, "e": 1432, "s": 1208, "text": "If you want to delete rows based on the values of a specific column, you can do so by slicing the original DataFrame. For instance, in order to drop all the rows where the colA is equal to 1.0, you can do so as shown below:" }, { "code": null, "e": 1613, "s": 1432, "text": "df = df.drop(df.index[df['colA'] == 1.0])print(df) colA colB colC colD1 2.0 True None NaN2 3.0 False c NaN3 4.0 False None NaN4 NaN True e 0.5" }, { "code": null, "e": 1737, "s": 1613, "text": "Another approach is to reverse the condition so that you can keep all the rows where colA is not equal to 1.0. For example," }, { "code": null, "e": 1761, "s": 1737, "text": "df = df[df.colA != 1.0]" }, { "code": null, "e": 2066, "s": 1761, "text": "Alternatively, if you want to drop rows where a column value is equal with any other value appearing in -say- a list of numbers, then you can make use of the isin() method. For instance, in order to drop all the rows where the column value of colA is 1.0, 2.0 or 3.0 then the following will do the trick:" }, { "code": null, "e": 2210, "s": 2066, "text": "df = df.drop(df.index[df['colA'].isin([1.0, 2.0, 3.0])])print(df) colA colB colC colD3 4.0 False None NaN4 NaN True e 0.5" }, { "code": null, "e": 2338, "s": 2210, "text": "In the same way, you can revert the condition in order to keep only the records that don’t satisfy the condition. For instance," }, { "code": null, "e": 2378, "s": 2338, "text": "df = df[~df.colA.isin([1.0, 2.0, 3.0])]" }, { "code": null, "e": 2426, "s": 2378, "text": "which is equivalent to the previous expression." }, { "code": null, "e": 2616, "s": 2426, "text": "In the same way, you can simply drop rows whose column value is not equal to a specific value. For instance, the following expression will drop all records not having the colA equal to 1.0:" }, { "code": null, "e": 2713, "s": 2616, "text": "df = df.drop(df.index[df['colA']!=1.0])print(df) colA colB colC colD0 1.0 True a 0.1" }, { "code": null, "e": 2925, "s": 2713, "text": "Now if you want to drop rows having null values in a specific column you can make use of the isnull() method. For instance, in order to drop all the rows with null values in column colC you can do the following:" }, { "code": null, "e": 3078, "s": 2925, "text": "df = df.drop(df.index[df['colC'].isnull()])print(df) colA colB colC colD0 1.0 True a 0.12 3.0 False c NaN4 NaN True e 0.5" }, { "code": null, "e": 3153, "s": 3078, "text": "Alternatively, you can reverse the condition and keep all non-null values:" }, { "code": null, "e": 3289, "s": 3153, "text": "df = df[df.colC.notnull()]print(df) colA colB colC colD0 1.0 True a 0.12 3.0 False c NaN4 NaN True e 0.5" }, { "code": null, "e": 3503, "s": 3289, "text": "On the other hand, if you want to drop rows having non-null values in a specific column, you can make use of the notnull() method. For instance, to drop all rows with non-null values in column colC you need to run" }, { "code": null, "e": 3635, "s": 3503, "text": "df = df.drop(df.index[df['colC'].notnull()])print(df) colA colB colC colD1 2.0 True None NaN3 4.0 False None NaN" }, { "code": null, "e": 3742, "s": 3635, "text": "Once again, you can reverse the condition and keep only null values by using isnull method as shown below:" }, { "code": null, "e": 3768, "s": 3742, "text": "df = df[df.colC.isnull()]" }, { "code": null, "e": 4002, "s": 3768, "text": "Now let’s assume that you want to drop rows by combining multiple conditions. For example, say you want to drop all the rows where both colC and colD are null. You can combine multiple expressions using the & operator as shown below." }, { "code": null, "e": 4177, "s": 4002, "text": "df = df.drop(df[df['colC'].isnull() & df['colD'].isnull()].index)print(df) colA colB colC colD0 1.0 True a 0.12 3.0 False c NaN4 NaN True e 0.5" }, { "code": null, "e": 4375, "s": 4177, "text": "If you want either of the conditions to be met, then you can use the | operator. In this case, all the rows that have null values in either colC or colD will be dropped from the returned DataFrame." }, { "code": null, "e": 4522, "s": 4375, "text": "df = df.drop(df[df['colC'].isnull() | df['colD'].isnull()].index)print(df) colA colB colC colD0 1.0 True a 0.14 NaN True e 0.5" }, { "code": null, "e": 4953, "s": 4522, "text": "In today’s guide, we explored how to delete rows from pandas DataFrames based on specific conditions. Specifically, we discussed how to perform row deletion when specific column value(s) of rows are equal (or not equal) to other value(s). Additionally, we discussed how to drop rows containing null or non-null values in specific columns. Finally, we explored how to combine multiple conditions when deleting rows from DataFrames." }, { "code": null, "e": 5070, "s": 4953, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read." } ]
Concat Method in C#
To concat lists in C#, ue the Concat method. The following is the list − var list1 = new List<int>{12, 40}; var list2 = new List<int>{98, 122, 199, 230}; Here is the Concat method − var res = list1.Concat(list2); The following is the example to work with Concat method − Live Demo using System.Collections.Generic; using System.Linq; using System; public class Demo { public static void Main() { // two lists var list1 = new List<int>{12, 40}; var list2 = new List<int>{98, 122, 199, 230}; // concat var res = list1.Concat(list2); foreach(int i in res) { Console.WriteLine(i); } } } 12 40 98 122 199 230
[ { "code": null, "e": 1107, "s": 1062, "text": "To concat lists in C#, ue the Concat method." }, { "code": null, "e": 1135, "s": 1107, "text": "The following is the list −" }, { "code": null, "e": 1216, "s": 1135, "text": "var list1 = new List<int>{12, 40};\nvar list2 = new List<int>{98, 122, 199, 230};" }, { "code": null, "e": 1244, "s": 1216, "text": "Here is the Concat method −" }, { "code": null, "e": 1275, "s": 1244, "text": "var res = list1.Concat(list2);" }, { "code": null, "e": 1333, "s": 1275, "text": "The following is the example to work with Concat method −" }, { "code": null, "e": 1344, "s": 1333, "text": " Live Demo" }, { "code": null, "e": 1710, "s": 1344, "text": "using System.Collections.Generic;\nusing System.Linq;\nusing System;\n\npublic class Demo {\n public static void Main() {\n\n // two lists\n var list1 = new List<int>{12, 40};\n var list2 = new List<int>{98, 122, 199, 230};\n \n // concat\n var res = list1.Concat(list2);\n\n foreach(int i in res) {\n Console.WriteLine(i);\n }\n }\n}" }, { "code": null, "e": 1731, "s": 1710, "text": "12\n40\n98\n122\n199\n230" } ]
5 Machine Learning Techniques for Sales Forecasting | by Molly Liebeskind | Towards Data Science
Forecasting sales is a common and essential use of machine learning (ML). Sales forecasts can be used to identify benchmarks and determine incremental impacts of new initiatives, plan resources in response to expected demand, and project future budgets. In this article, I will show how to implement 5 different ML models to predict sales. The data for this demonstration can be found on Kaggle and the full code is on GitHub. The first step is to load the data and transform it into a structure that we will then use for each of our models. In its raw form, each row of data represents a single day of sales at one of ten stores. Our goal is to predict monthly sales, so we will first consolidate all stores and days into total monthly sales. def load_data(): url = """https://www.kaggle.com/c/demand-forecasting-kernels only/download/ryQFx3IEtFjqjv3s0dXL%2Fversions%2FzjbSfpE39fdJl MotCpen%2Ffiles%2Ftrain.csv""" return pd.read_csv(url)def monthly_sales(data): data = data.copy() # Drop the day indicator from the date column data.date = data.date.apply(lambda x: str(x)[:-3]) # Sum sales per month data = data.groupby('date')['sales'].sum().reset_index() data.date = pd.to_datetime(data.date) data.to_csv('../data/monthly_data.csv') return datadata = load_data()monthly_data = monthly_sales(data) In our new data frame, each row now represents total sales in a given month across all stores. If we plot the total monthly sales over time, we see that average monthly sales increase over time, which means that our data is not stationary. To make it stationary, we will calculate the difference between sales in each month and add this into our data frame as a new column. Additional details on stationery and differencing can be found here. # Calculate difference in sales month over monthdef get_diff(data): data['sales_diff'] = data.sales.diff() data = data.dropna() return datastationary_df = get_diff(monthly_data) Below is a visual representation of how our data looked before and after the differencing transformation. Code for all plots can be found here. Now that our data represent monthly sales and we have transformed it to be stationary, we will set up the data for our different model types. To do this, we will define two different structures: one will be used for ARIMA modeling and the other will be used for the rest of the models. For our Arima model, we will need only a datetime index and the dependent variable (diff in sales) columns. def generate_arima_data(data): dt_data = data.set_index('date').drop('sales', axis=1) dt_data.dropna(axis=0) dt_data.to_csv('../data/arima_df.csv') return dt_dataarima_data = generate_arima_data(stationary_df) For our other models, we will create a new data frame where each feature represents a previous month’s sales. To determine how many months to include in our feature set, we will observe the autocorrelation and partial autocorrelation plots and use the rules for selecting lags in ARIMA modeling. This way, we can keep consistent a look-back period for our ARIMA and regressive models. Based on the above, we will choose our look-back period to be 12 months. We will, therefore, generate a data frame that has 13 columns, 1 column for each of the 12 months and the column for our dependent variable, difference in sales. Code for the below was grabbed from Baris Karaman’s data driven growth series. def generate_supervised(data): supervised_df = data.copy() #create column for each lag for i in range(1,13): col = 'lag_' + str(i) supervised_df[col] = supervised_df['sales_diff'].shift(i) #drop null values supervised_df = supervised_df.dropna().reset_index(drop=True) supervised_df.to_csv('../data/model_df.csv', index=False) return supervised_dfmodel_df = generate_supervised(stationary_df) Now we have two separate data structures, our Arima structure that includes a datetime index and our supervised structure that includes lags as features. To create and assess all of our models, we use a series of helper functions that perform the following functions. The code for all of the helper functions can be found here. Train test split: we separate our data so that the last 12 months are part of the test set and the rest of the data is used to train our modelScale the data: using a min-max scaler, we will scale the data so that all of our variables fall within the range of -1 to 1Reverse scaling: After running our models, we will use this helper function to reverse the scaling of step 2Create a predictions data frame: generate a data frame that includes the actual sales captured in our test set and the predicted results from our model so that we can quantify our successScore the models: this helper function will save the root mean squared error (RMSE) and mean absolute error (MAE) of our predictions to compare performance of our five models Train test split: we separate our data so that the last 12 months are part of the test set and the rest of the data is used to train our model Scale the data: using a min-max scaler, we will scale the data so that all of our variables fall within the range of -1 to 1 Reverse scaling: After running our models, we will use this helper function to reverse the scaling of step 2 Create a predictions data frame: generate a data frame that includes the actual sales captured in our test set and the predicted results from our model so that we can quantify our success Score the models: this helper function will save the root mean squared error (RMSE) and mean absolute error (MAE) of our predictions to compare performance of our five models For our regressive models, we can use the fit-predict structure of the scikit-learn library. We therefore can set up a base modeling structure that we will call for each model. The function below calls many of the helper functions outlined above to split the data, run the model, and output RMSE and MAE scores. def regressive_model(train_data, test_data, model, model_name): # Call helper functions to create X & y and scale data X_train, y_train, X_test, y_test, scaler_object = scale_data(train_data, test_data) # Run regression model mod = model mod.fit(X_train, y_train) predictions = mod.predict(X_test) # Call helper functions to undo scaling & create prediction df original_df = load_data('../data/monthly_data.csv') unscaled = undo_scaling(predictions, X_test, scaler_object) unscaled_df = predict_df(unscaled, original_df) # Call helper functions to print scores and plot results get_scores(unscaled_df, original_df, model_name) plot_results(unscaled_df, original_df, model_name)# Separate data into train and test setstrain, test = tts(model_df)# Call model frame work for linear regressionregressive_model(train, test, LinearRegression(),'LinearRegression')# Call model frame work for random forest regressor regressive_model(train, test, RandomForestRegressor(n_estimators=100, max_depth=20), 'RandomForest')# Call model frame work for XGBoostregressive_model(train, test, XGBRegressor(n_estimators=100, learning_rate=0.2), 'XGBoost') The output below shows the predictions (red) overlaid on top of the actual sales (blue) for each of the regressive models. While the results look similar, the nuanced differences equate to a few thousand dollars in sales, which we will see in the comparison section below. LSTM is a type of recurrent neural network that is particularly useful for making predictions with sequential data. For this purpose, we will use a very simple LSTM. For additional accuracy, seasonal features and additional model complexity can be added. def lstm_model(train_data, test_data): # Call helper functions to create X & y and scale data X_train, y_train, X_test, y_test, scaler_object = scale_data(train_data, test_data) X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1]) X_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1]) # Build LSTM model = Sequential() model.add(LSTM(4, batch_input_shape=(1, X_train.shape[1], X_train.shape[2]), stateful=True)) model.add(Dense(1)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(X_train, y_train, epochs=200, batch_size=1, verbose=1, shuffle=False) predictions = model.predict(X_test, batch_size=1) # Call helper functions to undo scaling & create prediction df original_df = load_data('../data/monthly_data.csv') unscaled = undo_scaling(predictions, X_test, scaler_object, lstm=True) unscaled_df = predict_df(unscaled, original_df) # Call helper functions to print scores and plot results get_scores(unscaled_df, original_df, 'LSTM') plot_results(unscaled_df, original_df, 'LSTM') The resulting plot looks similar to the three regressive plots above, so we will hold off on comparing the results until we look at the errors below. The ARIMA model looks slightly different than the models above. We use the statsmodels SARIMAX package to train the model and generate dynamic predictions. The SARIMA model breaks down into a few parts. AR: represented as p, is the autoregressive model I : represented as d, is the differencing term MA: represented as q, is the moving average model S: enables us to add a seasonal component In the code below, we define our model and then make dynamic predictions for the last 12 months of the data. For standard, non-dynamic predictions, the following month’s prediction is made using the actual sales from the prior months. In contrast, for dynamic predictions, the following month’s prediction is made using the predicted sales from the prior months. def sarimax_model(data): # Model sar = sm.tsa.statespace.SARIMAX(data.sales_diff, order=(12, 0, 0), seasonal_order=(0, 1, 0, 12), trend='c').fit() # Generate predictions start, end, dynamic = 40, 100, 7 data['pred_value'] = sar.predict(start=start, end=end, dynamic=dynamic) # Call helper functions to undo scaling & create prediction df original_df = load_data('../data/monthly_data.csv') unscaled_df = predict_df(data, original_df) # Call helper functions to print scores and plot results get_scores(unscaled_df, original_df, 'ARIMA') plot_results(unscaled_df, original_df, 'ARIMA') Again, the results look pretty good. We will dig in further below. To compare model performance, we will look at root mean squared error (RMSE) and mean absolute error (MAE). These measurements are both commonly used for comparing model performance, but they have slightly different intuition and mathematical meaning. MAE: the mean absolute error tells us on average how far our predictions are from the true value. In this case, all errors receive the same weight. RMSE: we calculate RMSE by taking the square root of the sum of all of the squared errors. When we square, the larger errors have a greater impact on the overall error while smaller errors do not have as much weight on the overall error. From the helper functions above, we use get_scores to calculate the RMSE and MAE scores for each model. These scores were saved in a dictionary and pickled. For comparison, we will transform that dictionary into a Pandas data frame and plot the results. def create_results_df(): # Load pickled scores for each model results_dict = pickle.load(open("model_scores.p", "rb")) # Create pandas df results_df = pd.DataFrame.from_dict(results_dict, orient='index', columns=['RMSE', 'MAE', 'R2']) results_df = results_df.sort_values(by='RMSE', ascending=False).reset_index() return results_dfresults = create_results_df() This gives us the following data frame. We can see that although our model outputs looked similar in the plots above, they do vary in their degree of accuracy. Below is a visual to help us see the difference. Plot code can be found here. What we see is that overall the XGBoost model had the best performance followed closely by the ARIMA and LSTM models. A caveat here is that all of the models above were derived in their most basic form to demonstrate how they can be used for sales forecasting. The models were only lightly tuned to minimize complexity. The LSTM for example could have many additional nodes and layers to increase performance. To identify which model is right for your use case, you should consider the following. The degree of model complexity vs interpretability you are comfortable with. Models can be tuned and features can be engineered to include seasonal information, holidays, weekends, etc. Understand how you will be using the results and how data will be coming in to update your model. Tune models using cross-validation or similar techniques to avoid overfitting data. The full code for this introduction into sales forecasting can be found here. Please add any questions or comments below.
[ { "code": null, "e": 512, "s": 172, "text": "Forecasting sales is a common and essential use of machine learning (ML). Sales forecasts can be used to identify benchmarks and determine incremental impacts of new initiatives, plan resources in response to expected demand, and project future budgets. In this article, I will show how to implement 5 different ML models to predict sales." }, { "code": null, "e": 599, "s": 512, "text": "The data for this demonstration can be found on Kaggle and the full code is on GitHub." }, { "code": null, "e": 916, "s": 599, "text": "The first step is to load the data and transform it into a structure that we will then use for each of our models. In its raw form, each row of data represents a single day of sales at one of ten stores. Our goal is to predict monthly sales, so we will first consolidate all stores and days into total monthly sales." }, { "code": null, "e": 1550, "s": 916, "text": "def load_data(): url = \"\"\"https://www.kaggle.com/c/demand-forecasting-kernels only/download/ryQFx3IEtFjqjv3s0dXL%2Fversions%2FzjbSfpE39fdJl MotCpen%2Ffiles%2Ftrain.csv\"\"\" return pd.read_csv(url)def monthly_sales(data): data = data.copy() # Drop the day indicator from the date column data.date = data.date.apply(lambda x: str(x)[:-3]) # Sum sales per month data = data.groupby('date')['sales'].sum().reset_index() data.date = pd.to_datetime(data.date) data.to_csv('../data/monthly_data.csv') return datadata = load_data()monthly_data = monthly_sales(data)" }, { "code": null, "e": 1645, "s": 1550, "text": "In our new data frame, each row now represents total sales in a given month across all stores." }, { "code": null, "e": 1993, "s": 1645, "text": "If we plot the total monthly sales over time, we see that average monthly sales increase over time, which means that our data is not stationary. To make it stationary, we will calculate the difference between sales in each month and add this into our data frame as a new column. Additional details on stationery and differencing can be found here." }, { "code": null, "e": 2190, "s": 1993, "text": "# Calculate difference in sales month over monthdef get_diff(data): data['sales_diff'] = data.sales.diff() data = data.dropna() return datastationary_df = get_diff(monthly_data)" }, { "code": null, "e": 2334, "s": 2190, "text": "Below is a visual representation of how our data looked before and after the differencing transformation. Code for all plots can be found here." }, { "code": null, "e": 2620, "s": 2334, "text": "Now that our data represent monthly sales and we have transformed it to be stationary, we will set up the data for our different model types. To do this, we will define two different structures: one will be used for ARIMA modeling and the other will be used for the rest of the models." }, { "code": null, "e": 2728, "s": 2620, "text": "For our Arima model, we will need only a datetime index and the dependent variable (diff in sales) columns." }, { "code": null, "e": 2963, "s": 2728, "text": "def generate_arima_data(data): dt_data = data.set_index('date').drop('sales', axis=1) dt_data.dropna(axis=0) dt_data.to_csv('../data/arima_df.csv') return dt_dataarima_data = generate_arima_data(stationary_df)" }, { "code": null, "e": 3348, "s": 2963, "text": "For our other models, we will create a new data frame where each feature represents a previous month’s sales. To determine how many months to include in our feature set, we will observe the autocorrelation and partial autocorrelation plots and use the rules for selecting lags in ARIMA modeling. This way, we can keep consistent a look-back period for our ARIMA and regressive models." }, { "code": null, "e": 3662, "s": 3348, "text": "Based on the above, we will choose our look-back period to be 12 months. We will, therefore, generate a data frame that has 13 columns, 1 column for each of the 12 months and the column for our dependent variable, difference in sales. Code for the below was grabbed from Baris Karaman’s data driven growth series." }, { "code": null, "e": 4102, "s": 3662, "text": "def generate_supervised(data): supervised_df = data.copy() #create column for each lag for i in range(1,13): col = 'lag_' + str(i) supervised_df[col] = supervised_df['sales_diff'].shift(i) #drop null values supervised_df = supervised_df.dropna().reset_index(drop=True) supervised_df.to_csv('../data/model_df.csv', index=False) return supervised_dfmodel_df = generate_supervised(stationary_df)" }, { "code": null, "e": 4256, "s": 4102, "text": "Now we have two separate data structures, our Arima structure that includes a datetime index and our supervised structure that includes lags as features." }, { "code": null, "e": 4430, "s": 4256, "text": "To create and assess all of our models, we use a series of helper functions that perform the following functions. The code for all of the helper functions can be found here." }, { "code": null, "e": 5166, "s": 4430, "text": "Train test split: we separate our data so that the last 12 months are part of the test set and the rest of the data is used to train our modelScale the data: using a min-max scaler, we will scale the data so that all of our variables fall within the range of -1 to 1Reverse scaling: After running our models, we will use this helper function to reverse the scaling of step 2Create a predictions data frame: generate a data frame that includes the actual sales captured in our test set and the predicted results from our model so that we can quantify our successScore the models: this helper function will save the root mean squared error (RMSE) and mean absolute error (MAE) of our predictions to compare performance of our five models" }, { "code": null, "e": 5309, "s": 5166, "text": "Train test split: we separate our data so that the last 12 months are part of the test set and the rest of the data is used to train our model" }, { "code": null, "e": 5434, "s": 5309, "text": "Scale the data: using a min-max scaler, we will scale the data so that all of our variables fall within the range of -1 to 1" }, { "code": null, "e": 5543, "s": 5434, "text": "Reverse scaling: After running our models, we will use this helper function to reverse the scaling of step 2" }, { "code": null, "e": 5731, "s": 5543, "text": "Create a predictions data frame: generate a data frame that includes the actual sales captured in our test set and the predicted results from our model so that we can quantify our success" }, { "code": null, "e": 5906, "s": 5731, "text": "Score the models: this helper function will save the root mean squared error (RMSE) and mean absolute error (MAE) of our predictions to compare performance of our five models" }, { "code": null, "e": 6218, "s": 5906, "text": "For our regressive models, we can use the fit-predict structure of the scikit-learn library. We therefore can set up a base modeling structure that we will call for each model. The function below calls many of the helper functions outlined above to split the data, run the model, and output RMSE and MAE scores." }, { "code": null, "e": 7595, "s": 6218, "text": "def regressive_model(train_data, test_data, model, model_name): # Call helper functions to create X & y and scale data X_train, y_train, X_test, y_test, scaler_object = scale_data(train_data, test_data) # Run regression model mod = model mod.fit(X_train, y_train) predictions = mod.predict(X_test) # Call helper functions to undo scaling & create prediction df original_df = load_data('../data/monthly_data.csv') unscaled = undo_scaling(predictions, X_test, scaler_object) unscaled_df = predict_df(unscaled, original_df) # Call helper functions to print scores and plot results get_scores(unscaled_df, original_df, model_name) plot_results(unscaled_df, original_df, model_name)# Separate data into train and test setstrain, test = tts(model_df)# Call model frame work for linear regressionregressive_model(train, test, LinearRegression(),'LinearRegression')# Call model frame work for random forest regressor regressive_model(train, test, RandomForestRegressor(n_estimators=100, max_depth=20), 'RandomForest')# Call model frame work for XGBoostregressive_model(train, test, XGBRegressor(n_estimators=100, learning_rate=0.2), 'XGBoost')" }, { "code": null, "e": 7868, "s": 7595, "text": "The output below shows the predictions (red) overlaid on top of the actual sales (blue) for each of the regressive models. While the results look similar, the nuanced differences equate to a few thousand dollars in sales, which we will see in the comparison section below." }, { "code": null, "e": 8123, "s": 7868, "text": "LSTM is a type of recurrent neural network that is particularly useful for making predictions with sequential data. For this purpose, we will use a very simple LSTM. For additional accuracy, seasonal features and additional model complexity can be added." }, { "code": null, "e": 9358, "s": 8123, "text": "def lstm_model(train_data, test_data): # Call helper functions to create X & y and scale data X_train, y_train, X_test, y_test, scaler_object = scale_data(train_data, test_data) X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1]) X_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1]) # Build LSTM model = Sequential() model.add(LSTM(4, batch_input_shape=(1, X_train.shape[1], X_train.shape[2]), stateful=True)) model.add(Dense(1)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(X_train, y_train, epochs=200, batch_size=1, verbose=1, shuffle=False) predictions = model.predict(X_test, batch_size=1) # Call helper functions to undo scaling & create prediction df original_df = load_data('../data/monthly_data.csv') unscaled = undo_scaling(predictions, X_test, scaler_object, lstm=True) unscaled_df = predict_df(unscaled, original_df) # Call helper functions to print scores and plot results get_scores(unscaled_df, original_df, 'LSTM') plot_results(unscaled_df, original_df, 'LSTM')" }, { "code": null, "e": 9508, "s": 9358, "text": "The resulting plot looks similar to the three regressive plots above, so we will hold off on comparing the results until we look at the errors below." }, { "code": null, "e": 9711, "s": 9508, "text": "The ARIMA model looks slightly different than the models above. We use the statsmodels SARIMAX package to train the model and generate dynamic predictions. The SARIMA model breaks down into a few parts." }, { "code": null, "e": 9761, "s": 9711, "text": "AR: represented as p, is the autoregressive model" }, { "code": null, "e": 9808, "s": 9761, "text": "I : represented as d, is the differencing term" }, { "code": null, "e": 9858, "s": 9808, "text": "MA: represented as q, is the moving average model" }, { "code": null, "e": 9900, "s": 9858, "text": "S: enables us to add a seasonal component" }, { "code": null, "e": 10263, "s": 9900, "text": "In the code below, we define our model and then make dynamic predictions for the last 12 months of the data. For standard, non-dynamic predictions, the following month’s prediction is made using the actual sales from the prior months. In contrast, for dynamic predictions, the following month’s prediction is made using the predicted sales from the prior months." }, { "code": null, "e": 11015, "s": 10263, "text": "def sarimax_model(data): # Model sar = sm.tsa.statespace.SARIMAX(data.sales_diff, order=(12, 0, 0), seasonal_order=(0, 1, 0, 12), trend='c').fit() # Generate predictions start, end, dynamic = 40, 100, 7 data['pred_value'] = sar.predict(start=start, end=end, dynamic=dynamic) # Call helper functions to undo scaling & create prediction df original_df = load_data('../data/monthly_data.csv') unscaled_df = predict_df(data, original_df) # Call helper functions to print scores and plot results get_scores(unscaled_df, original_df, 'ARIMA') plot_results(unscaled_df, original_df, 'ARIMA')" }, { "code": null, "e": 11082, "s": 11015, "text": "Again, the results look pretty good. We will dig in further below." }, { "code": null, "e": 11334, "s": 11082, "text": "To compare model performance, we will look at root mean squared error (RMSE) and mean absolute error (MAE). These measurements are both commonly used for comparing model performance, but they have slightly different intuition and mathematical meaning." }, { "code": null, "e": 11482, "s": 11334, "text": "MAE: the mean absolute error tells us on average how far our predictions are from the true value. In this case, all errors receive the same weight." }, { "code": null, "e": 11720, "s": 11482, "text": "RMSE: we calculate RMSE by taking the square root of the sum of all of the squared errors. When we square, the larger errors have a greater impact on the overall error while smaller errors do not have as much weight on the overall error." }, { "code": null, "e": 11974, "s": 11720, "text": "From the helper functions above, we use get_scores to calculate the RMSE and MAE scores for each model. These scores were saved in a dictionary and pickled. For comparison, we will transform that dictionary into a Pandas data frame and plot the results." }, { "code": null, "e": 12393, "s": 11974, "text": "def create_results_df(): # Load pickled scores for each model results_dict = pickle.load(open(\"model_scores.p\", \"rb\")) # Create pandas df results_df = pd.DataFrame.from_dict(results_dict, orient='index', columns=['RMSE', 'MAE', 'R2']) results_df = results_df.sort_values(by='RMSE', ascending=False).reset_index() return results_dfresults = create_results_df()" }, { "code": null, "e": 12433, "s": 12393, "text": "This gives us the following data frame." }, { "code": null, "e": 12631, "s": 12433, "text": "We can see that although our model outputs looked similar in the plots above, they do vary in their degree of accuracy. Below is a visual to help us see the difference. Plot code can be found here." }, { "code": null, "e": 13041, "s": 12631, "text": "What we see is that overall the XGBoost model had the best performance followed closely by the ARIMA and LSTM models. A caveat here is that all of the models above were derived in their most basic form to demonstrate how they can be used for sales forecasting. The models were only lightly tuned to minimize complexity. The LSTM for example could have many additional nodes and layers to increase performance." }, { "code": null, "e": 13128, "s": 13041, "text": "To identify which model is right for your use case, you should consider the following." }, { "code": null, "e": 13205, "s": 13128, "text": "The degree of model complexity vs interpretability you are comfortable with." }, { "code": null, "e": 13314, "s": 13205, "text": "Models can be tuned and features can be engineered to include seasonal information, holidays, weekends, etc." }, { "code": null, "e": 13412, "s": 13314, "text": "Understand how you will be using the results and how data will be coming in to update your model." }, { "code": null, "e": 13496, "s": 13412, "text": "Tune models using cross-validation or similar techniques to avoid overfitting data." } ]
Mock AWS Athena for your ETL tests | by Stefano Francavilla | Towards Data Science
I spent some time last weekend thinking about strategies to improve our ETL pipeline unit and integration tests. Just to quickly spice up an idea, a simplified component of the ETL process we have in place is something like the following: where a series of AWS Eventbridge rules process and transform the data injected from different sources and in different formats; the data is then ready to be reviewed in Athena before being saved in our Postgres database. The main goal of this exercise is to simulate the interaction with our datalake (Athena) in a local environment, somehow aligned with what we have in production. First of all, what is Athena: 📖Docs Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run. Athena is easy to use. Simply point to your data in Amazon S3, define the schema, and start querying using standard SQL. Most results are delivered within seconds. With Athena, there’s no need for complex ETL jobs to prepare your data for analysis. This makes it easy for anyone with SQL skills to quickly analyze large-scale datasets. Athena is out-of-the-box integrated with AWS Glue Data Catalog, allowing you to create a unified metadata repository across various services, crawl data sources to discover schemas and populate your Catalog with new and modified table and partition definitions, and maintain schema versioning. Put simply, by pointing Athena to a specific structured or semi-structured data stored in S3, it makes really easy to quickly analyze results by using SQL queries. When you run a query, Athena will parallelize it across hundreds/thousands of cores and deliver the result in seconds. Under the hood and at its core, Athena is a fusion of Hadoop/Hive for its Data Description Language (DDL) and Presto, which allows full standard SQL support and works with a variety of standard data formats, including CSV, JSON and Apache Parquet. We’re going to describe them in detail later in this guide. Some of the ingredients needed for this recipe to work are the following Docker images: moto server hive/hadoop presto We’re going to cover all of them in details in the following sections. 📝Note This guide assumes that you’re familiar with Docker, AWS S3 and Athena services Below I’m going to give you an overview of the docker images that will be used in this tutorial and their role in the whole process. At the end of this section, we’ll have a full docker compose file ready to be used for our tests. Let’s introduce each one of them with some examples. Moto is an amazing library to mock different AWS services both by using decorators for your specific tests or as a stand alone server. At the time of writing this article and at the best of my knowledge, it does not support the specific use case for Athena described here. For this guide, we’re going to use Moto as a stand alone server to serve the S3 service. Let’s start this exciting journey by filling up our empty docker-container with the first service. I’ve create a new project folder called mothena which contains only a docker-compose file as you can seen in the following image: The moto-server service is self-explanatory and the only thing to take into account is that we’ve exposed the port 5000, which is the default one used by Moto server. Now, we’re ready to launch our first service from our terminal (from our mothena directory) by typing the following command: docker-compose up As you can see from Figure 2, the Moto standalone server is now running on localhost:5000. Now, let’s try to create a bucket and make sure it works as expected. I’m using a jupyter notebook with the following snippet: The output result suggests us that something happened and the bucket named mothena has been created. I’ve used as region_name=”eu-west-1” but, feel free to input any region name you prefer. The most important piece to note here is that boto3 client accepts a parameter called endpoint_url which basically refers to our local endpoint. You can read more here. But, it’s not finished yet, as a proof that everything worked correctly, let’s have a look at the container logs in the terminal: Figure 4 shows us that a PUT request has been executed with HTTP status code 200. Everything works! Now, we can stop our container (type Ctrl+C in the terminal window where the container runs) and proceed with the next section. As said at the beginning of this guide, under the hood, Athena runs Hadoop/Hive for its DDL. So, we need to include Hadoop/Hive in the picture too. Lets briefly describe what Hadoop and Hive are (taking the definition from their official websites): 📖Docs The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures. The Apache Hive data warehouse software facilitates reading, writing, and managing large datasets residing in distributed storage using SQL. Structure can be projected onto data already in storage. A command line tool and JDBC driver are provided to connect users to Hive. In short, Hadoop is an open source framework responsible to easily store and manage large datasets (from gigabytes to petabytes) of data across a cluster of servers: this means that instead of using one computer, Hadoop allows the use of multiple computers (clusters) to analyze massive datasets in parallel and to quickly execute distributed processes against huge amounts of data. It’s the foundation layer on top of which other services and applications can be built. Hive is indeed an application that runs over the Hadoop framework for processing/querying this distributed data using a SQL like interface. This means that, when we create a table in Hadoop, we can specify the location where the data (e.g. .csv or .parquet files) resides and, in our case, it will be S3. We’re going to use this repo for the Hadoop/Hive image and more specifically, the hdp3.1-hive. Let’s first clone the project by running the following command in the terminal: git clone https://github.com/prestosql/docker-images.git Now, before building the image, there is something we need to take into account: we want the Hadoop cluster to “communicate” with the moto server. In doing so, we need to add some properties in one specific configuration files: prestodev/hdp3.1-hive/files/etc/hadoop/conf/core-site.xml - contains configuration information for the Hadoop daemon, including S3 specs such as endpoint, access key, access secrect, etc.. Core-site In the below gist, you can see the properties we’re going to add in core-site.xml; all of them are related to S3 and for more information, here you can find an extensive description of all the mentioned properties. Let’s review the ones we’ve added as there are some aspects that may require a bit of explanation: access key and access secret can be any non-null string we want. Moto doesn’t mind. As defined in the gist, I’m going to define them as ENV variables in the docker compose file (com.amazonaws.auth.EnvironmentVariableCredentialsProvider) we’re using s3a protocol and we’ll see later what this implies to create a table the endpoint refers to the pre-defined moto hostname, which is moto-server and has been defined in our docker-compose file 📝Note As you may know, by default Docker Compose sets up a single network for our app. Each service joins the default network and is both reachable and discoverable by other containers on that network by its hostname path style access set to True is particularly useful for s3a storage as it removes the need to set up DNS for virtual hosting. So in this way, we can have the following url style for s3: https://s3.Region.amazonaws.com/bucket-name/key-name , which for Moto means http://localhost:5000/bucket-name/key-name let’s disable ssl, not required Now that everything is set up, we can build the docker image and running it from our docker-compose. A new service will finally be added 🤓. Let’s follow the github README and build the image by typing in the terminal the following command: make prestodev/hdp3.1-hive This would take few minutes and the end result will be a successfully tagged image like what you see in Figure 6. It’s time to test if our Hadoop cluster works and, more importantly, works with moto. Let’s then add a new service in our docker-compose file like in Figure 7. You can see from the newly added service that we’ve included the access key and secret as ENV variables as defined in our core-site.xml. One question you may have is why exposing port 1000? The main reason in to allow communication with Hive from our script (via localhost), something we’re going to explore later in this guide. You can also have a look at the Docker file prestodev/hdp3.1-hive/Dockerfile and notice that there are 2 ports open for Hive: 9083 (used to work with Presto and it’s already available inside the containers’ network) and 10000. Ok, with 2 services in our docker-compose.yml, we can now run again from our terminal: docker-compose up And as you can see from Figure 9, they are running as expected. Now, let’s do something interesting here and imagine a scenario where we need to explore a subset (just few lines) of data from the new york residential properties sales transaction dataset (.parquet format, but any other compatible format is fine): I want to upload a file on S3 with a specific partition I can query the file by using Hive and save the result in a dataframe For this exercise and for all the ones you’ll see next, I’m going to use sqlalchemy with pyhive dialects installed. You can read more here in order to set them up. Having Hadoop and moto ready, you can run the following script and see what happens. The above code is pretty simple, basically we’re: Uploading the sample data on moto Creating a table and update metadata with MSCK REPAIR. I’ve also included the partitioned column downloaded_at following the specific S3 key structure. I thought this would make the exercise as much completed as possible for different use cases Retrieving results and save them in a dataframe. See Figure 10 As reference, in Figure 11 you can also see what’s going on in our containers, including all the GET requests. And that’s it for this section. But, in order to fully align with Athena, we need to add the last tile in the puzzle which is Presto; so, let’s stop docker-compose (CRTL-C) again and go straight to the next section. What is Presto? 📖Docs From prestosql: Presto is a highly parallel and distributed query engine, that is built from the ground up for efficient, low latency analytics. Presto (I’m using prestosql) supports ANSI SQL semantics and allows querying data where it lives, including Hive, Cassandra, relational databases or even proprietary data stores. Indeed, Presto has different connectors and Hive connector is one of them. First, we need to clone Presto docker and add a new catalog. We’ve introduced the concept of connector before, what’s a catalog? 📖Docs A Presto catalog contains schemas and references a data source via a connector. For example, you can configure a JMX catalog to provide access to JMX information via the JMX connector. When you run a SQL statement in Presto, you are running it against one or more catalogs. Other examples of catalogs include the hive catalog to connect to a Hive data source. When addressing a table in Presto, the fully-qualified table name is always rooted in a catalog. For example, a fully-qualified table name of hive.test_data.test refers to the test table in the test_data schema in the hive catalog. Catalogs are defined in properties files stored in the Presto configuration directory. Hive already defines a hive catalog, we just need to reference it by adding our hive.properties in our presto catalog folder as you can see in Figure 12. The structure of the properties is pretty straightforward and as defined here we’re: Using hive-hadoop2 as connector Defining which Hadoop endpoint Presto should connect to (do you remember docker-compose, hostname, same network?) using the thrift protocol Defining path style here again to true Defining S3 endpoint to point to our local moto service And that’s it! Let’s move to the Presto directory and build the image from the terminal with the following command: Docker build . -t prestosql-docker Once finished, we can go back to our mothena docker-compose.yml and add the new service as follows: As you can see, Presto includes aws access secret and key as ENV variables and exposes port 8080. We’re ready to change our previous code snippet and include Presto to retrieve our data instead of Hive. Let’s now run back again the mothena docker-compose and update our code snippet as follows: As you can see, we’ve added the Presto engine which connects to the hive catalog and uses it to retrieve the pandas dataframe. The result will be the same dataframe you’ve see in Figure 10. Wow, I have learned a lot writing this guide and I hope you too 🎉. Now you have locally the fully (almost :)) functional Athena service that you may use in your script or unit/integration tests on CodeBuild for example. With all the services available on localhost, other than boto3 and pandas, you can use any other library that accepts sqlalchemy connection/engine or endpoint overwriting such as pyarrow, s3fs, some awswrangler functions, etc. Here you can find the source code where I’ve pushed missing images on Docker Hub. Please, feel free to share your feedback in the comments, including improvements on this guide.
[ { "code": null, "e": 160, "s": 47, "text": "I spent some time last weekend thinking about strategies to improve our ETL pipeline unit and integration tests." }, { "code": null, "e": 286, "s": 160, "text": "Just to quickly spice up an idea, a simplified component of the ETL process we have in place is something like the following:" }, { "code": null, "e": 508, "s": 286, "text": "where a series of AWS Eventbridge rules process and transform the data injected from different sources and in different formats; the data is then ready to be reviewed in Athena before being saved in our Postgres database." }, { "code": null, "e": 670, "s": 508, "text": "The main goal of this exercise is to simulate the interaction with our datalake (Athena) in a local environment, somehow aligned with what we have in production." }, { "code": null, "e": 700, "s": 670, "text": "First of all, what is Athena:" }, { "code": null, "e": 706, "s": 700, "text": "📖Docs" }, { "code": null, "e": 930, "s": 706, "text": "Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run." }, { "code": null, "e": 1266, "s": 930, "text": "Athena is easy to use. Simply point to your data in Amazon S3, define the schema, and start querying using standard SQL. Most results are delivered within seconds. With Athena, there’s no need for complex ETL jobs to prepare your data for analysis. This makes it easy for anyone with SQL skills to quickly analyze large-scale datasets." }, { "code": null, "e": 1560, "s": 1266, "text": "Athena is out-of-the-box integrated with AWS Glue Data Catalog, allowing you to create a unified metadata repository across various services, crawl data sources to discover schemas and populate your Catalog with new and modified table and partition definitions, and maintain schema versioning." }, { "code": null, "e": 1843, "s": 1560, "text": "Put simply, by pointing Athena to a specific structured or semi-structured data stored in S3, it makes really easy to quickly analyze results by using SQL queries. When you run a query, Athena will parallelize it across hundreds/thousands of cores and deliver the result in seconds." }, { "code": null, "e": 2151, "s": 1843, "text": "Under the hood and at its core, Athena is a fusion of Hadoop/Hive for its Data Description Language (DDL) and Presto, which allows full standard SQL support and works with a variety of standard data formats, including CSV, JSON and Apache Parquet. We’re going to describe them in detail later in this guide." }, { "code": null, "e": 2239, "s": 2151, "text": "Some of the ingredients needed for this recipe to work are the following Docker images:" }, { "code": null, "e": 2251, "s": 2239, "text": "moto server" }, { "code": null, "e": 2263, "s": 2251, "text": "hive/hadoop" }, { "code": null, "e": 2270, "s": 2263, "text": "presto" }, { "code": null, "e": 2341, "s": 2270, "text": "We’re going to cover all of them in details in the following sections." }, { "code": null, "e": 2347, "s": 2341, "text": "📝Note" }, { "code": null, "e": 2427, "s": 2347, "text": "This guide assumes that you’re familiar with Docker, AWS S3 and Athena services" }, { "code": null, "e": 2560, "s": 2427, "text": "Below I’m going to give you an overview of the docker images that will be used in this tutorial and their role in the whole process." }, { "code": null, "e": 2658, "s": 2560, "text": "At the end of this section, we’ll have a full docker compose file ready to be used for our tests." }, { "code": null, "e": 2711, "s": 2658, "text": "Let’s introduce each one of them with some examples." }, { "code": null, "e": 2984, "s": 2711, "text": "Moto is an amazing library to mock different AWS services both by using decorators for your specific tests or as a stand alone server. At the time of writing this article and at the best of my knowledge, it does not support the specific use case for Athena described here." }, { "code": null, "e": 3073, "s": 2984, "text": "For this guide, we’re going to use Moto as a stand alone server to serve the S3 service." }, { "code": null, "e": 3172, "s": 3073, "text": "Let’s start this exciting journey by filling up our empty docker-container with the first service." }, { "code": null, "e": 3302, "s": 3172, "text": "I’ve create a new project folder called mothena which contains only a docker-compose file as you can seen in the following image:" }, { "code": null, "e": 3469, "s": 3302, "text": "The moto-server service is self-explanatory and the only thing to take into account is that we’ve exposed the port 5000, which is the default one used by Moto server." }, { "code": null, "e": 3594, "s": 3469, "text": "Now, we’re ready to launch our first service from our terminal (from our mothena directory) by typing the following command:" }, { "code": null, "e": 3612, "s": 3594, "text": "docker-compose up" }, { "code": null, "e": 3703, "s": 3612, "text": "As you can see from Figure 2, the Moto standalone server is now running on localhost:5000." }, { "code": null, "e": 3830, "s": 3703, "text": "Now, let’s try to create a bucket and make sure it works as expected. I’m using a jupyter notebook with the following snippet:" }, { "code": null, "e": 4020, "s": 3830, "text": "The output result suggests us that something happened and the bucket named mothena has been created. I’ve used as region_name=”eu-west-1” but, feel free to input any region name you prefer." }, { "code": null, "e": 4189, "s": 4020, "text": "The most important piece to note here is that boto3 client accepts a parameter called endpoint_url which basically refers to our local endpoint. You can read more here." }, { "code": null, "e": 4319, "s": 4189, "text": "But, it’s not finished yet, as a proof that everything worked correctly, let’s have a look at the container logs in the terminal:" }, { "code": null, "e": 4401, "s": 4319, "text": "Figure 4 shows us that a PUT request has been executed with HTTP status code 200." }, { "code": null, "e": 4547, "s": 4401, "text": "Everything works! Now, we can stop our container (type Ctrl+C in the terminal window where the container runs) and proceed with the next section." }, { "code": null, "e": 4695, "s": 4547, "text": "As said at the beginning of this guide, under the hood, Athena runs Hadoop/Hive for its DDL. So, we need to include Hadoop/Hive in the picture too." }, { "code": null, "e": 4796, "s": 4695, "text": "Lets briefly describe what Hadoop and Hive are (taking the definition from their official websites):" }, { "code": null, "e": 4802, "s": 4796, "text": "📖Docs" }, { "code": null, "e": 5355, "s": 4802, "text": "The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures." }, { "code": null, "e": 5628, "s": 5355, "text": "The Apache Hive data warehouse software facilitates reading, writing, and managing large datasets residing in distributed storage using SQL. Structure can be projected onto data already in storage. A command line tool and JDBC driver are provided to connect users to Hive." }, { "code": null, "e": 6099, "s": 5628, "text": "In short, Hadoop is an open source framework responsible to easily store and manage large datasets (from gigabytes to petabytes) of data across a cluster of servers: this means that instead of using one computer, Hadoop allows the use of multiple computers (clusters) to analyze massive datasets in parallel and to quickly execute distributed processes against huge amounts of data. It’s the foundation layer on top of which other services and applications can be built." }, { "code": null, "e": 6239, "s": 6099, "text": "Hive is indeed an application that runs over the Hadoop framework for processing/querying this distributed data using a SQL like interface." }, { "code": null, "e": 6404, "s": 6239, "text": "This means that, when we create a table in Hadoop, we can specify the location where the data (e.g. .csv or .parquet files) resides and, in our case, it will be S3." }, { "code": null, "e": 6499, "s": 6404, "text": "We’re going to use this repo for the Hadoop/Hive image and more specifically, the hdp3.1-hive." }, { "code": null, "e": 6579, "s": 6499, "text": "Let’s first clone the project by running the following command in the terminal:" }, { "code": null, "e": 6636, "s": 6579, "text": "git clone https://github.com/prestosql/docker-images.git" }, { "code": null, "e": 6783, "s": 6636, "text": "Now, before building the image, there is something we need to take into account: we want the Hadoop cluster to “communicate” with the moto server." }, { "code": null, "e": 6864, "s": 6783, "text": "In doing so, we need to add some properties in one specific configuration files:" }, { "code": null, "e": 7053, "s": 6864, "text": "prestodev/hdp3.1-hive/files/etc/hadoop/conf/core-site.xml - contains configuration information for the Hadoop daemon, including S3 specs such as endpoint, access key, access secrect, etc.." }, { "code": null, "e": 7063, "s": 7053, "text": "Core-site" }, { "code": null, "e": 7278, "s": 7063, "text": "In the below gist, you can see the properties we’re going to add in core-site.xml; all of them are related to S3 and for more information, here you can find an extensive description of all the mentioned properties." }, { "code": null, "e": 7377, "s": 7278, "text": "Let’s review the ones we’ve added as there are some aspects that may require a bit of explanation:" }, { "code": null, "e": 7614, "s": 7377, "text": "access key and access secret can be any non-null string we want. Moto doesn’t mind. As defined in the gist, I’m going to define them as ENV variables in the docker compose file (com.amazonaws.auth.EnvironmentVariableCredentialsProvider)" }, { "code": null, "e": 7695, "s": 7614, "text": "we’re using s3a protocol and we’ll see later what this implies to create a table" }, { "code": null, "e": 7818, "s": 7695, "text": "the endpoint refers to the pre-defined moto hostname, which is moto-server and has been defined in our docker-compose file" }, { "code": null, "e": 7824, "s": 7818, "text": "📝Note" }, { "code": null, "e": 8035, "s": 7824, "text": "As you may know, by default Docker Compose sets up a single network for our app. Each service joins the default network and is both reachable and discoverable by other containers on that network by its hostname" }, { "code": null, "e": 8341, "s": 8035, "text": "path style access set to True is particularly useful for s3a storage as it removes the need to set up DNS for virtual hosting. So in this way, we can have the following url style for s3: https://s3.Region.amazonaws.com/bucket-name/key-name , which for Moto means http://localhost:5000/bucket-name/key-name" }, { "code": null, "e": 8373, "s": 8341, "text": "let’s disable ssl, not required" }, { "code": null, "e": 8513, "s": 8373, "text": "Now that everything is set up, we can build the docker image and running it from our docker-compose. A new service will finally be added 🤓." }, { "code": null, "e": 8613, "s": 8513, "text": "Let’s follow the github README and build the image by typing in the terminal the following command:" }, { "code": null, "e": 8640, "s": 8613, "text": "make prestodev/hdp3.1-hive" }, { "code": null, "e": 8754, "s": 8640, "text": "This would take few minutes and the end result will be a successfully tagged image like what you see in Figure 6." }, { "code": null, "e": 8840, "s": 8754, "text": "It’s time to test if our Hadoop cluster works and, more importantly, works with moto." }, { "code": null, "e": 8914, "s": 8840, "text": "Let’s then add a new service in our docker-compose file like in Figure 7." }, { "code": null, "e": 9051, "s": 8914, "text": "You can see from the newly added service that we’ve included the access key and secret as ENV variables as defined in our core-site.xml." }, { "code": null, "e": 9243, "s": 9051, "text": "One question you may have is why exposing port 1000? The main reason in to allow communication with Hive from our script (via localhost), something we’re going to explore later in this guide." }, { "code": null, "e": 9470, "s": 9243, "text": "You can also have a look at the Docker file prestodev/hdp3.1-hive/Dockerfile and notice that there are 2 ports open for Hive: 9083 (used to work with Presto and it’s already available inside the containers’ network) and 10000." }, { "code": null, "e": 9557, "s": 9470, "text": "Ok, with 2 services in our docker-compose.yml, we can now run again from our terminal:" }, { "code": null, "e": 9575, "s": 9557, "text": "docker-compose up" }, { "code": null, "e": 9639, "s": 9575, "text": "And as you can see from Figure 9, they are running as expected." }, { "code": null, "e": 9889, "s": 9639, "text": "Now, let’s do something interesting here and imagine a scenario where we need to explore a subset (just few lines) of data from the new york residential properties sales transaction dataset (.parquet format, but any other compatible format is fine):" }, { "code": null, "e": 9945, "s": 9889, "text": "I want to upload a file on S3 with a specific partition" }, { "code": null, "e": 10015, "s": 9945, "text": "I can query the file by using Hive and save the result in a dataframe" }, { "code": null, "e": 10179, "s": 10015, "text": "For this exercise and for all the ones you’ll see next, I’m going to use sqlalchemy with pyhive dialects installed. You can read more here in order to set them up." }, { "code": null, "e": 10264, "s": 10179, "text": "Having Hadoop and moto ready, you can run the following script and see what happens." }, { "code": null, "e": 10314, "s": 10264, "text": "The above code is pretty simple, basically we’re:" }, { "code": null, "e": 10348, "s": 10314, "text": "Uploading the sample data on moto" }, { "code": null, "e": 10593, "s": 10348, "text": "Creating a table and update metadata with MSCK REPAIR. I’ve also included the partitioned column downloaded_at following the specific S3 key structure. I thought this would make the exercise as much completed as possible for different use cases" }, { "code": null, "e": 10656, "s": 10593, "text": "Retrieving results and save them in a dataframe. See Figure 10" }, { "code": null, "e": 10767, "s": 10656, "text": "As reference, in Figure 11 you can also see what’s going on in our containers, including all the GET requests." }, { "code": null, "e": 10983, "s": 10767, "text": "And that’s it for this section. But, in order to fully align with Athena, we need to add the last tile in the puzzle which is Presto; so, let’s stop docker-compose (CRTL-C) again and go straight to the next section." }, { "code": null, "e": 10999, "s": 10983, "text": "What is Presto?" }, { "code": null, "e": 11005, "s": 10999, "text": "📖Docs" }, { "code": null, "e": 11150, "s": 11005, "text": "From prestosql: Presto is a highly parallel and distributed query engine, that is built from the ground up for efficient, low latency analytics." }, { "code": null, "e": 11404, "s": 11150, "text": "Presto (I’m using prestosql) supports ANSI SQL semantics and allows querying data where it lives, including Hive, Cassandra, relational databases or even proprietary data stores. Indeed, Presto has different connectors and Hive connector is one of them." }, { "code": null, "e": 11533, "s": 11404, "text": "First, we need to clone Presto docker and add a new catalog. We’ve introduced the concept of connector before, what’s a catalog?" }, { "code": null, "e": 11539, "s": 11533, "text": "📖Docs" }, { "code": null, "e": 11899, "s": 11539, "text": "A Presto catalog contains schemas and references a data source via a connector. For example, you can configure a JMX catalog to provide access to JMX information via the JMX connector. When you run a SQL statement in Presto, you are running it against one or more catalogs. Other examples of catalogs include the hive catalog to connect to a Hive data source." }, { "code": null, "e": 12131, "s": 11899, "text": "When addressing a table in Presto, the fully-qualified table name is always rooted in a catalog. For example, a fully-qualified table name of hive.test_data.test refers to the test table in the test_data schema in the hive catalog." }, { "code": null, "e": 12218, "s": 12131, "text": "Catalogs are defined in properties files stored in the Presto configuration directory." }, { "code": null, "e": 12372, "s": 12218, "text": "Hive already defines a hive catalog, we just need to reference it by adding our hive.properties in our presto catalog folder as you can see in Figure 12." }, { "code": null, "e": 12457, "s": 12372, "text": "The structure of the properties is pretty straightforward and as defined here we’re:" }, { "code": null, "e": 12489, "s": 12457, "text": "Using hive-hadoop2 as connector" }, { "code": null, "e": 12629, "s": 12489, "text": "Defining which Hadoop endpoint Presto should connect to (do you remember docker-compose, hostname, same network?) using the thrift protocol" }, { "code": null, "e": 12668, "s": 12629, "text": "Defining path style here again to true" }, { "code": null, "e": 12724, "s": 12668, "text": "Defining S3 endpoint to point to our local moto service" }, { "code": null, "e": 12840, "s": 12724, "text": "And that’s it! Let’s move to the Presto directory and build the image from the terminal with the following command:" }, { "code": null, "e": 12875, "s": 12840, "text": "Docker build . -t prestosql-docker" }, { "code": null, "e": 12975, "s": 12875, "text": "Once finished, we can go back to our mothena docker-compose.yml and add the new service as follows:" }, { "code": null, "e": 13073, "s": 12975, "text": "As you can see, Presto includes aws access secret and key as ENV variables and exposes port 8080." }, { "code": null, "e": 13178, "s": 13073, "text": "We’re ready to change our previous code snippet and include Presto to retrieve our data instead of Hive." }, { "code": null, "e": 13270, "s": 13178, "text": "Let’s now run back again the mothena docker-compose and update our code snippet as follows:" }, { "code": null, "e": 13397, "s": 13270, "text": "As you can see, we’ve added the Presto engine which connects to the hive catalog and uses it to retrieve the pandas dataframe." }, { "code": null, "e": 13460, "s": 13397, "text": "The result will be the same dataframe you’ve see in Figure 10." }, { "code": null, "e": 13527, "s": 13460, "text": "Wow, I have learned a lot writing this guide and I hope you too 🎉." }, { "code": null, "e": 13680, "s": 13527, "text": "Now you have locally the fully (almost :)) functional Athena service that you may use in your script or unit/integration tests on CodeBuild for example." }, { "code": null, "e": 13907, "s": 13680, "text": "With all the services available on localhost, other than boto3 and pandas, you can use any other library that accepts sqlalchemy connection/engine or endpoint overwriting such as pyarrow, s3fs, some awswrangler functions, etc." }, { "code": null, "e": 13989, "s": 13907, "text": "Here you can find the source code where I’ve pushed missing images on Docker Hub." } ]
Bayesian Marketing Mix Modeling in Python via PyMC3 | by Dr. Robert Kübler | Towards Data Science
In this article, I want to combine two concepts that I discussed in earlier posts: Bayesian modeling and marketing mix modeling. Since the chances are high that you are not familiar with both of these topics, let me give you a quick introduction and further readings. I will motivate what marketing mix modeling is,what Bayesian modeling is, andwhy it makes sense to combine both. motivate what marketing mix modeling is, what Bayesian modeling is, and why it makes sense to combine both. Then, I will show you how to do it in practice using PyMC3. If you are an eager reader of my articles (thank you!), you can skip a few sections to get right to the code. Otherwise, please just continue reading. A fundamental problem for every business is to decide on which channels to spend the marketing budget. You could spend 1.000€ on TV ads, 2.000€ on radio ads, and 3.000€ on web banners each day, just going with your gut feeling. But is this any good? Maybe the web banner channel is saturated already, and spending only 1.500€ there is just as good as 3.000€. Then you could save 1.500€, or put them into other, better-performing channels for more sales. Or maybe some channel even has a negative ROI — for each Euro you spend there on ads, you get less than one Euro back in return. We should definitely not waste too much money on such a channel, at least if it is not strategically important from a business perspective. To answer questions like this, you have to understand how the different media spendings (TV, radio, ...) impact your sales or other KPI of interest. In marketing mix modeling, you start with a dataset of media spendings. It usually gets extended with some control variables, i.e. further information about anything that might impact the target KPI, such as holidays, the weather, soccer championships, lockdowns, the price of a product, and many more. We will omit the control variables here, though, to keep it concise. Then, of course, you need a KPI you want to predict. This is often sales, number of new customers and such. So, a typical dataset might look like this: In my older articles, I describe the motivation and how to conduct marketing mix modeling in more detail. In order to understand the rest of this article, please check them both out here: towardsdatascience.com towardsdatascience.com Many estimators and models stem from a maximum likelihood approach. As an example, imagine that you want to estimate the probability p of a coin showing heads. You flip it 10 times and see 8 heads, what do you conclude? A natural estimate for the probability is then p = 8 / 10 = 80%, which also happens to be the maximum likelihood estimate. You could also calculate a confidence interval to see if this estimate is reliable, but we want to take another path. Imagine that we want to incorporate some prior knowledge about the probability p. If you have drawn the coin randomly from your wallet, for example, there is no reason to think that the coin is biased, so p should not be too far away from 50%, assuming that you are not a magician. With Bayesian modeling, you can incorporate this prior knowledge to end up with a density estimate of p, i.e. not a single value but an entire distribution. This distribution will probably have a peak somewhere between the maximum likelihood estimate and the prior, maybe 65%. All in all, Bayesian modeling is about finding a trade-off between prior knowledge and the observed data. In the picture above, this means the following: without any data, we start off with the blue curve. This is just a belief, a gut feeling. Then, we observe data that tells us to move the blue curve more towards the red one. We end up with the yellow hybrid curve, which depicts the so-called posterior distribution. You can read more about the motivation here: towardsdatascience.com Now, understanding the theory is good but we also have to be able to apply it to get things done. Usually, I use the awesome python library PyMC3 for Bayesian modeling. You can see it in action here: towardsdatascience.com You can define marketing mix models with a lot of hyperparameters: the saturation the carryover strength the carryover length ... Then, you can use a hyperparameter optimization method to find the optimal combination. That is what I have done in my other article about marketing mix modeling, An Upgraded Marketing Mix Modeling in Python. This approach works fine, but there is a thing about it that I don’t like: The hyperparameter estimates are often unstable. This means that completely different sets of hyperparameters might yield equally good models. There might be Model A with a TV carryover strength of 0.4 and a TV saturation of 0.8, and Model B with a TV carryover strength of 0.9 and a TV saturation of 0.5, both having the same r2 or MAPE on the test set. From a prediction standpoint, both models are interchangeable, if you stay within the marketing spend boundaries you have seen so far. However, extrapolating using Model A is completely different from extrapolating with Model B. And this is a rather unsatisfying and troublesome behavior because extrapolation is the thing to do when optimizing media budget. If you used to spend 0€ to 1.000€ per day on TV ads historically so far, for the optimization you have to know what happens when you spend 5.000€ or even 10.000€ as well. You need a model with excellent extrapolation capabilities. And usually, you have to choose between more than only two models. In this case, you can proceed in at least two ways You can pick the first model you create because you are not even aware of the problem. This approach is easy but dangerous. You can pick a model that seems right to you, some domain experts, or the stakeholders. For some people this is okay but I prefer not baking the output expectations into the model because of the following question: If somebody knows the answer already, why would I even build a model that just replicates that answer? There might be ways to do something reasonable from here as well but I want to show you how to circumvent this problem using Bayesian modeling now. First, let us grab our dataset. import pandas as pddata = pd.read_csv( 'https://raw.githubusercontent.com/Garve/datasets/4576d323bf2b66c906d5130d686245ad205505cf/mmm.csv', parse_dates=['Date'], index_col='Date')X = data.drop(columns=['Sales'])y = data['Sales'] Then, we have to define the saturation and carryover functionality, similar to the last article. In PyMC3 language, it might look like this: import theano.tensor as ttdef saturate(x, a): return 1 - tt.exp(-a*x)def carryover(x, strength, length=21): w = tt.as_tensor_variable( [tt.power(strength, i) for i in range(length)] ) x_lags = tt.stack( [tt.concatenate([ tt.zeros(i), x[:x.shape[0]-i] ]) for i in range(length)] ) return tt.dot(w, x_lags) The saturation function should be easy to grasp. The carryover, however, is a bit of work. Basically, you can express the carryover transformation as a matrix-vector multiplication. You just have to assemble the matrix x_lags and the vector w first. As an example, we can transform the input vector x = (x1, x2, x3, x4) with a carryover length of 3 via The carryover function in the code above does exactly this. If we have these functions, we can finally start modeling. import pymc3 as pmwith pm.Model() as mmm: channel_contributions = [] for channel in X.columns: coef = pm.Exponential(f'coef_{channel}', lam=0.0001) sat = pm.Exponential(f'sat_{channel}', lam=1) car = pm.Beta(f'car_{channel}', alpha=2, beta=2) channel_data = X[channel].values channel_contribution = pm.Deterministic( f'contribution_{channel}', coef * saturate( carryover( channel_data, car ), sat ) ) channel_contributions.append(channel_contribution) base = pm.Exponential('base', lam=0.0001) noise = pm.Exponential('noise', lam=0.0001) sales = pm.Normal( 'sales', mu=sum(channel_contributions) + base, sigma=noise, observed=y ) trace = pm.sample(return_inferencedata=True, tune=3000) We can see all parameters (no hyperparameters anymore!) marked in bold. It is the regression coefficients, saturation strength, carryover strength, the baseline, and the noise. Note that I did not take the carryover length into account, I rather set it to 21. This is because I could not figure out yet how to create matrices and vectors in the carrover function with variable dimensions in PyMC3. But usually, I would use a Poisson random variable for the carryover length. Leave me a note if you know how to do this properly! 😉 Maybe it is also a good time to give pyro a chance, another probabilistic programming language like PyMC3. Afterward, we can look at the usual pictures. Let us start with the posterior distributions. Executing import arviz as azaz.plot_posterior( trace, var_names=['~contribution'], filter_vars='like') yields Here, you can see the posteriors for all parameters. They all have a nice unimodal (=one peak) shape. You can also explore how pairs of variables behave together via az.plot_joint( trace, var_names=['coef_TV', 'sat_TV'],) Here you can see that the saturation strength and the regression coefficient as not independent, but negatively correlated: the higher the coefficient, the lower the saturation parameter tends to be. This makes sense because a higher coefficient can compensate for a slower increasing saturation curve (=lower sat_TV) and vice versa. Let us look at another one: az.plot_joint( trace, var_names=['car_TV', 'sat_TV'],) Here, we can see why hyperparameter optimization might have problems. Every dot in this picture is a potential model that you could find with a hyperparameter optimization. For a truly unique best model, we would rather see a point cloud tightly concentrated around a single point (car_TV_true, sat_TV_true). Here, however, we see that the TV carryover strength can have reasonable values between 0.4 and 0.5, depending on the saturation parameter. We can also check if the model is any good before we jump to conclusions. Executing import matplotlib.pyplot as pltwith mmm: posterior = pm.sample_posterior_predictive(trace)means = posterior['sales'].mean(0)stds = posterior['sales'].std(0)plt.figure(figsize=(20, 8))plt.plot(y.values, linewidth=2, c='r', label='Observations')plt.plot(means, linewidth=1, c='b', label='Mean prediction')plt.fill_between(np.arange(len(y)), means - 2*stds, means + 2*stds, alpha=0.33)plt.legend() gives us so it looks like the model picked up something useful. I will not go into detail about how to evaluate the performance of the model any further here, we can do this in the future. We dealt with distributions so far, but for our favorite channel contributions picture, let us take means to end up with a single value again. Since we introduced some channel contribution variables in the PyMC3 code, we can easily extract them now using a short compute_mean function. def compute_mean(trace, channel): return (trace .posterior[f'contribution_{channel}'] .values .reshape(4000, 200) .mean(0) )channels = ['Banners', 'Radio', 'TV']unadj_contributions = pd.DataFrame( {'Base': trace.posterior['base'].values.mean()}, index=X.index)for channel in channels: unadj_contributions[channel] = compute_mean(trace, channel)adj_contributions = (unadj_contributions .div(unadj_contributions.sum(axis=1), axis=0) .mul(y, axis=0) )ax = (adj_contributions .plot.area( figsize=(16, 10), linewidth=1, title='Predicted Sales and Breakdown', ylabel='Sales', xlabel='Date' ) ) handles, labels = ax.get_legend_handles_labels()ax.legend( handles[::-1], labels[::-1], title='Channels', loc="center left", bbox_to_anchor=(1.01, 0.5)) Looks good! In this article, we have discussed that marketing mix modeling using a maximum likelihood approach can be difficult because of the hyperparameters estimation. There might be many models that perform well on the test set but have completely different extrapolation behavior — the (hyper)parameters are quite unstable. However, proper extrapolation is the key to optimization. Therefore, we have designed a basic marketing mix model with saturation and carryover effects in the Bayesian setting. This proved useful because it estimates all the parameters at once, giving us more stable parameter estimates. We then implemented it using PyMC3 and created a nice contributions chart again to see how much the channel spendings contributed to the sales. We could now take the Bayesian model that we have created and extend it even further. For example, we can incorporate changing parameters over time. This can be useful if the TV carryover strength started out at 0.8 two years ago but slowly declined to 0.5 over time, which is an example of concept drift. We can easily model this using Gaussian random walks, as shown in my other article about rolling regression: towardsdatascience.com In the same way, we can model changing baselines. So far, we have treated the baseline as a single number that is fixed over the whole training time period. But maybe it increased over time as well because of our strategic advertising efforts. This is something that is hard to figure out using our old maximum likelihood models with hyperparameter optimization. I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 447, "s": 172, "text": "In this article, I want to combine two concepts that I discussed in earlier posts: Bayesian modeling and marketing mix modeling. Since the chances are high that you are not familiar with both of these topics, let me give you a quick introduction and further readings. I will" }, { "code": null, "e": 553, "s": 447, "text": "motivate what marketing mix modeling is,what Bayesian modeling is, andwhy it makes sense to combine both." }, { "code": null, "e": 594, "s": 553, "text": "motivate what marketing mix modeling is," }, { "code": null, "e": 625, "s": 594, "text": "what Bayesian modeling is, and" }, { "code": null, "e": 661, "s": 625, "text": "why it makes sense to combine both." }, { "code": null, "e": 721, "s": 661, "text": "Then, I will show you how to do it in practice using PyMC3." }, { "code": null, "e": 872, "s": 721, "text": "If you are an eager reader of my articles (thank you!), you can skip a few sections to get right to the code. Otherwise, please just continue reading." }, { "code": null, "e": 1122, "s": 872, "text": "A fundamental problem for every business is to decide on which channels to spend the marketing budget. You could spend 1.000€ on TV ads, 2.000€ on radio ads, and 3.000€ on web banners each day, just going with your gut feeling. But is this any good?" }, { "code": null, "e": 1326, "s": 1122, "text": "Maybe the web banner channel is saturated already, and spending only 1.500€ there is just as good as 3.000€. Then you could save 1.500€, or put them into other, better-performing channels for more sales." }, { "code": null, "e": 1595, "s": 1326, "text": "Or maybe some channel even has a negative ROI — for each Euro you spend there on ads, you get less than one Euro back in return. We should definitely not waste too much money on such a channel, at least if it is not strategically important from a business perspective." }, { "code": null, "e": 1744, "s": 1595, "text": "To answer questions like this, you have to understand how the different media spendings (TV, radio, ...) impact your sales or other KPI of interest." }, { "code": null, "e": 2268, "s": 1744, "text": "In marketing mix modeling, you start with a dataset of media spendings. It usually gets extended with some control variables, i.e. further information about anything that might impact the target KPI, such as holidays, the weather, soccer championships, lockdowns, the price of a product, and many more. We will omit the control variables here, though, to keep it concise. Then, of course, you need a KPI you want to predict. This is often sales, number of new customers and such. So, a typical dataset might look like this:" }, { "code": null, "e": 2456, "s": 2268, "text": "In my older articles, I describe the motivation and how to conduct marketing mix modeling in more detail. In order to understand the rest of this article, please check them both out here:" }, { "code": null, "e": 2479, "s": 2456, "text": "towardsdatascience.com" }, { "code": null, "e": 2502, "s": 2479, "text": "towardsdatascience.com" }, { "code": null, "e": 2963, "s": 2502, "text": "Many estimators and models stem from a maximum likelihood approach. As an example, imagine that you want to estimate the probability p of a coin showing heads. You flip it 10 times and see 8 heads, what do you conclude? A natural estimate for the probability is then p = 8 / 10 = 80%, which also happens to be the maximum likelihood estimate. You could also calculate a confidence interval to see if this estimate is reliable, but we want to take another path." }, { "code": null, "e": 3245, "s": 2963, "text": "Imagine that we want to incorporate some prior knowledge about the probability p. If you have drawn the coin randomly from your wallet, for example, there is no reason to think that the coin is biased, so p should not be too far away from 50%, assuming that you are not a magician." }, { "code": null, "e": 3522, "s": 3245, "text": "With Bayesian modeling, you can incorporate this prior knowledge to end up with a density estimate of p, i.e. not a single value but an entire distribution. This distribution will probably have a peak somewhere between the maximum likelihood estimate and the prior, maybe 65%." }, { "code": null, "e": 3943, "s": 3522, "text": "All in all, Bayesian modeling is about finding a trade-off between prior knowledge and the observed data. In the picture above, this means the following: without any data, we start off with the blue curve. This is just a belief, a gut feeling. Then, we observe data that tells us to move the blue curve more towards the red one. We end up with the yellow hybrid curve, which depicts the so-called posterior distribution." }, { "code": null, "e": 3988, "s": 3943, "text": "You can read more about the motivation here:" }, { "code": null, "e": 4011, "s": 3988, "text": "towardsdatascience.com" }, { "code": null, "e": 4211, "s": 4011, "text": "Now, understanding the theory is good but we also have to be able to apply it to get things done. Usually, I use the awesome python library PyMC3 for Bayesian modeling. You can see it in action here:" }, { "code": null, "e": 4234, "s": 4211, "text": "towardsdatascience.com" }, { "code": null, "e": 4301, "s": 4234, "text": "You can define marketing mix models with a lot of hyperparameters:" }, { "code": null, "e": 4316, "s": 4301, "text": "the saturation" }, { "code": null, "e": 4339, "s": 4316, "text": "the carryover strength" }, { "code": null, "e": 4360, "s": 4339, "text": "the carryover length" }, { "code": null, "e": 4364, "s": 4360, "text": "..." }, { "code": null, "e": 4573, "s": 4364, "text": "Then, you can use a hyperparameter optimization method to find the optimal combination. That is what I have done in my other article about marketing mix modeling, An Upgraded Marketing Mix Modeling in Python." }, { "code": null, "e": 4648, "s": 4573, "text": "This approach works fine, but there is a thing about it that I don’t like:" }, { "code": null, "e": 4697, "s": 4648, "text": "The hyperparameter estimates are often unstable." }, { "code": null, "e": 4806, "s": 4697, "text": "This means that completely different sets of hyperparameters might yield equally good models. There might be" }, { "code": null, "e": 4882, "s": 4806, "text": "Model A with a TV carryover strength of 0.4 and a TV saturation of 0.8, and" }, { "code": null, "e": 4954, "s": 4882, "text": "Model B with a TV carryover strength of 0.9 and a TV saturation of 0.5," }, { "code": null, "e": 5138, "s": 4954, "text": "both having the same r2 or MAPE on the test set. From a prediction standpoint, both models are interchangeable, if you stay within the marketing spend boundaries you have seen so far." }, { "code": null, "e": 5533, "s": 5138, "text": "However, extrapolating using Model A is completely different from extrapolating with Model B. And this is a rather unsatisfying and troublesome behavior because extrapolation is the thing to do when optimizing media budget. If you used to spend 0€ to 1.000€ per day on TV ads historically so far, for the optimization you have to know what happens when you spend 5.000€ or even 10.000€ as well." }, { "code": null, "e": 5593, "s": 5533, "text": "You need a model with excellent extrapolation capabilities." }, { "code": null, "e": 5711, "s": 5593, "text": "And usually, you have to choose between more than only two models. In this case, you can proceed in at least two ways" }, { "code": null, "e": 5835, "s": 5711, "text": "You can pick the first model you create because you are not even aware of the problem. This approach is easy but dangerous." }, { "code": null, "e": 6050, "s": 5835, "text": "You can pick a model that seems right to you, some domain experts, or the stakeholders. For some people this is okay but I prefer not baking the output expectations into the model because of the following question:" }, { "code": null, "e": 6153, "s": 6050, "text": "If somebody knows the answer already, why would I even build a model that just replicates that answer?" }, { "code": null, "e": 6301, "s": 6153, "text": "There might be ways to do something reasonable from here as well but I want to show you how to circumvent this problem using Bayesian modeling now." }, { "code": null, "e": 6333, "s": 6301, "text": "First, let us grab our dataset." }, { "code": null, "e": 6570, "s": 6333, "text": "import pandas as pddata = pd.read_csv( 'https://raw.githubusercontent.com/Garve/datasets/4576d323bf2b66c906d5130d686245ad205505cf/mmm.csv', parse_dates=['Date'], index_col='Date')X = data.drop(columns=['Sales'])y = data['Sales']" }, { "code": null, "e": 6711, "s": 6570, "text": "Then, we have to define the saturation and carryover functionality, similar to the last article. In PyMC3 language, it might look like this:" }, { "code": null, "e": 7085, "s": 6711, "text": "import theano.tensor as ttdef saturate(x, a): return 1 - tt.exp(-a*x)def carryover(x, strength, length=21): w = tt.as_tensor_variable( [tt.power(strength, i) for i in range(length)] ) x_lags = tt.stack( [tt.concatenate([ tt.zeros(i), x[:x.shape[0]-i] ]) for i in range(length)] ) return tt.dot(w, x_lags)" }, { "code": null, "e": 7438, "s": 7085, "text": "The saturation function should be easy to grasp. The carryover, however, is a bit of work. Basically, you can express the carryover transformation as a matrix-vector multiplication. You just have to assemble the matrix x_lags and the vector w first. As an example, we can transform the input vector x = (x1, x2, x3, x4) with a carryover length of 3 via" }, { "code": null, "e": 7557, "s": 7438, "text": "The carryover function in the code above does exactly this. If we have these functions, we can finally start modeling." }, { "code": null, "e": 8493, "s": 7557, "text": "import pymc3 as pmwith pm.Model() as mmm: channel_contributions = [] for channel in X.columns: coef = pm.Exponential(f'coef_{channel}', lam=0.0001) sat = pm.Exponential(f'sat_{channel}', lam=1) car = pm.Beta(f'car_{channel}', alpha=2, beta=2) channel_data = X[channel].values channel_contribution = pm.Deterministic( f'contribution_{channel}', coef * saturate( carryover( channel_data, car ), sat ) ) channel_contributions.append(channel_contribution) base = pm.Exponential('base', lam=0.0001) noise = pm.Exponential('noise', lam=0.0001) sales = pm.Normal( 'sales', mu=sum(channel_contributions) + base, sigma=noise, observed=y ) trace = pm.sample(return_inferencedata=True, tune=3000)" }, { "code": null, "e": 8670, "s": 8493, "text": "We can see all parameters (no hyperparameters anymore!) marked in bold. It is the regression coefficients, saturation strength, carryover strength, the baseline, and the noise." }, { "code": null, "e": 9130, "s": 8670, "text": "Note that I did not take the carryover length into account, I rather set it to 21. This is because I could not figure out yet how to create matrices and vectors in the carrover function with variable dimensions in PyMC3. But usually, I would use a Poisson random variable for the carryover length. Leave me a note if you know how to do this properly! 😉 Maybe it is also a good time to give pyro a chance, another probabilistic programming language like PyMC3." }, { "code": null, "e": 9233, "s": 9130, "text": "Afterward, we can look at the usual pictures. Let us start with the posterior distributions. Executing" }, { "code": null, "e": 9335, "s": 9233, "text": "import arviz as azaz.plot_posterior( trace, var_names=['~contribution'], filter_vars='like')" }, { "code": null, "e": 9342, "s": 9335, "text": "yields" }, { "code": null, "e": 9508, "s": 9342, "text": "Here, you can see the posteriors for all parameters. They all have a nice unimodal (=one peak) shape. You can also explore how pairs of variables behave together via" }, { "code": null, "e": 9570, "s": 9508, "text": "az.plot_joint( trace, var_names=['coef_TV', 'sat_TV'],)" }, { "code": null, "e": 9904, "s": 9570, "text": "Here you can see that the saturation strength and the regression coefficient as not independent, but negatively correlated: the higher the coefficient, the lower the saturation parameter tends to be. This makes sense because a higher coefficient can compensate for a slower increasing saturation curve (=lower sat_TV) and vice versa." }, { "code": null, "e": 9932, "s": 9904, "text": "Let us look at another one:" }, { "code": null, "e": 9993, "s": 9932, "text": "az.plot_joint( trace, var_names=['car_TV', 'sat_TV'],)" }, { "code": null, "e": 10166, "s": 9993, "text": "Here, we can see why hyperparameter optimization might have problems. Every dot in this picture is a potential model that you could find with a hyperparameter optimization." }, { "code": null, "e": 10442, "s": 10166, "text": "For a truly unique best model, we would rather see a point cloud tightly concentrated around a single point (car_TV_true, sat_TV_true). Here, however, we see that the TV carryover strength can have reasonable values between 0.4 and 0.5, depending on the saturation parameter." }, { "code": null, "e": 10526, "s": 10442, "text": "We can also check if the model is any good before we jump to conclusions. Executing" }, { "code": null, "e": 10924, "s": 10526, "text": "import matplotlib.pyplot as pltwith mmm: posterior = pm.sample_posterior_predictive(trace)means = posterior['sales'].mean(0)stds = posterior['sales'].std(0)plt.figure(figsize=(20, 8))plt.plot(y.values, linewidth=2, c='r', label='Observations')plt.plot(means, linewidth=1, c='b', label='Mean prediction')plt.fill_between(np.arange(len(y)), means - 2*stds, means + 2*stds, alpha=0.33)plt.legend()" }, { "code": null, "e": 10933, "s": 10924, "text": "gives us" }, { "code": null, "e": 11113, "s": 10933, "text": "so it looks like the model picked up something useful. I will not go into detail about how to evaluate the performance of the model any further here, we can do this in the future." }, { "code": null, "e": 11399, "s": 11113, "text": "We dealt with distributions so far, but for our favorite channel contributions picture, let us take means to end up with a single value again. Since we introduced some channel contribution variables in the PyMC3 code, we can easily extract them now using a short compute_mean function." }, { "code": null, "e": 12336, "s": 11399, "text": "def compute_mean(trace, channel): return (trace .posterior[f'contribution_{channel}'] .values .reshape(4000, 200) .mean(0) )channels = ['Banners', 'Radio', 'TV']unadj_contributions = pd.DataFrame( {'Base': trace.posterior['base'].values.mean()}, index=X.index)for channel in channels: unadj_contributions[channel] = compute_mean(trace, channel)adj_contributions = (unadj_contributions .div(unadj_contributions.sum(axis=1), axis=0) .mul(y, axis=0) )ax = (adj_contributions .plot.area( figsize=(16, 10), linewidth=1, title='Predicted Sales and Breakdown', ylabel='Sales', xlabel='Date' ) ) handles, labels = ax.get_legend_handles_labels()ax.legend( handles[::-1], labels[::-1], title='Channels', loc=\"center left\", bbox_to_anchor=(1.01, 0.5))" }, { "code": null, "e": 12348, "s": 12336, "text": "Looks good!" }, { "code": null, "e": 12665, "s": 12348, "text": "In this article, we have discussed that marketing mix modeling using a maximum likelihood approach can be difficult because of the hyperparameters estimation. There might be many models that perform well on the test set but have completely different extrapolation behavior — the (hyper)parameters are quite unstable." }, { "code": null, "e": 12953, "s": 12665, "text": "However, proper extrapolation is the key to optimization. Therefore, we have designed a basic marketing mix model with saturation and carryover effects in the Bayesian setting. This proved useful because it estimates all the parameters at once, giving us more stable parameter estimates." }, { "code": null, "e": 13097, "s": 12953, "text": "We then implemented it using PyMC3 and created a nice contributions chart again to see how much the channel spendings contributed to the sales." }, { "code": null, "e": 13512, "s": 13097, "text": "We could now take the Bayesian model that we have created and extend it even further. For example, we can incorporate changing parameters over time. This can be useful if the TV carryover strength started out at 0.8 two years ago but slowly declined to 0.5 over time, which is an example of concept drift. We can easily model this using Gaussian random walks, as shown in my other article about rolling regression:" }, { "code": null, "e": 13535, "s": 13512, "text": "towardsdatascience.com" }, { "code": null, "e": 13898, "s": 13535, "text": "In the same way, we can model changing baselines. So far, we have treated the baseline as a single number that is fixed over the whole training time period. But maybe it increased over time as well because of our strategic advertising efforts. This is something that is hard to figure out using our old maximum likelihood models with hyperparameter optimization." }, { "code": null, "e": 13988, "s": 13898, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 14014, "s": 13988, "text": "As the last point, if you" }, { "code": null, "e": 14117, "s": 14014, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 14179, "s": 14117, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 14221, "s": 14179, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 14278, "s": 14221, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 14391, "s": 14278, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 14436, "s": 14391, "text": "Thanks a lot, if you consider supporting me!" } ]
Scala Set map() method with example - GeeksforGeeks
18 Oct, 2019 The map() method is utilized to build a new set by applying a function to all elements of this set. Method Definition: def map[B](f: (A) => B): immutable.Set[B] Return Type: It returns a new set containing all the elements after applying the given function. Example #1: // Scala program of map() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(5, 1, 3, 2, 4) // Applying map method val result = s1.map(x => x*x) // Display output println(result) } } Set(25, 1, 9, 16, 4) Example #2: // Scala program of map() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(5, 1, 3, 2, 4) // Applying map method val result = s1.map(x => x/2) // Display output println(result) } } Set(2, 0, 1) Scala scala-collection Scala-Method Scala-Set Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala Tutorial – Learn Scala with Step By Step Guide Scala Lists Hello World in Scala Operators in Scala Class and Object in Scala Inheritance in Scala Scala Constructors Scala | Arrays How to get the first element of List in Scala Break statement in Scala
[ { "code": null, "e": 23882, "s": 23854, "text": "\n18 Oct, 2019" }, { "code": null, "e": 23982, "s": 23882, "text": "The map() method is utilized to build a new set by applying a function to all elements of this set." }, { "code": null, "e": 24043, "s": 23982, "text": "Method Definition: def map[B](f: (A) => B): immutable.Set[B]" }, { "code": null, "e": 24140, "s": 24043, "text": "Return Type: It returns a new set containing all the elements after applying the given function." }, { "code": null, "e": 24152, "s": 24140, "text": "Example #1:" }, { "code": "// Scala program of map() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(5, 1, 3, 2, 4) // Applying map method val result = s1.map(x => x*x) // Display output println(result) } } ", "e": 24489, "s": 24152, "text": null }, { "code": null, "e": 24511, "s": 24489, "text": "Set(25, 1, 9, 16, 4)\n" }, { "code": null, "e": 24523, "s": 24511, "text": "Example #2:" }, { "code": "// Scala program of map() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(5, 1, 3, 2, 4) // Applying map method val result = s1.map(x => x/2) // Display output println(result) } } ", "e": 24860, "s": 24523, "text": null }, { "code": null, "e": 24874, "s": 24860, "text": "Set(2, 0, 1)\n" }, { "code": null, "e": 24880, "s": 24874, "text": "Scala" }, { "code": null, "e": 24897, "s": 24880, "text": "scala-collection" }, { "code": null, "e": 24910, "s": 24897, "text": "Scala-Method" }, { "code": null, "e": 24920, "s": 24910, "text": "Scala-Set" }, { "code": null, "e": 24926, "s": 24920, "text": "Scala" }, { "code": null, "e": 25024, "s": 24926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25033, "s": 25024, "text": "Comments" }, { "code": null, "e": 25046, "s": 25033, "text": "Old Comments" }, { "code": null, "e": 25099, "s": 25046, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 25111, "s": 25099, "text": "Scala Lists" }, { "code": null, "e": 25132, "s": 25111, "text": "Hello World in Scala" }, { "code": null, "e": 25151, "s": 25132, "text": "Operators in Scala" }, { "code": null, "e": 25177, "s": 25151, "text": "Class and Object in Scala" }, { "code": null, "e": 25198, "s": 25177, "text": "Inheritance in Scala" }, { "code": null, "e": 25217, "s": 25198, "text": "Scala Constructors" }, { "code": null, "e": 25232, "s": 25217, "text": "Scala | Arrays" }, { "code": null, "e": 25278, "s": 25232, "text": "How to get the first element of List in Scala" } ]
How to declare a global variable in Python?
A global variable is a variable that is declared outside the function but we need to use it inside the function. Live Demo def func(): print(a) a=10 func() 10 Here, variable a is global. As it is declared outside the function and can be used inside the function as well. Hence the scope of variable a is global. We will see what happens if we create a variable of same name as global variable inside the function. In the above example, the variable a is declared outside the function and hence is global. If we declare another variable with same name inside the function with some another value. That variable will act as the local variable of the function and its scope will be limited to inside the function. Outside the function, the global variable will hold its original value. It can be better understood with the help of an example. Live Demo a=10 def func(): a=5 print("Inside function:",a) func() print("Outside function:",a) Inside function: 5 Outside function: 10 In the above example, a is global variable whose value is 10. Later the func() is called. Inside func(), another variable a is declared with different value whose scope is only limited to inside the function. Hence, when value of a is printed outside the function later, it carries the same original value as global variable which 10. The keyword global is used when you need to declare a global variable inside a function. The scope of normal variable declared inside the function is only till the end of the function. However, if you want to use the variable outside of the function as well, use global keyword while declaring the variable. Understand the difference between both with the help of example implementations. def func(): a=5 print("Inside function:",a) func() print("Outside function:",a) Inside function: 5 Traceback (most recent call last): print("Outside function:",a) NameError: name 'a' is not defined In the above example, the value of a cannot be accessed outside the function, since it is a local variable. Thus, accessing the value of an outside function throws an exception. The exception raised in the above example can be resolved if we declare variable a using keyword global. Live Demo def func(): global a a=5 print("Inside function:",a) func() print("Outside function:",a) Inside function: 5 Outside function: 5 In the above example, the variable a is global and hence its value can be accessed outside the function as well.
[ { "code": null, "e": 1175, "s": 1062, "text": "A global variable is a variable that is declared outside the function but we need to use it inside the function." }, { "code": null, "e": 1186, "s": 1175, "text": " Live Demo" }, { "code": null, "e": 1222, "s": 1186, "text": "def func():\n print(a)\na=10\nfunc()" }, { "code": null, "e": 1225, "s": 1222, "text": "10" }, { "code": null, "e": 1378, "s": 1225, "text": "Here, variable a is global. As it is declared outside the function and can be used inside the function as well. Hence the scope of variable a is global." }, { "code": null, "e": 1480, "s": 1378, "text": "We will see what happens if we create a variable of same name as global variable inside the function." }, { "code": null, "e": 1571, "s": 1480, "text": "In the above example, the variable a is declared outside the function and hence is global." }, { "code": null, "e": 1849, "s": 1571, "text": "If we declare another variable with same name inside the function with some another value. That variable will act as the local variable of the function and its scope will be limited to inside the function. Outside the function, the global variable will hold its original value." }, { "code": null, "e": 1906, "s": 1849, "text": "It can be better understood with the help of an example." }, { "code": null, "e": 1917, "s": 1906, "text": " Live Demo" }, { "code": null, "e": 2005, "s": 1917, "text": "a=10\ndef func():\n a=5\nprint(\"Inside function:\",a)\nfunc()\nprint(\"Outside function:\",a)" }, { "code": null, "e": 2045, "s": 2005, "text": "Inside function: 5\nOutside function: 10" }, { "code": null, "e": 2135, "s": 2045, "text": "In the above example, a is global variable whose value is 10. Later the func() is called." }, { "code": null, "e": 2380, "s": 2135, "text": "Inside func(), another variable a is declared with different value whose scope is only limited to inside the function. Hence, when value of a is printed outside the function later, it carries the same original value as global variable which 10." }, { "code": null, "e": 2469, "s": 2380, "text": "The keyword global is used when you need to declare a global variable inside a function." }, { "code": null, "e": 2565, "s": 2469, "text": "The scope of normal variable declared inside the function is only till the end of the function." }, { "code": null, "e": 2688, "s": 2565, "text": "However, if you want to use the variable outside of the function as well, use global keyword while declaring the variable." }, { "code": null, "e": 2769, "s": 2688, "text": "Understand the difference between both with the help of example implementations." }, { "code": null, "e": 2855, "s": 2769, "text": "def func():\n a=5\n print(\"Inside function:\",a)\nfunc()\nprint(\"Outside function:\",a)" }, { "code": null, "e": 2973, "s": 2855, "text": "Inside function: 5\nTraceback (most recent call last):\nprint(\"Outside function:\",a)\nNameError: name 'a' is not defined" }, { "code": null, "e": 3151, "s": 2973, "text": "In the above example, the value of a cannot be accessed outside the function, since it is a local variable. Thus, accessing the value of an outside function throws an exception." }, { "code": null, "e": 3256, "s": 3151, "text": "The exception raised in the above example can be resolved if we declare variable a using keyword global." }, { "code": null, "e": 3267, "s": 3256, "text": " Live Demo" }, { "code": null, "e": 3365, "s": 3267, "text": "def func():\n global a\n a=5\n print(\"Inside function:\",a)\nfunc()\nprint(\"Outside function:\",a)" }, { "code": null, "e": 3404, "s": 3365, "text": "Inside function: 5\nOutside function: 5" }, { "code": null, "e": 3517, "s": 3404, "text": "In the above example, the variable a is global and hence its value can be accessed outside the function as well." } ]
Shifting Letters in C++
Suppose we have a string S of lowercase letters, and an integer array shifts. The shift of a letter means the next letter in the alphabet, for z, it will be a. Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times. We have to find the final string after all such shifts to S are applied. So if the string is “abc” and shifts = [3,5,9], then after shifting the first 1 letter of S by 3, will have “dbc”, shifting first two letters of S by 5, we have “igc”, and shifting first 3 letters of S by 9, we have “rpl”, and this is the answer. To solve this, we will follow these steps − for i in range size of shift array – 2 down to 0shift[i] := shift[i] + shift[i + 1]shift[i] := shift[i] mod 26 shift[i] := shift[i] + shift[i + 1] shift[i] := shift[i] mod 26 for i in range 0 to size of S – 1S[i] := ((S[i] – ASCII of a) + shifts[i] mod 26) + ASCII of a S[i] := ((S[i] – ASCII of a) + shifts[i] mod 26) + ASCII of a return S Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string shiftingLetters(string S, vector<int>& shifts) { for(int i = shifts.size() - 2 ;i >=0; i--){ shifts[i] += shifts[i + 1]; shifts[i] %= 26; } for(int i = 0; i < S.size(); i++) { S[i] = ( ((S[i] - 'a') + shifts[i]) % 26 + 'a'); } return S; } }; main(){ vector<int> v = {3,5,9}; Solution ob; cout << (ob.shiftingLetters("abc", v)); } "abc" [3,5,9] rpl
[ { "code": null, "e": 1624, "s": 1062, "text": "Suppose we have a string S of lowercase letters, and an integer array shifts. The shift of a letter means the next letter in the alphabet, for z, it will be a. Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times. We have to find the final string after all such shifts to S are applied. So if the string is “abc” and shifts = [3,5,9], then after shifting the first 1 letter of S by 3, will have “dbc”, shifting first two letters of S by 5, we have “igc”, and shifting first 3 letters of S by 9, we have “rpl”, and this is the answer." }, { "code": null, "e": 1668, "s": 1624, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1779, "s": 1668, "text": "for i in range size of shift array – 2 down to 0shift[i] := shift[i] + shift[i + 1]shift[i] := shift[i] mod 26" }, { "code": null, "e": 1815, "s": 1779, "text": "shift[i] := shift[i] + shift[i + 1]" }, { "code": null, "e": 1843, "s": 1815, "text": "shift[i] := shift[i] mod 26" }, { "code": null, "e": 1938, "s": 1843, "text": "for i in range 0 to size of S – 1S[i] := ((S[i] – ASCII of a) + shifts[i] mod 26) + ASCII of a" }, { "code": null, "e": 2000, "s": 1938, "text": "S[i] := ((S[i] – ASCII of a) + shifts[i] mod 26) + ASCII of a" }, { "code": null, "e": 2009, "s": 2000, "text": "return S" }, { "code": null, "e": 2079, "s": 2009, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2090, "s": 2079, "text": " Live Demo" }, { "code": null, "e": 2570, "s": 2090, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n string shiftingLetters(string S, vector<int>& shifts) {\n for(int i = shifts.size() - 2 ;i >=0; i--){\n shifts[i] += shifts[i + 1];\n shifts[i] %= 26;\n }\n for(int i = 0; i < S.size(); i++) {\n S[i] = ( ((S[i] - 'a') + shifts[i]) % 26 + 'a');\n }\n return S;\n }\n};\nmain(){\n vector<int> v = {3,5,9};\n Solution ob;\n cout << (ob.shiftingLetters(\"abc\", v));\n}" }, { "code": null, "e": 2584, "s": 2570, "text": "\"abc\"\n[3,5,9]" }, { "code": null, "e": 2588, "s": 2584, "text": "rpl" } ]
Koa.js - Quick Guide
A web application framework provides you with a simple API to build websites, web apps, and backends. You need not worry about low level protocols, processes, etc. Koa provides a minimal interface to build applications. It is a very small framework (600 LoC) which provides the required tools to build apps and is quite flexible. There are numerous modules available on npm for Koa, which can be directly plugged into it. Koa can be thought of as the core of express.js without all the bells and whistles. Koa has a small footprint (600 LoC) and is a very thin layer of abstraction over the node to create server side apps. It is completely pluggable and has a huge community. This also allows us to easily extend Koa and use it according to our needs. It is built using the bleeding edge technology (ES6) which gives it an edge over older frameworks such as express. Pug (earlier known as Jade) is a terse language for writing HTML templates. Produces HTML Supports dynamic code Supports reusability (DRY) It is one of the most popular templating language used with Koa. MongoDB is an open-source, document database designed for ease of development and scaling. We'll use this database to store data. Mongoose is a client API for node.js which makes it easy to access our database from our Koa application. To get started with developing using the Koa framework, you need to have Node and npm (node package manager) installed. If you don’t already have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. $ node --version $ npm --version You should receive an output similar to − v5.0.0 3.5.2 Please ensure your node version is above 6.5.0. Now that we have Node and npm set up, let us understand what npm is and how to use it. npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS. There are two ways to install a package using npm − globally and locally. Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following command. $ npm install -g <package-name> Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the −g flag. $ npm install <package-name> Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project. Step 1 − Fire up your terminal/cmd, create a new folder named hello-world and cd into it − Step 2 − Now to create the package.json file using npm, use the following. npm init It’ll ask you for the following information − Just keep pressing enter, and enter your name in the “author name” field. Step 3 − Now we have our package.json file set up, we’ll install Koa. To install Koa and add it in our package.json file, use the following command. $ npm install --save koa To confirm Koa installed correctly, run the following command. $ ls node_modules #(dir node_modules for windows) Tip − The --save flag can be replaced by -S flag. This flag ensures that Koa is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project, we just need to run the command npm install and it’ll find the dependencies in this file and install them for us. This is all we need to start development using the Koa framework. To make our development process a lot easier, we will install a tool from npm, nodemon. What this tool does is, it restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command. $ npm install -g nodemon Now we are all ready to dive into Koa! Once we have set up the development, it is time to start developing our first app using Koa. Create a new file called app.js and type the following in it. var koa = require('koa'); var app = new koa(); app.use(function* (){ this.body = 'Hello world!'; }); app.listen(3000, function(){ console.log('Server running on https://localhost:3000') }); Save the file, go to your terminal and type. $ nodemon app.js This will start the server. To test this app, open your browser and go to https://localhost:3000 and you should receive the following message. The first line imports Koa in our file. We have access to its API through the variable Koa. We use it to create an application and assign it to var app. app.use(function) − This function is a middleware, which gets called whenever our server gets a request. We'll learn more about middleware in the subsequent chapters. The callback function is a generator, which we'll see in the next chapter. The context of this generator is called context in Koa. This context is used to access and modify the request and response objects. We are setting the body of this response to be Hello world!. app.listen(port, function) − This function binds and listens for connections on the specified port. Port is the only required parameter here. The callback function is executed, if the app runs successfully. One of the most exciting new features of JavaScript ES6 is a new breed of function, called a generator. Before generators, the whole script was used to usually execute in a top to bottom order, without an easy way to stop code execution and resuming with the same stack later. Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Generators allow us to stop code execution in between. Hence, let’s take a look at a simple generator. var generator_func = function* (){ yield 1; yield 2; }; var itr = generator_func(); console.log(itr.next()); console.log(itr.next()); console.log(itr.next()); When running the above code, following will be the result. { value: 1, done: false } { value: 2, done: false } { value: undefined, done: true } Let’s look inside the above code. We first create a generator called generator_func(). We created an instance of this weird looking function and assigned it to itr. Then we started calling next() on this itr variable. Calling next() starts the generator and it runs until it hits a yield. Then it returns the object with value and done, where the value has the expression value. This expression can be anything. At this point, it pauses execution. Again when we call this function(next), the generator resumes execution from the last yield point with the function state being the same at the time of pause, till the next yield point. This is done till there are no more yield points in the code. So why are we discussing generators in this tutorial. As you might remember from the hello world program, we used a function* () notation to pass a callback to app.use(). Koa is an object, which contains an array of middleware generator functions, all of which are composed and executed in a stack-like manner upon each request. Koa also implements downstreaming followed by upstreaming of control flow. Take a look at the following example to understand this in a better way. var koa = require('koa'); var app = koa(); app.use(function* (next) { //do something before yielding to next generator function //in line which will be 1st event in downstream console.log("1"); yield next; //do something when the execution returns upstream, //this will be last event in upstream console.log("2"); }); app.use(function* (next) { // This shall be 2nd event downstream console.log("3"); yield next; // This would be 2nd event upstream console.log("4"); }); app.use(function* () { // Here it would be last function downstream console.log("5"); // Set response body this.body = "Hello Generators"; // First event of upstream (from the last to first) console.log("6"); }); app.listen(3000); When running the above code and navigating to https://localhost:3000/ we get the following output on our console. 1 3 5 6 4 2 This is essentially how Koa uses generators. It allows us to create compact middleware using this property and write code for both upstream and downstream functionalities, thus saving us from callbacks. Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the Koa-router module to easily create routes in Koa. Install this module using the following command. npm install --save koa-router Now that we have Koa-router installed, let’s look at a simple GET route example. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); // Define routes function *getMessage() { this.body = "Hello world!"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello". Our Koa app executes the callback function attached to this route and sends "Hello World!" as the response. We can also have multiple different methods at the same route. For example, var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); _.post('/hello', postMessage); function *getMessage() { this.body = "Hello world!"; }; function *postMessage() { this.body = "You just called the post method at '/hello'!\n"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); To test this request, open your terminal and use cURL to execute the following request curl -X POST "https://localhost:3000/hello" A special method, all, is provided by express to handle all types of http methods at a particular route using the same function. To use this method, try the following − _.all('/test', allMessage); function *allMessage(){ this.body = "All HTTP calls regardless of the verb will get this response"; }; We can now define routes; they are either static or fixed. To use dynamic routes, we need to provide different types of routes. Using dynamic routes allow us to pass parameters and process based on them. Following is an example of a dynamic route. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/:id', sendID); function *sendID() { this.body = 'The id you specified is ' + this.params.id; } app.use(_.routes()); app.listen(3000); To test this go to https://localhost:3000/123. You will get the following response. You can replace '123' in the URL with anything else and it'll be reflected in the response. Following is a complex example of the above. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/things/:name/:id', sendIdAndName); function *sendIdAndName(){ this.body = 'id: ' + this.params.id + ' and name: ' + this.params.name; }; app.use(_.routes()); app.listen(3000); To test this go to https://localhost:3000/things/tutorialspoint/12345. You can use the this.params object to access all the parameters you pass in the URL. Note that the above two have different paths. They will never overlap. Also if you want to execute the code when you get '/things', then you need to define it separately. You can also use regex to restrict URL parameter matching. Let's say you need the id to be five digits long number. You can use the following route definition. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/things/:id([0-9]{5})', sendID); function *sendID(){ this.body = 'id: ' + this.params.id; } app.use(_.routes()); app.listen(3000); Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you'll get a Not found message as response. For example, if we define the same routes as above, on requesting with a valid URL, we get − The HTTP method is supplied in the request and specifies the operation that the client has requested. The following table summarizes the commonly used HTTP methods. GET The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. POST The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI. PUT The PUT method requests that the server accept the data enclosed in the request as a modification to the existing object identified by the URI. If it does not exist, then PUT method should create one. DELETE The DELETE method requests that the server delete the specified resource. These are the most common HTTP methods. To learn more about them, head over to https://www.tutorialspoint.com/http/http_methods.htm. A Koa Request object is an abstraction on top of node's vanilla request object, providing additional functionality that is useful for everyday HTTP server development. The Koa request object is embedded in the context object, this. Let’s log out the request object whenever we get a request. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/hello', getMessage); function *getMessage(){ console.log(this.request); this.body = 'Your request has been logged.'; } app.use(_.routes()); app.listen(3000); When you run this code and navigate to https://localhost:3000/hello, then you will receive the following response. On your console, you'll get the request object logged out. { method: 'GET', url: '/hello/', header: { host: 'localhost:3000', connection: 'keep-alive', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36', accept: 'text/html,application/xhtml+xml, application/xml;q = 0.9,image/webp,*/*;q = 0.8', dnt: '1', 'accept-encoding': 'gzip, deflate, sdch', 'accept-language': 'en-US,en;q = 0.8' } } We have access to many useful properties of the request using this object. Let us look at some examples. Provides all the request headers. Provides the request method(GET, POST, etc.) Provides the full request URL. Provides the path of the request. Without query string and base url. Gives the parsed query string. For example, if we log this on a request such as https://localhost:3000/hello/?name=Ayush&age=20&country=India, then we'll get the following object. { name: 'Ayush', age: '20', country: 'India' } This function returns true or false based on whether the requested resources accept the given request type. You can read more about the request object in the docs at Request. A Koa Response object is an abstraction on top of node's vanilla response object, providing additional functionality that is useful for everyday HTTP server development. The Koa response object is embedded in the context object, this. Let’s log out the response object whenever we get a request. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/hello', getMessage); function *getMessage(){ this.body = 'Your request has been logged.'; console.log(this.response); } app.use(_.routes()); app.listen(3000); When you run this code and navigate to https://localhost:3000/hello then you'll receive the following response. On your console, you'll get the request object logged out. { status: 200, message: 'OK', header: { 'content-type': 'text/plain; charset=utf-8', 'content-length': '12' }, body: 'Your request has been logged.' } The status and message are automatically set by Koa but can be modified by us. If we don’t set the response body, the status code is set to 404. Once we set the response body, the status is set to 200 by default. We can explicitly override this behavior. We have access to many useful properties of the response using this object. Let us look at some examples − Provides all the response headers. Provides the response status (200, 404, 500, etc). This property is also used to set the response status. Provides the response message. This property is also used to set custom messages with responses. It is associated with response.status. Get or set the response body. Usually, we access it using the context object. This is just another way to access it. The body could be of the type: String, Buffer, Stream, Object or Null. Get or set the content type of the current response. This function is used to get the values of headers with case insensitive value field. This function is used to set a header on the response using field and value pair. This function is used to unset a header on the response using a field name. You can read more about the response object in the docs at Response. Redirection is very important when creating websites. If a malformed URL is requested or there are some errors on your server, you should redirect them to the respective error pages. Redirects can also be used to keep people out of restricted areas of your website. Let us create an error page and redirect to that page whenever someone requests a malformed URL. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/not_found', printErrorMessage); _.get('/hello', printHelloMessage); app.use(_.routes()); app.use(handle404Errors); function *printErrorMessage() { this.status = 404; this.body = "Sorry we do not have this resource."; } function *printHelloMessage() { this.status = 200; this.body = "Hey there!"; } function *handle404Errors(next) { if (404 != this.status) return; this.redirect('/not_found'); } app.listen(3000); When we run this code and navigate to any route other than /hello, we'll be redirected to /not_found. We have placed the middleware at the end (app.use function call to this middleware). This ensures we reach the middleware at last and send the corresponding response. Following are the results we see when we run the above code. When we navigate to https://localhost:3000/hello, we get − If we navigate to any other route, we get − Error handling plays an important part in building web applications. Koa uses middleware for this purpose as well. In Koa, you add a middleware that does try { yield next } as one of the first middleware. If we encounter any error downstream, we return to the associated catch clause and handle the error here. For example − var koa = require('koa'); var app = koa(); //Error handling middleware app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; this.body = err.message; this.app.emit('error', err, this); } }); //Create an error in the next middleware //Set the error message and status code and throw it using context object app.use(function *(next) { //This will set status and message this.throw('Error Message', 500); }); app.listen(3000); We have deliberately created an error in the above code and are handling the error in our first middleware's catch block. This is then emitted to our console as well as sent as the response to our client. Following is the error message we get when we trigger this error. InternalServerError: Error Message at Object.module.exports.throw (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23) at Object.<anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13) at next (native) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5 at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10) at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63) at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5 Right now any request sent to the server will result in this error. Middleware functions are functions that have access to the context object and the next middleware function in the application’s request-response cycle. These functions are used to modify the request and response objects for tasks such as parsing request bodies, adding response headers, etc. Koa goes a step further by yielding 'downstream', then flowing the control back 'upstream'. This effect is called cascading. Following is a simple example of a middleware function in action. var koa = require('koa'); var app = koa(); var _ = router(); //Simple request time logger app.use(function* (next) { console.log("A new request received at " + Date.now()); //This function call is very important. It tells that more processing is //required for the current request and is in the next middleware function/route handler. yield next; }); app.listen(3000); The above middleware is called for every request on the server. Thus after every request, we will get the following message in the console. A new request received at 1467267512545 To restrict it to a specific route (and all its subroutes), we just need to create the routes like we did for routing. Actually its these middleware only that handle our request. For example, var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Simple request time logger _.get('/request/*', function* (next) { console.log("A new request received at " + Date.now()); yield next; }); app.use(_.routes()); app.listen(3000); Now whenever you request any subroute of '/request', only then it'll log the time. One of the most important things about middleware in Koa is that the order in which they are written/included in your file, are the order in which they are executed downstream. As soon as we hit a yield statement in a middleware, it switches to the next middleware in line, till we reach the last. Then again we start moving back up and resuming functions from yield statements. For example, in the following code snippet, the first function executes first till yield, then the second middleware till yield, then the third. As we have no more middleware here, we start moving back up, executing in a reverse order, i.e., third, second, first. This example summarizes how to use middleware the Koa way. var koa = require('koa'); var app = koa(); //Order of middlewares app.use(first); app.use(second); app.use(third); function *first(next) { console.log("I'll be logged first. "); //Now we yield to the next middleware yield next; //We'll come back here at the end after all other middlewares have ended console.log("I'll be logged last. "); }; function *second(next) { console.log("I'll be logged second. "); yield next; console.log("I'll be logged fifth. "); }; function *third(next) { console.log("I'll be logged third. "); yield next; console.log("I'll be logged fourth. "); }; app.listen(3000); When we visit '/' after running this code, on our console we will get − I'll be logged first. I'll be logged second. I'll be logged third. I'll be logged fourth. I'll be logged fifth. I'll be logged last. The following diagram summarizes what is actually happening in the above example. Now that we know how to create our own middleware, let us discuss some of the most commonly used community created middleware. A list of third party middleware for express is available here. Following are some of the most commonly used middleware − koa-bodyparser koa-router koa-static koa-compress We'll discuss multiple middleware in the subsequent chapters. Pug is a templating engine. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine, which has a variety of features such as filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this. To use Pug with Koa, we need to install it using the following command. $ npm install --save pug koa-pug Once pug is installed, set it as the templating engine for your app. Add the following code to your app.js file. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app //Equivalent to app.use(pug) }); var _ = router(); //Instantiate the router app.use(_.routes()); //Use the routes defined using the router app.listen(3000); Now, create a new directory called views. Inside the directory, create a file named first_view.pug, and enter the following data in it. doctype html html head title = "Hello Pug" body p.greetings#people Hello Views! To run this page, add the following route to your app. _.get('/hello', getMessage); // Define routes function *getMessage(){ this.render('first_view'); }; You'll receive the output as − What Pug does is, it converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to <!DOCTYPE html> <html> <head> <title>Hello Pug</title> </head> <body> <p class = "greetings" id = "people">Hello Views!</p> </body> </html> Pug is capable of doing much more than simplifying HTML markup. Let’s explore some of these features of Pug. Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. However, the <body> tag was on the same indentation, thus it was a sibling of <head> tag. We don’t need to close tags. As soon as Pug encounters the next tag on the same or the outer indentation level, it closes the tag for us. There are three methods to put text inside of a tag − Space seperated − h1 Welcome to Pug Piped text − div | To insert multiline text, | You can use the pipe operator. Block of text − div. But that gets tedious if you have a lot of text. You can use "." at the end of tag to denote block of text. To put tags inside this block, simply enter tag in a new line and indent it accordingly. Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to html comments(<!--comment-->). For example, //This is a Pug comment This comment gets converted to − <!--This is a Pug comment--> To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes, and id for a given html tag. div.container.column.main#division(width = "100",height = "100") This line of code, gets converted to − <div class = "container column main" id = "division" width = "100" height = "100"></div> When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following code. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app // equals to pug.use(app) and app.use(pug.middleware) }); var _ = router(); //Instantiate the router _.get('//dynamic_view', dynamicMessage); // Define routes function *dynamicMessage(){ this.render('dynamic', { name: "TutorialsPoint", url:"https://www.tutorialspoint.com" }); }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); Then, create a new view file in the views directory, named dynamic.pug, using the following code. html head title = name body h1 = name a(href = url) URL Open localhost:3000/dynamic in your browser and following should be the output. − We can also use these passed variables within the text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we want to insert Greetings from TutorialsPoint, then we have to use the following code. html head title = name body h1 Greetings from #{name} a(href = url) URL This method of using values is called interpolation. We can use conditional statements and looping constructs as well. Consider this practical example, if a user is logged in we would want to display "Hi, User" and if not, then we would want to show him a "Login/Sign Up" link. To achieve this, we can define a simple template such as − html head title Simple template body if(user) h1 Hi, #{user.name} else a(href = "/sign_up") Sign Up When we render this using our routes, and if we pass an object like − this.render('/dynamic',{user: {name: "Ayush", age: "20"} }); It'll give a message displaying Hi, Ayush. However, if we don’t pass any object or pass one with no user key, then we will get a Sign up link. Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to every view, we can use an include. Following example shows how we can use an include − Create three views with the following code − div.header. I'm the header for this website. html head title Simple template body include ./header.pug h3 I'm the main content include ./footer.pug div.footer. I'm the footer for this website. Create a route for this as follows. var koa = require('koa'); var router = require('koa-router'); var app = koa(); var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app //Equivalent to app.use(pug) }); var _ = router(); //Instantiate the router _.get('/components', getComponents); function *getComponents(){ this.render('content.pug'); } app.use(_.routes()); //Use the routes defined using the router app.listen(3000); Go to localhost:3000/components, you should get the following output. include can also be used to include plaintext, CSS and JavaScript. There are many other features of Pug. However, those are out of the scope for this tutorial. You can further explore Pug at Pug. Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the koa-body. To install this, go to your terminal and use − $ npm install --save koa-body Replace your app.js file contents with the following code. var koa = require('koa'); var router = require('koa-router'); var bodyParser = require('koa-body'); var app = koa(); //Set up Pug var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app //Equivalent to app.use(pug) }); //Set up body parsing middleware app.use(bodyParser({ formidable:{uploadDir: './uploads'}, multipart: true, urlencoded: true })); _.get('/', renderForm); _.post('/', handleForm); function * renderForm(){ this.render('form'); } function *handleForm(){ console.log(this.request.body); console.log(this.req.body); this.body = this.request.body; //This is where the parsed request is stored } app.use(_.routes()); app.listen(3000); The new things we are doing here are importing the body parser and multer. We are using the body parser for parsing json and x-www-form-urlencoded header requests, while we use multer for parsing multipart/form-data. Let us create a html form to test this out! Create a new view named form.pug with the following code. html head title Form Tester body form(action = "/", method = "POST") div label(for = "say") Say: input(name = "say" value = "Hi") br div label(for = "to") To: input(name = "to" value = "Koa form") br button(type = "submit") Send my greetings Run your server using − nodemon index.js Now go to localhost:3000/ and fill the form as you like, and submit it. You'll receive the response as − Take a look at your console, it'll show you the body of your request as a JavaScript object. For example − The this.request.body object contains your parsed request body. To use fields from that object, just use them as normal JS objects. This is just one way to send a request. There are many other ways, but those are irrelevant to cover here, because our Koa app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page. Web applications need to provide the functionality to allow file uploads. Let us see how we can receive files from the clients and store them on our server. We have already used the koa-body middleware for parsing requests. This middleware is also used for handling file uploads. Let us create a form that allows us to upload files and then save these files using Koa. First create a template named file_upload.pug with the following contents. html head title File uploads body form(action = "/upload" method = "POST" enctype = "multipart/form-data") div input(type = "text" name = "name" placeholder = "Name") div input(type = "file" name = "image") div input(type = "submit") Note that you need to give the same encoding type as above in your form. Now let us handle this data on our server. var koa = require('koa'); var router = require('koa-router'); var bodyParser = require('koa-body'); var app = koa(); //Set up Pug var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app }); //Set up body parsing middleware app.use(bodyParser({ formidable:{uploadDir: './uploads'}, //This is where the files would come multipart: true, urlencoded: true })); var _ = router(); //Instantiate the router _.get('/files', renderForm); _.post('/upload', handleForm); function * renderForm(){ this.render('file_upload'); } function *handleForm(){ console.log("Files: ", this.request.body.files); console.log("Fields: ", this.request.body.fields); this.body = "Received your data!"; //This is where the parsed request is stored } app.use(_.routes()); app.listen(3000); When you run this, you get the following form. When you submit this, your console will produce the following output. The files that were uploaded are stored in the path in the above output. You can access the files in the request using this.request.body.files and the fields in that request by this.request.body.fields. Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default doesn't allow you to serve static files. We need a middleware to serve this purpose. Go ahead and install koa-serve − $ npm install --save koa-static Now we need to use this middleware. Before that create a directory called public. We will store all our static files here. This allows us to keep our server code secure as nothing above this public folder would be accessible to the clients. After you've created a public directory, create a file named hello.txt in it with any content you like. Now add the following to your app.js. var serve = require('koa-static'); var koa = require('koa'); var app = koa(); app.use(serve('./public')); app.listen(3000); Note − Koa looks up the files relative to the static directory, so the name of the static directory is not part of the URL. The root route is now set to your public dir, so all static files you load will be considering public as the root. To test that this is working fine, run your app and visit https://localhost:3000/hello.txt You should get the following output. Note that this is not a HTML document or Pug view, rather it is a simple txt file. We can also set multiple static assets directories using − var serve = require('koa-static'); var koa = require('koa'); var app = koa(); app.use(serve('./public')); app.use(serve('./images')); app.listen(3000); Now when we request a file, Koa will search these directories and send us the matching file. Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps keep track of the users actions. There are numerous uses of HTTP Cookies. Session management Personalization(Recommendation systems) User tracking To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app. var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie() { this.cookies.set('foo', 'bar', {httpOnly: false}); } var _ = router(); app.use(_.routes()); app.listen(3000); To check if the cookie is set or not, just go to your browser, fire up the console, and enter − console.log(document.cookie); This will produce the following output (you may have more cookies set maybe due to extensions in your browser). "foo = bar" Here is an example of the above. The browser also sends back cookies every time it queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route. console.log('Cookies: foo = ', this.cookies.get('foo')); Next time you send a request to this route, you'll get the following output. Cookies: foo = bar You can add cookies that expire. To add a cookie that expires, just pass an object with the property 'expires' set to the time when you want it to expire. For example, var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set('name', 'value', { httpOnly: false, expires: 360000 + Date.now() }); } var _ = router(); app.use(_.routes()); app.listen(3000); To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code. var koa = require('koa'); var router = require('koa-router'); var app = koa(); _.get('/', setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set('name', ''); } var _ = router(); app.use(_.routes()); app.listen(3000); This will unset the said cookie. Note that you should leave the HttpOnly option to be true when not using the cookie in the client side code. HTTP is stateless, hence in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. However, they are both readable on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID. We'll need the koa-session, thus install it using − npm install --save koa-session We will put the koa-session middleware in place. In this example, we'll use the RAM to store sessions. Never use this in production environments. The session middleware handles everything, i.e. creating the session, setting the session cookie, and creating the session object in context object. Whenever we make a request from the same client again, we will have their session information stored with us (given that server was not restarted). We can add more properties to this session object. In the following example, we will create a view counter for a client. var session = require('koa-session'); var koa = require('koa'); var app = koa(); app.keys = ['Shh, its a secret!']; app.use(session(app)); // Include the session middleware app.use(function *(){ var n = this.session.views || 0; this.session.views = ++n; if(n === 1) this.body = 'Welcome here for the first time!'; else this.body = "You've visited this page " + n + " times!"; }) app.listen(3000); What the above code does is, when a user visits the site, it creates a new session for the user and assigns a cookie. Next time the user visits, the cookie is checked and the page_view session variable is updated accordingly. Now if you run the app and go to localhost:3000, you'll get the following response. If you revisit the page, the page counter will increase. In this case, the page was refreshed 12 times. Authentication is a process in which the credentials provided are compared to those on file in the database of authorized users' information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access. We'll be creating a very basic authentication system that'll use Basic HTTP Authentication. This is the simplest possible way to enforce access control as it doesn't require cookies, sessions, or anything else. To use this, the client has to send the Authorization header along with every request it makes. The username and password are not encrypted, but are concatenated in a single string like the following. username:password This string is encoded with Base64, and the word Basic is put before this value. For example, if your username is Ayush and password India, then the string "Ayush:India" would be sent as encoded in the authorization header. Authorization: Basic QXl1c2g6SW5kaWE= To implement this in your koa app, you'll need the koa-basic-auth middleware. Install it using − $ npm install --save koa-basic-auth Now open your app.js file and enter the following code in it. //This is what the authentication would be checked against var credentials = { name: 'Ayush', pass: 'India' } var koa = require('koa'); var auth = require('koa-basic-auth'); var _ = require('koa-router')(); var app = koa(); //Error handling middleware app.use(function *(next){ try { yield next; } catch (err) { if (401 == err.status) { this.status = 401; this.set('WWW-Authenticate', 'Basic'); this.body = 'You have no access here'; } else { throw err; } } }); // Set up authentication here as first middleware. // This returns an error if user is not authenticated. _.get('/protected', auth(credentials), function *(){ this.body = 'You have access to the protected area.'; yield next; }); // No authentication middleware present here. _.get('/unprotected', function*(next){ this.body = "Anyone can access this area"; yield next; }); app.use(_.routes()); app.listen(3000); We have created an error handling middleware to handle all authentication related errors. Then, we have created 2 routes − /protected − This route can only be accessed if the user sends the correct authentication header. For all others, it'll give an error. /protected − This route can only be accessed if the user sends the correct authentication header. For all others, it'll give an error. /unprotected − This route can be accessed by anyone, with or without the authentication. /unprotected − This route can be accessed by anyone, with or without the authentication. Now if you send a request to /protected without an authentication header or with the wrong credentials, you'll receive an error. For example, $ curl https://localhost:3000/protected You'll receive the response as − HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic Content-Type: text/plain; charset=utf-8 Content-Length: 28 Date: Sat, 17 Sep 2016 19:05:56 GMT Connection: keep-alive Please authenticate yourself However, with the right credentials, you'll get the expected response. For example, $ curl -H "Authorization: basic QXl1c2g6SW5kaWE=" https://localhost:3000/protected -i You'll get the response as − HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 38 Date: Sat, 17 Sep 2016 19:07:33 GMT Connection: keep-alive You have access to the protected area. The /unprotected route is still accessible to everyone. Compression is a simple, effective way to save bandwidth and speed up your site. It is only compatible with modern browsers and should be used with caution if your users use legacy browsers as well. When sending responses from the server, if compression is used, it can greatly improve the load time. We'll be using a middleware called koa-compress to take care of the compression of files as well as setting appropriate headers. Go ahead and install the middleware using − $ npm install --save koa-compress Now in your app.js file, add the following code − var koa = require('koa'); var router = require('koa-router'); var app = koa(); var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app //Equivalent to app.use(pug) }); app.use(compress({ filter: function (content_type) { return /text/i.test(content_type) }, threshold: 2048, flush: require('zlib').Z_SYNC_FLUSH })); var _ = router(); //Instantiate the router _.get('/', getRoot); function *getRoot(next){ this.render('index'); } app.use(_.routes()); //Use the routes defined using the router app.listen(3000); This puts our compression middleware in place. The filter option is a function that checks the response content type to decide whether to compress. The threshold option is the minimum response size in bytes to compress. This ensures we don’t compress every little response. Following is a response without compression. Following is the similar response with compression. If you look at the size tab at the bottom, you can very well see the difference between the two. There is more than 150% improvement, when we compress the files. Caching is the term for storing reusable responses in order to make subsequent requests faster. Every browser ships with an implementation of a HTTP cache. All we have to do is ensure that each server response provides correct HTTP header directives to instruct the browser on when and for how long the response can be cached by the browser. Following are some benefits of including caching in your web apps − Your network costs decrease. If your content is cached, you'll need to send less of it for every subsequent request. Your network costs decrease. If your content is cached, you'll need to send less of it for every subsequent request. Speed and performance of your website increases. Speed and performance of your website increases. Your content can be made available even if your client is offline. Your content can be made available even if your client is offline. We'll be using the koa-static-cache middleware to implement caching in our app. Install these middleware using − $ npm install --save koa-static-cache Go to your app.js file and add the following code to it. var koa = require('koa'); var app = koa(); var path = require('path'); var staticCache = require('koa-static-cache'); app.use(staticCache(path.join(__dirname, 'public'), { maxAge: 365 * 24 * 60 * 60 //Add these files to caches for a year })) app.listen(3000); The koa-static-cache middleware is used to cache server responses on the client side. The cache-control header is set according to the options we provide while initializing the cache object. We have set the expiration time of this cached response to 1 year. Following are the comparisons of request we have sent before and after the file was cached. Before this file was cached, the returned status code was 200, which is OK. The response headers had multiple information regarding the content to be cached and had also given an ETag for the content. The next time the request was sent, it was sent along with the ETtag. Since our content hadn't changed on the server, its corresponding ETag also remained the same and the client was told that the copy it has locally is up-to-date with what the server would provide and should use the local one instead of requesting again. Note − For invalidating any cached file, you just need to change its file name and update its reference. This will ensure that you have a new file to send to the client and the client can’t load it back from the cache. We are receiving the requests, but are not storing them anywhere. We need a Database to store the data. We'll use a famous NoSQL database called MongoDB. To install and read about Mongo, head over to this link. In order to use Mongo with Koa, we need a client API for the node. There are multiple options for us, however for this tutorial we'll stick to mongoose. Mongoose is used for document modeling in Node for MongoDB. Document modeling means that, we will create a Model (much like a class in document-oriented programming), and then we will produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these "documents", then finally, we will write these documents in our database. Now that we have Mongo installed, let us install mongoose, the same way we have been installing our other node packages. $ npm install --save mongoose Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter "mongo". A Mongo shell will start, enter the following. use my_db A new database will be created for you. Whenever you open the Mongo shell, it'll default to "test" db and you'll have to change to your database using the same command as above. To use mongoose, we will require it in our app.js file and then connect to the mongod service running on mongodb://localhost var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); app.use(_.routes()); app.listen(3000); Now our app is connected to our database, let’s create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any routes. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.use(_.routes()); app.listen(3000); The above code defines the schema for a person and is used to create a mongoose Model Person. Now we will create a new html form, which will get the details of a person and save it to our database. To create the form, create a new view file called person.pug in the views directory with the following content. html head title Person body form(action = "/person", method = "POST") div label(for = "name") Name: input(name = "name") br div label(for = "age") Age: input(name = "age") br div label(for = "nationality") Nationality: input(name = "nationality") br button(type = "submit") Create new person Also add a new get route in index.js to render this document. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); _.get('/person', getPerson); function *getPerson(next){ this.render('person'); yield next; } app.use(_.routes()); app.listen(3000); Go to localhost:3000/person to check if our form is displaying right. Note that this is just the UI, it’s not working yet. This is how our form looks. We'll now define a post route handler at '/person' which will handle this request. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); _.post('/person', createPerson); function *createPerson(next){ var self = this; var personInfo = self.request.body; //Get the parsed information if(!personInfo.name || !personInfo.age || !personInfo.nationality){ self.render( 'show_message', {message: "Sorry, you provided wrong info", type: "error"}); } else { var newPerson = new Person({ name: personInfo.name, age: personInfo.age, nationality: personInfo.nationality }); yield newPerson.save(function(err, res) { if(err) self.render('show_message', {message: "Database error", type: "error"}); else self.render('show_message', {message: "New person added", type: "success", person: personInfo}); }); } } app.use(_.routes()); app.listen(3000); In the above code, if we receive any empty field or do not receive any field, we will send an error response. However, if we receive a well-formed document, then we create a newPerson document from the Person model and save it to our DB using newPerson.save() function. This is defined in mongoose and accepts a callback as argument. This callback has two arguments, error and response. This will render show_message view, so we need to create that as well. To show the response from this route, we will also need to create a show_message view. Create a new view with the following code. html head title Person body if(type = "error") h3(style = "color:red") #{message} else h3 New person, name: #{person.name}, age: #{person.age} and nationality: #{person.nationality} added! Following is the response we receive on successfully submitting the form (show_message.pug). We now have an interface to create persons! Mongoose provides a lot of functions for retrieving documents, we will focus on three of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response. The three functions are − This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example, this will fetch all the documents from the persons’ collection. Person.find(function(err, response){ console.log(response); }); This will fetch all documents where the field name is "Ayush" and age is 20. Person.find({name: "Ayush", age: 20}, function(err, response){ console.log(response); }); We can also provide the projection we need, i.e., the fields we need. For example, if we want only the names of the people whose nationality is "Indian", we use − Person.find({nationality: "Indian"}, "name", function(err, response) { console.log(response); }); This functions always fetches a single, most relevant document. It has the same exact arguments as Model.find(). This function takes in the _id (defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example, Person.findById("507f1f77bcf86cd799439011", function(err, response){ console.log(response); }); Let's create a route to view all people records. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); _.get('/people', getPeople); function *getPeople(next){ var self = this; yield Person.find(function(err, response){ self.body = response; }); } app.use(_.routes()); app.listen(3000); Mongoose provides three functions to update documents. This function takes a condition and an updates the object as input and applies the changes to all the documents matching the conditions in the collection. For example, the following code will update all Person documents to have a nationality "American". Person.update({age: 25}, {nationality: "American"}, function(err, response){ console.log(response); }); It does exactly what is says. Finds one document based on the query and updates that according to the second argument. It also takes a callback as the last argument. For example, Person.findOneAndUpdate({name: "Ayush"}, {age: 40}, function(err, response){ console.log(response); }); This function updates a single document identified by its id. For example, Person.findByIdAndUpdate("507f1f77bcf86cd799439011", {name: "James"}, function(err, response){ console.log(response); }); Let’s create a route to update people. This will be a PUT route with the id as a parameter and details in the payload. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); _.put('/people/:id', updatePerson); function *updatePerson() { var self = this; yield Person.findByIdAndUpdate(self.params.id, {$set: {self.request.body}}, function(err, response){ if(err) { self.body = { message: "Error in updating person with id " + self.params.id}; } else { self.body = response; } }); } app.use(_.routes()); app.listen(3000); To test this route, enter the following in your terminal (replace the id with an id from your created people). curl -X PUT --data "name = James&age = 20&nationality = American" https://localhost:3000/people/507f1f77bcf86cd799439011 This will update the document associated with the id provided in the route with the above details. We have covered Create, Read and Update, now we'll see how mongoose can be used to Delete documents. There are three functions here, exactly like update. This function takes a condition object as input and removes all the documents matching the conditions. For example, if we need to remove all people aged 20, Person.remove({age:20}); This functions removes a single, most relevant document according to conditions object. For example, Person.findOneAndRemove({name: "Ayush"}); This function removes a single document identified by its id. For example, Person.findByIdAndRemove("507f1f77bcf86cd799439011"); Now let’s create a route to delete people from our database. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); _.delete('/people/:id', deletePerson); function *deletePerson(next){ var self = this; yield Person.findByIdAndRemove(self.params.id, function(err, response){ if(err) { self.body = {message: "Error in deleting record id " + self.params.id}; } else { self.body = {message: "Person with id " + self.params.id + " removed."}; } }); } app.use(_.routes()); app.listen(3000); To test this out, use the following curl command − curl -X DELETE https://localhost:3000/people/507f1f77bcf86cd799439011 This will remove the person with the given id producing the following message. − {message: "Person with id 507f1f77bcf86cd799439011 removed."} This wraps up how we can create simple CRUD applications using MongoDB, mongoose and Koa. To explore mongoose further, read the API docs. To create mobile applications, single page applications, use AJAX calls and provide data to clients, you'll need an API. A popular architectural style of how to structure and name these APIs and the endpoints is called REST(Representational Transfer State). HTTP 1.1 was designed keeping REST principles in mind. REST was introduced by Roy Fielding in 2000 in his paper Fielding Dissertations. RESTful URIs and methods provide us with almost all information we need to process a request. The following table summarizes how the various verbs should be used and how URIs should be named. We'll be creating a movies API towards the end, so let’s discuss how it'll be structured. Now let’s create this API in Koa. We will be using JSON as our transport data format as it is easy to work with in JavaScript and has loads of other benefits. Replace your index.js file with the following − var koa = require('koa'); var router = require('koa-router'); var bodyParser = require('koa-body'); var app = koa(); //Set up body parsing middleware app.use(bodyParser({ formidable:{uploadDir: './uploads'}, multipart: true, urlencoded: true })); //Require the Router we defined in movies.js var movies = require('./movies.js'); //Use the Router on the sub route /movies app.use(movies.routes()); app.listen(3000); Now that we have our application set up, let us concentrate on creating the API. First set up the movies.js file. We are not using a database to store the movies but are storing them in memory, so every time the server restarts the movies added by us will vanish. This can easily be mimicked using a database or a file (using node fs module). Import koa-router, create a Router and export it using module.exports. var Router = require('koa-router'); var router = Router({ prefix: '/movies' }); //Prefixed all routes with /movies var movies = [ {id: 101, name: "Fight Club", year: 1999, rating: 8.1}, {id: 102, name: "Inception", year: 2010, rating: 8.7}, {id: 103, name: "The Dark Knight", year: 2008, rating: 9}, {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9} ]; //Routes will go here module.exports = router; Define the GET route for getting all the movies. router.get('/', sendMovies); function *sendMovies(next){ this.body = movies; yield next; } That's it. To test out if this is working fine, run your app, then open your terminal and enter − curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies You'll get the following response − [{"id":101,"name":"Fight Club","year":1999,"rating":8.1},{"id":102,"name":"Inception","year":2010,"rating":8.7}, {"id":103,"name":"The Dark Knight","year":2008,"rating":9},{"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}] We have a route to get all the movies. Now let’s create a route to get a specific movie by its id. router.get('/:id([0-9]{3,})', sendMovieWithId); function *sendMovieWithId(next){ var ctx = this; var currMovie = movies.filter(function(movie){ if(movie.id == ctx.params.id){ return true; } }); if(currMovie.length == 1){ this.body = currMovie[0]; } else { this.response.status = 404;//Set status to 404 as movie was not found this.body = {message: "Not Found"}; } yield next; } This will get us the movies according to the id that we provide. To test this out, use the following command in your terminal. curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies/101 You'll get the response as − {"id":101,"name":"Fight Club","year":1999,"rating":8.1} If you visit an invalid route, it'll produce a cannot GET error, while if you visit a valid route with an id that doesn’t exist, it'll produce a 404 error. We are done with the GET routes. Now, let’s move on to POST route. Use the following route to handle the POSTed data. router.post('/', addNewMovie); function *addNewMovie(next){ //Check if all fields are provided and are valid: if(!this.request.body.name || !this.request.body.year.toString().match(/^[0-9]{4}$/g) || !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){ this.response.status = 400; this.body = {message: "Bad Request"}; } else { var newId = movies[movies.length-1].id+1; movies.push({ id: newId, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }); this.body = {message: "New movie created.", location: "/movies/" + newId}; } yield next; } This will create a new movie and store it in the movies variable. To test this route out, enter the following in your terminal − curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5" https://localhost:3000/movies You'll get the following response − {"message":"New movie created.","location":"/movies/105"} To test if this was added to the movies object, run the get request for /movies/105 again. You'll get the following response − {"id":105,"name":"Toy story","year":"1995","rating":"8.5"} Let’s move on to create the PUT and DELETE routes. The PUT route is almost exactly the same as the POST route. We will be specifying the id for the object that'll be updated/created. Create the route in the following way − router.put('/:id', updateMovieWithId); function *updateMovieWithId(next){ //Check if all fields are provided and are valid: if(!this.request.body.name || !this.request.body.year.toString().match(/^[0-9]{4}$/g) || !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g) || !this.params.id.toString().match(/^[0-9]{3,}$/g)){ this.response.status = 400; this.body = {message: "Bad Request"}; } else { //Gets us the index of movie with given id. var updateIndex = movies.map(function(movie){ return movie.id; }).indexOf(parseInt(this.params.id)); if(updateIndex === -1){ //Movie not found, create new movies.push({ id: this.params.id, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }); this.body = {message: "New movie created.", location: "/movies/" + this.params.id}; } else { //Update existing movie movies[updateIndex] = { id: this.params.id, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }; this.body = {message: "Movie id " + this.params.id + " updated.", location: "/movies/" + this.params.id}; } } } This route will do the function we specified in the table above. It'll update the object with new details if it exists. If it doesn't exist, it'll create a new object. To test out this route, use the following curl command. This will update an existing movie. To create a new Movie, just change the id to a non-existing id. curl -X PUT --data "name = Toy%20story&year = 1995&rating = 8.5" https://localhost:3000/movies/101 {"message":"Movie id 101 updated.","location":"/movies/101"} Use the following code to create a delete route. router.delete('/:id', deleteMovieWithId); function *deleteMovieWithId(next){ var removeIndex = movies.map(function(movie){ return movie.id; }).indexOf(this.params.id); //Gets us the index of movie with given id. if(removeIndex === -1){ this.body = {message: "Not found"}; } else { movies.splice(removeIndex, 1); this.body = {message: "Movie id " + this.params.id + " removed."}; } } Test the route in the same way we did for the others. On successful deletion (for example id 105), you will get − {message: "Movie id 105 removed."} Finally, our movies.js file looks like − var Router = require('koa-router'); var router = Router({ prefix: '/movies' }); //Prefixed all routes with /movies var movies = [ {id: 101, name: "Fight Club", year: 1999, rating: 8.1}, {id: 102, name: "Inception", year: 2010, rating: 8.7}, {id: 103, name: "The Dark Knight", year: 2008, rating: 9}, {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9} ]; //Routes will go here router.get('/', sendMovies); router.get('/:id([0-9]{3,})', sendMovieWithId); router.post('/', addNewMovie); router.put('/:id', updateMovieWithId); router.delete('/:id', deleteMovieWithId); function *deleteMovieWithId(next){ var removeIndex = movies.map(function(movie){ return movie.id; }).indexOf(this.params.id); //Gets us the index of movie with given id. if(removeIndex === -1){ this.body = {message: "Not found"}; } else { movies.splice(removeIndex, 1); this.body = {message: "Movie id " + this.params.id + " removed."}; } } function *updateMovieWithId(next) { //Check if all fields are provided and are valid: if(!this.request.body.name || !this.request.body.year.toString().match(/^[0-9]{4}$/g) || !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g) || !this.params.id.toString().match(/^[0-9]{3,}$/g)){ this.response.status = 400; this.body = {message: "Bad Request"}; } else { //Gets us the index of movie with given id. var updateIndex = movies.map(function(movie){ return movie.id; }).indexOf(parseInt(this.params.id)); if(updateIndex === -1){ //Movie not found, create new movies.push({ id: this.params.id, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }); this.body = {message: "New movie created.", location: "/movies/" + this.params.id}; } else { //Update existing movie movies[updateIndex] = { id: this.params.id, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }; this.body = {message: "Movie id " + this.params.id + " updated.", location: "/movies/" + this.params.id}; } } } function *addNewMovie(next){ //Check if all fields are provided and are valid: if(!this.request.body.name || !this.request.body.year.toString().match(/^[0-9]{4}$/g) || !this.request.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){ this.response.status = 400; this.body = {message: "Bad Request"}; } else { var newId = movies[movies.length-1].id+1; movies.push({ id: newId, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }); this.body = {message: "New movie created.", location: "/movies/" + newId}; } yield next; } function *sendMovies(next){ this.body = movies; yield next; } function *sendMovieWithId(next){ var ctx = this var currMovie = movies.filter(function(movie){ if(movie.id == ctx.params.id){ return true; } }); if(currMovie.length == 1){ this.body = currMovie[0]; } else { this.response.status = 404;//Set status to 404 as movie was not found this.body = {message: "Not Found"}; } yield next; } module.exports = router; This completes our REST API. Now you can create much more complex applications using this simple architectural style and Koa. Logging is quite useful when creating web applications as they tell us where exactly things went wrong. We also get the context for the things that went wrong and can come up with possible solutions for the same. To enable logging in Koa, we need the middleware, koa-logger. Install it using the following command. $ npm install --save-dev koa-logger Now in your application, add the following code to enable logging. var logger = require('koa-logger') var koa = require('koa') var app = koa() app.use(logger()) app.use(function*(){ this.body = "Hello Logger"; }) app.listen(3000) Run this server and visit any route on the server. You should see the logs like − Now if you get an error on a specific route or request, these logs should help you figure out what went wrong in each of them. Scaffolding allows us to easily create a skeleton for a web application. We manually created our public directory, added middleware, created separate route files, etc. A scaffolding tool sets up all these things for us so that we can directly get started with building our application. The scaffolder we'll use is called Yeoman. It is a scaffolding tool built for Node.js but also has generators for several other frameworks (such as flask, rails, django, etc.). To install yeoman, enter the following command in your terminal. $ npm install -g yeoman Yeoman uses generators to scaffold out applications. To check out the generators available on npm to use with yeoman, head over here. For the purpose of this tutorial, we'll use the 'generator-koa'. To install this generator, enter the following command in your terminal. $ npm install -g generator-koa To use this generator, enter − yo koa Then it'll create a directory structure and will create the following files for you. It'll also install the necessary npm modules and bower components for you. create package.json create test/routeSpec.js create views/layout.html create views/list.html create public/styles/main.css create public/scripts/.gitkeep create controllers/messages.js create app.js create .editorconfig create .jshintrc I'm all done. Running npm install & bower install for you to install the required dependencies. If this fails, try running the command yourself. This generator creates a very simple structure for us. . ├── controllers │ └── messages.js ├── public | ├── scripts | └── styles | └── main.css ├── test | └── routeSpec.js ├── views | ├── layout.html | └── list.html ├── .editorconfig ├── .jshintrc ├── app.js └── package.json Explore the many generators available for Koa and choose the one that fits you right. Steps to working with all generators is the same. You'll need to install a generator, run it using yeoman, it'll ask you some questions and then create a skeleton for your application based on your answers. Following is a list of resources we have used while developing this tutorial − Koajs.com Koajs.com Koajs - Examples A list of examples created by the community Koajs - Examples A list of examples created by the community List of official and 3rd party middlewares. List of official and 3rd party middlewares. A CRUD API using koa.js - A short screencast that goes through creating a CRUD API in Koa.js A CRUD API using koa.js - A short screencast that goes through creating a CRUD API in Koa.js Koa.js Quickstart screencast Koa.js Quickstart screencast Introduction to Koa.js and generators Introduction to Koa.js and generators Print Add Notes Bookmark this page
[ { "code": null, "e": 2270, "s": 2106, "text": "A web application framework provides you with a simple API to build websites, web apps, and backends. You need not worry about low level protocols, processes, etc." }, { "code": null, "e": 2612, "s": 2270, "text": "Koa provides a minimal interface to build applications. It is a very small framework (600 LoC) which provides the required tools to build apps and is quite flexible. There are numerous modules available on npm for Koa, which can be directly plugged into it. Koa can be thought of as the core of express.js without all the bells and whistles." }, { "code": null, "e": 2974, "s": 2612, "text": "Koa has a small footprint (600 LoC) and is a very thin layer of abstraction over the node to create server side apps. It is completely pluggable and has a huge community. This also allows us to easily extend Koa and use it according to our needs. It is built using the bleeding edge technology (ES6) which gives it an edge over older frameworks such as express." }, { "code": null, "e": 3050, "s": 2974, "text": "Pug (earlier known as Jade) is a terse language for writing HTML templates." }, { "code": null, "e": 3064, "s": 3050, "text": "Produces HTML" }, { "code": null, "e": 3086, "s": 3064, "text": "Supports dynamic code" }, { "code": null, "e": 3113, "s": 3086, "text": "Supports reusability (DRY)" }, { "code": null, "e": 3178, "s": 3113, "text": "It is one of the most popular templating language used with Koa." }, { "code": null, "e": 3308, "s": 3178, "text": "MongoDB is an open-source, document database designed for ease of development and scaling. We'll use this database to store data." }, { "code": null, "e": 3414, "s": 3308, "text": "Mongoose is a client API for node.js which makes it easy to access our database from our Koa application." }, { "code": null, "e": 3721, "s": 3414, "text": "To get started with developing using the Koa framework, you need to have Node and npm (node package manager) installed. If you don’t already have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal." }, { "code": null, "e": 3755, "s": 3721, "text": "$ node --version\n$ npm --version\n" }, { "code": null, "e": 3797, "s": 3755, "text": "You should receive an output similar to −" }, { "code": null, "e": 3811, "s": 3797, "text": "v5.0.0\n3.5.2\n" }, { "code": null, "e": 3946, "s": 3811, "text": "Please ensure your node version is above 6.5.0. Now that we have Node and npm set up, let us understand what npm is and how to use it." }, { "code": null, "e": 4313, "s": 3946, "text": "npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS." }, { "code": null, "e": 4387, "s": 4313, "text": "There are two ways to install a package using npm − globally and locally." }, { "code": null, "e": 4539, "s": 4387, "text": "Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following command." }, { "code": null, "e": 4572, "s": 4539, "text": "$ npm install -g <package-name>\n" }, { "code": null, "e": 4813, "s": 4572, "text": "Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the −g flag." }, { "code": null, "e": 4843, "s": 4813, "text": "$ npm install <package-name>\n" }, { "code": null, "e": 5053, "s": 4843, "text": "Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project." }, { "code": null, "e": 5144, "s": 5053, "text": "Step 1 − Fire up your terminal/cmd, create a new folder named hello-world and cd into it −" }, { "code": null, "e": 5219, "s": 5144, "text": "Step 2 − Now to create the package.json file using npm, use the following." }, { "code": null, "e": 5229, "s": 5219, "text": "npm init\n" }, { "code": null, "e": 5275, "s": 5229, "text": "It’ll ask you for the following information −" }, { "code": null, "e": 5349, "s": 5275, "text": "Just keep pressing enter, and enter your name in the “author name” field." }, { "code": null, "e": 5498, "s": 5349, "text": "Step 3 − Now we have our package.json file set up, we’ll install Koa. To install Koa and add it in our package.json file, use the following command." }, { "code": null, "e": 5524, "s": 5498, "text": "$ npm install --save koa\n" }, { "code": null, "e": 5587, "s": 5524, "text": "To confirm Koa installed correctly, run the following command." }, { "code": null, "e": 5638, "s": 5587, "text": "$ ls node_modules #(dir node_modules for windows)\n" }, { "code": null, "e": 5973, "s": 5638, "text": "Tip − The --save flag can be replaced by -S flag. This flag ensures that Koa is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project, we just need to run the command npm install and it’ll find the dependencies in this file and install them for us." }, { "code": null, "e": 6349, "s": 5973, "text": "This is all we need to start development using the Koa framework. To make our development process a lot easier, we will install a tool from npm, nodemon. What this tool does is, it restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command." }, { "code": null, "e": 6375, "s": 6349, "text": "$ npm install -g nodemon\n" }, { "code": null, "e": 6414, "s": 6375, "text": "Now we are all ready to dive into Koa!" }, { "code": null, "e": 6569, "s": 6414, "text": "Once we have set up the development, it is time to start developing our first app using Koa. Create a new file called app.js and type the following in it." }, { "code": null, "e": 6767, "s": 6569, "text": "var koa = require('koa');\nvar app = new koa();\n\napp.use(function* (){\n this.body = 'Hello world!';\n});\n\napp.listen(3000, function(){\n console.log('Server running on https://localhost:3000')\n});" }, { "code": null, "e": 6812, "s": 6767, "text": "Save the file, go to your terminal and type." }, { "code": null, "e": 6830, "s": 6812, "text": "$ nodemon app.js\n" }, { "code": null, "e": 6973, "s": 6830, "text": "This will start the server. To test this app, open your browser and go to https://localhost:3000 and you should receive the following message." }, { "code": null, "e": 7126, "s": 6973, "text": "The first line imports Koa in our file. We have access to its API through the variable Koa. We use it to create an application and assign it to var app." }, { "code": null, "e": 7561, "s": 7126, "text": "app.use(function) − This function is a middleware, which gets called whenever our server gets a request. We'll learn more about middleware in the subsequent chapters. The callback function is a generator, which we'll see in the next chapter. The context of this generator is called context in Koa. This context is used to access and modify the request and response objects. We are setting the body of this response to be Hello world!." }, { "code": null, "e": 7768, "s": 7561, "text": "app.listen(port, function) − This function binds and listens for connections on the specified port. Port is the only required parameter here. The callback function is executed, if the app runs successfully." }, { "code": null, "e": 8181, "s": 7768, "text": "One of the most exciting new features of JavaScript ES6 is a new breed of function, called a generator. Before generators, the whole script was used to usually execute in a top to bottom order, without an easy way to stop code execution and resuming with the same stack later. Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances." }, { "code": null, "e": 8284, "s": 8181, "text": "Generators allow us to stop code execution in between. Hence, let’s take a look at a simple generator." }, { "code": null, "e": 8450, "s": 8284, "text": "var generator_func = function* (){\n yield 1;\n yield 2;\n};\n\nvar itr = generator_func();\nconsole.log(itr.next());\nconsole.log(itr.next());\nconsole.log(itr.next());" }, { "code": null, "e": 8509, "s": 8450, "text": "When running the above code, following will be the result." }, { "code": null, "e": 8595, "s": 8509, "text": "{ value: 1, done: false }\n{ value: 2, done: false }\n{ value: undefined, done: true }\n" }, { "code": null, "e": 8813, "s": 8595, "text": "Let’s look inside the above code. We first create a generator called generator_func(). We created an instance of this weird looking function and assigned it to itr. Then we started calling next() on this itr variable." }, { "code": null, "e": 9291, "s": 8813, "text": "Calling next() starts the generator and it runs until it hits a yield. Then it returns the object with value and done, where the value has the expression value. This expression can be anything. At this point, it pauses execution. Again when we call this function(next), the generator resumes execution from the last yield point with the function state being the same at the time of pause, till the next yield point. This is done till there are no more yield points in the code." }, { "code": null, "e": 9695, "s": 9291, "text": "So why are we discussing generators in this tutorial. As you might remember from the hello world program, we used a function* () notation to pass a callback to app.use(). Koa is an object, which contains an array of middleware generator functions, all of which are composed and executed in a stack-like manner upon each request. Koa also implements downstreaming followed by upstreaming of control flow." }, { "code": null, "e": 9768, "s": 9695, "text": "Take a look at the following example to understand this in a better way." }, { "code": null, "e": 10543, "s": 9768, "text": "var koa = require('koa');\nvar app = koa();\n \napp.use(function* (next) {\n //do something before yielding to next generator function \n \n //in line which will be 1st event in downstream\n console.log(\"1\");\n yield next;\n \n //do something when the execution returns upstream, \n //this will be last event in upstream\n console.log(\"2\");\n});\napp.use(function* (next) {\n // This shall be 2nd event downstream\n console.log(\"3\");\n yield next;\n \n // This would be 2nd event upstream\n console.log(\"4\");\n});\napp.use(function* () { \n // Here it would be last function downstream\n console.log(\"5\");\n \n // Set response body\n this.body = \"Hello Generators\";\n\n // First event of upstream (from the last to first)\n console.log(\"6\");\n});\n\napp.listen(3000);" }, { "code": null, "e": 10657, "s": 10543, "text": "When running the above code and navigating to https://localhost:3000/ we get the following output on our console." }, { "code": null, "e": 10670, "s": 10657, "text": "1\n3\n5\n6\n4\n2\n" }, { "code": null, "e": 10873, "s": 10670, "text": "This is essentially how Koa uses generators. It allows us to create compact middleware using this property and write code for both upstream and downstream functionalities, thus saving us from callbacks." }, { "code": null, "e": 11135, "s": 10873, "text": "Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the Koa-router module to easily create routes in Koa. Install this module using the following command." }, { "code": null, "e": 11166, "s": 11135, "text": "npm install --save koa-router\n" }, { "code": null, "e": 11247, "s": 11166, "text": "Now that we have Koa-router installed, let’s look at a simple GET route example." }, { "code": null, "e": 11583, "s": 11247, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router(); //Instantiate the router\n_.get('/hello', getMessage); // Define routes\n\nfunction *getMessage() {\n this.body = \"Hello world!\";\n};\n\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 11802, "s": 11583, "text": "If we run our application and go to localhost:3000/hello, the server receives a get request at route \"/hello\". Our Koa app executes the callback function attached to this route and sends \"Hello World!\" as the response." }, { "code": null, "e": 11878, "s": 11802, "text": "We can also have multiple different methods at the same route. For example," }, { "code": null, "e": 12295, "s": 11878, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router(); //Instantiate the router\n\n_.get('/hello', getMessage);\n_.post('/hello', postMessage);\n\nfunction *getMessage() {\n\tthis.body = \"Hello world!\";\n};\nfunction *postMessage() {\n this.body = \"You just called the post method at '/hello'!\\n\";\n};\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 12382, "s": 12295, "text": "To test this request, open your terminal and use cURL to execute the following request" }, { "code": null, "e": 12427, "s": 12382, "text": "curl -X POST \"https://localhost:3000/hello\"\n" }, { "code": null, "e": 12596, "s": 12427, "text": "A special method, all, is provided by express to handle all types of http methods at a particular route using the same function. To use this method, try the following −" }, { "code": null, "e": 12731, "s": 12596, "text": "_.all('/test', allMessage);\n\nfunction *allMessage(){\n this.body = \"All HTTP calls regardless of the verb will get this response\";\n};" }, { "code": null, "e": 12979, "s": 12731, "text": "We can now define routes; they are either static or fixed. To use dynamic routes, we need to provide different types of routes. Using dynamic routes allow us to pass parameters and process based on them. Following is an example of a dynamic route." }, { "code": null, "e": 13225, "s": 12979, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router();\n\n_.get('/:id', sendID);\n\nfunction *sendID() {\n this.body = 'The id you specified is ' + this.params.id;\n}\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 13309, "s": 13225, "text": "To test this go to https://localhost:3000/123. You will get the following response." }, { "code": null, "e": 13446, "s": 13309, "text": "You can replace '123' in the URL with anything else and it'll be reflected in the response. Following is a complex example of the above." }, { "code": null, "e": 13735, "s": 13446, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router();\n\n_.get('/things/:name/:id', sendIdAndName);\n\nfunction *sendIdAndName(){\n this.body = 'id: ' + this.params.id + ' and name: ' + this.params.name;\n};\n\napp.use(_.routes());\n\napp.listen(3000);" }, { "code": null, "e": 13806, "s": 13735, "text": "To test this go to https://localhost:3000/things/tutorialspoint/12345." }, { "code": null, "e": 14062, "s": 13806, "text": "You can use the this.params object to access all the parameters you pass in the URL. Note that the above two have different paths. They will never overlap. Also if you want to execute the code when you get '/things', then you need to define it separately." }, { "code": null, "e": 14222, "s": 14062, "text": "You can also use regex to restrict URL parameter matching. Let's say you need the id to be five digits long number. You can use the following route definition." }, { "code": null, "e": 14464, "s": 14222, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router();\n\n_.get('/things/:id([0-9]{5})', sendID);\n\nfunction *sendID(){\n this.body = 'id: ' + this.params.id;\n}\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 14687, "s": 14464, "text": "Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you'll get a Not found message as response." }, { "code": null, "e": 14780, "s": 14687, "text": "For example, if we define the same routes as above, on requesting with a valid URL, we get −" }, { "code": null, "e": 14945, "s": 14780, "text": "The HTTP method is supplied in the request and specifies the operation that the client has requested. The following table summarizes the commonly used HTTP methods." }, { "code": null, "e": 14949, "s": 14945, "text": "GET" }, { "code": null, "e": 15095, "s": 14949, "text": "The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect." }, { "code": null, "e": 15100, "s": 15095, "text": "POST" }, { "code": null, "e": 15243, "s": 15100, "text": "The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI." }, { "code": null, "e": 15247, "s": 15243, "text": "PUT" }, { "code": null, "e": 15448, "s": 15247, "text": "The PUT method requests that the server accept the data enclosed in the request as a modification to the existing object identified by the URI. If it does not exist, then PUT method should create one." }, { "code": null, "e": 15455, "s": 15448, "text": "DELETE" }, { "code": null, "e": 15529, "s": 15455, "text": "The DELETE method requests that the server delete the specified resource." }, { "code": null, "e": 15662, "s": 15529, "text": "These are the most common HTTP methods. To learn more about them, head over to https://www.tutorialspoint.com/http/http_methods.htm." }, { "code": null, "e": 15954, "s": 15662, "text": "A Koa Request object is an abstraction on top of node's vanilla request object, providing additional functionality that is useful for everyday HTTP server development. The Koa request object is embedded in the context object, this. Let’s log out the request object whenever we get a request." }, { "code": null, "e": 16226, "s": 15954, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router();\n\n_.get('/hello', getMessage);\n\nfunction *getMessage(){\n console.log(this.request);\n this.body = 'Your request has been logged.';\n}\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 16341, "s": 16226, "text": "When you run this code and navigate to https://localhost:3000/hello, then you will receive the following response." }, { "code": null, "e": 16400, "s": 16341, "text": "On your console, you'll get the request object logged out." }, { "code": null, "e": 16922, "s": 16400, "text": "{ \n method: 'GET',\n url: '/hello/',\n header: \n { \n host: 'localhost:3000',\n connection: 'keep-alive',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) \n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',\n accept: 'text/html,application/xhtml+xml,\n application/xml;q = 0.9,image/webp,*/*;q = 0.8',\n dnt: '1',\n 'accept-encoding': 'gzip, deflate, sdch',\n 'accept-language': 'en-US,en;q = 0.8' \n }\n}\n" }, { "code": null, "e": 17027, "s": 16922, "text": "We have access to many useful properties of the request using this object. Let us look at some examples." }, { "code": null, "e": 17061, "s": 17027, "text": "Provides all the request headers." }, { "code": null, "e": 17106, "s": 17061, "text": "Provides the request method(GET, POST, etc.)" }, { "code": null, "e": 17137, "s": 17106, "text": "Provides the full request URL." }, { "code": null, "e": 17206, "s": 17137, "text": "Provides the path of the request. Without query string and base url." }, { "code": null, "e": 17386, "s": 17206, "text": "Gives the parsed query string. For example, if we log this on a request such as https://localhost:3000/hello/?name=Ayush&age=20&country=India, then we'll get the following object." }, { "code": null, "e": 17443, "s": 17386, "text": "{\n name: 'Ayush',\n age: '20',\n country: 'India'\n}\n" }, { "code": null, "e": 17551, "s": 17443, "text": "This function returns true or false based on whether the requested resources accept the given request type." }, { "code": null, "e": 17618, "s": 17551, "text": "You can read more about the request object in the docs at Request." }, { "code": null, "e": 17914, "s": 17618, "text": "A Koa Response object is an abstraction on top of node's vanilla response object, providing additional functionality that is useful for everyday HTTP server development. The Koa response object is embedded in the context object, this. Let’s log out the response object whenever we get a request." }, { "code": null, "e": 18188, "s": 17914, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router();\n\n_.get('/hello', getMessage);\n\nfunction *getMessage(){\n this.body = 'Your request has been logged.';\n console.log(this.response);\n}\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 18300, "s": 18188, "text": "When you run this code and navigate to https://localhost:3000/hello then you'll receive the following response." }, { "code": null, "e": 18359, "s": 18300, "text": "On your console, you'll get the request object logged out." }, { "code": null, "e": 18545, "s": 18359, "text": "{ \n status: 200,\n message: 'OK',\n header: \n {\n 'content-type': 'text/plain; charset=utf-8',\n 'content-length': '12' \n },\n body: 'Your request has been logged.' \n}\n" }, { "code": null, "e": 18800, "s": 18545, "text": "The status and message are automatically set by Koa but can be modified by us. If we don’t set the response body, the status code is set to 404. Once we set the response body, the status is set to 200 by default. We can explicitly override this behavior." }, { "code": null, "e": 18907, "s": 18800, "text": "We have access to many useful properties of the response using this object. Let us look at some examples −" }, { "code": null, "e": 18942, "s": 18907, "text": "Provides all the response headers." }, { "code": null, "e": 19048, "s": 18942, "text": "Provides the response status (200, 404, 500, etc). This property is also used to set the response status." }, { "code": null, "e": 19184, "s": 19048, "text": "Provides the response message. This property is also used to set custom messages with responses. It is associated with response.status." }, { "code": null, "e": 19372, "s": 19184, "text": "Get or set the response body. Usually, we access it using the context object. This is just another way to access it. The body could be of the type: String, Buffer, Stream, Object or Null." }, { "code": null, "e": 19425, "s": 19372, "text": "Get or set the content type of the current response." }, { "code": null, "e": 19511, "s": 19425, "text": "This function is used to get the values of headers with case insensitive value field." }, { "code": null, "e": 19593, "s": 19511, "text": "This function is used to set a header on the response using field and value pair." }, { "code": null, "e": 19669, "s": 19593, "text": "This function is used to unset a header on the response using a field name." }, { "code": null, "e": 19738, "s": 19669, "text": "You can read more about the response object in the docs at Response." }, { "code": null, "e": 20004, "s": 19738, "text": "Redirection is very important when creating websites. If a malformed URL is requested or there are some errors on your server, you should redirect them to the respective error pages. Redirects can also be used to keep people out of restricted areas of your website." }, { "code": null, "e": 20101, "s": 20004, "text": "Let us create an error page and redirect to that page whenever someone requests a malformed URL." }, { "code": null, "e": 20640, "s": 20101, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\nvar _ = router();\n\n_.get('/not_found', printErrorMessage);\n_.get('/hello', printHelloMessage);\n\napp.use(_.routes());\napp.use(handle404Errors);\n\nfunction *printErrorMessage() {\n this.status = 404;\n this.body = \"Sorry we do not have this resource.\";\n}\nfunction *printHelloMessage() {\n this.status = 200;\n this.body = \"Hey there!\";\n}\nfunction *handle404Errors(next) {\n if (404 != this.status) return;\n this.redirect('/not_found');\n}\napp.listen(3000);" }, { "code": null, "e": 20970, "s": 20640, "text": "When we run this code and navigate to any route other than /hello, we'll be redirected to /not_found. We have placed the middleware at the end (app.use function call to this middleware). This ensures we reach the middleware at last and send the corresponding response. Following are the results we see when we run the above code." }, { "code": null, "e": 21029, "s": 20970, "text": "When we navigate to https://localhost:3000/hello, we get −" }, { "code": null, "e": 21073, "s": 21029, "text": "If we navigate to any other route, we get −" }, { "code": null, "e": 21188, "s": 21073, "text": "Error handling plays an important part in building web applications. Koa uses middleware for this purpose as well." }, { "code": null, "e": 21398, "s": 21188, "text": "In Koa, you add a middleware that does try { yield next } as one of the first middleware. If we encounter any error downstream, we return to the associated catch clause and handle the error here. For example −" }, { "code": null, "e": 21905, "s": 21398, "text": "var koa = require('koa');\nvar app = koa();\n\n//Error handling middleware\napp.use(function *(next) {\n try {\n yield next;\n } catch (err) {\n this.status = err.status || 500;\n this.body = err.message;\n this.app.emit('error', err, this);\n }\n});\n\n//Create an error in the next middleware\n//Set the error message and status code and throw it using context object\n\napp.use(function *(next) {\n //This will set status and message\n this.throw('Error Message', 500);\n});\n\napp.listen(3000);" }, { "code": null, "e": 22176, "s": 21905, "text": "We have deliberately created an error in the above code and are handling the error in our first middleware's catch block. This is then emitted to our console as well as sent as the response to our client. Following is the error message we get when we trigger this error." }, { "code": null, "e": 22948, "s": 22176, "text": "InternalServerError: Error Message\n at Object.module.exports.throw \n (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23)\n at Object.<anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13)\n at next (native)\n at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19)\n at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5\n at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10)\n at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63)\n at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29)\n at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7)\n at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5\n" }, { "code": null, "e": 23016, "s": 22948, "text": "Right now any request sent to the server will result in this error." }, { "code": null, "e": 23433, "s": 23016, "text": "Middleware functions are functions that have access to the context object and the next middleware function in the application’s request-response cycle. These functions are used to modify the request and response objects for tasks such as parsing request bodies, adding response headers, etc. Koa goes a step further by yielding 'downstream', then flowing the control back 'upstream'. This effect is called cascading." }, { "code": null, "e": 23499, "s": 23433, "text": "Following is a simple example of a middleware function in action." }, { "code": null, "e": 23887, "s": 23499, "text": "var koa = require('koa');\nvar app = koa();\nvar _ = router();\n\n//Simple request time logger\napp.use(function* (next) {\n console.log(\"A new request received at \" + Date.now());\n \n //This function call is very important. It tells that more processing is \n //required for the current request and is in the next middleware function/route handler.\n yield next;\n});\n\napp.listen(3000);" }, { "code": null, "e": 24027, "s": 23887, "text": "The above middleware is called for every request on the server. Thus after every request, we will get the following message in the console." }, { "code": null, "e": 24068, "s": 24027, "text": "A new request received at 1467267512545\n" }, { "code": null, "e": 24247, "s": 24068, "text": "To restrict it to a specific route (and all its subroutes), we just need to create the routes like we did for routing. Actually its these middleware only that handle our request." }, { "code": null, "e": 24260, "s": 24247, "text": "For example," }, { "code": null, "e": 24545, "s": 24260, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar _ = router();\n\n//Simple request time logger\n_.get('/request/*', function* (next) {\n console.log(\"A new request received at \" + Date.now());\n yield next;\n});\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 24628, "s": 24545, "text": "Now whenever you request any subroute of '/request', only then it'll log the time." }, { "code": null, "e": 25007, "s": 24628, "text": "One of the most important things about middleware in Koa is that the order in which they are written/included in your file, are the order in which they are executed downstream. As soon as we hit a yield statement in a middleware, it switches to the next middleware in line, till we reach the last. Then again we start moving back up and resuming functions from yield statements." }, { "code": null, "e": 25330, "s": 25007, "text": "For example, in the following code snippet, the first function executes first till yield, then the second middleware till yield, then the third. As we have no more middleware here, we start moving back up, executing in a reverse order, i.e., third, second, first. This example summarizes how to use middleware the Koa way." }, { "code": null, "e": 25973, "s": 25330, "text": "var koa = require('koa');\nvar app = koa();\n\n//Order of middlewares\napp.use(first);\napp.use(second);\napp.use(third);\n\nfunction *first(next) {\n console.log(\"I'll be logged first. \");\n \n //Now we yield to the next middleware\n yield next;\n \n //We'll come back here at the end after all other middlewares have ended\n console.log(\"I'll be logged last. \");\n};\n\nfunction *second(next) {\n console.log(\"I'll be logged second. \");\n yield next;\n console.log(\"I'll be logged fifth. \");\n};\n\nfunction *third(next) {\n console.log(\"I'll be logged third. \");\n yield next;\n console.log(\"I'll be logged fourth. \");\n};\n\napp.listen(3000);" }, { "code": null, "e": 26045, "s": 25973, "text": "When we visit '/' after running this code, on our console we will get −" }, { "code": null, "e": 26185, "s": 26045, "text": "I'll be logged first. \nI'll be logged second. \nI'll be logged third. \nI'll be logged fourth. \nI'll be logged fifth. \nI'll be logged last. \n" }, { "code": null, "e": 26267, "s": 26185, "text": "The following diagram summarizes what is actually happening in the above example." }, { "code": null, "e": 26394, "s": 26267, "text": "Now that we know how to create our own middleware, let us discuss some of the most commonly used community created middleware." }, { "code": null, "e": 26516, "s": 26394, "text": "A list of third party middleware for express is available here. Following are some of the most commonly used middleware −" }, { "code": null, "e": 26531, "s": 26516, "text": "koa-bodyparser" }, { "code": null, "e": 26542, "s": 26531, "text": "koa-router" }, { "code": null, "e": 26553, "s": 26542, "text": "koa-static" }, { "code": null, "e": 26566, "s": 26553, "text": "koa-compress" }, { "code": null, "e": 26628, "s": 26566, "text": "We'll discuss multiple middleware in the subsequent chapters." }, { "code": null, "e": 26973, "s": 26628, "text": "Pug is a templating engine. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine, which has a variety of features such as filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this." }, { "code": null, "e": 27045, "s": 26973, "text": "To use Pug with Koa, we need to install it using the following command." }, { "code": null, "e": 27079, "s": 27045, "text": "$ npm install --save pug koa-pug\n" }, { "code": null, "e": 27192, "s": 27079, "text": "Once pug is installed, set it as the templating engine for your app. Add the following code to your app.js file." }, { "code": null, "e": 27540, "s": 27192, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar Pug = require('koa-pug');\nvar pug = new Pug({\n viewPath: './views',\n basedir: './views',\n app: app //Equivalent to app.use(pug)\n});\n\nvar _ = router(); //Instantiate the router\n\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 27676, "s": 27540, "text": "Now, create a new directory called views. Inside the directory, create a file named first_view.pug, and enter the following data in it." }, { "code": null, "e": 27774, "s": 27676, "text": "doctype html\nhtml\n head\n title = \"Hello Pug\"\n body\n p.greetings#people Hello Views!" }, { "code": null, "e": 27829, "s": 27774, "text": "To run this page, add the following route to your app." }, { "code": null, "e": 27933, "s": 27829, "text": "_.get('/hello', getMessage); // Define routes\n\nfunction *getMessage(){\n this.render('first_view');\n};" }, { "code": null, "e": 27964, "s": 27933, "text": "You'll receive the output as −" }, { "code": null, "e": 28200, "s": 27964, "text": "What Pug does is, it converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to" }, { "code": null, "e": 28369, "s": 28200, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Hello Pug</title>\n </head>\n \n <body>\n <p class = \"greetings\" id = \"people\">Hello Views!</p>\n </body>\n</html>" }, { "code": null, "e": 28478, "s": 28369, "text": "Pug is capable of doing much more than simplifying HTML markup. Let’s explore some of these features of Pug." }, { "code": null, "e": 28708, "s": 28478, "text": "Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. However, the <body> tag was on the same indentation, thus it was a sibling of <head> tag." }, { "code": null, "e": 28846, "s": 28708, "text": "We don’t need to close tags. As soon as Pug encounters the next tag on the same or the outer indentation level, it closes the tag for us." }, { "code": null, "e": 28900, "s": 28846, "text": "There are three methods to put text inside of a tag −" }, { "code": null, "e": 28918, "s": 28900, "text": "Space seperated −" }, { "code": null, "e": 28937, "s": 28918, "text": "h1 Welcome to Pug\n" }, { "code": null, "e": 28950, "s": 28937, "text": "Piped text −" }, { "code": null, "e": 29023, "s": 28950, "text": "div\n | To insert multiline text, \n | You can use the pipe operator.\n" }, { "code": null, "e": 29039, "s": 29023, "text": "Block of text −" }, { "code": null, "e": 29257, "s": 29039, "text": "div.\n But that gets tedious if you have a lot of text. \n You can use \".\" at the end of tag to denote block of text. \n To put tags inside this block, simply enter tag in a new line and \n indent it accordingly.\n" }, { "code": null, "e": 29399, "s": 29257, "text": "Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to html comments(<!--comment-->). For example," }, { "code": null, "e": 29424, "s": 29399, "text": "//This is a Pug comment\n" }, { "code": null, "e": 29457, "s": 29424, "text": "This comment gets converted to −" }, { "code": null, "e": 29487, "s": 29457, "text": "<!--This is a Pug comment-->\n" }, { "code": null, "e": 29717, "s": 29487, "text": "To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes, and id for a given html tag." }, { "code": null, "e": 29783, "s": 29717, "text": "div.container.column.main#division(width = \"100\",height = \"100\")\n" }, { "code": null, "e": 29822, "s": 29783, "text": "This line of code, gets converted to −" }, { "code": null, "e": 29912, "s": 29822, "text": "<div class = \"container column main\" id = \"division\" width = \"100\" height = \"100\"></div>\n" }, { "code": null, "e": 30090, "s": 29912, "text": "When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following code." }, { "code": null, "e": 30663, "s": 30090, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar Pug = require('koa-pug');\nvar pug = new Pug({\n viewPath: './views',\n basedir: './views',\n app: app // equals to pug.use(app) and app.use(pug.middleware)\n});\n\nvar _ = router(); //Instantiate the router\n\n_.get('//dynamic_view', dynamicMessage); // Define routes\n\nfunction *dynamicMessage(){\n this.render('dynamic', {\n name: \"TutorialsPoint\", \n url:\"https://www.tutorialspoint.com\"\n });\n};\n\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 30761, "s": 30663, "text": "Then, create a new view file in the views directory, named dynamic.pug, using the following code." }, { "code": null, "e": 30841, "s": 30761, "text": "html\n head\n title = name\n body\n h1 = name\n a(href = url) URL" }, { "code": null, "e": 30923, "s": 30841, "text": "Open localhost:3000/dynamic in your browser and following should be the output. −" }, { "code": null, "e": 31190, "s": 30923, "text": "We can also use these passed variables within the text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we want to insert Greetings from TutorialsPoint, then we have to use the following code." }, { "code": null, "e": 31286, "s": 31190, "text": "html\n head\n title = name\n body\n h1 Greetings from #{name}\n a(href = url) URL" }, { "code": null, "e": 31339, "s": 31286, "text": "This method of using values is called interpolation." }, { "code": null, "e": 31623, "s": 31339, "text": "We can use conditional statements and looping constructs as well. Consider this practical example, if a user is logged in we would want to display \"Hi, User\" and if not, then we would want to show him a \"Login/Sign Up\" link. To achieve this, we can define a simple template such as −" }, { "code": null, "e": 31765, "s": 31623, "text": "html\n head\n title Simple template\n body\n if(user)\n h1 Hi, #{user.name}\n else\n a(href = \"/sign_up\") Sign Up" }, { "code": null, "e": 31835, "s": 31765, "text": "When we render this using our routes, and if we pass an object like −" }, { "code": null, "e": 31900, "s": 31835, "text": "this.render('/dynamic',{user: \n {name: \"Ayush\", age: \"20\"}\n});" }, { "code": null, "e": 32043, "s": 31900, "text": "It'll give a message displaying Hi, Ayush. However, if we don’t pass any object or pass one with no user key, then we will get a Sign up link." }, { "code": null, "e": 32321, "s": 32043, "text": "Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to every view, we can use an include. Following example shows how we can use an include −" }, { "code": null, "e": 32366, "s": 32321, "text": "Create three views with the following code −" }, { "code": null, "e": 32415, "s": 32366, "text": "div.header.\n I'm the header for this website.\n" }, { "code": null, "e": 32548, "s": 32415, "text": "html\n head\n title Simple template\n body\n include ./header.pug\n h3 I'm the main content\n include ./footer.pug" }, { "code": null, "e": 32597, "s": 32548, "text": "div.footer.\n I'm the footer for this website.\n" }, { "code": null, "e": 32633, "s": 32597, "text": "Create a route for this as follows." }, { "code": null, "e": 33080, "s": 32633, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar Pug = require('koa-pug');\nvar pug = new Pug({\n viewPath: './views',\n basedir: './views',\n app: app //Equivalent to app.use(pug)\n});\n\nvar _ = router(); //Instantiate the router\n\n_.get('/components', getComponents);\n\nfunction *getComponents(){\n this.render('content.pug');\n}\n\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 33150, "s": 33080, "text": "Go to localhost:3000/components, you should get the following output." }, { "code": null, "e": 33217, "s": 33150, "text": "include can also be used to include plaintext, CSS and JavaScript." }, { "code": null, "e": 33346, "s": 33217, "text": "There are many other features of Pug. However, those are out of the scope for this tutorial. You can further explore Pug at Pug." }, { "code": null, "e": 33587, "s": 33346, "text": "Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the koa-body. To install this, go to your terminal and use −" }, { "code": null, "e": 33618, "s": 33587, "text": "$ npm install --save koa-body\n" }, { "code": null, "e": 33677, "s": 33618, "text": "Replace your app.js file contents with the following code." }, { "code": null, "e": 34404, "s": 33677, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar bodyParser = require('koa-body');\nvar app = koa();\n\n//Set up Pug\nvar Pug = require('koa-pug');\nvar pug = new Pug({\n viewPath: './views',\n basedir: './views',\n app: app //Equivalent to app.use(pug)\n});\n\n//Set up body parsing middleware\napp.use(bodyParser({\n formidable:{uploadDir: './uploads'},\n multipart: true,\n urlencoded: true\n}));\n\n_.get('/', renderForm);\n_.post('/', handleForm);\n\nfunction * renderForm(){\n this.render('form');\n}\nfunction *handleForm(){\n console.log(this.request.body);\n console.log(this.req.body);\n this.body = this.request.body; //This is where the parsed request is stored\n}\n\napp.use(_.routes()); \napp.listen(3000);" }, { "code": null, "e": 34621, "s": 34404, "text": "The new things we are doing here are importing the body parser and multer. We are using the body parser for parsing json and x-www-form-urlencoded header requests, while we use multer for parsing multipart/form-data." }, { "code": null, "e": 34723, "s": 34621, "text": "Let us create a html form to test this out! Create a new view named form.pug with the following code." }, { "code": null, "e": 35078, "s": 34723, "text": "html\n head\n title Form Tester\n body\n form(action = \"/\", method = \"POST\")\n div\n label(for = \"say\") Say: \n input(name = \"say\" value = \"Hi\")\n br\n div\n label(for = \"to\") To: \n input(name = \"to\" value = \"Koa form\")\n br\n button(type = \"submit\") Send my greetings" }, { "code": null, "e": 35102, "s": 35078, "text": "Run your server using −" }, { "code": null, "e": 35120, "s": 35102, "text": "nodemon index.js\n" }, { "code": null, "e": 35225, "s": 35120, "text": "Now go to localhost:3000/ and fill the form as you like, and submit it. You'll receive the response as −" }, { "code": null, "e": 35332, "s": 35225, "text": "Take a look at your console, it'll show you the body of your request as a JavaScript object. For example −" }, { "code": null, "e": 35464, "s": 35332, "text": "The this.request.body object contains your parsed request body. To use fields from that object, just use them as normal JS objects." }, { "code": null, "e": 35718, "s": 35464, "text": "This is just one way to send a request. There are many other ways, but those are irrelevant to cover here, because our Koa app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page." }, { "code": null, "e": 35875, "s": 35718, "text": "Web applications need to provide the functionality to allow file uploads. Let us see how we can receive files from the clients and store them on our server." }, { "code": null, "e": 36162, "s": 35875, "text": "We have already used the koa-body middleware for parsing requests. This middleware is also used for handling file uploads. Let us create a form that allows us to upload files and then save these files using Koa. First create a template named file_upload.pug with the following contents." }, { "code": null, "e": 36497, "s": 36162, "text": "html\n head\n title File uploads\n body\n form(action = \"/upload\" method = \"POST\" enctype = \"multipart/form-data\")\n div\n input(type = \"text\" name = \"name\" placeholder = \"Name\")\n \n div\n input(type = \"file\" name = \"image\")\n \n div\n input(type = \"submit\")" }, { "code": null, "e": 36613, "s": 36497, "text": "Note that you need to give the same encoding type as above in your form. Now let us handle this data on our server." }, { "code": null, "e": 37459, "s": 36613, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar bodyParser = require('koa-body');\nvar app = koa();\n\n//Set up Pug\nvar Pug = require('koa-pug');\nvar pug = new Pug({\n viewPath: './views',\n basedir: './views',\n app: app \n});\n\n//Set up body parsing middleware\napp.use(bodyParser({\n formidable:{uploadDir: './uploads'}, //This is where the files would come\n multipart: true,\n urlencoded: true\n}));\n\nvar _ = router(); //Instantiate the router\n\n_.get('/files', renderForm);\n_.post('/upload', handleForm);\n\nfunction * renderForm(){\n this.render('file_upload');\n}\n\nfunction *handleForm(){\n console.log(\"Files: \", this.request.body.files);\n console.log(\"Fields: \", this.request.body.fields);\n this.body = \"Received your data!\"; //This is where the parsed request is stored\n}\n\napp.use(_.routes()); \napp.listen(3000);" }, { "code": null, "e": 37506, "s": 37459, "text": "When you run this, you get the following form." }, { "code": null, "e": 37576, "s": 37506, "text": "When you submit this, your console will produce the following output." }, { "code": null, "e": 37779, "s": 37576, "text": "The files that were uploaded are stored in the path in the above output. You can access the files in the request using this.request.body.files and the fields in that request by this.request.body.fields." }, { "code": null, "e": 37946, "s": 37779, "text": "Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default doesn't allow you to serve static files." }, { "code": null, "e": 38023, "s": 37946, "text": "We need a middleware to serve this purpose. Go ahead and install koa-serve −" }, { "code": null, "e": 38056, "s": 38023, "text": "$ npm install --save koa-static\n" }, { "code": null, "e": 38439, "s": 38056, "text": "Now we need to use this middleware. Before that create a directory called public. We will store all our static files here. This allows us to keep our server code secure as nothing above this public folder would be accessible to the clients. After you've created a public directory, create a file named hello.txt in it with any content you like. Now add the following to your app.js." }, { "code": null, "e": 38565, "s": 38439, "text": "var serve = require('koa-static');\nvar koa = require('koa');\nvar app = koa();\n\napp.use(serve('./public'));\n\napp.listen(3000);" }, { "code": null, "e": 38895, "s": 38565, "text": "Note − Koa looks up the files relative to the static directory, so the name of the static directory is not part of the URL. The root route is now set to your public dir, so all static files you load will be considering public as the root. To test that this is working fine, run your app and visit https://localhost:3000/hello.txt" }, { "code": null, "e": 39015, "s": 38895, "text": "You should get the following output. Note that this is not a HTML document or Pug view, rather it is a simple txt file." }, { "code": null, "e": 39074, "s": 39015, "text": "We can also set multiple static assets directories using −" }, { "code": null, "e": 39228, "s": 39074, "text": "var serve = require('koa-static');\nvar koa = require('koa');\nvar app = koa();\n\napp.use(serve('./public'));\napp.use(serve('./images'));\n\napp.listen(3000);" }, { "code": null, "e": 39321, "s": 39228, "text": "Now when we request a file, Koa will search these directories and send us the matching file." }, { "code": null, "e": 39602, "s": 39321, "text": "Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps keep track of the users actions. There are numerous uses of HTTP Cookies." }, { "code": null, "e": 39621, "s": 39602, "text": "Session management" }, { "code": null, "e": 39661, "s": 39621, "text": "Personalization(Recommendation systems)" }, { "code": null, "e": 39675, "s": 39661, "text": "User tracking" }, { "code": null, "e": 39826, "s": 39675, "text": "To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app." }, { "code": null, "e": 40071, "s": 39826, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\n_.get('/', setACookie);\n\nfunction *setACookie() {\n this.cookies.set('foo', 'bar', {httpOnly: false});\n}\n\nvar _ = router();\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 40167, "s": 40071, "text": "To check if the cookie is set or not, just go to your browser, fire up the console, and enter −" }, { "code": null, "e": 40198, "s": 40167, "text": "console.log(document.cookie);\n" }, { "code": null, "e": 40310, "s": 40198, "text": "This will produce the following output (you may have more cookies set maybe due to extensions in your browser)." }, { "code": null, "e": 40323, "s": 40310, "text": "\"foo = bar\"\n" }, { "code": null, "e": 40356, "s": 40323, "text": "Here is an example of the above." }, { "code": null, "e": 40531, "s": 40356, "text": "The browser also sends back cookies every time it queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route." }, { "code": null, "e": 40589, "s": 40531, "text": "console.log('Cookies: foo = ', this.cookies.get('foo'));\n" }, { "code": null, "e": 40666, "s": 40589, "text": "Next time you send a request to this route, you'll get the following output." }, { "code": null, "e": 40686, "s": 40666, "text": "Cookies: foo = bar\n" }, { "code": null, "e": 40854, "s": 40686, "text": "You can add cookies that expire. To add a cookie that expires, just pass an object with the property 'expires' set to the time when you want it to expire. For example," }, { "code": null, "e": 41192, "s": 40854, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\n_.get('/', setACookie);\n\nfunction *setACookie(){\n //Expires after 360000 ms from the time it is set.\n\tthis.cookies.set('name', 'value', { \n httpOnly: false, expires: 360000 + Date.now() });\n}\n\nvar _ = router();\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 41331, "s": 41192, "text": "To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code." }, { "code": null, "e": 41608, "s": 41331, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\n_.get('/', setACookie);\n\nfunction *setACookie(){\n //Expires after 360000 ms from the time it is set.\n this.cookies.set('name', '');\n}\n\nvar _ = router();\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 41750, "s": 41608, "text": "This will unset the said cookie. Note that you should leave the HttpOnly option to be true when not using the cookie in the client side code." }, { "code": null, "e": 42237, "s": 41750, "text": "HTTP is stateless, hence in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. However, they are both readable on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID." }, { "code": null, "e": 42289, "s": 42237, "text": "We'll need the koa-session, thus install it using −" }, { "code": null, "e": 42321, "s": 42289, "text": "npm install --save koa-session\n" }, { "code": null, "e": 42616, "s": 42321, "text": "We will put the koa-session middleware in place. In this example, we'll use the RAM to store sessions. Never use this in production environments. The session middleware handles everything, i.e. creating the session, setting the session cookie, and creating the session object in context object." }, { "code": null, "e": 42885, "s": 42616, "text": "Whenever we make a request from the same client again, we will have their session information stored with us (given that server was not restarted). We can add more properties to this session object. In the following example, we will create a view counter for a client." }, { "code": null, "e": 43314, "s": 42885, "text": "var session = require('koa-session');\nvar koa = require('koa');\nvar app = koa();\n\napp.keys = ['Shh, its a secret!'];\napp.use(session(app)); // Include the session middleware\n\napp.use(function *(){\n var n = this.session.views || 0;\n this.session.views = ++n;\n \n if(n === 1)\n this.body = 'Welcome here for the first time!';\n else\n this.body = \"You've visited this page \" + n + \" times!\";\n})\n\napp.listen(3000);" }, { "code": null, "e": 43540, "s": 43314, "text": "What the above code does is, when a user visits the site, it creates a new session for the user and assigns a cookie. Next time the user visits, the cookie is checked and the page_view session variable is updated accordingly." }, { "code": null, "e": 43624, "s": 43540, "text": "Now if you run the app and go to localhost:3000, you'll get the following response." }, { "code": null, "e": 43728, "s": 43624, "text": "If you revisit the page, the page counter will increase. In this case, the page was refreshed 12 times." }, { "code": null, "e": 44034, "s": 43728, "text": "Authentication is a process in which the credentials provided are compared to those on file in the database of authorized users' information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access." }, { "code": null, "e": 44446, "s": 44034, "text": "We'll be creating a very basic authentication system that'll use Basic HTTP Authentication. This is the simplest possible way to enforce access control as it doesn't require cookies, sessions, or anything else. To use this, the client has to send the Authorization header along with every request it makes. The username and password are not encrypted, but are concatenated in a single string like the following." }, { "code": null, "e": 44465, "s": 44446, "text": "username:password\n" }, { "code": null, "e": 44689, "s": 44465, "text": "This string is encoded with Base64, and the word Basic is put before this value. For example, if your username is Ayush and password India, then the string \"Ayush:India\" would be sent as encoded in the authorization header." }, { "code": null, "e": 44728, "s": 44689, "text": "Authorization: Basic QXl1c2g6SW5kaWE=\n" }, { "code": null, "e": 44825, "s": 44728, "text": "To implement this in your koa app, you'll need the koa-basic-auth middleware. Install it using −" }, { "code": null, "e": 44862, "s": 44825, "text": "$ npm install --save koa-basic-auth\n" }, { "code": null, "e": 44924, "s": 44862, "text": "Now open your app.js file and enter the following code in it." }, { "code": null, "e": 45886, "s": 44924, "text": "//This is what the authentication would be checked against\nvar credentials = { name: 'Ayush', pass: 'India' }\n\nvar koa = require('koa');\nvar auth = require('koa-basic-auth');\nvar _ = require('koa-router')();\n\nvar app = koa();\n\n//Error handling middleware\napp.use(function *(next){\n try {\n yield next;\n } catch (err) {\n if (401 == err.status) {\n this.status = 401;\n this.set('WWW-Authenticate', 'Basic');\n this.body = 'You have no access here';\n } else {\n throw err;\n }\n }\n});\n\n// Set up authentication here as first middleware. \n// This returns an error if user is not authenticated.\n_.get('/protected', auth(credentials), function *(){\n this.body = 'You have access to the protected area.';\n yield next;\n});\n\n// No authentication middleware present here.\n_.get('/unprotected', function*(next){\n this.body = \"Anyone can access this area\";\n yield next;\n});\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 46009, "s": 45886, "text": "We have created an error handling middleware to handle all authentication related errors. Then, we have created 2 routes −" }, { "code": null, "e": 46144, "s": 46009, "text": "/protected − This route can only be accessed if the user sends the correct authentication header. For all others, it'll give an error." }, { "code": null, "e": 46279, "s": 46144, "text": "/protected − This route can only be accessed if the user sends the correct authentication header. For all others, it'll give an error." }, { "code": null, "e": 46368, "s": 46279, "text": "/unprotected − This route can be accessed by anyone, with or without the authentication." }, { "code": null, "e": 46457, "s": 46368, "text": "/unprotected − This route can be accessed by anyone, with or without the authentication." }, { "code": null, "e": 46599, "s": 46457, "text": "Now if you send a request to /protected without an authentication header or with the wrong credentials, you'll receive an error. For example," }, { "code": null, "e": 46640, "s": 46599, "text": "$ curl https://localhost:3000/protected\n" }, { "code": null, "e": 46673, "s": 46640, "text": "You'll receive the response as −" }, { "code": null, "e": 46872, "s": 46673, "text": "HTTP/1.1 401 Unauthorized\nWWW-Authenticate: Basic\nContent-Type: text/plain; charset=utf-8\nContent-Length: 28\nDate: Sat, 17 Sep 2016 19:05:56 GMT\nConnection: keep-alive\n\nPlease authenticate yourself\n" }, { "code": null, "e": 46956, "s": 46872, "text": "However, with the right credentials, you'll get the expected response. For example," }, { "code": null, "e": 47043, "s": 46956, "text": "$ curl -H \"Authorization: basic QXl1c2g6SW5kaWE=\" https://localhost:3000/protected -i\n" }, { "code": null, "e": 47072, "s": 47043, "text": "You'll get the response as −" }, { "code": null, "e": 47247, "s": 47072, "text": "HTTP/1.1 200 OK\nContent-Type: text/plain; charset=utf-8\nContent-Length: 38\nDate: Sat, 17 Sep 2016 19:07:33 GMT\nConnection: keep-alive\n\nYou have access to the protected area.\n" }, { "code": null, "e": 47303, "s": 47247, "text": "The /unprotected route is still accessible to everyone." }, { "code": null, "e": 47502, "s": 47303, "text": "Compression is a simple, effective way to save bandwidth and speed up your site. It is only compatible with modern browsers and should be used with caution if your users use legacy browsers as well." }, { "code": null, "e": 47733, "s": 47502, "text": "When sending responses from the server, if compression is used, it can greatly improve the load time. We'll be using a middleware called koa-compress to take care of the compression of files as well as setting appropriate headers." }, { "code": null, "e": 47777, "s": 47733, "text": "Go ahead and install the middleware using −" }, { "code": null, "e": 47812, "s": 47777, "text": "$ npm install --save koa-compress\n" }, { "code": null, "e": 47862, "s": 47812, "text": "Now in your app.js file, add the following code −" }, { "code": null, "e": 48452, "s": 47862, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar app = koa();\n\nvar Pug = require('koa-pug');\nvar pug = new Pug({\n viewPath: './views',\n basedir: './views',\n app: app //Equivalent to app.use(pug)\n});\n\napp.use(compress({\n filter: function (content_type) {\n return /text/i.test(content_type)\n },\n threshold: 2048,\n flush: require('zlib').Z_SYNC_FLUSH\n}));\n\nvar _ = router(); //Instantiate the router\n\n_.get('/', getRoot);\n\nfunction *getRoot(next){\n this.render('index');\n}\n\napp.use(_.routes()); //Use the routes defined using the router\napp.listen(3000);" }, { "code": null, "e": 48726, "s": 48452, "text": "This puts our compression middleware in place. The filter option is a function that checks the response content type to decide whether to compress. The threshold option is the minimum response size in bytes to compress. This ensures we don’t compress every little response." }, { "code": null, "e": 48771, "s": 48726, "text": "Following is a response without compression." }, { "code": null, "e": 48823, "s": 48771, "text": "Following is the similar response with compression." }, { "code": null, "e": 48985, "s": 48823, "text": "If you look at the size tab at the bottom, you can very well see the difference between the two. There is more than 150% improvement, when we compress the files." }, { "code": null, "e": 49327, "s": 48985, "text": "Caching is the term for storing reusable responses in order to make subsequent requests faster. Every browser ships with an implementation of a HTTP cache. All we have to do is ensure that each server response provides correct HTTP header directives to instruct the browser on when and for how long the response can be cached by the browser." }, { "code": null, "e": 49395, "s": 49327, "text": "Following are some benefits of including caching in your web apps −" }, { "code": null, "e": 49512, "s": 49395, "text": "Your network costs decrease. If your content is cached, you'll need to send less of it for every subsequent request." }, { "code": null, "e": 49629, "s": 49512, "text": "Your network costs decrease. If your content is cached, you'll need to send less of it for every subsequent request." }, { "code": null, "e": 49678, "s": 49629, "text": "Speed and performance of your website increases." }, { "code": null, "e": 49727, "s": 49678, "text": "Speed and performance of your website increases." }, { "code": null, "e": 49794, "s": 49727, "text": "Your content can be made available even if your client is offline." }, { "code": null, "e": 49861, "s": 49794, "text": "Your content can be made available even if your client is offline." }, { "code": null, "e": 49974, "s": 49861, "text": "We'll be using the koa-static-cache middleware to implement caching in our app. Install these middleware using −" }, { "code": null, "e": 50013, "s": 49974, "text": "$ npm install --save koa-static-cache\n" }, { "code": null, "e": 50070, "s": 50013, "text": "Go to your app.js file and add the following code to it." }, { "code": null, "e": 50337, "s": 50070, "text": "var koa = require('koa');\nvar app = koa();\n\nvar path = require('path');\nvar staticCache = require('koa-static-cache');\n\napp.use(staticCache(path.join(__dirname, 'public'), {\n maxAge: 365 * 24 * 60 * 60 //Add these files to caches for a year\n}))\n\napp.listen(3000);" }, { "code": null, "e": 50687, "s": 50337, "text": "The koa-static-cache middleware is used to cache server responses on the client side. The cache-control header is set according to the options we provide while initializing the cache object. We have set the expiration time of this cached response to 1 year. Following are the comparisons of request we have sent before and after the file was cached." }, { "code": null, "e": 50888, "s": 50687, "text": "Before this file was cached, the returned status code was 200, which is OK. The response headers had multiple information regarding the content to be cached and had also given an ETag for the content." }, { "code": null, "e": 51212, "s": 50888, "text": "The next time the request was sent, it was sent along with the ETtag. Since our content hadn't changed on the server, its corresponding ETag also remained the same and the client was told that the copy it has locally is up-to-date with what the server would provide and should use the local one instead of requesting again." }, { "code": null, "e": 51431, "s": 51212, "text": "Note − For invalidating any cached file, you just need to change its file name and update its reference. This will ensure that you have a new file to send to the client and the client can’t load it back from the cache." }, { "code": null, "e": 51642, "s": 51431, "text": "We are receiving the requests, but are not storing them anywhere. We need a Database to store the data. We'll use a famous NoSQL database called MongoDB. To install and read about Mongo, head over to this link." }, { "code": null, "e": 52175, "s": 51642, "text": "In order to use Mongo with Koa, we need a client API for the node. There are multiple options for us, however for this tutorial we'll stick to mongoose. Mongoose is used for document modeling in Node for MongoDB. Document modeling means that, we will create a Model (much like a class in document-oriented programming), and then we will produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these \"documents\", then finally, we will write these documents in our database." }, { "code": null, "e": 52296, "s": 52175, "text": "Now that we have Mongo installed, let us install mongoose, the same way we have been installing our other node packages." }, { "code": null, "e": 52327, "s": 52296, "text": "$ npm install --save mongoose\n" }, { "code": null, "e": 52522, "s": 52327, "text": "Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter \"mongo\". A Mongo shell will start, enter the following." }, { "code": null, "e": 52533, "s": 52522, "text": "use my_db\n" }, { "code": null, "e": 52711, "s": 52533, "text": "A new database will be created for you. Whenever you open the Mongo shell, it'll default to \"test\" db and you'll have to change to your database using the same command as above." }, { "code": null, "e": 52836, "s": 52711, "text": "To use mongoose, we will require it in our app.js file and then connect to the mongod service running on mongodb://localhost" }, { "code": null, "e": 53036, "s": 52836, "text": "var koa = require('koa');\nvar _ = require('koa-router')();\nvar app = koa();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 53232, "s": 53036, "text": "Now our app is connected to our database, let’s create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any routes." }, { "code": null, "e": 53584, "s": 53232, "text": "var koa = require('koa');\nvar _ = require('koa-router')();\nvar app = koa();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 53678, "s": 53584, "text": "The above code defines the schema for a person and is used to create a mongoose Model Person." }, { "code": null, "e": 53894, "s": 53678, "text": "Now we will create a new html form, which will get the details of a person and save it to our database. To create the form, create a new view file called person.pug in the views directory with the following content." }, { "code": null, "e": 54342, "s": 53894, "text": "html\n head\n title Person\n body\n form(action = \"/person\", method = \"POST\")\n div\n label(for = \"name\") Name: \n input(name = \"name\")\n br\n div\n label(for = \"age\") Age: \n input(name = \"age\")\n br\n div\n label(for = \"nationality\") Nationality: \n input(name = \"nationality\")\n br\n button(type = \"submit\") Create new person" }, { "code": null, "e": 54404, "s": 54342, "text": "Also add a new get route in index.js to render this document." }, { "code": null, "e": 54857, "s": 54404, "text": "var koa = require('koa');\nvar _ = require('koa-router')();\nvar app = koa();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\n_.get('/person', getPerson);\n\nfunction *getPerson(next){\n this.render('person');\n yield next;\n}\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 55008, "s": 54857, "text": "Go to localhost:3000/person to check if our form is displaying right. Note that this is just the UI, it’s not working yet. This is how our form looks." }, { "code": null, "e": 55091, "s": 55008, "text": "We'll now define a post route handler at '/person' which will handle this request." }, { "code": null, "e": 56262, "s": 55091, "text": "var koa = require('koa');\nvar _ = require('koa-router')();\nvar app = koa();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\n_.post('/person', createPerson);\n\nfunction *createPerson(next){\n var self = this;\n var personInfo = self.request.body; //Get the parsed information\n \n if(!personInfo.name || !personInfo.age || !personInfo.nationality){\n self.render(\n 'show_message', {message: \"Sorry, you provided wrong info\", type: \"error\"});\n } else {\n var newPerson = new Person({\n name: personInfo.name,\n age: personInfo.age,\n nationality: personInfo.nationality\n });\n yield newPerson.save(function(err, res) {\n if(err)\n self.render('show_message', \n {message: \"Database error\", type: \"error\"});\n else\n self.render('show_message', \n {message: \"New person added\", type: \"success\", person: personInfo});\n });\n }\n}\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 56720, "s": 56262, "text": "In the above code, if we receive any empty field or do not receive any field, we will send an error response. However, if we receive a well-formed document, then we create a newPerson document from the Person model and save it to our DB using newPerson.save() function. This is defined in mongoose and accepts a callback as argument. This callback has two arguments, error and response. This will render show_message view, so we need to create that as well." }, { "code": null, "e": 56850, "s": 56720, "text": "To show the response from this route, we will also need to create a show_message view. Create a new view with the following code." }, { "code": null, "e": 57120, "s": 56850, "text": "html\n head\n title Person\n body\n if(type = \"error\")\n h3(style = \"color:red\") #{message}\n else\n h3 New person, name: \n #{person.name}, age: \n #{person.age} and nationality: \n #{person.nationality} added!" }, { "code": null, "e": 57213, "s": 57120, "text": "Following is the response we receive on successfully submitting the form (show_message.pug)." }, { "code": null, "e": 57257, "s": 57213, "text": "We now have an interface to create persons!" }, { "code": null, "e": 57490, "s": 57257, "text": "Mongoose provides a lot of functions for retrieving documents, we will focus on three of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response." }, { "code": null, "e": 57516, "s": 57490, "text": "The three functions are −" }, { "code": null, "e": 57725, "s": 57516, "text": "This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example, this will fetch all the documents from the persons’ collection." }, { "code": null, "e": 57792, "s": 57725, "text": "Person.find(function(err, response){\n console.log(response);\n});" }, { "code": null, "e": 57869, "s": 57792, "text": "This will fetch all documents where the field name is \"Ayush\" and age is 20." }, { "code": null, "e": 57972, "s": 57869, "text": "Person.find({name: \"Ayush\", age: 20}, \n function(err, response){\n console.log(response);\n });" }, { "code": null, "e": 58135, "s": 57972, "text": "We can also provide the projection we need, i.e., the fields we need. For example, if we want only the names of the people whose nationality is \"Indian\", we use −" }, { "code": null, "e": 58246, "s": 58135, "text": "Person.find({nationality: \"Indian\"}, \n \"name\", function(err, response) {\n console.log(response);\n });" }, { "code": null, "e": 58359, "s": 58246, "text": "This functions always fetches a single, most relevant document. It has the same exact arguments as Model.find()." }, { "code": null, "e": 58514, "s": 58359, "text": "This function takes in the _id (defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example," }, { "code": null, "e": 58623, "s": 58514, "text": "Person.findById(\"507f1f77bcf86cd799439011\", \n function(err, response){\n console.log(response);\n });" }, { "code": null, "e": 58672, "s": 58623, "text": "Let's create a route to view all people records." }, { "code": null, "e": 59187, "s": 58672, "text": "var koa = require('koa');\nvar _ = require('koa-router')();\nvar app = koa();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\n_.get('/people', getPeople);\nfunction *getPeople(next){\n var self = this;\n \n yield Person.find(function(err, response){\n self.body = response;\n });\n}\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 59242, "s": 59187, "text": "Mongoose provides three functions to update documents." }, { "code": null, "e": 59496, "s": 59242, "text": "This function takes a condition and an updates the object as input and applies the changes to all the documents matching the conditions in the collection. For example, the following code will update all Person documents to have a nationality \"American\"." }, { "code": null, "e": 59616, "s": 59496, "text": "Person.update({age: 25},\n {nationality: \"American\"}, \n function(err, response){\n console.log(response);\n });" }, { "code": null, "e": 59795, "s": 59616, "text": "It does exactly what is says. Finds one document based on the query and updates that according to the second argument. It also takes a callback as the last argument. For example," }, { "code": null, "e": 59916, "s": 59795, "text": "Person.findOneAndUpdate({name: \"Ayush\"}, \n {age: 40}, \n function(err, response){\n console.log(response);\n });" }, { "code": null, "e": 59991, "s": 59916, "text": "This function updates a single document identified by its id. For example," }, { "code": null, "e": 60130, "s": 59991, "text": "Person.findByIdAndUpdate(\"507f1f77bcf86cd799439011\", \n {name: \"James\"}, \n function(err, response){\n console.log(response);\n });" }, { "code": null, "e": 60249, "s": 60130, "text": "Let’s create a route to update people. This will be a PUT route with the id as a parameter and details in the payload." }, { "code": null, "e": 60982, "s": 60249, "text": "var koa = require('koa');\nvar _ = require('koa-router')();\nvar app = koa();\nvar mongoose = require('mongoose');\n\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\n_.put('/people/:id', updatePerson);\n\nfunction *updatePerson() {\n var self = this;\n yield Person.findByIdAndUpdate(self.params.id, \n {$set: {self.request.body}}, function(err, response){\n \n if(err) {\n self.body = {\n message: \"Error in updating person with id \" + self.params.id};\n } else {\n self.body = response;\n }\n });\n}\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 61093, "s": 60982, "text": "To test this route, enter the following in your terminal (replace the id with an id from your created people)." }, { "code": null, "e": 61215, "s": 61093, "text": "curl -X PUT --data \"name = James&age = 20&nationality = American\" https://localhost:3000/people/507f1f77bcf86cd799439011\n" }, { "code": null, "e": 61314, "s": 61215, "text": "This will update the document associated with the id provided in the route with the above details." }, { "code": null, "e": 61468, "s": 61314, "text": "We have covered Create, Read and Update, now we'll see how mongoose can be used to Delete documents. There are three functions here, exactly like update." }, { "code": null, "e": 61625, "s": 61468, "text": "This function takes a condition object as input and removes all the documents matching the conditions. For example, if we need to remove all people aged 20," }, { "code": null, "e": 61651, "s": 61625, "text": "Person.remove({age:20});\n" }, { "code": null, "e": 61752, "s": 61651, "text": "This functions removes a single, most relevant document according to conditions object. For example," }, { "code": null, "e": 61795, "s": 61752, "text": "Person.findOneAndRemove({name: \"Ayush\"});\n" }, { "code": null, "e": 61870, "s": 61795, "text": "This function removes a single document identified by its id. For example," }, { "code": null, "e": 61925, "s": 61870, "text": "Person.findByIdAndRemove(\"507f1f77bcf86cd799439011\");\n" }, { "code": null, "e": 61986, "s": 61925, "text": "Now let’s create a route to delete people from our database." }, { "code": null, "e": 62714, "s": 61986, "text": "var koa = require('koa');\nvar _ = require('koa-router')();\nvar app = koa();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\n_.delete('/people/:id', deletePerson);\nfunction *deletePerson(next){\n var self = this;\n yield Person.findByIdAndRemove(self.params.id, function(err, response){\n if(err) {\n self.body = {message: \"Error in deleting record id \" + self.params.id};\n } else {\n self.body = {message: \"Person with id \" + self.params.id + \" removed.\"};\n }\n });\n}\n\napp.use(_.routes());\napp.listen(3000);" }, { "code": null, "e": 62765, "s": 62714, "text": "To test this out, use the following curl command −" }, { "code": null, "e": 62836, "s": 62765, "text": "curl -X DELETE https://localhost:3000/people/507f1f77bcf86cd799439011\n" }, { "code": null, "e": 62917, "s": 62836, "text": "This will remove the person with the given id producing the following message. −" }, { "code": null, "e": 62980, "s": 62917, "text": "{message: \"Person with id 507f1f77bcf86cd799439011 removed.\"}\n" }, { "code": null, "e": 63118, "s": 62980, "text": "This wraps up how we can create simple CRUD applications using MongoDB, mongoose and Koa. To explore mongoose further, read the API docs." }, { "code": null, "e": 63512, "s": 63118, "text": "To create mobile applications, single page applications, use AJAX calls and provide data to clients, you'll need an API. A popular architectural style of how to structure and name these APIs and the endpoints is called REST(Representational Transfer State). HTTP 1.1 was designed keeping REST principles in mind. REST was introduced by Roy Fielding in 2000 in his paper Fielding Dissertations." }, { "code": null, "e": 63794, "s": 63512, "text": "RESTful URIs and methods provide us with almost all information we need to process a request. The following table summarizes how the various verbs should be used and how URIs should be named. We'll be creating a movies API towards the end, so let’s discuss how it'll be structured." }, { "code": null, "e": 64001, "s": 63794, "text": "Now let’s create this API in Koa. We will be using JSON as our transport data format as it is easy to work with in JavaScript and has loads of other benefits. Replace your index.js file with the following −" }, { "code": null, "e": 64430, "s": 64001, "text": "var koa = require('koa');\nvar router = require('koa-router');\nvar bodyParser = require('koa-body');\n\nvar app = koa();\n\n//Set up body parsing middleware\napp.use(bodyParser({\n formidable:{uploadDir: './uploads'},\n multipart: true,\n urlencoded: true\n}));\n\n//Require the Router we defined in movies.js\nvar movies = require('./movies.js');\n\n//Use the Router on the sub route /movies\napp.use(movies.routes());\n\napp.listen(3000);" }, { "code": null, "e": 64773, "s": 64430, "text": "Now that we have our application set up, let us concentrate on creating the API. First set up the movies.js file. We are not using a database to store the movies but are storing them in memory, so every time the server restarts the movies added by us will vanish. This can easily be mimicked using a database or a file (using node fs module)." }, { "code": null, "e": 64844, "s": 64773, "text": "Import koa-router, create a Router and export it using module.exports." }, { "code": null, "e": 65269, "s": 64844, "text": "var Router = require('koa-router');\nvar router = Router({\n prefix: '/movies'\n}); //Prefixed all routes with /movies\n\nvar movies = [\n {id: 101, name: \"Fight Club\", year: 1999, rating: 8.1},\n {id: 102, name: \"Inception\", year: 2010, rating: 8.7},\n {id: 103, name: \"The Dark Knight\", year: 2008, rating: 9},\n {id: 104, name: \"12 Angry Men\", year: 1957, rating: 8.9}\n];\n\n//Routes will go here\n\nmodule.exports = router;" }, { "code": null, "e": 65318, "s": 65269, "text": "Define the GET route for getting all the movies." }, { "code": null, "e": 65415, "s": 65318, "text": "router.get('/', sendMovies);\nfunction *sendMovies(next){\n this.body = movies;\n yield next;\n}" }, { "code": null, "e": 65513, "s": 65415, "text": "That's it. To test out if this is working fine, run your app, then open your terminal and enter −" }, { "code": null, "e": 65617, "s": 65513, "text": "curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" -X GET localhost:3000/movies\n" }, { "code": null, "e": 65653, "s": 65617, "text": "You'll get the following response −" }, { "code": null, "e": 65886, "s": 65653, "text": "[{\"id\":101,\"name\":\"Fight \nClub\",\"year\":1999,\"rating\":8.1},{\"id\":102,\"name\":\"Inception\",\"year\":2010,\"rating\":8.7},\n{\"id\":103,\"name\":\"The Dark Knight\",\"year\":2008,\"rating\":9},{\"id\":104,\"name\":\"12 Angry \nMen\",\"year\":1957,\"rating\":8.9}]" }, { "code": null, "e": 65985, "s": 65886, "text": "We have a route to get all the movies. Now let’s create a route to get a specific movie by its id." }, { "code": null, "e": 66424, "s": 65985, "text": "router.get('/:id([0-9]{3,})', sendMovieWithId);\n\nfunction *sendMovieWithId(next){\n var ctx = this;\n var currMovie = movies.filter(function(movie){\n if(movie.id == ctx.params.id){\n return true;\n }\n });\n if(currMovie.length == 1){\n this.body = currMovie[0];\n } else {\n this.response.status = 404;//Set status to 404 as movie was not found\n this.body = {message: \"Not Found\"};\n }\n yield next;\n}" }, { "code": null, "e": 66551, "s": 66424, "text": "This will get us the movies according to the id that we provide. To test this out, use the following command in your terminal." }, { "code": null, "e": 66659, "s": 66551, "text": "curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" -X GET localhost:3000/movies/101\n" }, { "code": null, "e": 66688, "s": 66659, "text": "You'll get the response as −" }, { "code": null, "e": 66745, "s": 66688, "text": "{\"id\":101,\"name\":\"Fight Club\",\"year\":1999,\"rating\":8.1}\n" }, { "code": null, "e": 66901, "s": 66745, "text": "If you visit an invalid route, it'll produce a cannot GET error, while if you visit a valid route with an id that doesn’t exist, it'll produce a 404 error." }, { "code": null, "e": 66968, "s": 66901, "text": "We are done with the GET routes. Now, let’s move on to POST route." }, { "code": null, "e": 67019, "s": 66968, "text": "Use the following route to handle the POSTed data." }, { "code": null, "e": 67728, "s": 67019, "text": "router.post('/', addNewMovie);\n\nfunction *addNewMovie(next){\n //Check if all fields are provided and are valid:\n if(!this.request.body.name || \n !this.request.body.year.toString().match(/^[0-9]{4}$/g) || \n !this.request.body.rating.toString().match(/^[0-9]\\.[0-9]$/g)){\n \n this.response.status = 400;\n this.body = {message: \"Bad Request\"};\n } else {\n var newId = movies[movies.length-1].id+1;\n \n movies.push({\n id: newId,\n name: this.request.body.name,\n year: this.request.body.year,\n rating: this.request.body.rating\n });\n this.body = {message: \"New movie created.\", location: \"/movies/\" + newId};\n }\n yield next;\n}" }, { "code": null, "e": 67857, "s": 67728, "text": "This will create a new movie and store it in the movies variable. To test this route out, enter the following in your terminal −" }, { "code": null, "e": 67955, "s": 67857, "text": "curl -X POST --data \"name = Toy%20story&year = 1995&rating = 8.5\" \nhttps://localhost:3000/movies\n" }, { "code": null, "e": 67991, "s": 67955, "text": "You'll get the following response −" }, { "code": null, "e": 68050, "s": 67991, "text": "{\"message\":\"New movie created.\",\"location\":\"/movies/105\"}\n" }, { "code": null, "e": 68177, "s": 68050, "text": "To test if this was added to the movies object, run the get request for /movies/105 again. You'll get the following response −" }, { "code": null, "e": 68237, "s": 68177, "text": "{\"id\":105,\"name\":\"Toy story\",\"year\":\"1995\",\"rating\":\"8.5\"}\n" }, { "code": null, "e": 68288, "s": 68237, "text": "Let’s move on to create the PUT and DELETE routes." }, { "code": null, "e": 68460, "s": 68288, "text": "The PUT route is almost exactly the same as the POST route. We will be specifying the id for the object that'll be updated/created. Create the route in the following way −" }, { "code": null, "e": 69830, "s": 68460, "text": "router.put('/:id', updateMovieWithId);\n\nfunction *updateMovieWithId(next){\n //Check if all fields are provided and are valid:\n if(!this.request.body.name || \n !this.request.body.year.toString().match(/^[0-9]{4}$/g) || \n !this.request.body.rating.toString().match(/^[0-9]\\.[0-9]$/g) ||\n !this.params.id.toString().match(/^[0-9]{3,}$/g)){\n \n this.response.status = 400;\n this.body = {message: \"Bad Request\"};\n } else {\n //Gets us the index of movie with given id.\n var updateIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(parseInt(this.params.id));\n \n if(updateIndex === -1){\n //Movie not found, create new movies.push({\n id: this.params.id,\n name: this.request.body.name,\n year: this.request.body.year,\n rating: this.request.body.rating\n });\n this.body = {message: \"New movie created.\", location: \"/movies/\" + this.params.id}; \n } else {\n //Update existing movie\n movies[updateIndex] = {\n id: this.params.id,\n name: this.request.body.name,\n year: this.request.body.year,\n rating: this.request.body.rating\n };\n this.body = {message: \"Movie id \" + this.params.id + \" updated.\", location: \"/movies/\" + this.params.id};\n }\n }\n}" }, { "code": null, "e": 70154, "s": 69830, "text": "This route will do the function we specified in the table above. It'll update the object with new details if it exists. If it doesn't exist, it'll create a new object. To test out this route, use the following curl command. This will update an existing movie. To create a new Movie, just change the id to a non-existing id." }, { "code": null, "e": 70255, "s": 70154, "text": "curl -X PUT --data \"name = Toy%20story&year = 1995&rating = 8.5\" \nhttps://localhost:3000/movies/101\n" }, { "code": null, "e": 70317, "s": 70255, "text": "{\"message\":\"Movie id 101 updated.\",\"location\":\"/movies/101\"}\n" }, { "code": null, "e": 70366, "s": 70317, "text": "Use the following code to create a delete route." }, { "code": null, "e": 70793, "s": 70366, "text": "router.delete('/:id', deleteMovieWithId);\n\nfunction *deleteMovieWithId(next){\n var removeIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(this.params.id); //Gets us the index of movie with given id.\n \n if(removeIndex === -1){\n this.body = {message: \"Not found\"};\n } else {\n movies.splice(removeIndex, 1);\n this.body = {message: \"Movie id \" + this.params.id + \" removed.\"};\n }\n}" }, { "code": null, "e": 70907, "s": 70793, "text": "Test the route in the same way we did for the others. On successful deletion (for example id 105), you will get −" }, { "code": null, "e": 70943, "s": 70907, "text": "{message: \"Movie id 105 removed.\"}\n" }, { "code": null, "e": 70984, "s": 70943, "text": "Finally, our movies.js file looks like −" }, { "code": null, "e": 74470, "s": 70984, "text": "var Router = require('koa-router');\nvar router = Router({\n prefix: '/movies'\n}); //Prefixed all routes with /movies\nvar movies = [\n {id: 101, name: \"Fight Club\", year: 1999, rating: 8.1},\n {id: 102, name: \"Inception\", year: 2010, rating: 8.7},\n {id: 103, name: \"The Dark Knight\", year: 2008, rating: 9},\n {id: 104, name: \"12 Angry Men\", year: 1957, rating: 8.9}\n];\n\n//Routes will go here\nrouter.get('/', sendMovies);\nrouter.get('/:id([0-9]{3,})', sendMovieWithId);\nrouter.post('/', addNewMovie);\nrouter.put('/:id', updateMovieWithId);\nrouter.delete('/:id', deleteMovieWithId);\n\nfunction *deleteMovieWithId(next){\n var removeIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(this.params.id); //Gets us the index of movie with given id.\n \n if(removeIndex === -1){\n this.body = {message: \"Not found\"};\n } else {\n movies.splice(removeIndex, 1);\n this.body = {message: \"Movie id \" + this.params.id + \" removed.\"};\n }\n}\n\nfunction *updateMovieWithId(next) {\n //Check if all fields are provided and are valid:\n if(!this.request.body.name ||\n !this.request.body.year.toString().match(/^[0-9]{4}$/g) ||\n !this.request.body.rating.toString().match(/^[0-9]\\.[0-9]$/g) ||\n !this.params.id.toString().match(/^[0-9]{3,}$/g)){\n \n this.response.status = 400;\n this.body = {message: \"Bad Request\"};\n } else {\n //Gets us the index of movie with given id.\n var updateIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(parseInt(this.params.id));\n \n if(updateIndex === -1){\n //Movie not found, create new\n movies.push({\n id: this.params.id,\n name: this.request.body.name,\n year: this.request.body.year,\n rating: this.request.body.rating\n });\n this.body = {message: \"New movie created.\", location: \"/movies/\" + this.params.id};\n } else {\n //Update existing movie\n movies[updateIndex] = {\n id: this.params.id,\n name: this.request.body.name,\n year: this.request.body.year,\n rating: this.request.body.rating\n };\n this.body = {message: \"Movie id \" + this.params.id + \" updated.\", \n location: \"/movies/\" + this.params.id};\n }\n }\n}\n\nfunction *addNewMovie(next){\n //Check if all fields are provided and are valid:\n if(!this.request.body.name ||\n !this.request.body.year.toString().match(/^[0-9]{4}$/g) ||\n !this.request.body.rating.toString().match(/^[0-9]\\.[0-9]$/g)){\n \n this.response.status = 400;\n this.body = {message: \"Bad Request\"};\n } else {\n var newId = movies[movies.length-1].id+1;\n \n movies.push({\n id: newId,\n name: this.request.body.name,\n year: this.request.body.year,\n rating: this.request.body.rating\n });\n this.body = {message: \"New movie created.\", location: \"/movies/\" + newId};\n }\n yield next;\n}\nfunction *sendMovies(next){\n this.body = movies;\n yield next;\n}\nfunction *sendMovieWithId(next){\n var ctx = this\n \n var currMovie = movies.filter(function(movie){\n if(movie.id == ctx.params.id){\n return true;\n }\n });\n if(currMovie.length == 1){\n this.body = currMovie[0];\n } else {\n this.response.status = 404;//Set status to 404 as movie was not found\n this.body = {message: \"Not Found\"};\n }\n yield next;\n}\nmodule.exports = router;" }, { "code": null, "e": 74596, "s": 74470, "text": "This completes our REST API. Now you can create much more complex applications using this simple architectural style and Koa." }, { "code": null, "e": 74809, "s": 74596, "text": "Logging is quite useful when creating web applications as they tell us where exactly things went wrong. We also get the context for the things that went wrong and can come up with possible solutions for the same." }, { "code": null, "e": 74911, "s": 74809, "text": "To enable logging in Koa, we need the middleware, koa-logger. Install it using the following command." }, { "code": null, "e": 74948, "s": 74911, "text": "$ npm install --save-dev koa-logger\n" }, { "code": null, "e": 75015, "s": 74948, "text": "Now in your application, add the following code to enable logging." }, { "code": null, "e": 75184, "s": 75015, "text": "var logger = require('koa-logger')\nvar koa = require('koa')\n\nvar app = koa()\napp.use(logger())\n\napp.use(function*(){\n this.body = \"Hello Logger\";\n})\n\napp.listen(3000)" }, { "code": null, "e": 75266, "s": 75184, "text": "Run this server and visit any route on the server. You should see the logs like −" }, { "code": null, "e": 75393, "s": 75266, "text": "Now if you get an error on a specific route or request, these logs should help you figure out what went wrong in each of them." }, { "code": null, "e": 75679, "s": 75393, "text": "Scaffolding allows us to easily create a skeleton for a web application. We manually created our public directory, added middleware, created separate route files, etc. A scaffolding tool sets up all these things for us so that we can directly get started with building our application." }, { "code": null, "e": 75921, "s": 75679, "text": "The scaffolder we'll use is called Yeoman. It is a scaffolding tool built for Node.js but also has generators for several other frameworks (such as flask, rails, django, etc.). To install yeoman, enter the following command in your terminal." }, { "code": null, "e": 75946, "s": 75921, "text": "$ npm install -g yeoman\n" }, { "code": null, "e": 76218, "s": 75946, "text": "Yeoman uses generators to scaffold out applications. To check out the generators available on npm to use with yeoman, head over here. For the purpose of this tutorial, we'll use the 'generator-koa'. To install this generator, enter the following command in your terminal." }, { "code": null, "e": 76250, "s": 76218, "text": "$ npm install -g generator-koa\n" }, { "code": null, "e": 76281, "s": 76250, "text": "To use this generator, enter −" }, { "code": null, "e": 76289, "s": 76281, "text": "yo koa\n" }, { "code": null, "e": 76449, "s": 76289, "text": "Then it'll create a directory structure and will create the following files for you. It'll also install the necessary npm modules and bower components for you." }, { "code": null, "e": 76835, "s": 76449, "text": "create package.json\ncreate test/routeSpec.js\ncreate views/layout.html\ncreate views/list.html\ncreate public/styles/main.css\ncreate public/scripts/.gitkeep\ncreate controllers/messages.js\ncreate app.js\ncreate .editorconfig\ncreate .jshintrc\n\nI'm all done. Running npm install & bower install for you to install \nthe required dependencies. \nIf this fails, try running the command yourself.\n" }, { "code": null, "e": 76890, "s": 76835, "text": "This generator creates a very simple structure for us." }, { "code": null, "e": 77134, "s": 76890, "text": ".\n├── controllers\n│ └── messages.js\n├── public\n| ├── scripts\n| └── styles\n| └── main.css \n├── test\n| └── routeSpec.js\n├── views\n| ├── layout.html\n| └── list.html\n├── .editorconfig\n├── .jshintrc\n├── app.js\n└── package.json\n" }, { "code": null, "e": 77427, "s": 77134, "text": "Explore the many generators available for Koa and choose the one that fits you right. Steps to working with all generators is the same. You'll need to install a generator, run it using yeoman, it'll ask you some questions and then create a skeleton for your application based on your answers." }, { "code": null, "e": 77506, "s": 77427, "text": "Following is a list of resources we have used while developing this tutorial −" }, { "code": null, "e": 77516, "s": 77506, "text": "Koajs.com" }, { "code": null, "e": 77526, "s": 77516, "text": "Koajs.com" }, { "code": null, "e": 77587, "s": 77526, "text": "Koajs - Examples A list of examples created by the community" }, { "code": null, "e": 77648, "s": 77587, "text": "Koajs - Examples A list of examples created by the community" }, { "code": null, "e": 77692, "s": 77648, "text": "List of official and 3rd party middlewares." }, { "code": null, "e": 77736, "s": 77692, "text": "List of official and 3rd party middlewares." }, { "code": null, "e": 77829, "s": 77736, "text": "A CRUD API using koa.js - A short screencast that goes through creating a CRUD API in Koa.js" }, { "code": null, "e": 77922, "s": 77829, "text": "A CRUD API using koa.js - A short screencast that goes through creating a CRUD API in Koa.js" }, { "code": null, "e": 77951, "s": 77922, "text": "Koa.js Quickstart screencast" }, { "code": null, "e": 77980, "s": 77951, "text": "Koa.js Quickstart screencast" }, { "code": null, "e": 78018, "s": 77980, "text": "Introduction to Koa.js and generators" }, { "code": null, "e": 78056, "s": 78018, "text": "Introduction to Koa.js and generators" }, { "code": null, "e": 78063, "s": 78056, "text": " Print" }, { "code": null, "e": 78074, "s": 78063, "text": " Add Notes" } ]
Algorithms | Graph Shortest Paths | Question 8 - GeeksforGeeks
28 Jun, 2021 In a weighted graph, assume that the shortest path from a source ‘s’ to a destination ‘t’ is correctly calculated using a shortest path algorithm. Is the following statement true?If we increase weight of every edge by 1, the shortest path always remains same.(A) Yes(B) NoAnswer: (B)Explanation: See the following counterexample. There are 4 edges s-a, a-b, b-t and s-t of wights 1, 1, 1 and 4 respectively. The shortest path from s to t is s-a, a-b, b-t. IF we increase weight of every edge by 1, the shortest path changes to s-t. 1 1 1 s-----a-----b-----t \ / \ / \______/ 4 Quiz of this Question Algorithms-Graph Shortest Paths Quiz Graph Shortest Paths Quiz Algorithms Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithms | Dynamic Programming | Question 2 Algorithms | Dynamic Programming | Question 3 Algorithms | Analysis of Algorithms | Question 8 Algorithms Quiz | Dynamic Programming | Question 8 Algorithms | Sorting | Question 9 GATE | GATE MOCK 2017 | Question 23 Algorithms | Sorting | Question 5 Algorithms | Graph Traversals | Question 12 Algorithms | Graph Traversals | Question 1 Algorithms | Sorting | Question 6
[ { "code": null, "e": 25054, "s": 25026, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25384, "s": 25054, "text": "In a weighted graph, assume that the shortest path from a source ‘s’ to a destination ‘t’ is correctly calculated using a shortest path algorithm. Is the following statement true?If we increase weight of every edge by 1, the shortest path always remains same.(A) Yes(B) NoAnswer: (B)Explanation: See the following counterexample." }, { "code": null, "e": 25586, "s": 25384, "text": "There are 4 edges s-a, a-b, b-t and s-t of wights 1, 1, 1 and 4 respectively. The shortest path from s to t is s-a, a-b, b-t. IF we increase weight of every edge by 1, the shortest path changes to s-t." }, { "code": null, "e": 25683, "s": 25586, "text": "\n 1 1 1\ns-----a-----b-----t\n \\ /\n \\ /\n \\______/\n 4" }, { "code": null, "e": 25705, "s": 25683, "text": "Quiz of this Question" }, { "code": null, "e": 25742, "s": 25705, "text": "Algorithms-Graph Shortest Paths Quiz" }, { "code": null, "e": 25768, "s": 25742, "text": "Graph Shortest Paths Quiz" }, { "code": null, "e": 25784, "s": 25768, "text": "Algorithms Quiz" }, { "code": null, "e": 25882, "s": 25784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25891, "s": 25882, "text": "Comments" }, { "code": null, "e": 25904, "s": 25891, "text": "Old Comments" }, { "code": null, "e": 25950, "s": 25904, "text": "Algorithms | Dynamic Programming | Question 2" }, { "code": null, "e": 25996, "s": 25950, "text": "Algorithms | Dynamic Programming | Question 3" }, { "code": null, "e": 26045, "s": 25996, "text": "Algorithms | Analysis of Algorithms | Question 8" }, { "code": null, "e": 26096, "s": 26045, "text": "Algorithms Quiz | Dynamic Programming | Question 8" }, { "code": null, "e": 26130, "s": 26096, "text": "Algorithms | Sorting | Question 9" }, { "code": null, "e": 26166, "s": 26130, "text": "GATE | GATE MOCK 2017 | Question 23" }, { "code": null, "e": 26200, "s": 26166, "text": "Algorithms | Sorting | Question 5" }, { "code": null, "e": 26244, "s": 26200, "text": "Algorithms | Graph Traversals | Question 12" }, { "code": null, "e": 26287, "s": 26244, "text": "Algorithms | Graph Traversals | Question 1" } ]
Explain Polymorphism in PHP.
To begin with, Polymorphism is gotten from the Greek words Poly (which means many) and morphism (which meaning forms). Polymorphism portrays an example in object-oriented programming where methods in various classes that do similar things should have a similar name. Polymorphism is essentially an OOP pattern that enables numerous classes with different functionalities to execute or share a commonInterface. The usefulness of polymorphism is code written in different classes doesn't have any effect which class it belongs because they are used in the same way. In order to ensure that the classes do implement the polymorphism guideline, we can pick between one of the two alternatives of either abstract classes or interfaces. So let's implement the polymorphism principle with the help of the interface. Interface An interface is similar to a class except that it cannot contain code. An interface can define method names and arguments, but not the contents of the methods. Any classes executing an interface must execute all methods characterized by the interface. <?php interface Machine { public function calcTask(); } class Circle implements Machine { private $radius; public function __construct($radius){ $this -> radius = $radius; } public function calcTask(){ return $this -> radius * $this -> radius * pi(); } } class Rectangle implements Machine { private $width; private $height; public function __construct($width, $height){ $this -> width = $width; $this -> height = $height; } public function calcTask(){ return $this -> width * $this -> height; } } $mycirc = new Circle(3); $myrect = new Rectangle(3,4); echo $mycirc->calcTask(); echo $myrect->calcTask(); ?> 28.274 12 The interface with the name of " Machine" commits all the classes that implement it to define an abstract method with the name of calcTask(). In accordance, the Circle class implements the interface by defining the callTask() method with the respective body inside it. The rectangle class also implements the Machine interface but defines the method calcTask() with a different body that differs from the circle class CalTask() method. The polymorphism guideline says that, for this situation, all the methods that calculate the task would have the equivalent name. Now, at whatever point we would need to compute the Task for the different Classes, we would call a method with the name of calcTask() without giving a lot of consideration to the details of how to actually calculate the Task for the different Machine. The main thing that we would need to know is the name of the method that calculates the Task.
[ { "code": null, "e": 1181, "s": 1062, "text": "To begin with, Polymorphism is gotten from the Greek words Poly (which means many) and morphism (which meaning forms)." }, { "code": null, "e": 1793, "s": 1181, "text": "Polymorphism portrays an example in object-oriented programming where methods in various classes that do similar things should have a similar name. Polymorphism is essentially an OOP pattern that enables numerous classes with different functionalities to execute or share a commonInterface. The usefulness of polymorphism is code written in different classes doesn't have any effect which class it belongs because they are used in the same way. In order to ensure that the classes do implement the polymorphism guideline, we can pick between one of the two alternatives of either abstract classes or interfaces." }, { "code": null, "e": 1871, "s": 1793, "text": "So let's implement the polymorphism principle with the help of the interface." }, { "code": null, "e": 2133, "s": 1871, "text": "Interface An interface is similar to a class except that it cannot contain code. An interface can define method names and arguments, but not the contents of the methods. Any classes executing an interface must execute all methods characterized by the interface." }, { "code": null, "e": 2888, "s": 2133, "text": "<?php\n interface Machine {\n public function calcTask();\n }\n class Circle implements Machine {\n private $radius;\n public function __construct($radius){\n $this -> radius = $radius;\n }\n public function calcTask(){\n return $this -> radius * $this -> radius * pi();\n }\n }\n class Rectangle implements Machine {\n private $width;\n private $height;\n public function __construct($width, $height){\n $this -> width = $width;\n $this -> height = $height;\n }\n public function calcTask(){\n return $this -> width * $this -> height;\n }\n }\n $mycirc = new Circle(3);\n $myrect = new Rectangle(3,4);\n echo $mycirc->calcTask();\n echo $myrect->calcTask();\n?>" }, { "code": null, "e": 2898, "s": 2888, "text": "28.274\n12" }, { "code": null, "e": 3811, "s": 2898, "text": "The interface with the name of \" Machine\" commits all the classes that implement it to define an abstract method with the name of calcTask(). In accordance, the Circle class implements the interface by defining the callTask() method with the respective body inside it. The rectangle class also implements the Machine interface but defines the method calcTask() with a different body that differs from the circle class CalTask() method. The polymorphism guideline says that, for this situation, all the methods that calculate the task would have the equivalent name. Now, at whatever point we would need to compute the Task for the different Classes, we would call a method with the name of calcTask() without giving a lot of consideration to the details of how to actually calculate the Task for the different Machine. The main thing that we would need to know is the name of the method that calculates the Task." } ]
Parallel Coordinates Plots with Plotly | by Darío Weitz | Towards Data Science
Data visualization is a tool for storytelling. It is common for a data scientist to have to find patterns or trends that are hidden in multidimensional datasets with multiple numerical variables. Parallel Plots or Parallel Coordinates Plots (PCPs) are data visualization charts appropriate for comparing numerous numerical variables simultaneously when those variables have different scales and/or different units of measurement. In a PCP each numerical variable has its own axis. Besides, all axes are drawn vertical, parallel, and equally spaced. Records of the data set are represented as line segments connected across each axis. These segments form a polyline, which arises from the values taken by the different numerical variables on their corresponding axes. The following figure shows a PCP with four numerical variables and six records for each variable. So we have four vertical, parallel, and equally spaced axes with their corresponding labels. There are six polylines made up of four connected points, one on each axis. Each polyline has its particular color according to the numerical value adopted by a fifth variable. Patterns, trends, or clusters between the different numerical variables are analyzed according to the degree of parallelism between the polylines: a certain degree of parallelism in the lines joining parallel axes implies a positive relationship between the corresponding variables; crisscrossing (X-shaped) between the lines joining parallel axes implies a negative relationship between them; crisscrossing with no defined order implies that no particular relationship exists. Any attempt to find patterns or relationships across the variables shown in Figure 1 would be misleading because of the different orders of magnitude between variable 4 and variables 1 and 3: we must proceed with a data normalization task prior to draw the figure. Normalization or Scaling techniques transform original data into a new scale that allows us to compare values of initially different magnitudes. Two classical techniques for scaling are called Normalization and Standardization. Normalization scales each axis in PCP between its minimum and maximum values. With this procedure, the lowest value is set to 0, the highest to 1, and all other values in between are transformed accordingly. Standardization uses the mean and the standard deviation to transform the original numerical values into a common scale. Storytelling with PCPs is usually difficult to communicate, even for technical and scientific audiences, because there’s no way to avoid the typical polylines jumble. The techniques of reordering and brushing could enhance the readability of the plot. Reordering is based on the idea that relationships, clusters, or patterns between adjacent variables are more easily visualized than between non-adjacent ones. Reordering consists basically in changing the order of the vertical axes until some kind of pattern or relationship appears in the display. Brushing minimizes clutter and reveals relationships by highlighting selected lines while others are faded. Diverging color scales are appropriate for those visualization tools that do not have a built-in method for brushing. We used PCP to analyze data from a Kaggle Competition related to evaluating how some chemical properties affect the quality of red variants of the Portuguese “Vinho Verde” wine [Cortez et al., 2009]. The organoleptic quality of wines can be influenced by any of the following chemical or physical properties: alcohol, residual sugar, density, pH, fixed acidity, volatile acidity, citric acid, chlorides, free sulfur dioxide, total sulfur dioxide, and sulfates. Quality scores between 0 (Bad) and 10 (Excellent) were provided for each wine in the dataset. First, we imported Plotly Express as px, and the libraries Numpy & Pandas as np and pd respectively. We included a function to switch off a particular warning. import plotly.express as pximport numpy as npimport pandas as pdpd.set_option('mode.chained_assignment', None) Then we used the read_csv function to read the comma-separated values (csv) file into the corresponding dataframe (df). We used the describe() method to generate descriptive statistics (mean, std. dev., min, max, etc.) that summarize the central tendency, shape, and dispersion of the dataset. Then, we used isnull() to detect missing values. df = pd.read_csv(path +'winequality-red.csv', sep=';', header = 0, names=['fixed acidity', 'volatile acidity', 'citric acidity','residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol', 'quality'])first10 = df.head(10)stat_basic = df.describe()count_null = df.isnull().sum() The screenshot below shows the first ten records of the dataset: We decided to eliminate the outliers using Z-scores. Remember that a Z-score is the number of standard deviations away from the mean for every data point of the dataset. We calculated Z-scores using stats.zscore(df) from the open source scientific library for Python ScyPy. After several tests, we selected the value 6 as the outlier filtering threshold. from scipy import statszT = np.abs(stats.zscore(df))df2 = df[(zT < 6).all(axis =1)] We decided to split the dataset into high quality and low quality wines in order to reduce the number of lines, minimize clutter and improve pattern detection: df_highq = df2[df2['quality'] > 6]df_lowq = df2[df2['quality'] <= 6] The screenshot of the dataset clearly shows the need for a scaling task before plotting the PCP. First of all, we normalized our dataset using the scikit-learn object MinMaxScaler. Remember that MinMaxScaler rescales the data from its original value so all the new values are within the range 0–1. from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()df_highqN = df_highqdf_highqN[['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH','sulphates','alcohol']] =scaler.fit_transform(df_highqN[[ 'fixed acidity', 'volatile acidity', 'citric acidity','residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']]) For the parallel coordinate plot in this article, the Plotly Express function is px.parallel_coordinates and the corresponding parameters are: data_frame; color= a name of a column in data_frame whose values are used to indicate the colors of lines; dimensions= names of columns in data_frame whose values are used to draw the lines; color_continuous_scale= to choose any of the built-in color scales; color_continuous_midpoint= to set an appropriate midpoint value when using a diverging color scale; title= to set the figure title. fig0 = px.parallel_coordinates(df_highqN, color="quality", dimensions=['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol' ], color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=7.5, title = 'PCP High Quality Wines Without Reordering')fig0.show() It’s really a mess. There is no way to get any useful information, so we decided to try different reordering schemes until we got Figure 3. fig1 = px.parallel_coordinates(df_highqN, color="quality", dimensions=['residual sugar', 'chlorides', 'sulphates', 'volatile acidity', 'density', 'pH', 'citric acidity', 'alcohol' ], color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=7.5, title = 'PCP High Quality Wines After Reordering')fig1.show() The figure shows that high quality wines have low levels of residual sugar, chlorides, and sulphates, and high levels of alcohol and citric acid. Let’s look at what happens with low-quality wines: df_lowq2 = df_lowqdf_lowq2[['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']] = scaler.fit_transform(df_lowq2[[ 'fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']])fig2 = px.parallel_coordinates(df_lowq2, color="quality", dimensions=['residual sugar', 'chlorides', 'sulphates', 'volatile acidity', 'alcohol', 'pH','density', 'citric acidity' ], color_continuous_scale=px.colors.diverging.RdYlBu, color_continuous_midpoint=4, title = 'PCP Low Quality Wines After Reordering')fig2.show() It seems that low quality wines have high levels of chlorides, sulphates, and volatile acidity. Finally, we would like to know if scaling with the standardization technique improves the storytelling. from sklearn.preprocessing import StandardScalerscalerST = StandardScaler()df_highqS = df_highqdf_highqS[['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']] = scalerST.fit_transform(df_highqS[[ 'fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']])fig3 = px.parallel_coordinates(df_highqS, color="quality", dimensions=['residual sugar', 'chlorides', 'sulphates', 'fixed acidity', 'density', 'volatile acidity','pH', 'citric acidity' ], color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=7.5, title= 'PCP High Quality Wines After Standardization')fig3.show() As can be seen, the display is equivalent to that of Figure 3 with the additional difficulty of showing negative values for chemical and physical properties that do not correspond. In summary, Parallel Coordinates Plots are very complex graphics that require several preprocessing steps. They are only recommended for data sets with a large number of numerical variables. Always use Normalization as the scaling technique. Their complexity does not allow to guarantee an adequate storytelling. If you find this article of interest, please read my previous (https://medium.com/@dar.wtz): Diverging Bars, Why & How, Storytelling with Divergences towardsdatascience.com Slope Charts, Why & How, Storytelling with Slopes
[ { "code": null, "e": 602, "s": 172, "text": "Data visualization is a tool for storytelling. It is common for a data scientist to have to find patterns or trends that are hidden in multidimensional datasets with multiple numerical variables. Parallel Plots or Parallel Coordinates Plots (PCPs) are data visualization charts appropriate for comparing numerous numerical variables simultaneously when those variables have different scales and/or different units of measurement." }, { "code": null, "e": 939, "s": 602, "text": "In a PCP each numerical variable has its own axis. Besides, all axes are drawn vertical, parallel, and equally spaced. Records of the data set are represented as line segments connected across each axis. These segments form a polyline, which arises from the values taken by the different numerical variables on their corresponding axes." }, { "code": null, "e": 1307, "s": 939, "text": "The following figure shows a PCP with four numerical variables and six records for each variable. So we have four vertical, parallel, and equally spaced axes with their corresponding labels. There are six polylines made up of four connected points, one on each axis. Each polyline has its particular color according to the numerical value adopted by a fifth variable." }, { "code": null, "e": 1785, "s": 1307, "text": "Patterns, trends, or clusters between the different numerical variables are analyzed according to the degree of parallelism between the polylines: a certain degree of parallelism in the lines joining parallel axes implies a positive relationship between the corresponding variables; crisscrossing (X-shaped) between the lines joining parallel axes implies a negative relationship between them; crisscrossing with no defined order implies that no particular relationship exists." }, { "code": null, "e": 2195, "s": 1785, "text": "Any attempt to find patterns or relationships across the variables shown in Figure 1 would be misleading because of the different orders of magnitude between variable 4 and variables 1 and 3: we must proceed with a data normalization task prior to draw the figure. Normalization or Scaling techniques transform original data into a new scale that allows us to compare values of initially different magnitudes." }, { "code": null, "e": 2607, "s": 2195, "text": "Two classical techniques for scaling are called Normalization and Standardization. Normalization scales each axis in PCP between its minimum and maximum values. With this procedure, the lowest value is set to 0, the highest to 1, and all other values in between are transformed accordingly. Standardization uses the mean and the standard deviation to transform the original numerical values into a common scale." }, { "code": null, "e": 2859, "s": 2607, "text": "Storytelling with PCPs is usually difficult to communicate, even for technical and scientific audiences, because there’s no way to avoid the typical polylines jumble. The techniques of reordering and brushing could enhance the readability of the plot." }, { "code": null, "e": 3159, "s": 2859, "text": "Reordering is based on the idea that relationships, clusters, or patterns between adjacent variables are more easily visualized than between non-adjacent ones. Reordering consists basically in changing the order of the vertical axes until some kind of pattern or relationship appears in the display." }, { "code": null, "e": 3385, "s": 3159, "text": "Brushing minimizes clutter and reveals relationships by highlighting selected lines while others are faded. Diverging color scales are appropriate for those visualization tools that do not have a built-in method for brushing." }, { "code": null, "e": 3940, "s": 3385, "text": "We used PCP to analyze data from a Kaggle Competition related to evaluating how some chemical properties affect the quality of red variants of the Portuguese “Vinho Verde” wine [Cortez et al., 2009]. The organoleptic quality of wines can be influenced by any of the following chemical or physical properties: alcohol, residual sugar, density, pH, fixed acidity, volatile acidity, citric acid, chlorides, free sulfur dioxide, total sulfur dioxide, and sulfates. Quality scores between 0 (Bad) and 10 (Excellent) were provided for each wine in the dataset." }, { "code": null, "e": 4100, "s": 3940, "text": "First, we imported Plotly Express as px, and the libraries Numpy & Pandas as np and pd respectively. We included a function to switch off a particular warning." }, { "code": null, "e": 4212, "s": 4100, "text": "import plotly.express as pximport numpy as npimport pandas as pdpd.set_option('mode.chained_assignment', None)" }, { "code": null, "e": 4555, "s": 4212, "text": "Then we used the read_csv function to read the comma-separated values (csv) file into the corresponding dataframe (df). We used the describe() method to generate descriptive statistics (mean, std. dev., min, max, etc.) that summarize the central tendency, shape, and dispersion of the dataset. Then, we used isnull() to detect missing values." }, { "code": null, "e": 5018, "s": 4555, "text": "df = pd.read_csv(path +'winequality-red.csv', sep=';', header = 0, names=['fixed acidity', 'volatile acidity', 'citric acidity','residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol', 'quality'])first10 = df.head(10)stat_basic = df.describe()count_null = df.isnull().sum()" }, { "code": null, "e": 5083, "s": 5018, "text": "The screenshot below shows the first ten records of the dataset:" }, { "code": null, "e": 5438, "s": 5083, "text": "We decided to eliminate the outliers using Z-scores. Remember that a Z-score is the number of standard deviations away from the mean for every data point of the dataset. We calculated Z-scores using stats.zscore(df) from the open source scientific library for Python ScyPy. After several tests, we selected the value 6 as the outlier filtering threshold." }, { "code": null, "e": 5523, "s": 5438, "text": "from scipy import statszT = np.abs(stats.zscore(df))df2 = df[(zT < 6).all(axis =1)]" }, { "code": null, "e": 5683, "s": 5523, "text": "We decided to split the dataset into high quality and low quality wines in order to reduce the number of lines, minimize clutter and improve pattern detection:" }, { "code": null, "e": 5754, "s": 5683, "text": "df_highq = df2[df2['quality'] > 6]df_lowq = df2[df2['quality'] <= 6]" }, { "code": null, "e": 6052, "s": 5754, "text": "The screenshot of the dataset clearly shows the need for a scaling task before plotting the PCP. First of all, we normalized our dataset using the scikit-learn object MinMaxScaler. Remember that MinMaxScaler rescales the data from its original value so all the new values are within the range 0–1." }, { "code": null, "e": 6705, "s": 6052, "text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()df_highqN = df_highqdf_highqN[['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH','sulphates','alcohol']] =scaler.fit_transform(df_highqN[[ 'fixed acidity', 'volatile acidity', 'citric acidity','residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']])" }, { "code": null, "e": 7239, "s": 6705, "text": "For the parallel coordinate plot in this article, the Plotly Express function is px.parallel_coordinates and the corresponding parameters are: data_frame; color= a name of a column in data_frame whose values are used to indicate the colors of lines; dimensions= names of columns in data_frame whose values are used to draw the lines; color_continuous_scale= to choose any of the built-in color scales; color_continuous_midpoint= to set an appropriate midpoint value when using a diverging color scale; title= to set the figure title." }, { "code": null, "e": 7766, "s": 7239, "text": "fig0 = px.parallel_coordinates(df_highqN, color=\"quality\", dimensions=['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol' ], color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=7.5, title = 'PCP High Quality Wines Without Reordering')fig0.show()" }, { "code": null, "e": 7906, "s": 7766, "text": "It’s really a mess. There is no way to get any useful information, so we decided to try different reordering schemes until we got Figure 3." }, { "code": null, "e": 8357, "s": 7906, "text": "fig1 = px.parallel_coordinates(df_highqN, color=\"quality\", dimensions=['residual sugar', 'chlorides', 'sulphates', 'volatile acidity', 'density', 'pH', 'citric acidity', 'alcohol' ], color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=7.5, title = 'PCP High Quality Wines After Reordering')fig1.show()" }, { "code": null, "e": 8503, "s": 8357, "text": "The figure shows that high quality wines have low levels of residual sugar, chlorides, and sulphates, and high levels of alcohol and citric acid." }, { "code": null, "e": 8554, "s": 8503, "text": "Let’s look at what happens with low-quality wines:" }, { "code": null, "e": 9504, "s": 8554, "text": "df_lowq2 = df_lowqdf_lowq2[['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']] = scaler.fit_transform(df_lowq2[[ 'fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']])fig2 = px.parallel_coordinates(df_lowq2, color=\"quality\", dimensions=['residual sugar', 'chlorides', 'sulphates', 'volatile acidity', 'alcohol', 'pH','density', 'citric acidity' ], color_continuous_scale=px.colors.diverging.RdYlBu, color_continuous_midpoint=4, title = 'PCP Low Quality Wines After Reordering')fig2.show()" }, { "code": null, "e": 9600, "s": 9504, "text": "It seems that low quality wines have high levels of chlorides, sulphates, and volatile acidity." }, { "code": null, "e": 9704, "s": 9600, "text": "Finally, we would like to know if scaling with the standardization technique improves the storytelling." }, { "code": null, "e": 10757, "s": 9704, "text": "from sklearn.preprocessing import StandardScalerscalerST = StandardScaler()df_highqS = df_highqdf_highqS[['fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']] = scalerST.fit_transform(df_highqS[[ 'fixed acidity', 'volatile acidity', 'citric acidity', 'residual sugar', 'chlorides','free sulfur dioxide', 'total sulfur dioxide','density', 'pH', 'sulphates', 'alcohol']])fig3 = px.parallel_coordinates(df_highqS, color=\"quality\", dimensions=['residual sugar', 'chlorides', 'sulphates', 'fixed acidity', 'density', 'volatile acidity','pH', 'citric acidity' ], color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=7.5, title= 'PCP High Quality Wines After Standardization')fig3.show()" }, { "code": null, "e": 10938, "s": 10757, "text": "As can be seen, the display is equivalent to that of Figure 3 with the additional difficulty of showing negative values for chemical and physical properties that do not correspond." }, { "code": null, "e": 11251, "s": 10938, "text": "In summary, Parallel Coordinates Plots are very complex graphics that require several preprocessing steps. They are only recommended for data sets with a large number of numerical variables. Always use Normalization as the scaling technique. Their complexity does not allow to guarantee an adequate storytelling." }, { "code": null, "e": 11344, "s": 11251, "text": "If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):" }, { "code": null, "e": 11401, "s": 11344, "text": "Diverging Bars, Why & How, Storytelling with Divergences" }, { "code": null, "e": 11424, "s": 11401, "text": "towardsdatascience.com" } ]
How to get a horizontal scrollbar in Tkinter?
The Scrollbar widget in tkinter is one of the useful widgets that is used to pack the container elements and their contents with a scrollbar. With Scrollbars, we can view large sets of data very efficiently. Generally, Tkinter allows to add vertical and horizontal scrollbars. To add a horizontal scrollbar in an application, we've to use the orientation as Horizontal in the scrollbar constructor. Let us create a text editor that contains a horizontal scrollbar in it. # 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") # Add a Scrollbar(horizontal) h=Scrollbar(win, orient='horizontal') h.pack(side=BOTTOM, fill='x') # Add a text widget text=Text(win, font=("Calibri, 16"), wrap=NONE, xscrollcommand=h.set) text.pack() # Add some text in the text widget for i in range(5): text.insert(END, "Welcome to Tutorialspoint...") # Attach the scrollbar with the text widget h.config(command=text.xview) win.mainloop() If we run the above code, it will display a text editor that will have some text in it. The text widget is packed with a horizontal scrollbar which gets visible whenever the text overflows.
[ { "code": null, "e": 1270, "s": 1062, "text": "The Scrollbar widget in tkinter is one of the useful widgets that is used to pack the container elements and their contents with a scrollbar. With Scrollbars, we can view large sets of data very efficiently." }, { "code": null, "e": 1461, "s": 1270, "text": "Generally, Tkinter allows to add vertical and horizontal scrollbars. To add a horizontal scrollbar in an application, we've to use the orientation as Horizontal in the scrollbar constructor." }, { "code": null, "e": 1533, "s": 1461, "text": "Let us create a text editor that contains a horizontal scrollbar in it." }, { "code": null, "e": 2131, "s": 1533, "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\n# Add a Scrollbar(horizontal)\nh=Scrollbar(win, orient='horizontal')\nh.pack(side=BOTTOM, fill='x')\n\n# Add a text widget\ntext=Text(win, font=(\"Calibri, 16\"), wrap=NONE, xscrollcommand=h.set)\ntext.pack()\n\n# Add some text in the text widget\nfor i in range(5):\n text.insert(END, \"Welcome to Tutorialspoint...\")\n\n# Attach the scrollbar with the text widget\nh.config(command=text.xview)\n\nwin.mainloop()" }, { "code": null, "e": 2321, "s": 2131, "text": "If we run the above code, it will display a text editor that will have some text in it. The text widget is packed with a horizontal scrollbar which gets visible whenever the text overflows." } ]
GATE | GATE-CS-2004 | Question 63
25 Oct, 2018 Direction for questions 63 to 64:Consider the following program segment for a hypothetical CPU having three user registers R1, R2 and R3. Instruction Operation Instruction Size(in words) MOV R1,5000; R1 ¬ Memory[5000] 2 MOV R2, (R1); R2 ¬ Memory[(R1)] 1 ADD R2, R3; R2 ¬ R2 + R3 1 MOV 6000, R2; Memory [6000] ¬ R2 2 HALT Machine halts 1 Consider that the memory is byte addressable with size 32 bits, and the program has been loaded starting from memory location 1000 (decimal). If an interrupt occurs while the CPU has been halted after executing the HALT instruction, the return address (in decimal) saved in the stack will be(A) 1007(B) 1020(C) 1024(D) 1028Answer: (D)Explanation: Instructions size are given in words. So first instruction will take 2 words i.e 8 bytes(as 32 bit byte addressable, word size will be 32 bit ) so on for 2nd instruction 4 byte, for 3rd 4 bytes, 4th 8 bytes..5th 4 bytes. As 1st instruction starts from 1000 and the size is 8 bytes second instruction address will be 1008, like wise 3rd instruction address will be 1012,4th instruction address 1016,5th instruction address 1024 and halt instruction address will be 1028. As an interrupt occurs executing the HALT instruction, the return address (in decimal) saved in the stack will be the address of the halt instruction ..so answer is 1028.Note – If interrupt occur, then value of PC will be return address of that instruction after HALT.Quiz of this Question GATE-CS-2004 GATE-GATE-CS-2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 40 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Oct, 2018" }, { "code": null, "e": 166, "s": 28, "text": "Direction for questions 63 to 64:Consider the following program segment for a hypothetical CPU having three user registers R1, R2 and R3." }, { "code": null, "e": 456, "s": 166, "text": " Instruction Operation Instruction Size(in words)\n MOV R1,5000; R1 ¬ Memory[5000] 2\n MOV R2, (R1); R2 ¬ Memory[(R1)] 1\n ADD R2, R3; R2 ¬ R2 + R3 1\n MOV 6000, R2; Memory [6000] ¬ R2 2\n HALT Machine halts 1 " }, { "code": null, "e": 1563, "s": 456, "text": "Consider that the memory is byte addressable with size 32 bits, and the program has been loaded starting from memory location 1000 (decimal). If an interrupt occurs while the CPU has been halted after executing the HALT instruction, the return address (in decimal) saved in the stack will be(A) 1007(B) 1020(C) 1024(D) 1028Answer: (D)Explanation: Instructions size are given in words. So first instruction will take 2 words i.e 8 bytes(as 32 bit byte addressable, word size will be 32 bit ) so on for 2nd instruction 4 byte, for 3rd 4 bytes, 4th 8 bytes..5th 4 bytes. As 1st instruction starts from 1000 and the size is 8 bytes second instruction address will be 1008, like wise 3rd instruction address will be 1012,4th instruction address 1016,5th instruction address 1024 and halt instruction address will be 1028. As an interrupt occurs executing the HALT instruction, the return address (in decimal) saved in the stack will be the address of the halt instruction ..so answer is 1028.Note – If interrupt occur, then value of PC will be return address of that instruction after HALT.Quiz of this Question" }, { "code": null, "e": 1576, "s": 1563, "text": "GATE-CS-2004" }, { "code": null, "e": 1594, "s": 1576, "text": "GATE-GATE-CS-2004" }, { "code": null, "e": 1599, "s": 1594, "text": "GATE" }, { "code": null, "e": 1697, "s": 1599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1739, "s": 1697, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1801, "s": 1739, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1843, "s": 1801, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 1877, "s": 1843, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 1911, "s": 1877, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1953, "s": 1911, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1995, "s": 1953, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2029, "s": 1995, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 2063, "s": 2029, "text": "GATE | GATE CS 1996 | Question 38" } ]
Riemann Sum
24 Jun, 2021 Definite integrals are an important part of calculus. They are used to calculate the areas, volumes, etc of arbitrary shapes for which formulas are not defined. Analytically they are just indefinite integrals with limits on top of them, but graphically they represent the area under the curve. The limits denote the boundaries between which the area should be calculated. These concepts hold a lot of importance in the field of electrical engineering, robotics, etc. For defining integrals, Riemann sums are used in which we calculate the area under any curve using infinitesimally small rectangles. Let’s look at this interpretation of definite integrals in detail. Riemann’s sums are a method for approximating the area under the curve. The intuition behind it is, if we divide the area into very small rectangles, we can calculate the area of each rectangle and then add them to find the area of the total region. This is the same intuition as the intuition behind the definite integrals. So, these sums can be also be used to approximate and define the definite integrals. Definite integrals are nothing but integrals with limits, they are used to find the areas, volumes, etc under arbitrary curve shapes. Consider the figure below, the goal is to calculate the area enclosed by this curve between x = a and x = b and the x-axis. Now let’s start with dividing the given area into a number of rectangles, assuming the area is divided into ‘n’ rectangles of equal width. Notice that these rectangles do not cover the full area, so it is an approximation of the area. But as the number of rectangles increases, the approximation comes closer and closer to the actual area. In the definite integral notation, this area will be represented as, This area can be approximated by divided the area under the curve into n equally sized rectangles. So, the interval [a, b] is divided into n-subintervals defined by the points. a = x0 < x1 < x2 < .... xn-2< xn-1 < xn = b Then, the n intervals are, [x0, x1], [x1, x2], .... [xn-1, xn] So, for the ith rectangle, the width will be, [xi-1, xi]. The area for ith rectangle Ai = f(xi)(xi — xi-1) So, the total area will be This sum is called the Riemann sum. Since the height of the rectangle is determined by the right limit of the interval, this is called the right-Riemann sum. The figure below shows the left-Riemann sum. Summation Notation The steps given below should be followed to find the summation notation of the riemann integral. Step 1: Find out the width of each interval. Let’s denote the width of interval with Step 2: Let xi denote the right-endpoint of the rectangle xi = a + .i Step 3: Define the area of each rectangle. Step 4: Sum the areas Let’s say the goal is to calculate the area under the graph of the function f(x) = x3, the area will be calculated between the limits x = 0 to x = 4. Divide the interval into four equal parts, the intervals will be [0, 1], [1, 2], [2, 3] and [3, 4]. The riemann sum then, can be written as follows, A(1) + A(2) + A(3) + A(4) = Let’s calculate the right sum Riemann sum. Assume xi denotes the right endpoint of the ith rectangle. So, the formula for xi = i. Now, the value of the function at these points becomes, f(xi) = (i)3 So, A(i) = (height)(width) = (i)3 The Riemann sum becomes, A(1) + A(2) + A(3) + A(4) = ⇒ A(1) + A(2) + A(3) + A(4) = So, this way almost all the Riemann sums can be represented in a sigma notation. Let’s work out some problems with these concepts. Question 1: Choose which type of the Riemann integral is shown below in the figure. Left-Riemann Sum Right-Riemann SumMid-point Riemann Sum Left-Riemann Sum Right-Riemann Sum Mid-point Riemann Sum Solution: Since the values of the intervals are decided according to the left-end point of the interval. This is a left-Riemann Sum Answer-(1). Question 2: Calculate the Left-Riemann Sum for the function given in the figure above. Solution: Dividing the interval into four equal parts that is n = 4. The width of each interval will be, x0 = 0, x1 = 1, x2 = 2, x3 = 0 and x4 = 0 The value of the function in each interval will be the value of the function at the right-end of the interval. ⇒A = ⇒A = ⇒A = f(1)(2) + f(2)(2)+ f(3)(2) + f(4)(2) ⇒A = (f(1) + f(2) + f(3)+ f(4))(2) ⇒A = (1 + 2 + 3+ 4)(2) ⇒A = (10)(2) ⇒A = 20 Question 3: Consider a function f(x) = 5 – 2x, its area is calculated from riemann sum from x = 0 to x = 4, the whole area is divided into 4 rectangles. Find the riemann sum in sigma notation Answer: Step (i): Calculate the width The whole length is divided into 4 equal parts, xi = 0 and xl = 4, Width of an interval is given by = Where xi = initial point, and xl – last point and n= number of parts n = 4 Step(ii): a = 0, xi = 0 + i ⇒ xi = i Step (iii): Ai = Height x Width = f(xi) = (5 – 2i)(1) = 5 – 2i Total Area = A(1) + A(2) + A(3) + A(4) + A(5) = Question 4: Consider a function f(x) = x2, its area is calculated from riemann sum from x = 0 to x = 3, the whole area is divided into 3 rectangles. Find the riemann sum in sigma notation Answer: Step (i): Calculate the width The whole length is divided into 3 equal parts, xi = 0 and xl = 3, Width of an interval is given by = Where xi = initial point, and xl – last point and n= number of parts n = 3 Step(ii): a = 0, xi = 0 + i ⇒ xi = i Step (iii) Ai = Height x Width = f(xi) = (i2) Total Area = A(1) + A(2) + A(3) + A(4) + A(5) = Question 5: Consider a function f(x) = √x, its area is calculated from riemann sum from x = 0 to x = 4, the whole area is divided into 4 rectangles. Find the riemann sum in sigma notation Answer: Step (i): Calculate the width The whole length is divided into 4 equal parts, xi = 0 and xl = 4, Width of an interval is given by = Where xi = initial point, and xl – last point and n= number of parts n = 4 Step(ii): a = 0, xi = 0 + i ⇒ xi = i Step (iii) Ai = Height x Width = f(xi) = (√i)(1) = √i Total Area = A(1) + A(2) + A(3) + A(4) = Question 6: Consider a function f(x) = x2, its area is calculated from riemann sum from x = 0 to x = 2, the whole area is divided into 2 rectangles. Find the riemann sum in sigma notation Answer: Step (i): Calculate the width The whole length is divided into 2 equal parts, xi = 0 and xl = 2, Width of an interval is given by = Where xi = initial point, and xl – last point and n= number of parts n = 2 Step(ii): a = 0, xi = 0 + i ⇒ xi = i Step (iii): Ai = Height x Width = f(xi) = (i2)(1) = i2 Total Area = A(1) + A(2) + A(3) + A(4) = Question 7: Consider a function f(x) = 3(x + 3), its area is calculated from riemann sum from x = 0 to x = 6, the whole area is divided into 6 rectangles. Find the riemann sum in sigma notation Answer: Step (i): Calculate the width The whole length is divided into 4 equal parts, xi = 0 and xl = 6, Width of an interval is given by = Where xi = initial point, and xl – last point and n= number of parts n = 6 Step(ii): a = 0, xi = 0 + i ⇒ xi = i Step (iii): Ai = Height x Width = f(xi) = (3(i + 3))(1) = 3(i + 3) Total Area = A(1) + A(2) + A(3) + A(4) = Picked Class 12 School Learning School Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting Algorithms in Python Cardinality in DBMS Querying Data from a Database using fetchone() and fetchall() Intrinsic Semiconductors and Extrinsic Semiconductors How to Create a Database Connection? How to Align Text in HTML? What are Different Output Devices? Generations of Computers - Computer Fundamentals Cloud Deployment Models What is a Storage Device? Definition, Types, Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 696, "s": 28, "text": "Definite integrals are an important part of calculus. They are used to calculate the areas, volumes, etc of arbitrary shapes for which formulas are not defined. Analytically they are just indefinite integrals with limits on top of them, but graphically they represent the area under the curve. The limits denote the boundaries between which the area should be calculated. These concepts hold a lot of importance in the field of electrical engineering, robotics, etc. For defining integrals, Riemann sums are used in which we calculate the area under any curve using infinitesimally small rectangles. Let’s look at this interpretation of definite integrals in detail. " }, { "code": null, "e": 1365, "s": 696, "text": "Riemann’s sums are a method for approximating the area under the curve. The intuition behind it is, if we divide the area into very small rectangles, we can calculate the area of each rectangle and then add them to find the area of the total region. This is the same intuition as the intuition behind the definite integrals. So, these sums can be also be used to approximate and define the definite integrals. Definite integrals are nothing but integrals with limits, they are used to find the areas, volumes, etc under arbitrary curve shapes. Consider the figure below, the goal is to calculate the area enclosed by this curve between x = a and x = b and the x-axis. " }, { "code": null, "e": 1706, "s": 1365, "text": "Now let’s start with dividing the given area into a number of rectangles, assuming the area is divided into ‘n’ rectangles of equal width. Notice that these rectangles do not cover the full area, so it is an approximation of the area. But as the number of rectangles increases, the approximation comes closer and closer to the actual area. " }, { "code": null, "e": 1776, "s": 1706, "text": "In the definite integral notation, this area will be represented as, " }, { "code": null, "e": 1954, "s": 1776, "text": "This area can be approximated by divided the area under the curve into n equally sized rectangles. So, the interval [a, b] is divided into n-subintervals defined by the points. " }, { "code": null, "e": 1998, "s": 1954, "text": "a = x0 < x1 < x2 < .... xn-2< xn-1 < xn = b" }, { "code": null, "e": 2026, "s": 1998, "text": "Then, the n intervals are, " }, { "code": null, "e": 2062, "s": 2026, "text": "[x0, x1], [x1, x2], .... [xn-1, xn]" }, { "code": null, "e": 2121, "s": 2062, "text": "So, for the ith rectangle, the width will be, [xi-1, xi]. " }, { "code": null, "e": 2170, "s": 2121, "text": "The area for ith rectangle Ai = f(xi)(xi — xi-1)" }, { "code": null, "e": 2198, "s": 2170, "text": "So, the total area will be " }, { "code": null, "e": 2402, "s": 2198, "text": "This sum is called the Riemann sum. Since the height of the rectangle is determined by the right limit of the interval, this is called the right-Riemann sum. The figure below shows the left-Riemann sum. " }, { "code": null, "e": 2421, "s": 2402, "text": "Summation Notation" }, { "code": null, "e": 2518, "s": 2421, "text": "The steps given below should be followed to find the summation notation of the riemann integral." }, { "code": null, "e": 2604, "s": 2518, "text": "Step 1: Find out the width of each interval. Let’s denote the width of interval with " }, { "code": null, "e": 2674, "s": 2604, "text": "Step 2: Let xi denote the right-endpoint of the rectangle xi = a + .i" }, { "code": null, "e": 2718, "s": 2674, "text": "Step 3: Define the area of each rectangle. " }, { "code": null, "e": 2741, "s": 2718, "text": "Step 4: Sum the areas " }, { "code": null, "e": 2891, "s": 2741, "text": "Let’s say the goal is to calculate the area under the graph of the function f(x) = x3, the area will be calculated between the limits x = 0 to x = 4." }, { "code": null, "e": 2992, "s": 2891, "text": "Divide the interval into four equal parts, the intervals will be [0, 1], [1, 2], [2, 3] and [3, 4]. " }, { "code": null, "e": 3042, "s": 2992, "text": "The riemann sum then, can be written as follows, " }, { "code": null, "e": 3071, "s": 3042, "text": "A(1) + A(2) + A(3) + A(4) = " }, { "code": null, "e": 3174, "s": 3071, "text": "Let’s calculate the right sum Riemann sum. Assume xi denotes the right endpoint of the ith rectangle. " }, { "code": null, "e": 3259, "s": 3174, "text": "So, the formula for xi = i. Now, the value of the function at these points becomes, " }, { "code": null, "e": 3272, "s": 3259, "text": "f(xi) = (i)3" }, { "code": null, "e": 3300, "s": 3272, "text": "So, A(i) = (height)(width) " }, { "code": null, "e": 3321, "s": 3300, "text": " = (i)3" }, { "code": null, "e": 3347, "s": 3321, "text": "The Riemann sum becomes, " }, { "code": null, "e": 3377, "s": 3347, "text": " A(1) + A(2) + A(3) + A(4) = " }, { "code": null, "e": 3408, "s": 3377, "text": "⇒ A(1) + A(2) + A(3) + A(4) = " }, { "code": null, "e": 3490, "s": 3408, "text": "So, this way almost all the Riemann sums can be represented in a sigma notation. " }, { "code": null, "e": 3541, "s": 3490, "text": "Let’s work out some problems with these concepts. " }, { "code": null, "e": 3626, "s": 3541, "text": "Question 1: Choose which type of the Riemann integral is shown below in the figure. " }, { "code": null, "e": 3683, "s": 3626, "text": "Left-Riemann Sum Right-Riemann SumMid-point Riemann Sum " }, { "code": null, "e": 3701, "s": 3683, "text": "Left-Riemann Sum " }, { "code": null, "e": 3719, "s": 3701, "text": "Right-Riemann Sum" }, { "code": null, "e": 3742, "s": 3719, "text": "Mid-point Riemann Sum " }, { "code": null, "e": 3753, "s": 3742, "text": "Solution: " }, { "code": null, "e": 3876, "s": 3753, "text": "Since the values of the intervals are decided according to the left-end point of the interval. This is a left-Riemann Sum " }, { "code": null, "e": 3888, "s": 3876, "text": "Answer-(1)." }, { "code": null, "e": 3976, "s": 3888, "text": "Question 2: Calculate the Left-Riemann Sum for the function given in the figure above. " }, { "code": null, "e": 3987, "s": 3976, "text": "Solution: " }, { "code": null, "e": 4083, "s": 3987, "text": "Dividing the interval into four equal parts that is n = 4. The width of each interval will be, " }, { "code": null, "e": 4125, "s": 4083, "text": "x0 = 0, x1 = 1, x2 = 2, x3 = 0 and x4 = 0" }, { "code": null, "e": 4237, "s": 4125, "text": "The value of the function in each interval will be the value of the function at the right-end of the interval. " }, { "code": null, "e": 4243, "s": 4237, "text": "⇒A = " }, { "code": null, "e": 4249, "s": 4243, "text": "⇒A = " }, { "code": null, "e": 4291, "s": 4249, "text": "⇒A = f(1)(2) + f(2)(2)+ f(3)(2) + f(4)(2)" }, { "code": null, "e": 4326, "s": 4291, "text": "⇒A = (f(1) + f(2) + f(3)+ f(4))(2)" }, { "code": null, "e": 4349, "s": 4326, "text": "⇒A = (1 + 2 + 3+ 4)(2)" }, { "code": null, "e": 4362, "s": 4349, "text": "⇒A = (10)(2)" }, { "code": null, "e": 4370, "s": 4362, "text": "⇒A = 20" }, { "code": null, "e": 4562, "s": 4370, "text": "Question 3: Consider a function f(x) = 5 – 2x, its area is calculated from riemann sum from x = 0 to x = 4, the whole area is divided into 4 rectangles. Find the riemann sum in sigma notation" }, { "code": null, "e": 4571, "s": 4562, "text": "Answer: " }, { "code": null, "e": 4601, "s": 4571, "text": "Step (i): Calculate the width" }, { "code": null, "e": 4650, "s": 4601, "text": "The whole length is divided into 4 equal parts, " }, { "code": null, "e": 4670, "s": 4650, "text": "xi = 0 and xl = 4, " }, { "code": null, "e": 4706, "s": 4670, "text": "Width of an interval is given by = " }, { "code": null, "e": 4776, "s": 4706, "text": "Where xi = initial point, and xl – last point and n= number of parts " }, { "code": null, "e": 4783, "s": 4776, "text": "n = 4 " }, { "code": null, "e": 4794, "s": 4783, "text": "Step(ii): " }, { "code": null, "e": 4802, "s": 4794, "text": "a = 0, " }, { "code": null, "e": 4815, "s": 4802, "text": "xi = 0 + i " }, { "code": null, "e": 4824, "s": 4815, "text": "⇒ xi = i" }, { "code": null, "e": 4837, "s": 4824, "text": "Step (iii): " }, { "code": null, "e": 4858, "s": 4837, "text": "Ai = Height x Width " }, { "code": null, "e": 4871, "s": 4858, "text": " = f(xi) " }, { "code": null, "e": 4889, "s": 4871, "text": " = (5 – 2i)(1)" }, { "code": null, "e": 4902, "s": 4889, "text": " = 5 – 2i" }, { "code": null, "e": 4948, "s": 4902, "text": "Total Area = A(1) + A(2) + A(3) + A(4) + A(5)" }, { "code": null, "e": 4969, "s": 4948, "text": " = " }, { "code": null, "e": 5157, "s": 4969, "text": "Question 4: Consider a function f(x) = x2, its area is calculated from riemann sum from x = 0 to x = 3, the whole area is divided into 3 rectangles. Find the riemann sum in sigma notation" }, { "code": null, "e": 5166, "s": 5157, "text": "Answer: " }, { "code": null, "e": 5196, "s": 5166, "text": "Step (i): Calculate the width" }, { "code": null, "e": 5245, "s": 5196, "text": "The whole length is divided into 3 equal parts, " }, { "code": null, "e": 5265, "s": 5245, "text": "xi = 0 and xl = 3, " }, { "code": null, "e": 5301, "s": 5265, "text": "Width of an interval is given by = " }, { "code": null, "e": 5371, "s": 5301, "text": "Where xi = initial point, and xl – last point and n= number of parts " }, { "code": null, "e": 5378, "s": 5371, "text": "n = 3 " }, { "code": null, "e": 5389, "s": 5378, "text": "Step(ii): " }, { "code": null, "e": 5397, "s": 5389, "text": "a = 0, " }, { "code": null, "e": 5410, "s": 5397, "text": "xi = 0 + i " }, { "code": null, "e": 5419, "s": 5410, "text": "⇒ xi = i" }, { "code": null, "e": 5431, "s": 5419, "text": "Step (iii) " }, { "code": null, "e": 5452, "s": 5431, "text": "Ai = Height x Width " }, { "code": null, "e": 5465, "s": 5452, "text": " = f(xi) " }, { "code": null, "e": 5476, "s": 5465, "text": " = (i2)" }, { "code": null, "e": 5522, "s": 5476, "text": "Total Area = A(1) + A(2) + A(3) + A(4) + A(5)" }, { "code": null, "e": 5543, "s": 5522, "text": " = " }, { "code": null, "e": 5731, "s": 5543, "text": "Question 5: Consider a function f(x) = √x, its area is calculated from riemann sum from x = 0 to x = 4, the whole area is divided into 4 rectangles. Find the riemann sum in sigma notation" }, { "code": null, "e": 5740, "s": 5731, "text": "Answer: " }, { "code": null, "e": 5770, "s": 5740, "text": "Step (i): Calculate the width" }, { "code": null, "e": 5819, "s": 5770, "text": "The whole length is divided into 4 equal parts, " }, { "code": null, "e": 5839, "s": 5819, "text": "xi = 0 and xl = 4, " }, { "code": null, "e": 5875, "s": 5839, "text": "Width of an interval is given by = " }, { "code": null, "e": 5945, "s": 5875, "text": "Where xi = initial point, and xl – last point and n= number of parts " }, { "code": null, "e": 5952, "s": 5945, "text": "n = 4 " }, { "code": null, "e": 5963, "s": 5952, "text": "Step(ii): " }, { "code": null, "e": 5971, "s": 5963, "text": "a = 0, " }, { "code": null, "e": 5983, "s": 5971, "text": "xi = 0 + i " }, { "code": null, "e": 5992, "s": 5983, "text": "⇒ xi = i" }, { "code": null, "e": 6004, "s": 5992, "text": "Step (iii) " }, { "code": null, "e": 6025, "s": 6004, "text": "Ai = Height x Width " }, { "code": null, "e": 6038, "s": 6025, "text": " = f(xi) " }, { "code": null, "e": 6052, "s": 6038, "text": " = (√i)(1)" }, { "code": null, "e": 6061, "s": 6052, "text": " = √i" }, { "code": null, "e": 6101, "s": 6061, "text": "Total Area = A(1) + A(2) + A(3) + A(4) " }, { "code": null, "e": 6122, "s": 6101, "text": " = " }, { "code": null, "e": 6310, "s": 6122, "text": "Question 6: Consider a function f(x) = x2, its area is calculated from riemann sum from x = 0 to x = 2, the whole area is divided into 2 rectangles. Find the riemann sum in sigma notation" }, { "code": null, "e": 6319, "s": 6310, "text": "Answer: " }, { "code": null, "e": 6349, "s": 6319, "text": "Step (i): Calculate the width" }, { "code": null, "e": 6398, "s": 6349, "text": "The whole length is divided into 2 equal parts, " }, { "code": null, "e": 6418, "s": 6398, "text": "xi = 0 and xl = 2, " }, { "code": null, "e": 6454, "s": 6418, "text": "Width of an interval is given by = " }, { "code": null, "e": 6524, "s": 6454, "text": "Where xi = initial point, and xl – last point and n= number of parts " }, { "code": null, "e": 6531, "s": 6524, "text": "n = 2 " }, { "code": null, "e": 6542, "s": 6531, "text": "Step(ii): " }, { "code": null, "e": 6550, "s": 6542, "text": "a = 0, " }, { "code": null, "e": 6563, "s": 6550, "text": "xi = 0 + i " }, { "code": null, "e": 6572, "s": 6563, "text": "⇒ xi = i" }, { "code": null, "e": 6584, "s": 6572, "text": "Step (iii):" }, { "code": null, "e": 6605, "s": 6584, "text": "Ai = Height x Width " }, { "code": null, "e": 6618, "s": 6605, "text": " = f(xi) " }, { "code": null, "e": 6632, "s": 6618, "text": " = (i2)(1)" }, { "code": null, "e": 6641, "s": 6632, "text": " = i2" }, { "code": null, "e": 6681, "s": 6641, "text": "Total Area = A(1) + A(2) + A(3) + A(4) " }, { "code": null, "e": 6702, "s": 6681, "text": " = " }, { "code": null, "e": 6896, "s": 6702, "text": "Question 7: Consider a function f(x) = 3(x + 3), its area is calculated from riemann sum from x = 0 to x = 6, the whole area is divided into 6 rectangles. Find the riemann sum in sigma notation" }, { "code": null, "e": 6905, "s": 6896, "text": "Answer: " }, { "code": null, "e": 6935, "s": 6905, "text": "Step (i): Calculate the width" }, { "code": null, "e": 6984, "s": 6935, "text": "The whole length is divided into 4 equal parts, " }, { "code": null, "e": 7004, "s": 6984, "text": "xi = 0 and xl = 6, " }, { "code": null, "e": 7040, "s": 7004, "text": "Width of an interval is given by = " }, { "code": null, "e": 7110, "s": 7040, "text": "Where xi = initial point, and xl – last point and n= number of parts " }, { "code": null, "e": 7117, "s": 7110, "text": "n = 6 " }, { "code": null, "e": 7128, "s": 7117, "text": "Step(ii): " }, { "code": null, "e": 7136, "s": 7128, "text": "a = 0, " }, { "code": null, "e": 7149, "s": 7136, "text": "xi = 0 + i " }, { "code": null, "e": 7158, "s": 7149, "text": "⇒ xi = i" }, { "code": null, "e": 7170, "s": 7158, "text": "Step (iii):" }, { "code": null, "e": 7191, "s": 7170, "text": "Ai = Height x Width " }, { "code": null, "e": 7204, "s": 7191, "text": " = f(xi) " }, { "code": null, "e": 7224, "s": 7204, "text": " = (3(i + 3))(1)" }, { "code": null, "e": 7239, "s": 7224, "text": " = 3(i + 3)" }, { "code": null, "e": 7279, "s": 7239, "text": "Total Area = A(1) + A(2) + A(3) + A(4) " }, { "code": null, "e": 7300, "s": 7279, "text": " = " }, { "code": null, "e": 7307, "s": 7300, "text": "Picked" }, { "code": null, "e": 7316, "s": 7307, "text": "Class 12" }, { "code": null, "e": 7332, "s": 7316, "text": "School Learning" }, { "code": null, "e": 7351, "s": 7332, "text": "School Mathematics" }, { "code": null, "e": 7449, "s": 7351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7478, "s": 7449, "text": "Sorting Algorithms in Python" }, { "code": null, "e": 7498, "s": 7478, "text": "Cardinality in DBMS" }, { "code": null, "e": 7560, "s": 7498, "text": "Querying Data from a Database using fetchone() and fetchall()" }, { "code": null, "e": 7614, "s": 7560, "text": "Intrinsic Semiconductors and Extrinsic Semiconductors" }, { "code": null, "e": 7651, "s": 7614, "text": "How to Create a Database Connection?" }, { "code": null, "e": 7678, "s": 7651, "text": "How to Align Text in HTML?" }, { "code": null, "e": 7713, "s": 7678, "text": "What are Different Output Devices?" }, { "code": null, "e": 7762, "s": 7713, "text": "Generations of Computers - Computer Fundamentals" }, { "code": null, "e": 7786, "s": 7762, "text": "Cloud Deployment Models" } ]
sector() function in C
06 Dec, 2019 The header file graphics.h contains sector() function which draws and fills an elliptical pie slice with (x, y) as center, (s_angle, e_angle) as starting and ending angle and (x_radius, y_radius) as x and y radius of sector.Syntax : void sector(int x, int y, int s_angle, int e_angle, int x_radius, int y_radius); where, (x, y) is center of the sector. (s_angle, e_angle) are starting and ending angles. (x_radius, y_radius) are x and y radius of sector. Examples : Input : x = 200, y = 200, s_angle = 0, e_angle = 150, x_radius = 50, y_radius = 65 Output : Input : x = 200, y = 200, s_angle = 30, e_angle = 120, x_radius = 90, y_radius = 85 Output : Below is the implementation of sector() function : // C Implementation for sector()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sector function sector(200, 200, 0, 150, 50, 65); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;} Output : Akanksha_Rai c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2019" }, { "code": null, "e": 287, "s": 54, "text": "The header file graphics.h contains sector() function which draws and fills an elliptical pie slice with (x, y) as center, (s_angle, e_angle) as starting and ending angle and (x_radius, y_radius) as x and y radius of sector.Syntax :" }, { "code": null, "e": 549, "s": 287, "text": "void sector(int x, int y, int s_angle, \n int e_angle, int x_radius, \n int y_radius);\n\nwhere,\n(x, y) is center of the sector.\n(s_angle, e_angle) are starting \nand ending angles.\n(x_radius, y_radius) are x and y\nradius of sector.\n" }, { "code": null, "e": 560, "s": 549, "text": "Examples :" }, { "code": null, "e": 787, "s": 560, "text": "Input : x = 200, y = 200, s_angle = 0,\n e_angle = 150, x_radius = 50, \n y_radius = 65\nOutput : \n\nInput : x = 200, y = 200, s_angle = 30, \n e_angle = 120, x_radius = 90, \n y_radius = 85 \nOutput : \n" }, { "code": null, "e": 838, "s": 787, "text": "Below is the implementation of sector() function :" }, { "code": "// C Implementation for sector()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // sector function sector(200, 200, 0, 150, 50, 65); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}", "e": 1481, "s": 838, "text": null }, { "code": null, "e": 1490, "s": 1481, "text": "Output :" }, { "code": null, "e": 1505, "s": 1492, "text": "Akanksha_Rai" }, { "code": null, "e": 1516, "s": 1505, "text": "c-graphics" }, { "code": null, "e": 1534, "s": 1516, "text": "computer-graphics" }, { "code": null, "e": 1545, "s": 1534, "text": "C Language" } ]
WPF - Togglebutton
A Toggle Button is a control that can switch states, such as CheckBox and RadioButton. The hierarchical inheritance of ToggleButton class is as follows − IsChecked Gets or sets whether the ToggleButton is checked. IsCheckedProperty Identifies the IsChecked dependency property. IsThreeState Gets or sets a value that indicates whether the control supports three states. IsThreeStateProperty Identifies the IsThreeState dependency property. Checked Fires when a ToggleButton is checked. Indeterminate Fires when the state of a ToggleButton is switched to the indeterminate state. Unchecked Occurs when a ToggleButton is unchecked. Let’s create a new WPF project with WPFToggleButtonControl. Drag a text block and a toggle button from the toolbox. Change the background color of the text block from the properties window. The following example shows the usage of ToggleButton in an XAML application. The following XAML code creates a ToggleButton and initializes it with some properties. <Window x:Class = "WPFToggleButtonControl.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFToggleButtonControl" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <ToggleButton x:Name = "tb" Content = "Toggle" Checked = "HandleCheck" Unchecked = "HandleUnchecked"Margin = "20" Width = "108"HorizontalAlignment = "Center" /> <TextBlock x:Name = "text2" Margin = "20" Width = "300" HorizontalAlignment = "Center" FontSize = "24" Background = "#FFFDE0E0" /> </StackPanel> </Window> Here is the C# implementation of Checked and Unchecked events. using System.Windows; namespace WPFToggleButtonControl { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void HandleCheck(object sender, RoutedEventArgs e) { text2.Text = "Button is Checked"; } private void HandleUnchecked(object sender, RoutedEventArgs e) { text2.Text = "Button is unchecked."; } } } When you compile and execute the above code, it will produce the following window. When you click the button, it will change the color and update the text block. We recommend that you execute the above example code and try the other properties and events of ToggleButton.
[ { "code": null, "e": 2308, "s": 2154, "text": "A Toggle Button is a control that can switch states, such as CheckBox and RadioButton. The hierarchical inheritance of ToggleButton class is as follows −" }, { "code": null, "e": 2318, "s": 2308, "text": "IsChecked" }, { "code": null, "e": 2368, "s": 2318, "text": "Gets or sets whether the ToggleButton is checked." }, { "code": null, "e": 2386, "s": 2368, "text": "IsCheckedProperty" }, { "code": null, "e": 2432, "s": 2386, "text": "Identifies the IsChecked dependency property." }, { "code": null, "e": 2445, "s": 2432, "text": "IsThreeState" }, { "code": null, "e": 2524, "s": 2445, "text": "Gets or sets a value that indicates whether the control supports three states." }, { "code": null, "e": 2545, "s": 2524, "text": "IsThreeStateProperty" }, { "code": null, "e": 2594, "s": 2545, "text": "Identifies the IsThreeState dependency property." }, { "code": null, "e": 2602, "s": 2594, "text": "Checked" }, { "code": null, "e": 2640, "s": 2602, "text": "Fires when a ToggleButton is checked." }, { "code": null, "e": 2654, "s": 2640, "text": "Indeterminate" }, { "code": null, "e": 2733, "s": 2654, "text": "Fires when the state of a ToggleButton is switched to the indeterminate state." }, { "code": null, "e": 2743, "s": 2733, "text": "Unchecked" }, { "code": null, "e": 2784, "s": 2743, "text": "Occurs when a ToggleButton is unchecked." }, { "code": null, "e": 2844, "s": 2784, "text": "Let’s create a new WPF project with WPFToggleButtonControl." }, { "code": null, "e": 2900, "s": 2844, "text": "Drag a text block and a toggle button from the toolbox." }, { "code": null, "e": 2974, "s": 2900, "text": "Change the background color of the text block from the properties window." }, { "code": null, "e": 3053, "s": 2974, "text": "The following example shows the usage of ToggleButton in an XAML application. " }, { "code": null, "e": 3141, "s": 3053, "text": "The following XAML code creates a ToggleButton and initializes it with some properties." }, { "code": null, "e": 3989, "s": 3141, "text": "<Window x:Class = \"WPFToggleButtonControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFToggleButtonControl\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <StackPanel> \n <ToggleButton x:Name = \"tb\" Content = \"Toggle\" \n Checked = \"HandleCheck\" Unchecked = \"HandleUnchecked\"Margin = \"20\"\n Width = \"108\"HorizontalAlignment = \"Center\" /> \n <TextBlock x:Name = \"text2\" Margin = \"20\" Width = \"300\" \n HorizontalAlignment = \"Center\" FontSize = \"24\" Background = \"#FFFDE0E0\" />\n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 4052, "s": 3989, "text": "Here is the C# implementation of Checked and Unchecked events." }, { "code": null, "e": 4588, "s": 4052, "text": "using System.Windows; \n\nnamespace WPFToggleButtonControl { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void HandleCheck(object sender, RoutedEventArgs e) { \n text2.Text = \"Button is Checked\"; \n } \n\t\t\n private void HandleUnchecked(object sender, RoutedEventArgs e) { \n text2.Text = \"Button is unchecked.\"; \n } \n\t\t\n } \n}" }, { "code": null, "e": 4750, "s": 4588, "text": "When you compile and execute the above code, it will produce the following window. When you click the button, it will change the color and update the text block." } ]
Inserting NULL as default in SQLAlchemy
22 Jun, 2022 In this article, we will see how to insert NULL as default in SQLAlchemy in Python. The default value can be provided using the default parameter while defining the table (creating the table). We will be using mySQL local database for the examples in this article. Feel free to use any database you may like but you need to modify the connection string with the type of database you are working on and the credentials. In the above example, we have created a sales table in the database. We have defined 3 columns for the sales table, namely, product, quantity, and description. The product column is the primary key whereas for the description column we have provided a default=None parameter. This parameter is equal to providing a default value to a column in traditional SQL queries. When we first inserted the product ‘Refrigerator’, we provided a description along with it (visible in output as well). For the second entry, i.e., product ‘Washing Machine’ we did not provide any description parameter so it takes in the default value. The default value provided is None which is equivalent to NULL in SQL. In this example, we have used SQLAlchemy ORM. Python from sqlalchemy.orm import sessionmakerimport sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks") # CREATE THE SALES TABLE MODEL# TO USE IT FOR QUERYINGclass Sales(Base): __tablename__ = 'sales' product = db.Column(db.String(50), primary_key=True) quantity = db.Column(db.Integer) description = db.Column(db.String(100), default=None) # CREATE SALES TABLE IF IT# DOES NOT EXIST ALREADYBase.metadata.create_all(engine, tables=[Sales.__table__]) # CREATE A SESSION OBJECT TO# COMMIT SQL QUERIES TO DATABASESession = sessionmaker(bind=engine)session = Session() # INSERT NEW RECORD WITH A DESCRIPTIONnew_record = Sales(product='Refrigerator', quantity=15, description='The season is too hot!')session.add(new_record)session.commit() # INSERT NEW RECORD WITHOUT DESCRIPTION SO# THAT IT TAKES DEFAULT NULL VALUE AS DEFINEDnew_record = Sales(product='Washing Machine', quantity=12)session.add(new_record)session.commit() Output: In the second example, we have inserted two new records for products ‘Televisions’ and ‘Laptops’. If we look at the code, the syntax for defining the default value for a column in a table is the same for both SQLAlchemy Core and ORM. The ‘Televisions’ record is provided with a description (visible in the output as well). For the second entry i.e., ‘Laptops’ , the description parameter is not provided so it by default takes in the value provided as the default parameter while creating or defining the table. Please note that the output consists of the previous two records as well seen in the SQLAlchemy ORM example. Python import sqlalchemy as db # CREATE THE METADATA OBJECTmetadata_obj = db.MetaData() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks") # CREATE THE SALES TABLE MODEL TO USE IT FOR QUERYINGsales = db.Table( 'sales', metadata_obj, db.Column('product', db.String(50), primary_key=True), db.Column('quantity', db.String(100)), db.Column('description', db.Integer, default=None),) # CREATE SALES TABLE IF# IT DOES NOT EXIST ALREADYmetadata_obj.create_all(engine) # INSERT NEW RECORD WITH A DESCRIPTIONwith engine.connect() as conn: conn.execute( db.insert(sales).values( product='Televisions', quantity=25, description='This value is inserted\ using SQLAlchemy Core!' ) ) # INSERT NEW RECORD WITHOUT DESCRIPTION SO# THAT IT TAKES DEFAULT NULL VALUE AS DEFINEDwith engine.connect() as conn: conn.execute( db.insert(sales).values( product='Laptops', quantity=31 ) ) Output: nikhatkhan11 Picked Python-SQLAlchemy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 112, "s": 28, "text": "In this article, we will see how to insert NULL as default in SQLAlchemy in Python." }, { "code": null, "e": 447, "s": 112, "text": "The default value can be provided using the default parameter while defining the table (creating the table). We will be using mySQL local database for the examples in this article. Feel free to use any database you may like but you need to modify the connection string with the type of database you are working on and the credentials." }, { "code": null, "e": 1186, "s": 447, "text": "In the above example, we have created a sales table in the database. We have defined 3 columns for the sales table, namely, product, quantity, and description. The product column is the primary key whereas for the description column we have provided a default=None parameter. This parameter is equal to providing a default value to a column in traditional SQL queries. When we first inserted the product ‘Refrigerator’, we provided a description along with it (visible in output as well). For the second entry, i.e., product ‘Washing Machine’ we did not provide any description parameter so it takes in the default value. The default value provided is None which is equivalent to NULL in SQL. In this example, we have used SQLAlchemy ORM." }, { "code": null, "e": 1193, "s": 1186, "text": "Python" }, { "code": "from sqlalchemy.orm import sessionmakerimport sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine( \"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # CREATE THE SALES TABLE MODEL# TO USE IT FOR QUERYINGclass Sales(Base): __tablename__ = 'sales' product = db.Column(db.String(50), primary_key=True) quantity = db.Column(db.Integer) description = db.Column(db.String(100), default=None) # CREATE SALES TABLE IF IT# DOES NOT EXIST ALREADYBase.metadata.create_all(engine, tables=[Sales.__table__]) # CREATE A SESSION OBJECT TO# COMMIT SQL QUERIES TO DATABASESession = sessionmaker(bind=engine)session = Session() # INSERT NEW RECORD WITH A DESCRIPTIONnew_record = Sales(product='Refrigerator', quantity=15, description='The season is too hot!')session.add(new_record)session.commit() # INSERT NEW RECORD WITHOUT DESCRIPTION SO# THAT IT TAKES DEFAULT NULL VALUE AS DEFINEDnew_record = Sales(product='Washing Machine', quantity=12)session.add(new_record)session.commit()", "e": 2421, "s": 1193, "text": null }, { "code": null, "e": 2429, "s": 2421, "text": "Output:" }, { "code": null, "e": 3050, "s": 2429, "text": "In the second example, we have inserted two new records for products ‘Televisions’ and ‘Laptops’. If we look at the code, the syntax for defining the default value for a column in a table is the same for both SQLAlchemy Core and ORM. The ‘Televisions’ record is provided with a description (visible in the output as well). For the second entry i.e., ‘Laptops’ , the description parameter is not provided so it by default takes in the value provided as the default parameter while creating or defining the table. Please note that the output consists of the previous two records as well seen in the SQLAlchemy ORM example." }, { "code": null, "e": 3057, "s": 3050, "text": "Python" }, { "code": "import sqlalchemy as db # CREATE THE METADATA OBJECTmetadata_obj = db.MetaData() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine( \"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # CREATE THE SALES TABLE MODEL TO USE IT FOR QUERYINGsales = db.Table( 'sales', metadata_obj, db.Column('product', db.String(50), primary_key=True), db.Column('quantity', db.String(100)), db.Column('description', db.Integer, default=None),) # CREATE SALES TABLE IF# IT DOES NOT EXIST ALREADYmetadata_obj.create_all(engine) # INSERT NEW RECORD WITH A DESCRIPTIONwith engine.connect() as conn: conn.execute( db.insert(sales).values( product='Televisions', quantity=25, description='This value is inserted\\ using SQLAlchemy Core!' ) ) # INSERT NEW RECORD WITHOUT DESCRIPTION SO# THAT IT TAKES DEFAULT NULL VALUE AS DEFINEDwith engine.connect() as conn: conn.execute( db.insert(sales).values( product='Laptops', quantity=31 ) )", "e": 4133, "s": 3057, "text": null }, { "code": null, "e": 4141, "s": 4133, "text": "Output:" }, { "code": null, "e": 4154, "s": 4141, "text": "nikhatkhan11" }, { "code": null, "e": 4161, "s": 4154, "text": "Picked" }, { "code": null, "e": 4179, "s": 4161, "text": "Python-SQLAlchemy" }, { "code": null, "e": 4186, "s": 4179, "text": "Python" }, { "code": null, "e": 4284, "s": 4186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4316, "s": 4284, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4343, "s": 4316, "text": "Python Classes and Objects" }, { "code": null, "e": 4364, "s": 4343, "text": "Python OOPs Concepts" }, { "code": null, "e": 4387, "s": 4364, "text": "Introduction To PYTHON" }, { "code": null, "e": 4443, "s": 4387, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4474, "s": 4443, "text": "Python | os.path.join() method" }, { "code": null, "e": 4516, "s": 4474, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4558, "s": 4516, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4597, "s": 4558, "text": "Python | Get unique values from a list" } ]
Node.js fs.read() Method
08 Oct, 2021 Node.js is used for server-side scripting. Reading and writing files are the two most important operations that are performed in any application. Node.js offers a wide range of inbuilt functionalities to perform read and write operations. The fs package contains the functions required for file operations. The read() method of fs package reads the file using a file descriptor. In order to read files without file descriptor the readFile() method of fs package can be used. Syntax fs.read(fd, buffer, offset, length, position, callback) Parameters: fd: File descriptor returned by fs.open() method. buffer: Stores the data fetched from the file. offset: Offset in the buffer indicating where to start writing at. length: An integer that specifies the number of bytes to read. position: An integer that specifies where to begin reading from in the file. If position is null, data is read from the current file position. callback: The callback function accepts the three arguments ie. (err, bytesRead, buffer). Explanation: The fs.open() method opens the file and returns a file descriptor. A file descriptor is a number or index that is stored in the file descriptor table by the kernel and is used to uniquely identify an open file in the computer’s operating system. The fs.read() method reads the file using the file descriptor and stores in the buffer. The contents of the buffer are printed out as output. The fs.close() method is used to close the file. Example 1: var fs = require("fs");var buffer = new Buffer.alloc(1024); console.log("Open existing file");fs.open('gfg.txt', 'r+', function (err, fd) { if (err) { return console.error(err); } console.log("Reading the file"); fs.read(fd, buffer, 0, buffer.length, 0, function (err, bytes) { if (err) { console.log(err); } if (bytes > 0) { console.log(buffer. slice(0, bytes).toString()); } console.log(bytes + " bytes read"); // Close the opened file. fs.close(fd, function (err) { if (err) { console.log(err); } console.log("File closed successfully"); }); });}); Output: Open existing file Reading the file 0 bytes read File closed successfully Example 2: Taking dynamic input for file name/path. // Module required to accept user// input from consolevar readline = require('readline-sync');var fs = require("fs"); var path = readline.question("Enter file path: ");console.log("Entered path : " + path); console.log("File Content "); fs.stat(path, function (error, stats) { // 'r' specifies read mode fs.open(path, "r", function (error, fd) { var buffer = new Buffer.alloc(stats.size); fs.read(fd, buffer, 0, buffer.length, null, function (error, bytesRead, buffer) { var data = buffer.toString("utf8"); console.log(data); }); });}); Output: C:\Users\User\Desktop>node read3.js Enter file path: new.txt Entered path : new.txt File Content Hello World.. Welcome to GeeksForGeeks.. This is a Node.js program Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows JWT Authentication with Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 503, "s": 28, "text": "Node.js is used for server-side scripting. Reading and writing files are the two most important operations that are performed in any application. Node.js offers a wide range of inbuilt functionalities to perform read and write operations. The fs package contains the functions required for file operations. The read() method of fs package reads the file using a file descriptor. In order to read files without file descriptor the readFile() method of fs package can be used." }, { "code": null, "e": 510, "s": 503, "text": "Syntax" }, { "code": null, "e": 566, "s": 510, "text": "fs.read(fd, buffer, offset, length, position, callback)" }, { "code": null, "e": 578, "s": 566, "text": "Parameters:" }, { "code": null, "e": 628, "s": 578, "text": "fd: File descriptor returned by fs.open() method." }, { "code": null, "e": 675, "s": 628, "text": "buffer: Stores the data fetched from the file." }, { "code": null, "e": 742, "s": 675, "text": "offset: Offset in the buffer indicating where to start writing at." }, { "code": null, "e": 805, "s": 742, "text": "length: An integer that specifies the number of bytes to read." }, { "code": null, "e": 948, "s": 805, "text": "position: An integer that specifies where to begin reading from in the file. If position is null, data is read from the current file position." }, { "code": null, "e": 1038, "s": 948, "text": "callback: The callback function accepts the three arguments ie. (err, bytesRead, buffer)." }, { "code": null, "e": 1488, "s": 1038, "text": "Explanation: The fs.open() method opens the file and returns a file descriptor. A file descriptor is a number or index that is stored in the file descriptor table by the kernel and is used to uniquely identify an open file in the computer’s operating system. The fs.read() method reads the file using the file descriptor and stores in the buffer. The contents of the buffer are printed out as output. The fs.close() method is used to close the file." }, { "code": null, "e": 1499, "s": 1488, "text": "Example 1:" }, { "code": "var fs = require(\"fs\");var buffer = new Buffer.alloc(1024); console.log(\"Open existing file\");fs.open('gfg.txt', 'r+', function (err, fd) { if (err) { return console.error(err); } console.log(\"Reading the file\"); fs.read(fd, buffer, 0, buffer.length, 0, function (err, bytes) { if (err) { console.log(err); } if (bytes > 0) { console.log(buffer. slice(0, bytes).toString()); } console.log(bytes + \" bytes read\"); // Close the opened file. fs.close(fd, function (err) { if (err) { console.log(err); } console.log(\"File closed successfully\"); }); });});", "e": 2296, "s": 1499, "text": null }, { "code": null, "e": 2304, "s": 2296, "text": "Output:" }, { "code": null, "e": 2379, "s": 2304, "text": "Open existing file\nReading the file\n0 bytes read\nFile closed successfully\n" }, { "code": null, "e": 2431, "s": 2379, "text": "Example 2: Taking dynamic input for file name/path." }, { "code": "// Module required to accept user// input from consolevar readline = require('readline-sync');var fs = require(\"fs\"); var path = readline.question(\"Enter file path: \");console.log(\"Entered path : \" + path); console.log(\"File Content \"); fs.stat(path, function (error, stats) { // 'r' specifies read mode fs.open(path, \"r\", function (error, fd) { var buffer = new Buffer.alloc(stats.size); fs.read(fd, buffer, 0, buffer.length, null, function (error, bytesRead, buffer) { var data = buffer.toString(\"utf8\"); console.log(data); }); });});", "e": 3048, "s": 2431, "text": null }, { "code": null, "e": 3056, "s": 3048, "text": "Output:" }, { "code": null, "e": 3221, "s": 3056, "text": "C:\\Users\\User\\Desktop>node read3.js\nEnter file path: new.txt\nEntered path : new.txt\nFile Content\nHello World..\nWelcome to GeeksForGeeks..\nThis is a Node.js program\n" }, { "code": null, "e": 3239, "s": 3221, "text": "Node.js-fs-module" }, { "code": null, "e": 3246, "s": 3239, "text": "Picked" }, { "code": null, "e": 3254, "s": 3246, "text": "Node.js" }, { "code": null, "e": 3271, "s": 3254, "text": "Web Technologies" }, { "code": null, "e": 3369, "s": 3271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3426, "s": 3369, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3480, "s": 3426, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3520, "s": 3480, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3555, "s": 3520, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3587, "s": 3555, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3649, "s": 3587, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3710, "s": 3649, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3760, "s": 3710, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3803, "s": 3760, "text": "How to fetch data from an API in ReactJS ?" } ]
Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
06 Aug, 2021 Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with sum 5 exists 2 \ 3 But the leaf node 8 has the maximum sum. Approach: We traverse the tree in bottom-up manner. For every traversed node, we store the information of maximum and minimum of that subtree, a variable isBST to store if it is a BST, variable currmax to store the maximum sum of BST found till now, and a variable sum to store the sum of Left and Right subtree(which is also a BST) rooted under the current node.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Binary tree nodestruct Node { struct Node* left; struct Node* right; int data; Node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Information stored in every// node during bottom up traversalstruct Info { // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST bool isBST; // Sum of the nodes of the sub-tree // rooted under the current node int sum; // Max sum of BST found till now int currmax;}; // Returns information about subtree such as// subtree with maximum sum which is also a BSTInfo MaxSumBSTUtil(struct Node* root, int& maxsum){ // Base case if (root == NULL) return { INT_MIN, INT_MAX, true, 0, 0 }; // If current node is a leaf node then // return from the function and store // information about the leaf node if (root->left == NULL && root->right == NULL) { maxsum = max(maxsum, root->data); return { root->data, root->data, true, root->data, maxsum }; } // Store information about the left subtree Info L = MaxSumBSTUtil(root->left, maxsum); // Store information about the right subtree Info R = MaxSumBSTUtil(root->right, maxsum); Info BST; // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root->data && R.min > root->data) { BST.max = max(root->data, max(L.max, R.max)); BST.min = min(root->data, min(L.min, R.min)); maxsum = max(maxsum, R.sum + root->data + L.sum); BST.sum = R.sum + root->data + L.sum; // Update the current maximum sum BST.currmax = maxsum; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum; BST.sum = R.sum + root->data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTint MaxSumBST(struct Node* root){ int maxsum = INT_MIN; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codeint main(){ struct Node* root = new Node(5); root->left = new Node(14); root->right = new Node(3); root->left->left = new Node(6); root->right->right = new Node(7); root->left->left->left = new Node(9); root->left->left->right = new Node(1); cout << MaxSumBST(root); return 0;} // Java implementation of the approachclass GFG{ // Binary tree nodestatic class Node{ Node left; Node right; int data; Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Information stored in every// node during bottom up traversalstatic class Info{ // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST boolean isBST; // Sum of the nodes of the sub-tree // rooted under the current node int sum; // Max sum of BST found till now int currmax; Info(int m,int mi,boolean is,int su,int cur) { max = m; min = mi; isBST = is; sum = su; currmax = cur; } Info(){}}; static class INT{ int a;} // Returns information about subtree such as// subtree with the maximum sum which is also a BSTstatic Info MaxSumBSTUtil( Node root, INT maxsum){ // Base case if (root == null) return new Info( Integer.MIN_VALUE, Integer.MAX_VALUE, true, 0, 0 ); // If current node is a leaf node then // return from the function and store // information about the leaf node if (root.left == null && root.right == null) { maxsum.a = Math.max(maxsum.a, root.data); return new Info( root.data, root.data, true, root.data, maxsum.a ); } // Store information about the left subtree Info L = MaxSumBSTUtil(root.left, maxsum); // Store information about the right subtree Info R = MaxSumBSTUtil(root.right, maxsum); Info BST=new Info(); // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root.data && R.min > root.data) { BST.max = Math.max(root.data, Math.max(L.max, R.max)); BST.min = Math.min(root.data, Math.min(L.min, R.min)); maxsum.a = Math.max(maxsum.a, R.sum + root.data + L.sum); BST.sum = R.sum + root.data + L.sum; // Update the current maximum sum BST.currmax = maxsum.a; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum.a; BST.sum = R.sum + root.data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTstatic int MaxSumBST( Node root){ INT maxsum = new INT(); maxsum.a = Integer.MIN_VALUE; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codepublic static void main(String args[]){ Node root = new Node(5); root.left = new Node(14); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(9); root.left.left.right = new Node(1); System.out.println( MaxSumBST(root));}} // This code is contributed by Arnab Kundu # Python3 implementation of# the above approachfrom sys import maxsize as INT_MAXINT_MIN = -INT_MAX # Binary tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Information stored in every# node during bottom up traversalclass Info: def __init__(self, _max, _min, isBST, _sum, currmax): # Max Value in the subtree self.max = _max # Min value in the subtree self.min = _min # If subtree is BST self.isBST = isBST # Sum of the nodes of the sub-tree # rooted under the current node self.sum = _sum # Max sum of BST found till now self.currmax = currmax # Returns information about# subtree such as subtree# with maximum sum which# is also a BSTdef MaxSumBSTUtil(root: Node) -> Info: global maxsum # Base case if (root is None): return Info(INT_MIN, INT_MAX, True, 0, 0) # If current node is a # leaf node then return # from the function and store # information about the leaf node if (root.left is None and root.right is None): maxsum = max(maxsum, root.data) return Info(root.data, root.data, True, root.data, maxsum) # Store information about # the left subtree L = MaxSumBSTUtil(root.left) # Store information about # the right subtree R = MaxSumBSTUtil(root.right) BST = Info # If the subtree rooted under # the current node is a BST if (L.isBST and R.isBST and L.max < root.data and R.min > root.data): BST.max = max(root.data, max(L.max, R.max)) BST.min = min(root.data, min(L.min, R.min)) maxsum = max(maxsum, R.sum + root.data + L.sum) BST.sum = R.sum + root.data + L.sum # Update the current maximum sum BST.currmax = maxsum BST.isBST = True return BST # If the whole tree is not # a BST then update the # current maximum sum BST.isBST = False BST.currmax = maxsum BST.sum = R.sum + root.data + L.sum return BST # Function to return the maximum# sum subtree which is also a BSTdef MaxSumBST(root: Node) -> int: global maxsum return MaxSumBSTUtil(root).currmax # Driver codeif __name__ == "__main__": root = Node(5) root.left = Node(14) root.right = Node(3) root.left.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(9) root.left.left.right = Node(1) maxsum = INT_MIN print(MaxSumBST(root)) # This code is contributed by sanjeev2552 // C# implementation of the approachusing System; class GFG{ // Binary tree nodepublic class Node{ public Node left; public Node right; public int data; public Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Information stored in every// node during bottom up traversalpublic class Info{ // Max Value in the subtree public int max; // Min value in the subtree public int min; // If subtree is BST public bool isBST; // Sum of the nodes of the sub-tree // rooted under the current node public int sum; // Max sum of BST found till now public int currmax; public Info(int m,int mi,bool s,int su,int cur) { max = m; min = mi; isBST = s; sum = su; currmax = cur; } public Info(){}}; public class INT{ public int a;} // Returns information about subtree such as// subtree with the maximum sum which is also a BSTstatic Info MaxSumBSTUtil( Node root, INT maxsum){ // Base case if (root == null) return new Info( int.MinValue, int.MaxValue, true, 0, 0 ); // If current node is a leaf node then // return from the function and store // information about the leaf node if (root.left == null && root.right == null) { maxsum.a = Math.Max(maxsum.a, root.data); return new Info( root.data, root.data, true, root.data, maxsum.a ); } // Store information about the left subtree Info L = MaxSumBSTUtil(root.left, maxsum); // Store information about the right subtree Info R = MaxSumBSTUtil(root.right, maxsum); Info BST = new Info(); // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root.data && R.min > root.data) { BST.max = Math.Max(root.data, Math.Max(L.max, R.max)); BST.min = Math.Min(root.data, Math.Min(L.min, R.min)); maxsum.a = Math.Max(maxsum.a, R.sum + root.data + L.sum); BST.sum = R.sum + root.data + L.sum; // Update the current maximum sum BST.currmax = maxsum.a; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum.a; BST.sum = R.sum + root.data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTstatic int MaxSumBST( Node root){ INT maxsum = new INT(); maxsum.a = int.MinValue; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codepublic static void Main(String []args){ Node root = new Node(5); root.left = new Node(14); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(9); root.left.left.right = new Node(1); Console.WriteLine( MaxSumBST(root));}} // This code has been contributed by 29AjayKumar <script> // Javascript implementation of the approach // Binary tree nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Information stored in every// node during bottom up traversalclass Info{ constructor(m,mi,s,su,cur) { // max Value in the subtree this.max = m; // min value in the subtree this.min = mi; // If subtree is BST this.isBST = s; // Sum of the nodes of the sub-tree // rooted under the current node this.sum = su; // max sum of BST found till now this.currmax = cur; }}; class INT{ constructor() { this.a = 0; }} // Returns information about subtree such as// subtree with the maximum sum which is also a BSTfunction MaxSumBSTUtil( root, maxsum){ // Base case if (root == null) return new Info( -1000000000, 1000000000, true, 0, 0 ); // If current node is a leaf node then // return from the function and store // information about the leaf node if (root.left == null && root.right == null) { maxsum.a = Math.max(maxsum.a, root.data); return new Info( root.data, root.data, true, root.data, maxsum.a ); } // Store information about the left subtree var L = MaxSumBSTUtil(root.left, maxsum); // Store information about the right subtree var R = MaxSumBSTUtil(root.right, maxsum); var BST = new Info(); // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root.data && R.min > root.data) { BST.max = Math.max(root.data, Math.max(L.max, R.max)); BST.min = Math.min(root.data, Math.min(L.min, R.min)); maxsum.a = Math.max(maxsum.a, R.sum + root.data + L.sum); BST.sum = R.sum + root.data + L.sum; // Update the current maximum sum BST.currmax = maxsum.a; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum.a; BST.sum = R.sum + root.data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTfunction MaxSumBST( root){ var maxsum = new INT(); maxsum.a = -1000000000; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codevar root = new Node(5);root.left = new Node(14);root.right = new Node(3);root.left.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(9);root.left.left.right = new Node(1);document.write( MaxSumBST(root)); // This code is contributed by itsok.</script> 10 Time Complexity: O(N) Auxiliary Space: O(N) andrew1234 29AjayKumar nidhi_biet sanjeev2552 itsok pankajsharmagfg Binary Tree Marketing Binary Search Tree C++ Programs Data Structures Tree Data Structures Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Aug, 2021" }, { "code": null, "e": 179, "s": 52, "text": "Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: " }, { "code": null, "e": 606, "s": 179, "text": "Input : \n 7\n / \\\n 12 2\n / \\ \\\n 11 13 5\n / / \\\n 2 1 38 \n\nOutput:44\nBST rooted under node 5 has the maximum sum\n 5\n / \\\n 1 38\n\nInput:\n 5\n / \\\n 9 2\n / \\\n 6 3\n / \\\n8 7 \n\nOutput: 8\nHere each leaf node represents a binary search tree \nalso a BST with sum 5 exists\n 2\n \\\n 3\nBut the leaf node 8 has the maximum sum." }, { "code": null, "e": 1022, "s": 606, "text": "Approach: We traverse the tree in bottom-up manner. For every traversed node, we store the information of maximum and minimum of that subtree, a variable isBST to store if it is a BST, variable currmax to store the maximum sum of BST found till now, and a variable sum to store the sum of Left and Right subtree(which is also a BST) rooted under the current node.Below is the implementation of the above approach: " }, { "code": null, "e": 1026, "s": 1022, "text": "C++" }, { "code": null, "e": 1031, "s": 1026, "text": "Java" }, { "code": null, "e": 1039, "s": 1031, "text": "Python3" }, { "code": null, "e": 1042, "s": 1039, "text": "C#" }, { "code": null, "e": 1053, "s": 1042, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Binary tree nodestruct Node { struct Node* left; struct Node* right; int data; Node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Information stored in every// node during bottom up traversalstruct Info { // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST bool isBST; // Sum of the nodes of the sub-tree // rooted under the current node int sum; // Max sum of BST found till now int currmax;}; // Returns information about subtree such as// subtree with maximum sum which is also a BSTInfo MaxSumBSTUtil(struct Node* root, int& maxsum){ // Base case if (root == NULL) return { INT_MIN, INT_MAX, true, 0, 0 }; // If current node is a leaf node then // return from the function and store // information about the leaf node if (root->left == NULL && root->right == NULL) { maxsum = max(maxsum, root->data); return { root->data, root->data, true, root->data, maxsum }; } // Store information about the left subtree Info L = MaxSumBSTUtil(root->left, maxsum); // Store information about the right subtree Info R = MaxSumBSTUtil(root->right, maxsum); Info BST; // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root->data && R.min > root->data) { BST.max = max(root->data, max(L.max, R.max)); BST.min = min(root->data, min(L.min, R.min)); maxsum = max(maxsum, R.sum + root->data + L.sum); BST.sum = R.sum + root->data + L.sum; // Update the current maximum sum BST.currmax = maxsum; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum; BST.sum = R.sum + root->data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTint MaxSumBST(struct Node* root){ int maxsum = INT_MIN; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codeint main(){ struct Node* root = new Node(5); root->left = new Node(14); root->right = new Node(3); root->left->left = new Node(6); root->right->right = new Node(7); root->left->left->left = new Node(9); root->left->left->right = new Node(1); cout << MaxSumBST(root); return 0;}", "e": 3558, "s": 1053, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Binary tree nodestatic class Node{ Node left; Node right; int data; Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Information stored in every// node during bottom up traversalstatic class Info{ // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST boolean isBST; // Sum of the nodes of the sub-tree // rooted under the current node int sum; // Max sum of BST found till now int currmax; Info(int m,int mi,boolean is,int su,int cur) { max = m; min = mi; isBST = is; sum = su; currmax = cur; } Info(){}}; static class INT{ int a;} // Returns information about subtree such as// subtree with the maximum sum which is also a BSTstatic Info MaxSumBSTUtil( Node root, INT maxsum){ // Base case if (root == null) return new Info( Integer.MIN_VALUE, Integer.MAX_VALUE, true, 0, 0 ); // If current node is a leaf node then // return from the function and store // information about the leaf node if (root.left == null && root.right == null) { maxsum.a = Math.max(maxsum.a, root.data); return new Info( root.data, root.data, true, root.data, maxsum.a ); } // Store information about the left subtree Info L = MaxSumBSTUtil(root.left, maxsum); // Store information about the right subtree Info R = MaxSumBSTUtil(root.right, maxsum); Info BST=new Info(); // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root.data && R.min > root.data) { BST.max = Math.max(root.data, Math.max(L.max, R.max)); BST.min = Math.min(root.data, Math.min(L.min, R.min)); maxsum.a = Math.max(maxsum.a, R.sum + root.data + L.sum); BST.sum = R.sum + root.data + L.sum; // Update the current maximum sum BST.currmax = maxsum.a; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum.a; BST.sum = R.sum + root.data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTstatic int MaxSumBST( Node root){ INT maxsum = new INT(); maxsum.a = Integer.MIN_VALUE; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codepublic static void main(String args[]){ Node root = new Node(5); root.left = new Node(14); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(9); root.left.left.right = new Node(1); System.out.println( MaxSumBST(root));}} // This code is contributed by Arnab Kundu", "e": 6470, "s": 3558, "text": null }, { "code": "# Python3 implementation of# the above approachfrom sys import maxsize as INT_MAXINT_MIN = -INT_MAX # Binary tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Information stored in every# node during bottom up traversalclass Info: def __init__(self, _max, _min, isBST, _sum, currmax): # Max Value in the subtree self.max = _max # Min value in the subtree self.min = _min # If subtree is BST self.isBST = isBST # Sum of the nodes of the sub-tree # rooted under the current node self.sum = _sum # Max sum of BST found till now self.currmax = currmax # Returns information about# subtree such as subtree# with maximum sum which# is also a BSTdef MaxSumBSTUtil(root: Node) -> Info: global maxsum # Base case if (root is None): return Info(INT_MIN, INT_MAX, True, 0, 0) # If current node is a # leaf node then return # from the function and store # information about the leaf node if (root.left is None and root.right is None): maxsum = max(maxsum, root.data) return Info(root.data, root.data, True, root.data, maxsum) # Store information about # the left subtree L = MaxSumBSTUtil(root.left) # Store information about # the right subtree R = MaxSumBSTUtil(root.right) BST = Info # If the subtree rooted under # the current node is a BST if (L.isBST and R.isBST and L.max < root.data and R.min > root.data): BST.max = max(root.data, max(L.max, R.max)) BST.min = min(root.data, min(L.min, R.min)) maxsum = max(maxsum, R.sum + root.data + L.sum) BST.sum = R.sum + root.data + L.sum # Update the current maximum sum BST.currmax = maxsum BST.isBST = True return BST # If the whole tree is not # a BST then update the # current maximum sum BST.isBST = False BST.currmax = maxsum BST.sum = R.sum + root.data + L.sum return BST # Function to return the maximum# sum subtree which is also a BSTdef MaxSumBST(root: Node) -> int: global maxsum return MaxSumBSTUtil(root).currmax # Driver codeif __name__ == \"__main__\": root = Node(5) root.left = Node(14) root.right = Node(3) root.left.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(9) root.left.left.right = Node(1) maxsum = INT_MIN print(MaxSumBST(root)) # This code is contributed by sanjeev2552", "e": 9146, "s": 6470, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Binary tree nodepublic class Node{ public Node left; public Node right; public int data; public Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Information stored in every// node during bottom up traversalpublic class Info{ // Max Value in the subtree public int max; // Min value in the subtree public int min; // If subtree is BST public bool isBST; // Sum of the nodes of the sub-tree // rooted under the current node public int sum; // Max sum of BST found till now public int currmax; public Info(int m,int mi,bool s,int su,int cur) { max = m; min = mi; isBST = s; sum = su; currmax = cur; } public Info(){}}; public class INT{ public int a;} // Returns information about subtree such as// subtree with the maximum sum which is also a BSTstatic Info MaxSumBSTUtil( Node root, INT maxsum){ // Base case if (root == null) return new Info( int.MinValue, int.MaxValue, true, 0, 0 ); // If current node is a leaf node then // return from the function and store // information about the leaf node if (root.left == null && root.right == null) { maxsum.a = Math.Max(maxsum.a, root.data); return new Info( root.data, root.data, true, root.data, maxsum.a ); } // Store information about the left subtree Info L = MaxSumBSTUtil(root.left, maxsum); // Store information about the right subtree Info R = MaxSumBSTUtil(root.right, maxsum); Info BST = new Info(); // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root.data && R.min > root.data) { BST.max = Math.Max(root.data, Math.Max(L.max, R.max)); BST.min = Math.Min(root.data, Math.Min(L.min, R.min)); maxsum.a = Math.Max(maxsum.a, R.sum + root.data + L.sum); BST.sum = R.sum + root.data + L.sum; // Update the current maximum sum BST.currmax = maxsum.a; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum.a; BST.sum = R.sum + root.data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTstatic int MaxSumBST( Node root){ INT maxsum = new INT(); maxsum.a = int.MinValue; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codepublic static void Main(String []args){ Node root = new Node(5); root.left = new Node(14); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(9); root.left.left.right = new Node(1); Console.WriteLine( MaxSumBST(root));}} // This code has been contributed by 29AjayKumar", "e": 12135, "s": 9146, "text": null }, { "code": "<script> // Javascript implementation of the approach // Binary tree nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Information stored in every// node during bottom up traversalclass Info{ constructor(m,mi,s,su,cur) { // max Value in the subtree this.max = m; // min value in the subtree this.min = mi; // If subtree is BST this.isBST = s; // Sum of the nodes of the sub-tree // rooted under the current node this.sum = su; // max sum of BST found till now this.currmax = cur; }}; class INT{ constructor() { this.a = 0; }} // Returns information about subtree such as// subtree with the maximum sum which is also a BSTfunction MaxSumBSTUtil( root, maxsum){ // Base case if (root == null) return new Info( -1000000000, 1000000000, true, 0, 0 ); // If current node is a leaf node then // return from the function and store // information about the leaf node if (root.left == null && root.right == null) { maxsum.a = Math.max(maxsum.a, root.data); return new Info( root.data, root.data, true, root.data, maxsum.a ); } // Store information about the left subtree var L = MaxSumBSTUtil(root.left, maxsum); // Store information about the right subtree var R = MaxSumBSTUtil(root.right, maxsum); var BST = new Info(); // If the subtree rooted under the current node // is a BST if (L.isBST && R.isBST && L.max < root.data && R.min > root.data) { BST.max = Math.max(root.data, Math.max(L.max, R.max)); BST.min = Math.min(root.data, Math.min(L.min, R.min)); maxsum.a = Math.max(maxsum.a, R.sum + root.data + L.sum); BST.sum = R.sum + root.data + L.sum; // Update the current maximum sum BST.currmax = maxsum.a; BST.isBST = true; return BST; } // If the whole tree is not a BST then // update the current maximum sum BST.isBST = false; BST.currmax = maxsum.a; BST.sum = R.sum + root.data + L.sum; return BST;} // Function to return the maximum// sum subtree which is also a BSTfunction MaxSumBST( root){ var maxsum = new INT(); maxsum.a = -1000000000; return MaxSumBSTUtil(root, maxsum).currmax;} // Driver codevar root = new Node(5);root.left = new Node(14);root.right = new Node(3);root.left.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(9);root.left.left.right = new Node(1);document.write( MaxSumBST(root)); // This code is contributed by itsok.</script>", "e": 14853, "s": 12135, "text": null }, { "code": null, "e": 14856, "s": 14853, "text": "10" }, { "code": null, "e": 14902, "s": 14858, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 14913, "s": 14902, "text": "andrew1234" }, { "code": null, "e": 14925, "s": 14913, "text": "29AjayKumar" }, { "code": null, "e": 14936, "s": 14925, "text": "nidhi_biet" }, { "code": null, "e": 14948, "s": 14936, "text": "sanjeev2552" }, { "code": null, "e": 14954, "s": 14948, "text": "itsok" }, { "code": null, "e": 14970, "s": 14954, "text": "pankajsharmagfg" }, { "code": null, "e": 14982, "s": 14970, "text": "Binary Tree" }, { "code": null, "e": 14992, "s": 14982, "text": "Marketing" }, { "code": null, "e": 15011, "s": 14992, "text": "Binary Search Tree" }, { "code": null, "e": 15024, "s": 15011, "text": "C++ Programs" }, { "code": null, "e": 15040, "s": 15024, "text": "Data Structures" }, { "code": null, "e": 15045, "s": 15040, "text": "Tree" }, { "code": null, "e": 15061, "s": 15045, "text": "Data Structures" }, { "code": null, "e": 15080, "s": 15061, "text": "Binary Search Tree" }, { "code": null, "e": 15085, "s": 15080, "text": "Tree" } ]
Reverse digits of an integer with overflow handled
07 Jun, 2022 Write a program to reverse an integer assuming that the input is a 32-bit integer. If the reversed integer overflows, print -1 as the output. Let us see a simple approach to reverse digits of an integer. C++ C Java Python3 C# PHP Javascript // A simple C program to reverse digits of// an integer.#include <bits/stdc++.h>using namespace std; int reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Driver program to test reversDigits */int main(){ int num = 5896; cout << "Reverse of no. is " << reversDigits(num); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804) // A simple C program to reverse digits of// an integer.#include <stdio.h> int reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Driver program to test reversDigits */int main(){ int num = 5896; printf("Reverse of no. is %d", reversDigits(num)); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804) // Java program to reverse a number class GFG{ /* Iterative function to reverse digits of num*/ static int reversDigits(int num) { int rev_num = 0; while(num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code public static void main (String[] args) { int num = 4562; System.out.println("Reverse of no. is " + reversDigits(num)); }} // This code is contributed by Anant Agarwal. # Python program to reverse a number n = 4562;rev = 0 while(n > 0): a = n % 10 rev = rev * 10 + a n = n // 10 print(rev) # This code is contributed by Shariq Raza // C# program to reverse a numberusing System; class GFG{ // Iterative function to // reverse digits of num static int reversDigits(int num) { int rev_num = 0; while(num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code public static void Main() { int num = 4562; Console.Write("Reverse of no. is " + reversDigits(num)); }} // This code is contributed by Sam007 <?php// Iterative function to// reverse digits of numfunction reversDigits($num){ $rev_num = 0; while($num > 1) { $rev_num = $rev_num * 10 + $num % 10; $num = (int)$num / 10; } return $rev_num;} // Driver Code$num = 4562;echo "Reverse of no. is ", reversDigits($num); // This code is contributed by aj_36?> <script> // A simple Javascript program to reverse digits of// an integer. function reversDigits(num){ let rev_num = 0; while (num > 0) { rev_num = rev_num*10 + num%10; num = Math.floor(num/10); } return rev_num;} /* Driver program to test reversDigits */ let num = 5896; document.write("Reverse of no. is "+ reversDigits(num)); // This code is contributed by Mayank Tyagi </script> Reverse of no. is 6985 Time Complexity: O(log(num)) Auxiliary Space: O(1) However, if the number is large such that the reverse overflows, the output is some garbage value. If we run the code above with input as any large number say 1000000045, then the output is some garbage value like 1105032705 or any other garbage value. See this for the output.How to handle overflow? The idea is to store previous value of the sum can be stored in a variable which can be checked every time to see if the reverse overflowed or not.Below is the implementation to deal with such a situation. C++ C Java Python3 C# Javascript // C++ program to reverse digits// of a number#include <bits/stdc++.h> using namespace std; /* Iterative function to reversedigits of num*/int reversDigits(int num){ // Handling negative numbers bool negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num % 10; rev_num = (rev_num * 10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if ((rev_num - curr_digit) / 10 != prev_rev_num) { cout << "WARNING OVERFLOWED!!!" << endl; return 0; } prev_rev_num = rev_num; num = num / 10; } return (negativeFlag == true) ? -rev_num : rev_num;} // Driver Codeint main(){ int num = 12345; cout << "Reverse of no. is " << reversDigits(num) << endl; num = 1000000045; cout << "Reverse of no. is " << reversDigits(num) << endl; return 0;} // This code is contributed// by Akanksha Rai(Abby_akku) // C program to reverse digits of a number#include <stdio.h> /* Iterative function to reverse digits of num*/int reversDigits(int num){ // Handling negative numbers bool negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num%10; rev_num = (rev_num*10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if ((rev_num - curr_digit)/10 != prev_rev_num) { printf("WARNING OVERFLOWED!!!\n"); return 0; } prev_rev_num = rev_num; num = num/10; } return (negativeFlag == true)? -rev_num : rev_num;} /* Driver program to test reverse Digits */int main(){ int num = 12345; printf("Reverse of no. is %d\n", reversDigits(num)); num = 1000000045; printf("Reverse of no. is %d\n", reversDigits(num)); return 0;} // Java program to reverse digits of a number class ReverseDigits{ /* Iterative function to reverse digits of num*/ static int reversDigits(int num) { // Handling negative numbers boolean negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num%10; rev_num = (rev_num*10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if ((rev_num - curr_digit)/10 != prev_rev_num) { System.out.println("WARNING OVERFLOWED!!!"); return 0; } prev_rev_num = rev_num; num = num/10; } return (negativeFlag == true)? -rev_num : rev_num; } public static void main (String[] args) { int num = 12345; System.out.println("Reverse of no. is " + reversDigits(num)); num = 1000000045; System.out.println("Reverse of no. is " + reversDigits(num)); }} # Python program to reverse digits# of a number """ Iterative function to reversedigits of num"""def reversDigits(num): # Handling negative numbers negativeFlag = False if (num < 0): negativeFlag = True num = -num prev_rev_num = 0 rev_num = 0 while (num != 0): curr_digit = num % 10 rev_num = (rev_num * 10) + curr_digit # checking if the reverse overflowed or not. # The values of (rev_num - curr_digit)/10 and # prev_rev_num must be same if there was no # problem. if (rev_num >= 2147483647 or rev_num <= -2147483648): rev_num = 0 if ((rev_num - curr_digit) // 10 != prev_rev_num): print("WARNING OVERFLOWED!!!") return 0 prev_rev_num = rev_num num = num //10 return -rev_num if (negativeFlag == True) else rev_num # Driver codeif __name__ =="__main__": num = 12345 print("Reverse of no. is ",reversDigits(num)) num = 1000000045 print("Reverse of no. is ",reversDigits(num)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10) // C# program to reverse digits// of a numberusing System; class GFG{ /* Iterative function to reverse digits of num*/static int reversDigits(int num){ // Handling negative numbers bool negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num % 10; rev_num = (rev_num * 10) + curr_digit; // checking if the reverse overflowed // or not. The values of (rev_num - // curr_digit)/10 and prev_rev_num must // be same if there was no problem. if ((rev_num - curr_digit) / 10 != prev_rev_num) { Console.WriteLine("WARNING OVERFLOWED!!!"); return 0; } prev_rev_num = rev_num; num = num / 10; } return (negativeFlag == true) ? -rev_num : rev_num;} // Driver Codestatic public void Main (){ int num = 12345; Console.WriteLine("Reverse of no. is " + reversDigits(num)); num = 1000000045; Console.WriteLine("Reverse of no. is " + reversDigits(num));}} // This code is contributed by ajit <script>// JavaScript program to reverse digits// of a number /* Iterative function to reversedigits of num*/function reversDigits(num){ // Handling negative numbers let negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } let prev_rev_num = 0, rev_num = 0; while (num != 0) { let curr_digit = num % 10; rev_num = (rev_num * 10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if (rev_num >= 2147483647 || rev_num <= -2147483648) rev_num = 0; if (Math.floor((rev_num - curr_digit) / 10) != prev_rev_num) { document.write("WARNING OVERFLOWED!!!" + "<br>"); return 0; } prev_rev_num = rev_num; num = Math.floor(num / 10); } return (negativeFlag == true) ? -rev_num : rev_num;} // Driver Code let num = 12345; document.write("Reverse of no. is " + reversDigits(num) + "<br>"); num = 1000000045; document.write("Reverse of no. is " + reversDigits(num) + "<br>"); // This code is contributed by Surbhi Tyagi.</script> Reverse of no. is 54321 WARNING OVERFLOWED!!! Reverse of no. is 0 Time Complexity: O(log(num)) Auxiliary Space: O(1) Efficient Approach : The above approach won’t work if we are given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 – 1], then return 0. So we cannot multiply the number*10 and then check if the number overflows or not. We must check the overflow condition before multiply by 10 by using the following logic : You are checking the boundary case before you do the operation. (reversed >INT_MAX ) wouldn’t work because reversed will overflow and become negative if it goes past MAX_VALUE. Dividing MAX_VALUE by 10 lets you check the condition without overflowing INT_MAX is equal 2147483647. INT_MIN is equal -2147483648. Last digits are 7 and 8. This is the reason why we also check rem > 7 and rem < -8 conditions C++ Java Python3 Javascript // C++ program to reverse digits// of a number#include <bits/stdc++.h> using namespace std;int reversDigits(int num) { int rev = 0 ; while(num != 0){ int rem = num % 10 ; num /= 10 ; if(rev > INT_MAX/10 || rev == INT_MAX/10 && rem > 7){ return 0 ; } if(rev < INT_MIN/10 || rev == INT_MIN/10 && rem < -8){ return 0 ; } rev = rev*10 + rem ; } return rev ; } // Driver Codeint main(){ int num = 12345; cout << "Reverse of no. is " << reversDigits(num) << endl; num = 1000000045; cout << "Reverse of no. is " << reversDigits(num) << endl; return 0;} // Java program to reverse digits// of a numberpublic class GFG{ static int reversDigits(int num) { int rev = 0 ; while(num != 0){ int rem = num % 10 ; num /= 10 ; if(rev > Integer.MAX_VALUE/10 || rev == Integer.MAX_VALUE/10 && rem > 7){ return 0 ; } if(rev < Integer.MIN_VALUE/10 || rev == Integer.MIN_VALUE/10 && rem < -8){ return 0 ; } rev = rev*10 + rem ; } return rev ; } // Driver code public static void main (String[] args) { int num = 12345; System.out.println("Reverse of no. is " + reversDigits(num) ); num = 1000000045; System.out.println("Reverse of no. is " + reversDigits(num) ); }} // This code is contributed by jana_sayantan. # Python program for the above approachINT_MAX = 2147483647INT_MIN = -2147483648 def reversDigits(num): rev = 0 while(num > 0): rem = num % 10 num = (num//10) if(rev > INT_MAX/10 or rev == INT_MAX/10 and rem > 7): return 0 if(rev < INT_MIN/10 or rev == INT_MIN/10 and rem < -8): return 0 rev = rev*10 + rem return rev # Driver Codenum = 12345print(f"Reverse of no. is {reversDigits(num)}") num = 1000000045print(f"Reverse of no. is {reversDigits(num)}") # This code is contributed by shinjanpatra <script> // JavaScript program to reverse digits// of a number const INT_MAX = 2147483647;const INT_MIN = -2147483648; function reversDigits(num) { let rev = 0; while(num > 0){ let rem = num % 10 ; num = Math.floor(num/10) ; if(rev > INT_MAX/10 || rev == INT_MAX/10 && rem > 7){ return 0 ; } if(rev < INT_MIN/10 || rev == INT_MIN/10 && rem < -8){ return 0 ; } rev = rev*10 + rem ; } return rev ; } // Driver Code let num = 12345;document.write(`Reverse of no. is ${reversDigits(num)}`,"</br>"); num = 1000000045;document.write(`Reverse of no. is ${reversDigits(num)}`,"</br>"); // This code is contributed by shinjanpatra </script> Reverse of no. is 54321 Reverse of no. is 0 Time Complexity: O(log(num)) Auxiliary Space: O(1) This article is contributed by MAZHAR IMAM KHAN. 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. jit_t Akanksha_Rai SHUBHAMSINGH10 mayanktyagi1709 surbhityagi15 prasanna1995 amartyaghoshgfg shinjanpatra prophet1999 jana_sayantan krisania804 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Minimum number of jumps to reach end Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 260, "s": 54, "text": "Write a program to reverse an integer assuming that the input is a 32-bit integer. If the reversed integer overflows, print -1 as the output. Let us see a simple approach to reverse digits of an integer. " }, { "code": null, "e": 264, "s": 260, "text": "C++" }, { "code": null, "e": 266, "s": 264, "text": "C" }, { "code": null, "e": 271, "s": 266, "text": "Java" }, { "code": null, "e": 279, "s": 271, "text": "Python3" }, { "code": null, "e": 282, "s": 279, "text": "C#" }, { "code": null, "e": 286, "s": 282, "text": "PHP" }, { "code": null, "e": 297, "s": 286, "text": "Javascript" }, { "code": "// A simple C program to reverse digits of// an integer.#include <bits/stdc++.h>using namespace std; int reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Driver program to test reversDigits */int main(){ int num = 5896; cout << \"Reverse of no. is \" << reversDigits(num); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)", "e": 760, "s": 297, "text": null }, { "code": "// A simple C program to reverse digits of// an integer.#include <stdio.h> int reversDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Driver program to test reversDigits */int main(){ int num = 5896; printf(\"Reverse of no. is %d\", reversDigits(num)); return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)", "e": 1197, "s": 760, "text": null }, { "code": "// Java program to reverse a number class GFG{ /* Iterative function to reverse digits of num*/ static int reversDigits(int num) { int rev_num = 0; while(num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code public static void main (String[] args) { int num = 4562; System.out.println(\"Reverse of no. is \" + reversDigits(num)); }} // This code is contributed by Anant Agarwal.", "e": 1746, "s": 1197, "text": null }, { "code": "# Python program to reverse a number n = 4562;rev = 0 while(n > 0): a = n % 10 rev = rev * 10 + a n = n // 10 print(rev) # This code is contributed by Shariq Raza", "e": 1922, "s": 1746, "text": null }, { "code": "// C# program to reverse a numberusing System; class GFG{ // Iterative function to // reverse digits of num static int reversDigits(int num) { int rev_num = 0; while(num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code public static void Main() { int num = 4562; Console.Write(\"Reverse of no. is \" + reversDigits(num)); }} // This code is contributed by Sam007", "e": 2453, "s": 1922, "text": null }, { "code": "<?php// Iterative function to// reverse digits of numfunction reversDigits($num){ $rev_num = 0; while($num > 1) { $rev_num = $rev_num * 10 + $num % 10; $num = (int)$num / 10; } return $rev_num;} // Driver Code$num = 4562;echo \"Reverse of no. is \", reversDigits($num); // This code is contributed by aj_36?>", "e": 2818, "s": 2453, "text": null }, { "code": "<script> // A simple Javascript program to reverse digits of// an integer. function reversDigits(num){ let rev_num = 0; while (num > 0) { rev_num = rev_num*10 + num%10; num = Math.floor(num/10); } return rev_num;} /* Driver program to test reversDigits */ let num = 5896; document.write(\"Reverse of no. is \"+ reversDigits(num)); // This code is contributed by Mayank Tyagi </script>", "e": 3242, "s": 2818, "text": null }, { "code": null, "e": 3265, "s": 3242, "text": "Reverse of no. is 6985" }, { "code": null, "e": 3294, "s": 3265, "text": "Time Complexity: O(log(num))" }, { "code": null, "e": 3316, "s": 3294, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3824, "s": 3316, "text": "However, if the number is large such that the reverse overflows, the output is some garbage value. If we run the code above with input as any large number say 1000000045, then the output is some garbage value like 1105032705 or any other garbage value. See this for the output.How to handle overflow? The idea is to store previous value of the sum can be stored in a variable which can be checked every time to see if the reverse overflowed or not.Below is the implementation to deal with such a situation. " }, { "code": null, "e": 3828, "s": 3824, "text": "C++" }, { "code": null, "e": 3830, "s": 3828, "text": "C" }, { "code": null, "e": 3835, "s": 3830, "text": "Java" }, { "code": null, "e": 3843, "s": 3835, "text": "Python3" }, { "code": null, "e": 3846, "s": 3843, "text": "C#" }, { "code": null, "e": 3857, "s": 3846, "text": "Javascript" }, { "code": "// C++ program to reverse digits// of a number#include <bits/stdc++.h> using namespace std; /* Iterative function to reversedigits of num*/int reversDigits(int num){ // Handling negative numbers bool negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num % 10; rev_num = (rev_num * 10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if ((rev_num - curr_digit) / 10 != prev_rev_num) { cout << \"WARNING OVERFLOWED!!!\" << endl; return 0; } prev_rev_num = rev_num; num = num / 10; } return (negativeFlag == true) ? -rev_num : rev_num;} // Driver Codeint main(){ int num = 12345; cout << \"Reverse of no. is \" << reversDigits(num) << endl; num = 1000000045; cout << \"Reverse of no. is \" << reversDigits(num) << endl; return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 5081, "s": 3857, "text": null }, { "code": "// C program to reverse digits of a number#include <stdio.h> /* Iterative function to reverse digits of num*/int reversDigits(int num){ // Handling negative numbers bool negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num%10; rev_num = (rev_num*10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if ((rev_num - curr_digit)/10 != prev_rev_num) { printf(\"WARNING OVERFLOWED!!!\\n\"); return 0; } prev_rev_num = rev_num; num = num/10; } return (negativeFlag == true)? -rev_num : rev_num;} /* Driver program to test reverse Digits */int main(){ int num = 12345; printf(\"Reverse of no. is %d\\n\", reversDigits(num)); num = 1000000045; printf(\"Reverse of no. is %d\\n\", reversDigits(num)); return 0;}", "e": 6150, "s": 5081, "text": null }, { "code": "// Java program to reverse digits of a number class ReverseDigits{ /* Iterative function to reverse digits of num*/ static int reversDigits(int num) { // Handling negative numbers boolean negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num%10; rev_num = (rev_num*10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if ((rev_num - curr_digit)/10 != prev_rev_num) { System.out.println(\"WARNING OVERFLOWED!!!\"); return 0; } prev_rev_num = rev_num; num = num/10; } return (negativeFlag == true)? -rev_num : rev_num; } public static void main (String[] args) { int num = 12345; System.out.println(\"Reverse of no. is \" + reversDigits(num)); num = 1000000045; System.out.println(\"Reverse of no. is \" + reversDigits(num)); }}", "e": 7413, "s": 6150, "text": null }, { "code": "# Python program to reverse digits# of a number \"\"\" Iterative function to reversedigits of num\"\"\"def reversDigits(num): # Handling negative numbers negativeFlag = False if (num < 0): negativeFlag = True num = -num prev_rev_num = 0 rev_num = 0 while (num != 0): curr_digit = num % 10 rev_num = (rev_num * 10) + curr_digit # checking if the reverse overflowed or not. # The values of (rev_num - curr_digit)/10 and # prev_rev_num must be same if there was no # problem. if (rev_num >= 2147483647 or rev_num <= -2147483648): rev_num = 0 if ((rev_num - curr_digit) // 10 != prev_rev_num): print(\"WARNING OVERFLOWED!!!\") return 0 prev_rev_num = rev_num num = num //10 return -rev_num if (negativeFlag == True) else rev_num # Driver codeif __name__ ==\"__main__\": num = 12345 print(\"Reverse of no. is \",reversDigits(num)) num = 1000000045 print(\"Reverse of no. is \",reversDigits(num)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)", "e": 8570, "s": 7413, "text": null }, { "code": "// C# program to reverse digits// of a numberusing System; class GFG{ /* Iterative function to reverse digits of num*/static int reversDigits(int num){ // Handling negative numbers bool negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num % 10; rev_num = (rev_num * 10) + curr_digit; // checking if the reverse overflowed // or not. The values of (rev_num - // curr_digit)/10 and prev_rev_num must // be same if there was no problem. if ((rev_num - curr_digit) / 10 != prev_rev_num) { Console.WriteLine(\"WARNING OVERFLOWED!!!\"); return 0; } prev_rev_num = rev_num; num = num / 10; } return (negativeFlag == true) ? -rev_num : rev_num;} // Driver Codestatic public void Main (){ int num = 12345; Console.WriteLine(\"Reverse of no. is \" + reversDigits(num)); num = 1000000045; Console.WriteLine(\"Reverse of no. is \" + reversDigits(num));}} // This code is contributed by ajit", "e": 9791, "s": 8570, "text": null }, { "code": "<script>// JavaScript program to reverse digits// of a number /* Iterative function to reversedigits of num*/function reversDigits(num){ // Handling negative numbers let negativeFlag = false; if (num < 0) { negativeFlag = true; num = -num ; } let prev_rev_num = 0, rev_num = 0; while (num != 0) { let curr_digit = num % 10; rev_num = (rev_num * 10) + curr_digit; // checking if the reverse overflowed or not. // The values of (rev_num - curr_digit)/10 and // prev_rev_num must be same if there was no // problem. if (rev_num >= 2147483647 || rev_num <= -2147483648) rev_num = 0; if (Math.floor((rev_num - curr_digit) / 10) != prev_rev_num) { document.write(\"WARNING OVERFLOWED!!!\" + \"<br>\"); return 0; } prev_rev_num = rev_num; num = Math.floor(num / 10); } return (negativeFlag == true) ? -rev_num : rev_num;} // Driver Code let num = 12345; document.write(\"Reverse of no. is \" + reversDigits(num) + \"<br>\"); num = 1000000045; document.write(\"Reverse of no. is \" + reversDigits(num) + \"<br>\"); // This code is contributed by Surbhi Tyagi.</script>", "e": 11086, "s": 9791, "text": null }, { "code": null, "e": 11152, "s": 11086, "text": "Reverse of no. is 54321\nWARNING OVERFLOWED!!!\nReverse of no. is 0" }, { "code": null, "e": 11181, "s": 11152, "text": "Time Complexity: O(log(num))" }, { "code": null, "e": 11203, "s": 11181, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 11224, "s": 11203, "text": "Efficient Approach :" }, { "code": null, "e": 11442, "s": 11224, "text": "The above approach won’t work if we are given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 – 1], then return 0." }, { "code": null, "e": 11525, "s": 11442, "text": "So we cannot multiply the number*10 and then check if the number overflows or not." }, { "code": null, "e": 11615, "s": 11525, "text": "We must check the overflow condition before multiply by 10 by using the following logic :" }, { "code": null, "e": 11715, "s": 11615, "text": "You are checking the boundary case before you do the operation. (reversed >INT_MAX ) wouldn’t work " }, { "code": null, "e": 11794, "s": 11715, "text": "because reversed will overflow and become negative if it goes past MAX_VALUE. " }, { "code": null, "e": 11868, "s": 11794, "text": "Dividing MAX_VALUE by 10 lets you check the condition without overflowing" }, { "code": null, "e": 11929, "s": 11868, "text": "INT_MAX is equal 2147483647. INT_MIN is equal -2147483648. " }, { "code": null, "e": 12025, "s": 11929, "text": "Last digits are 7 and 8. This is the reason why we also check rem > 7 and rem < -8 conditions" }, { "code": null, "e": 12029, "s": 12025, "text": "C++" }, { "code": null, "e": 12034, "s": 12029, "text": "Java" }, { "code": null, "e": 12042, "s": 12034, "text": "Python3" }, { "code": null, "e": 12053, "s": 12042, "text": "Javascript" }, { "code": "// C++ program to reverse digits// of a number#include <bits/stdc++.h> using namespace std;int reversDigits(int num) { int rev = 0 ; while(num != 0){ int rem = num % 10 ; num /= 10 ; if(rev > INT_MAX/10 || rev == INT_MAX/10 && rem > 7){ return 0 ; } if(rev < INT_MIN/10 || rev == INT_MIN/10 && rem < -8){ return 0 ; } rev = rev*10 + rem ; } return rev ; } // Driver Codeint main(){ int num = 12345; cout << \"Reverse of no. is \" << reversDigits(num) << endl; num = 1000000045; cout << \"Reverse of no. is \" << reversDigits(num) << endl; return 0;}", "e": 12770, "s": 12053, "text": null }, { "code": "// Java program to reverse digits// of a numberpublic class GFG{ static int reversDigits(int num) { int rev = 0 ; while(num != 0){ int rem = num % 10 ; num /= 10 ; if(rev > Integer.MAX_VALUE/10 || rev == Integer.MAX_VALUE/10 && rem > 7){ return 0 ; } if(rev < Integer.MIN_VALUE/10 || rev == Integer.MIN_VALUE/10 && rem < -8){ return 0 ; } rev = rev*10 + rem ; } return rev ; } // Driver code public static void main (String[] args) { int num = 12345; System.out.println(\"Reverse of no. is \" + reversDigits(num) ); num = 1000000045; System.out.println(\"Reverse of no. is \" + reversDigits(num) ); }} // This code is contributed by jana_sayantan.", "e": 13510, "s": 12770, "text": null }, { "code": "# Python program for the above approachINT_MAX = 2147483647INT_MIN = -2147483648 def reversDigits(num): rev = 0 while(num > 0): rem = num % 10 num = (num//10) if(rev > INT_MAX/10 or rev == INT_MAX/10 and rem > 7): return 0 if(rev < INT_MIN/10 or rev == INT_MIN/10 and rem < -8): return 0 rev = rev*10 + rem return rev # Driver Codenum = 12345print(f\"Reverse of no. is {reversDigits(num)}\") num = 1000000045print(f\"Reverse of no. is {reversDigits(num)}\") # This code is contributed by shinjanpatra", "e": 14118, "s": 13510, "text": null }, { "code": "<script> // JavaScript program to reverse digits// of a number const INT_MAX = 2147483647;const INT_MIN = -2147483648; function reversDigits(num) { let rev = 0; while(num > 0){ let rem = num % 10 ; num = Math.floor(num/10) ; if(rev > INT_MAX/10 || rev == INT_MAX/10 && rem > 7){ return 0 ; } if(rev < INT_MIN/10 || rev == INT_MIN/10 && rem < -8){ return 0 ; } rev = rev*10 + rem ; } return rev ; } // Driver Code let num = 12345;document.write(`Reverse of no. is ${reversDigits(num)}`,\"</br>\"); num = 1000000045;document.write(`Reverse of no. is ${reversDigits(num)}`,\"</br>\"); // This code is contributed by shinjanpatra </script>", "e": 14888, "s": 14118, "text": null }, { "code": null, "e": 14932, "s": 14888, "text": "Reverse of no. is 54321\nReverse of no. is 0" }, { "code": null, "e": 14961, "s": 14932, "text": "Time Complexity: O(log(num))" }, { "code": null, "e": 14983, "s": 14961, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 15408, "s": 14983, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using 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": 15414, "s": 15408, "text": "jit_t" }, { "code": null, "e": 15427, "s": 15414, "text": "Akanksha_Rai" }, { "code": null, "e": 15442, "s": 15427, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 15458, "s": 15442, "text": "mayanktyagi1709" }, { "code": null, "e": 15472, "s": 15458, "text": "surbhityagi15" }, { "code": null, "e": 15485, "s": 15472, "text": "prasanna1995" }, { "code": null, "e": 15501, "s": 15485, "text": "amartyaghoshgfg" }, { "code": null, "e": 15514, "s": 15501, "text": "shinjanpatra" }, { "code": null, "e": 15526, "s": 15514, "text": "prophet1999" }, { "code": null, "e": 15540, "s": 15526, "text": "jana_sayantan" }, { "code": null, "e": 15552, "s": 15540, "text": "krisania804" }, { "code": null, "e": 15566, "s": 15552, "text": "number-digits" }, { "code": null, "e": 15579, "s": 15566, "text": "Mathematical" }, { "code": null, "e": 15592, "s": 15579, "text": "Mathematical" }, { "code": null, "e": 15690, "s": 15592, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15714, "s": 15690, "text": "Merge two sorted arrays" }, { "code": null, "e": 15735, "s": 15714, "text": "Operators in C / C++" }, { "code": null, "e": 15757, "s": 15735, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 15771, "s": 15757, "text": "Prime Numbers" }, { "code": null, "e": 15813, "s": 15771, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 15850, "s": 15813, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 15903, "s": 15850, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 15946, "s": 15903, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 15978, "s": 15946, "text": "Algorithm to solve Rubik's Cube" } ]
short keyword in C#
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. short is a keyword that is used to declare a variable which can store a signed integer value from the range -32, 768 to 32, 767. It is an alias of System.Int16. Syntax: short variable_name = value; short keyword occupies 2 bytes (16 bits) space in the memory. Example: Input: num: 2 Output: num: 2 Size of a short variable: 2 Input: num = 20200 Output: num: 20200 Type of num: System.Int16 Size of a short variable: 2 Example 1: // C# program for short keywordusing System;using System.Text; class Prog { static void Main(string[] args) { // variable declaration short num = 2; // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a short variable: " + sizeof(short)); }} Output: num: 2 Size of a short variable: 2 Example 2: // C# program for short keywordusing System;using System.Text; namespace Test { class Prog { static void Main(string[] args) { // variable declaration short num = 20200; // to print value Console.WriteLine("num: " + num); // to print type of variable Console.WriteLine("Type of num: " + num.GetType()); // to print size Console.WriteLine("Size of a short variable: " + sizeof(short)); // to print minimum & maximum value of short Console.WriteLine("Min value of short: " + short.MinValue); Console.WriteLine("Max value of short: " + short.MaxValue); // hit ENTER to exit Console.ReadLine(); }}} Output: num: 20200 Type of num: System.Int16 Size of a short variable: 2 Min value of short: -32768 Max value of short: 32767 CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 304, "s": 28, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. short is a keyword that is used to declare a variable which can store a signed integer value from the range -32, 768 to 32, 767. It is an alias of System.Int16." }, { "code": null, "e": 312, "s": 304, "text": "Syntax:" }, { "code": null, "e": 341, "s": 312, "text": "short variable_name = value;" }, { "code": null, "e": 403, "s": 341, "text": "short keyword occupies 2 bytes (16 bits) space in the memory." }, { "code": null, "e": 412, "s": 403, "text": "Example:" }, { "code": null, "e": 589, "s": 412, "text": "Input: num: 2\n\nOutput: num: 2\n Size of a short variable: 2\n\nInput: num = 20200\n\nOutput: num: 20200\n Type of num: System.Int16\n Size of a short variable: 2\n" }, { "code": null, "e": 600, "s": 589, "text": "Example 1:" }, { "code": "// C# program for short keywordusing System;using System.Text; class Prog { static void Main(string[] args) { // variable declaration short num = 2; // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a short variable: \" + sizeof(short)); }}", "e": 944, "s": 600, "text": null }, { "code": null, "e": 952, "s": 944, "text": "Output:" }, { "code": null, "e": 988, "s": 952, "text": "num: 2\nSize of a short variable: 2\n" }, { "code": null, "e": 999, "s": 988, "text": "Example 2:" }, { "code": "// C# program for short keywordusing System;using System.Text; namespace Test { class Prog { static void Main(string[] args) { // variable declaration short num = 20200; // to print value Console.WriteLine(\"num: \" + num); // to print type of variable Console.WriteLine(\"Type of num: \" + num.GetType()); // to print size Console.WriteLine(\"Size of a short variable: \" + sizeof(short)); // to print minimum & maximum value of short Console.WriteLine(\"Min value of short: \" + short.MinValue); Console.WriteLine(\"Max value of short: \" + short.MaxValue); // hit ENTER to exit Console.ReadLine(); }}}", "e": 1708, "s": 999, "text": null }, { "code": null, "e": 1716, "s": 1708, "text": "Output:" }, { "code": null, "e": 1835, "s": 1716, "text": "num: 20200\nType of num: System.Int16\nSize of a short variable: 2\nMin value of short: -32768\nMax value of short: 32767\n" }, { "code": null, "e": 1850, "s": 1835, "text": "CSharp-keyword" }, { "code": null, "e": 1853, "s": 1850, "text": "C#" }, { "code": null, "e": 1951, "s": 1853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1994, "s": 1951, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2043, "s": 1994, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2066, "s": 2043, "text": "Extension Method in C#" }, { "code": null, "e": 2082, "s": 2066, "text": "C# | List Class" }, { "code": null, "e": 2110, "s": 2082, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2171, "s": 2110, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 2194, "s": 2171, "text": "Switch Statement in C#" }, { "code": null, "e": 2219, "s": 2194, "text": "Lambda Expressions in C#" }, { "code": null, "e": 2241, "s": 2219, "text": "Partial Classes in C#" } ]
Create a Stacked Bar Chart using Recharts in ReactJS
30 Jul, 2021 Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). A stacked Bar Chart is the extension of a basic bar chart. It displays various discrete data in the same bar chart for a better comparison of data. Approach: To create a Stacked Bar Chart we use the BarChart component of recharts npm package. We firstly create a cartesian grid and X-axis and Y-Axis. Then add multiple Bar charts using Bar component and to get them stacked on top of each other use the same stackId for all charts. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts Step 3: After creating the ReactJS application, Install the required modules using the following command. npm install --save recharts Project Structure: It will look like the following. Example 1: In this example, we will create a basic stacked bar chart using BarChart and Bar component of recharts npm package. To stack the two bars on top of each other we will add same stackId to both Bar components. Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import { BarChart, Bar, XAxis, YAxis, CartesianGrid } from 'recharts'; const App = () => { // Sample data const data = [ { name: 'A', x: 12, y: 23, z: 122 }, { name: 'B', x: 22, y: 3, z: 73 }, { name: 'C', x: 13, y: 15, z: 32 }, { name: 'D', x: 44, y: 35, z: 23 }, { name: 'E', x: 35, y: 45, z: 20 }, { name: 'F', x: 62, y: 25, z: 29 }, { name: 'G', x: 37, y: 17, z: 61 }, { name: 'H', x: 28, y: 32, z: 45 }, { name: 'I', x: 19, y: 43, z: 93 }, ]; return ( <BarChart width={500} height={500} data={data} > <CartesianGrid /> <XAxis dataKey="name" /> <YAxis /> <Bar dataKey="x" stackId="a" fill="#8884d8" /> <Bar dataKey="y" stackId="a" fill="#82ca9d" /> </BarChart> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Output Example 2: In this example, we will change the color of bars using fill property. To add a tooltip that will display information about bar on hover and legend that will show labels for stacked bars, we will use Tooltip component and Legend component. Now change the following code in the App.js file. App.js import React from 'react';import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Legend, Tooltip } from 'recharts'; const App = () => { // Sample data const data = [ { name: "A", x: 30, y: 70 }, { name: "B", x: 12, y: 88 }, { name: "C", x: 15, y: 85 }, { name: "D", x: 35, y: 65 }, { name: "E", x: 54, y: 46 }, { name: "F", x: 72, y: 28 }, { name: "G", x: 32, y: 68 } ]; return ( <BarChart width={500} height={500} data={data} > <CartesianGrid /> <XAxis dataKey="name" /> <YAxis /> <Tooltip /> <Legend /> <Bar dataKey="x" stackId="a" fill="aqua" /> <Bar dataKey="y" stackId="a" fill="green" /> </BarChart> );} export default App; Output: Save the project using CTRL+S.Now open your browser and go to http://localhost:3000/, you will see the following output: Output React-Questions Recharts 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": 54, "s": 26, "text": "\n30 Jul, 2021" }, { "code": null, "e": 272, "s": 54, "text": "Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). " }, { "code": null, "e": 421, "s": 272, "text": "A stacked Bar Chart is the extension of a basic bar chart. It displays various discrete data in the same bar chart for a better comparison of data. " }, { "code": null, "e": 705, "s": 421, "text": "Approach: To create a Stacked Bar Chart we use the BarChart component of recharts npm package. We firstly create a cartesian grid and X-axis and Y-Axis. Then add multiple Bar charts using Bar component and to get them stacked on top of each other use the same stackId for all charts." }, { "code": null, "e": 757, "s": 707, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 852, "s": 757, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 916, "s": 852, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 948, "s": 916, "text": "npx create-react-app foldername" }, { "code": null, "e": 1061, "s": 948, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 1161, "s": 1061, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 1175, "s": 1161, "text": "cd foldername" }, { "code": null, "e": 1308, "s": 1175, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts" }, { "code": null, "e": 1414, "s": 1308, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command." }, { "code": null, "e": 1442, "s": 1414, "text": "npm install --save recharts" }, { "code": null, "e": 1494, "s": 1442, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1834, "s": 1494, "text": "Example 1: In this example, we will create a basic stacked bar chart using BarChart and Bar component of recharts npm package. To stack the two bars on top of each other we will add same stackId to both Bar components. Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1841, "s": 1834, "text": "App.js" }, { "code": "import React from 'react';import { BarChart, Bar, XAxis, YAxis, CartesianGrid } from 'recharts'; const App = () => { // Sample data const data = [ { name: 'A', x: 12, y: 23, z: 122 }, { name: 'B', x: 22, y: 3, z: 73 }, { name: 'C', x: 13, y: 15, z: 32 }, { name: 'D', x: 44, y: 35, z: 23 }, { name: 'E', x: 35, y: 45, z: 20 }, { name: 'F', x: 62, y: 25, z: 29 }, { name: 'G', x: 37, y: 17, z: 61 }, { name: 'H', x: 28, y: 32, z: 45 }, { name: 'I', x: 19, y: 43, z: 93 }, ]; return ( <BarChart width={500} height={500} data={data} > <CartesianGrid /> <XAxis dataKey=\"name\" /> <YAxis /> <Bar dataKey=\"x\" stackId=\"a\" fill=\"#8884d8\" /> <Bar dataKey=\"y\" stackId=\"a\" fill=\"#82ca9d\" /> </BarChart> );} export default App;", "e": 2713, "s": 1841, "text": null }, { "code": null, "e": 2826, "s": 2713, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2836, "s": 2826, "text": "npm start" }, { "code": null, "e": 2935, "s": 2836, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2942, "s": 2935, "text": "Output" }, { "code": null, "e": 3244, "s": 2942, "text": "Example 2: In this example, we will change the color of bars using fill property. To add a tooltip that will display information about bar on hover and legend that will show labels for stacked bars, we will use Tooltip component and Legend component. Now change the following code in the App.js file. " }, { "code": null, "e": 3251, "s": 3244, "text": "App.js" }, { "code": "import React from 'react';import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Legend, Tooltip } from 'recharts'; const App = () => { // Sample data const data = [ { name: \"A\", x: 30, y: 70 }, { name: \"B\", x: 12, y: 88 }, { name: \"C\", x: 15, y: 85 }, { name: \"D\", x: 35, y: 65 }, { name: \"E\", x: 54, y: 46 }, { name: \"F\", x: 72, y: 28 }, { name: \"G\", x: 32, y: 68 } ]; return ( <BarChart width={500} height={500} data={data} > <CartesianGrid /> <XAxis dataKey=\"name\" /> <YAxis /> <Tooltip /> <Legend /> <Bar dataKey=\"x\" stackId=\"a\" fill=\"aqua\" /> <Bar dataKey=\"y\" stackId=\"a\" fill=\"green\" /> </BarChart> );} export default App;", "e": 4047, "s": 3251, "text": null }, { "code": null, "e": 4176, "s": 4047, "text": "Output: Save the project using CTRL+S.Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4183, "s": 4176, "text": "Output" }, { "code": null, "e": 4199, "s": 4183, "text": "React-Questions" }, { "code": null, "e": 4208, "s": 4199, "text": "Recharts" }, { "code": null, "e": 4219, "s": 4208, "text": "JavaScript" }, { "code": null, "e": 4227, "s": 4219, "text": "ReactJS" }, { "code": null, "e": 4244, "s": 4227, "text": "Web Technologies" }, { "code": null, "e": 4342, "s": 4244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4403, "s": 4342, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4475, "s": 4403, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4515, "s": 4475, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4556, "s": 4515, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4602, "s": 4556, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 4645, "s": 4602, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4690, "s": 4645, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 4728, "s": 4690, "text": "Axios in React: A Guide for Beginners" } ]
Printing all solutions in N-Queen Problem
07 Jul, 2022 The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem. In previous post, we have discussed an approach that prints only one possible solution, so now in this post, the task is to print all solutions in N-Queen Problem. Each solution contains distinct board configurations of the N-queens’ placement, where the solutions are a permutation of [1,2,3..n] in increasing order, here the number in the ith place denotes that the ith-column queen is placed in the row with that number. For the example above solution is written as [[2 4 1 3 ] [3 1 4 2 ]]. The solution discussed here is an extension of the same approach. Backtracking Algorithm The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false. 1) Start in the leftmost column 2) If all queens are placed return true 3) Try all rows in the current column. Do following for every tried row. a) If the queen can be placed safely in this row then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution. b) If placing queen in [row, column] leads to a solution then return true. c) If placing queen doesn't lead to a solution then unmark this [row, column] (Backtrack) and go to step (a) to try other rows. 3) If all rows have been tried and nothing worked, return false to trigger backtracking. A modification is that we can find whether we have a previously placed queen in a column or in left diagonal or in right diagonal in O(1) time. We can observe that For all cells in a particular left diagonal , their row + col = constant.For all cells in a particular right diagonal, their row – col + n – 1 = constant. For all cells in a particular left diagonal , their row + col = constant. For all cells in a particular right diagonal, their row – col + n – 1 = constant. Let say n = 5, then we have a total of 2n-1 left and right diagonals Let say we placed a queen at (2,0) (2,0) have leftDiagonal value = 2. Now we can not place another queen at (1,1) and (0,2) because both of these have same leftDiagonal value as for (2,0). Similar thing can be noticed for right diagonal as well. Implementation: C++ Java Python3 C# /* C/C++ program to solve N Queen Problem usingbacktracking */#include <bits/stdc++.h>using namespace std; vector<vector<int> > result; /* A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when "col" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens */bool isSafe(vector<vector<int> > board, int row, int col){ int i, j; int N = board.size(); /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve NQueen problem */bool solveNQUtil(vector<vector<int> >& board, int col){ /* base case: If all queens are placed then return true */ int N = board.size(); if (col == N) { vector<int> v; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (board[i][j] == 1) v.push_back(j + 1); } } result.push_back(v); return true; } /* Consider this column and try placing this queen in all rows one by one */ bool res = false; for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; // Make result true if any placement // is possible res = solveNQUtil(board, col + 1) || res; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If queen can not be place in any row in this column col then return false */ return res;} /* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/ vector<vector<int> > nQueen(int n){ result.clear(); vector<vector<int> > board(n, vector<int>(n, 0)); if (solveNQUtil(board, 0) == false) { return {}; } sort(result.begin(), result.end()); return result;} // Driver Codeint main(){ int n = 4; vector<vector<int> > v = nQueen(n); for (auto ar : v) { cout << "["; for (auto it : ar) cout << it << " "; cout << "]"; } return 0;} /* Java program to solve N QueenProblem using backtracking */import java.util.*;class GfG { /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. */ static List<List<Integer>> nQueen(int n) { // cols[i] = true if there is a queen previously placed at ith column cols = new boolean[n]; // leftDiagonal[i] = true if there is a queen previously placed at // i = (row + col )th left diagonal leftDiagonal = new boolean[2*n]; // rightDiagonal[i] = true if there is a queen previously placed at // i = (row - col + n - 1)th rightDiagonal diagonal rightDiagonal = new boolean[2*n]; result = new ArrayList<>(); List<Integer> temp = new ArrayList<>(); for(int i=0;i<n;i++)temp.add(0); solveNQUtil(result,n,0,temp); return result; } private static void solveNQUtil(List<List<Integer>> result,int n,int row,List<Integer> comb){ if(row==n){ // if row==n it means we have successfully placed all n queens. // hence add current arrangement to our answer // comb represent current combination result.add(new ArrayList<>(comb)); return; } for(int col = 0;col<n;col++){ // if we have a queen previously placed in the current column // or in current left or right diagonal we continue if(cols[col] || leftDiagonal[row+col] || rightDiagonal[row-col+n]) continue; // otherwise we place a queen at cell[row][col] and //make current column, left diagonal and right diagonal true cols[col] = leftDiagonal[row+col] = rightDiagonal[row-col+n] = true; comb.set(col,row+1); // then we goto next row solveNQUtil(result,n,row+1,comb); // then we backtrack and remove our currently placed queen cols[col] = leftDiagonal[row+col] = rightDiagonal[row-col+n] = false; } } static List<List<Integer> > result = new ArrayList<List<Integer> >(); static boolean[] cols,leftDiagonal,rightDiagonal; // Driver code public static void main(String[] args) { int n = 4; List<List<Integer> > res = nQueen(n); System.out.println(res); }} ''' Python3 program to solve N Queen Problem usingbacktracking ''' result = [] # A utility function to print solution ''' A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when "col" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens ''' def isSafe(board, row, col): # Check this row on left side for i in range(col): if (board[row][i]): return False # Check upper diagonal on left side i = row j = col while i >= 0 and j >= 0: if(board[i][j]): return False i -= 1 j -= 1 # Check lower diagonal on left side i = row j = col while j >= 0 and i < 4: if(board[i][j]): return False i = i + 1 j = j - 1 return True ''' A recursive utility function to solve NQueen problem ''' def solveNQUtil(board, col): ''' base case: If all queens are placed then return true ''' if (col == 4): v = [] for i in board: for j in range(len(i)): if i[j] == 1: v.append(j+1) result.append(v) return True ''' Consider this column and try placing this queen in all rows one by one ''' res = False for i in range(4): ''' Check if queen can be placed on board[i][col] ''' if (isSafe(board, i, col)): # Place this queen in board[i][col] board[i][col] = 1 # Make result true if any placement # is possible res = solveNQUtil(board, col + 1) or res ''' If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] ''' board[i][col] = 0 # BACKTRACK ''' If queen can not be place in any row in this column col then return false ''' return res ''' This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.''' def solveNQ(n): result.clear() board = [[0 for j in range(n)] for i in range(n)] solveNQUtil(board, 0) result.sort() return result # Driver Coden = 4res = solveNQ(n)print(res) # This code is contributed by YatinGupta /* C# program to solve N QueenProblem using backtracking */using System;using System.Collections;using System.Collections.Generic; class GfG { static List<List<int> > result = new List<List<int> >(); /* A utility function to check if a queen can be placed on board[row,col]. Note that this function is called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */ static bool isSafe(int[, ] board, int row, int col, int N) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row, i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i, j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i, j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ static bool solveNQUtil(int[, ] board, int col, int N) { /* base case: If all queens are placed then return true */ if (col == N) { List<int> v = new List<int>(); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { if (board[i, j] == 1) v.Add(j + 1); } result.Add(v); return true; } /* Consider this column and try placing this queen in all rows one by one */ bool res = false; for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i,col] */ if (isSafe(board, i, col, N)) { /* Place this queen in board[i,col] */ board[i, col] = 1; // Make result true if any placement // is possible res = solveNQUtil(board, col + 1, N) || res; /* If placing queen in board[i,col] doesn't lead to a solution, then remove queen from board[i,col] */ board[i, col] = 0; // BACKTRACK } } /* If queen can not be place in any row in this column col then return false */ return res; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ static List<List<int> > solveNQ(int n) { result.Clear(); int[, ] board = new int[n, n]; solveNQUtil(board, 0, n); return result; } // Driver code public static void Main() { int n = 4; List<List<int> > res = solveNQ(n); for (int i = 0; i < res.Count; i++) { Console.Write("["); for (int j = 0; j < res[i].Count; j++) { Console.Write(res[i][j]+ " "); } Console.Write("]"); } }} /* This code contributed by PrinciRaj1992 */ [2 4 1 3 ][3 1 4 2 ] Efficient Backtracking Approach Using Bit-Masking Algorithm: There is always only one queen in each row and each column, so idea of backtracking is to start placing queen from the leftmost column of each row and find a column where the queen could be placed without collision with previously placed queens. It is repeated from the first row till the last row. While placing a queen, it is tracked as if it is not making a collision (row-wise, column-wise and diagonally) with queens placed in previous rows. Once it is found that the queen can’t be placed at a particular column index in a row, the algorithm backtracks and change the position of the queen placed in the previous row then moves forward to place the queen in the next row. Start with three-bit vector which is used to track safe place for queen placement row-wise, column-wise and diagonally in each iteration.Three-bit vector will contain information as bellow:rowmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row.ldmask: set bit index (i) of this bit vector will indicate, the queen can’t e placed at ith column of next row. It represents the unsafe column index for next row falls under left diagonal of queens placed in previous rows.rdmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. It represents the unsafe column index for next row falls right diagonal of queens placed in previous rows.There is a 2-D (NxN) matrix (board), which will have ‘ ‘ character at all indexes in beginning and it gets filled by ‘Q’ row-by-row. Once all rows are filled by ‘Q’, the current solution is pushed into the result list. Start with three-bit vector which is used to track safe place for queen placement row-wise, column-wise and diagonally in each iteration. Three-bit vector will contain information as bellow:rowmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row.ldmask: set bit index (i) of this bit vector will indicate, the queen can’t e placed at ith column of next row. It represents the unsafe column index for next row falls under left diagonal of queens placed in previous rows.rdmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. It represents the unsafe column index for next row falls right diagonal of queens placed in previous rows. rowmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. ldmask: set bit index (i) of this bit vector will indicate, the queen can’t e placed at ith column of next row. It represents the unsafe column index for next row falls under left diagonal of queens placed in previous rows. rdmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. It represents the unsafe column index for next row falls right diagonal of queens placed in previous rows. There is a 2-D (NxN) matrix (board), which will have ‘ ‘ character at all indexes in beginning and it gets filled by ‘Q’ row-by-row. Once all rows are filled by ‘Q’, the current solution is pushed into the result list. Below is the implementation of the above approach: C++ Java Python3 C# // CPP program for above approach#include <bits/stdc++.h> using namespace std; vector<vector<int> > result;// Program to solve N Queens problemvoid solveBoard(vector<vector<char> >& board, int row, int rowmask, int ldmask, int rdmask, int& ways){ int n = board.size(); // All_rows_filled is a bit mask having all N bits set int all_rows_filled = (1 << n) - 1; // If rowmask will have all bits set, means queen has // been placed successfully in all rows and board is // displayed if (rowmask == all_rows_filled) { vector<int> v; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board.size(); j++) { if (board[i][j] == 'Q') v.push_back(j + 1); } } result.push_back(v); return; } // We extract a bit mask(safe) by rowmask, // ldmask and rdmask. all set bits of 'safe' // indicates the safe column index for queen // placement of this iteration for row index(row). int safe = all_rows_filled & (~(rowmask | ldmask | rdmask)); while (safe) { // Extracts the right-most set bit // (safe column index) where queen // can be placed for this row int p = safe & (-safe); int col = (int)log2(p); board[row][col] = 'Q'; // This is very important: // we need to update rowmask, ldmask and rdmask // for next row as safe index for queen placement // will be decided by these three bit masks. // We have all three rowmask, ldmask and // rdmask as 0 in beginning. Suppose, we are placing // queen at 1st column index at 0th row. rowmask, // ldmask and rdmask will change for next row as // below: // rowmask's 1st bit will be set by OR operation // rowmask = 00000000000000000000000000000010 // ldmask will change by setting 1st // bit by OR operation and left shifting // by 1 as it has to block the next column // of next row because that will fall on left // diagonal. ldmask = // 00000000000000000000000000000100 // rdmask will change by setting 1st bit // by OR operation and right shifting by 1 // as it has to block the previous column // of next row because that will fall on right // diagonal. rdmask = // 00000000000000000000000000000001 // these bit masks will keep updated in each // iteration for next row solveBoard(board, row + 1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1, ways); // Reset right-most set bit to 0 so, // next iteration will continue by placing the queen // at another safe column index of this row safe = safe & (safe - 1); // Backtracking, replace 'Q' by ' ' board[row][col] = ' '; } return;} // Driver Codeint main(){ // Board size int n = 4; int ways = 0; vector<vector<char> > board; for (int i = 0; i < n; i++) { vector<char> tmp; for (int j = 0; j < n; j++) { tmp.push_back(' '); } board.push_back(tmp); } int rowmask = 0, ldmask = 0, rdmask = 0; int row = 0; // Function Call result.clear(); solveBoard(board, row, rowmask, ldmask, rdmask, ways); sort(result.begin(),result.end()); for (auto ar : result) { cout << "["; for (auto it : ar) cout << it << " "; cout << "]"; } return 0;}// This code is contributed by Nikhil Vinay // Java Program for above approachimport java.util.*;public class NQueenSolution { static List<List<Integer> > result = new ArrayList<List<Integer> >(); // Program to solve N-Queens Problem public void solveBoard(char[][] board, int row, int rowmask, int ldmask, int rdmask) { int n = board.length; // All_rows_filled is a bit mask // having all N bits set int all_rows_filled = (1 << n) - 1; // If rowmask will have all bits set, // means queen has been placed successfully // in all rows and board is displayed if (rowmask == all_rows_filled) { List<Integer> v = new ArrayList<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'Q') v.add(j + 1); } } result.add(v); return; } // We extract a bit mask(safe) by rowmask, // ldmask and rdmask. all set bits of 'safe' // indicates the safe column index for queen // placement of this iteration for row index(row). int safe = all_rows_filled & (~(rowmask | ldmask | rdmask)); while (safe > 0) { // Extracts the right-most set bit // (safe column index) where queen // can be placed for this row int p = safe & (-safe); int col = (int)(Math.log(p) / Math.log(2)); board[row][col] = 'Q'; // This is very important: // we need to update rowmask, ldmask and rdmask // for next row as safe index for queen // placement will be decided by these three bit // masks. // We have all three rowmask, ldmask and // rdmask as 0 in beginning. Suppose, we are // placing queen at 1st column index at 0th row. // rowmask, ldmask and rdmask will change for // next row as below: // rowmask's 1st bit will be set by OR operation // rowmask = 00000000000000000000000000000010 // ldmask will change by setting 1st // bit by OR operation and left shifting // by 1 as it has to block the next column // of next row because that will fall on left // diagonal. ldmask = // 00000000000000000000000000000100 // rdmask will change by setting 1st bit // by OR operation and right shifting by 1 // as it has to block the previous column // of next row because that will fall on right // diagonal. rdmask = // 00000000000000000000000000000001 // these bit masks will keep updated in each // iteration for next row solveBoard(board, row + 1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1); // Reset right-most set bit to 0 so, // next iteration will continue by placing the // queen at another safe column index of this // row safe = safe & (safe - 1); // Backtracking, replace 'Q' by ' ' board[row][col] = ' '; } } // Program to print board public void printBoard(char[][] board) { for (int i = 0; i < board.length; i++) { System.out.print("|"); for (int j = 0; j < board[i].length; j++) { System.out.print(board[i][j] + "|"); } System.out.println(); } } // Driver Code public static void main(String args[]) { // Board size int n = 4; char board[][] = new char[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i][j] = ' '; } } int rowmask = 0, ldmask = 0, rdmask = 0; int row = 0; NQueenSolution solution = new NQueenSolution(); // Function Call result.clear(); solution.solveBoard(board, row, rowmask, ldmask, rdmask); System.out.println(result); }} // This code is contributed by Nikhil Vinay # Python program for above approachimport math result = [] # Program to solve N-Queens Problem def solveBoard(board, row, rowmask, ldmask, rdmask): n = len(board) # All_rows_filled is a bit mask # having all N bits set all_rows_filled = (1 << n) - 1 # If rowmask will have all bits set, means # queen has been placed successfully # in all rows and board is displayed if (rowmask == all_rows_filled): v = [] for i in board: for j in range(len(i)): if i[j] == 'Q': v.append(j+1) result.append(v) # We extract a bit mask(safe) by rowmask, # ldmask and rdmask. all set bits of 'safe' # indicates the safe column index for queen # placement of this iteration for row index(row). safe = all_rows_filled & (~(rowmask | ldmask | rdmask)) while (safe > 0): # Extracts the right-most set bit # (safe column index) where queen # can be placed for this row p = safe & (-safe) col = (int)(math.log(p)/math.log(2)) board[row][col] = 'Q' # This is very important: # we need to update rowmask, ldmask and rdmask # for next row as safe index for queen placement # will be decided by these three bit masks. # We have all three rowmask, ldmask and # rdmask as 0 in beginning. Suppose, we are placing # queen at 1st column index at 0th row. rowmask, ldmask # and rdmask will change for next row as below: # rowmask's 1st bit will be set by OR operation # rowmask = 00000000000000000000000000000010 # ldmask will change by setting 1st # bit by OR operation and left shifting # by 1 as it has to block the next column # of next row because that will fall on left diagonal. # ldmask = 00000000000000000000000000000100 # rdmask will change by setting 1st bit # by OR operation and right shifting by 1 # as it has to block the previous column # of next row because that will fall on right diagonal. # rdmask = 00000000000000000000000000000001 # these bit masks will keep updated in each # iteration for next row solveBoard(board, row+1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1) # Reset right-most set bit to 0 so, next # iteration will continue by placing the queen # at another safe column index of this row safe = safe & (safe-1) # Backtracking, replace 'Q' by ' ' board[row][col] = ' ' # Program to print board def printBoard(board): for row in board: print("|" + "|".join(row) + "|") # Driver Code def main(): n = 4 # board size board = [] for i in range(n): row = [] for j in range(n): row.append(' ') board.append(row) rowmask = 0 ldmask = 0 rdmask = 0 row = 0 # Function Call result.clear() solveBoard(board, row, rowmask, ldmask, rdmask) result.sort() print(result) if __name__ == "__main__": main() # This code is contributed by Nikhil Vinay // C# program to print all solutions in N-Queen Problemusing System;using System.Collections;using System.Collections.Generic; public class NQueenSolution{ static List<List<int>> result = new List<List<int>>(); public void solveBoard(char[,] board, int row,int rowmask, int ldmask,int rdmask) { int n = board.GetLength(0); // All_rows_filled is a bit mask // having all N bits set int all_rows_filled = (1 << n) - 1; // If rowmask will have all bits set, // means queen has been placed successfully // in all rows and board is displayed if (rowmask == all_rows_filled) { List<int> v = new List<int>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i,j] == 'Q') v.Add(j + 1); } } result.Add(v); return; } // We extract a bit mask(safe) by rowmask, // ldmask and rdmask. all set bits of 'safe' // indicates the safe column index for queen // placement of this iteration for row index(row). int safe = ((all_rows_filled) & (~(rowmask | ldmask | rdmask))); while (safe > 0) { // Extracts the right-most set bit // (safe column index) where queen // can be placed for this row int p = safe & (-safe); int col = (int)(Math.Log(p) / Math.Log(2)); board[row,col] = 'Q'; // This is very important: // we need to update rowmask, ldmask and rdmask // for next row as safe index for queen // placement will be decided by these three bit // masks. // We have all three rowmask, ldmask and // rdmask as 0 in beginning. Suppose, we are // placing queen at 1st column index at 0th row. // rowmask, ldmask and rdmask will change for // next row as below: // rowmask's 1st bit will be set by OR operation // rowmask = 00000000000000000000000000000010 // ldmask will change by setting 1st // bit by OR operation and left shifting // by 1 as it has to block the next column // of next row because that will fall on left // diagonal. ldmask = // 00000000000000000000000000000100 // rdmask will change by setting 1st bit // by OR operation and right shifting by 1 // as it has to block the previous column // of next row because that will fall on right // diagonal. rdmask = // 00000000000000000000000000000001 // these bit masks will keep updated in each // iteration for next row solveBoard(board, row + 1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1); // Reset right-most set bit to 0 so, // next iteration will continue by placing the // queen at another safe column index of this // row safe = safe & (safe - 1); // Backtracking, replace 'Q' by ' ' board[row,col] = ' '; } } // Program to print board public void printBoard(char[,] board) { for (int i = 0; i < board.GetLength(0); i++) { Console.Write("|"); for (int j = 0; j < board.GetLength(1); j++) { Console.Write(board[i,j] + "|"); } Console.Write("\n"); } } static public void Main (){ int n = 4; char[,] board = new char[n,n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i,j] = ' '; } } int rowmask = 0, ldmask = 0, rdmask = 0; int row = 0; NQueenSolution solution = new NQueenSolution(); // Function Call result.Clear(); solution.solveBoard(board, row, rowmask, ldmask,rdmask); foreach (var sublist in result) { Console.Write("["); foreach (int item in sublist) { Console.Write(item+" "); } Console.Write("]"); } }} // This code is contributed by shruti456rawal [2 4 1 3 ][3 1 4 2 ] This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 29AjayKumar princiraj1992 YatinGupta nvinay UtkarshPandey6 moonlight23 anikaseth98 gulshankumarar231 akshaysingh98088 sagartomar9927 ankityadav870401 shruti456rawal hardikkoriintern chessboard-problems Backtracking Matrix Matrix Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 226, "s": 52, "text": "The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem. " }, { "code": null, "e": 786, "s": 226, "text": "In previous post, we have discussed an approach that prints only one possible solution, so now in this post, the task is to print all solutions in N-Queen Problem. Each solution contains distinct board configurations of the N-queens’ placement, where the solutions are a permutation of [1,2,3..n] in increasing order, here the number in the ith place denotes that the ith-column queen is placed in the row with that number. For the example above solution is written as [[2 4 1 3 ] [3 1 4 2 ]]. The solution discussed here is an extension of the same approach." }, { "code": null, "e": 810, "s": 786, "text": "Backtracking Algorithm " }, { "code": null, "e": 1192, "s": 810, "text": "The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false." }, { "code": null, "e": 1867, "s": 1192, "text": "1) Start in the leftmost column\n2) If all queens are placed\n return true\n3) Try all rows in the current column. Do following\n for every tried row.\n a) If the queen can be placed safely in this row\n then mark this [row, column] as part of the \n solution and recursively check if placing \n queen here leads to a solution.\n b) If placing queen in [row, column] leads to a\n solution then return true.\n c) If placing queen doesn't lead to a solution \n then unmark this [row, column] (Backtrack) \n and go to step (a) to try other rows.\n3) If all rows have been tried and nothing worked, \n return false to trigger backtracking." }, { "code": null, "e": 2032, "s": 1867, "text": "A modification is that we can find whether we have a previously placed queen in a column or in left diagonal or in right diagonal in O(1) time. We can observe that " }, { "code": null, "e": 2188, "s": 2032, "text": "For all cells in a particular left diagonal , their row + col = constant.For all cells in a particular right diagonal, their row – col + n – 1 = constant." }, { "code": null, "e": 2263, "s": 2188, "text": "For all cells in a particular left diagonal , their row + col = constant." }, { "code": null, "e": 2345, "s": 2263, "text": "For all cells in a particular right diagonal, their row – col + n – 1 = constant." }, { "code": null, "e": 2414, "s": 2345, "text": "Let say n = 5, then we have a total of 2n-1 left and right diagonals" }, { "code": null, "e": 2450, "s": 2414, "text": "Let say we placed a queen at (2,0) " }, { "code": null, "e": 2661, "s": 2450, "text": "(2,0) have leftDiagonal value = 2. Now we can not place another queen at (1,1) and (0,2) because both of these have same leftDiagonal value as for (2,0). Similar thing can be noticed for right diagonal as well." }, { "code": null, "e": 2677, "s": 2661, "text": "Implementation:" }, { "code": null, "e": 2681, "s": 2677, "text": "C++" }, { "code": null, "e": 2686, "s": 2681, "text": "Java" }, { "code": null, "e": 2694, "s": 2686, "text": "Python3" }, { "code": null, "e": 2697, "s": 2694, "text": "C#" }, { "code": "/* C/C++ program to solve N Queen Problem usingbacktracking */#include <bits/stdc++.h>using namespace std; vector<vector<int> > result; /* A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when \"col\" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens */bool isSafe(vector<vector<int> > board, int row, int col){ int i, j; int N = board.size(); /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;} /* A recursive utility function to solve NQueen problem */bool solveNQUtil(vector<vector<int> >& board, int col){ /* base case: If all queens are placed then return true */ int N = board.size(); if (col == N) { vector<int> v; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (board[i][j] == 1) v.push_back(j + 1); } } result.push_back(v); return true; } /* Consider this column and try placing this queen in all rows one by one */ bool res = false; for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; // Make result true if any placement // is possible res = solveNQUtil(board, col + 1) || res; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If queen can not be place in any row in this column col then return false */ return res;} /* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/ vector<vector<int> > nQueen(int n){ result.clear(); vector<vector<int> > board(n, vector<int>(n, 0)); if (solveNQUtil(board, 0) == false) { return {}; } sort(result.begin(), result.end()); return result;} // Driver Codeint main(){ int n = 4; vector<vector<int> > v = nQueen(n); for (auto ar : v) { cout << \"[\"; for (auto it : ar) cout << it << \" \"; cout << \"]\"; } return 0;}", "e": 5610, "s": 2697, "text": null }, { "code": "/* Java program to solve N QueenProblem using backtracking */import java.util.*;class GfG { /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. */ static List<List<Integer>> nQueen(int n) { // cols[i] = true if there is a queen previously placed at ith column cols = new boolean[n]; // leftDiagonal[i] = true if there is a queen previously placed at // i = (row + col )th left diagonal leftDiagonal = new boolean[2*n]; // rightDiagonal[i] = true if there is a queen previously placed at // i = (row - col + n - 1)th rightDiagonal diagonal rightDiagonal = new boolean[2*n]; result = new ArrayList<>(); List<Integer> temp = new ArrayList<>(); for(int i=0;i<n;i++)temp.add(0); solveNQUtil(result,n,0,temp); return result; } private static void solveNQUtil(List<List<Integer>> result,int n,int row,List<Integer> comb){ if(row==n){ // if row==n it means we have successfully placed all n queens. // hence add current arrangement to our answer // comb represent current combination result.add(new ArrayList<>(comb)); return; } for(int col = 0;col<n;col++){ // if we have a queen previously placed in the current column // or in current left or right diagonal we continue if(cols[col] || leftDiagonal[row+col] || rightDiagonal[row-col+n]) continue; // otherwise we place a queen at cell[row][col] and //make current column, left diagonal and right diagonal true cols[col] = leftDiagonal[row+col] = rightDiagonal[row-col+n] = true; comb.set(col,row+1); // then we goto next row solveNQUtil(result,n,row+1,comb); // then we backtrack and remove our currently placed queen cols[col] = leftDiagonal[row+col] = rightDiagonal[row-col+n] = false; } } static List<List<Integer> > result = new ArrayList<List<Integer> >(); static boolean[] cols,leftDiagonal,rightDiagonal; // Driver code public static void main(String[] args) { int n = 4; List<List<Integer> > res = nQueen(n); System.out.println(res); }}", "e": 7947, "s": 5610, "text": null }, { "code": "''' Python3 program to solve N Queen Problem usingbacktracking ''' result = [] # A utility function to print solution ''' A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when \"col\" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens ''' def isSafe(board, row, col): # Check this row on left side for i in range(col): if (board[row][i]): return False # Check upper diagonal on left side i = row j = col while i >= 0 and j >= 0: if(board[i][j]): return False i -= 1 j -= 1 # Check lower diagonal on left side i = row j = col while j >= 0 and i < 4: if(board[i][j]): return False i = i + 1 j = j - 1 return True ''' A recursive utility function to solve NQueen problem ''' def solveNQUtil(board, col): ''' base case: If all queens are placed then return true ''' if (col == 4): v = [] for i in board: for j in range(len(i)): if i[j] == 1: v.append(j+1) result.append(v) return True ''' Consider this column and try placing this queen in all rows one by one ''' res = False for i in range(4): ''' Check if queen can be placed on board[i][col] ''' if (isSafe(board, i, col)): # Place this queen in board[i][col] board[i][col] = 1 # Make result true if any placement # is possible res = solveNQUtil(board, col + 1) or res ''' If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] ''' board[i][col] = 0 # BACKTRACK ''' If queen can not be place in any row in this column col then return false ''' return res ''' This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.''' def solveNQ(n): result.clear() board = [[0 for j in range(n)] for i in range(n)] solveNQUtil(board, 0) result.sort() return result # Driver Coden = 4res = solveNQ(n)print(res) # This code is contributed by YatinGupta", "e": 10435, "s": 7947, "text": null }, { "code": "/* C# program to solve N QueenProblem using backtracking */using System;using System.Collections;using System.Collections.Generic; class GfG { static List<List<int> > result = new List<List<int> >(); /* A utility function to check if a queen can be placed on board[row,col]. Note that this function is called when \"col\" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */ static bool isSafe(int[, ] board, int row, int col, int N) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row, i] == 1) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i, j] == 1) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i, j] == 1) return false; return true; } /* A recursive utility function to solve N Queen problem */ static bool solveNQUtil(int[, ] board, int col, int N) { /* base case: If all queens are placed then return true */ if (col == N) { List<int> v = new List<int>(); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { if (board[i, j] == 1) v.Add(j + 1); } result.Add(v); return true; } /* Consider this column and try placing this queen in all rows one by one */ bool res = false; for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i,col] */ if (isSafe(board, i, col, N)) { /* Place this queen in board[i,col] */ board[i, col] = 1; // Make result true if any placement // is possible res = solveNQUtil(board, col + 1, N) || res; /* If placing queen in board[i,col] doesn't lead to a solution, then remove queen from board[i,col] */ board[i, col] = 0; // BACKTRACK } } /* If queen can not be place in any row in this column col then return false */ return res; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ static List<List<int> > solveNQ(int n) { result.Clear(); int[, ] board = new int[n, n]; solveNQUtil(board, 0, n); return result; } // Driver code public static void Main() { int n = 4; List<List<int> > res = solveNQ(n); for (int i = 0; i < res.Count; i++) { Console.Write(\"[\"); for (int j = 0; j < res[i].Count; j++) { Console.Write(res[i][j]+ \" \"); } Console.Write(\"]\"); } }} /* This code contributed by PrinciRaj1992 */", "e": 13773, "s": 10435, "text": null }, { "code": null, "e": 13794, "s": 13773, "text": "[2 4 1 3 ][3 1 4 2 ]" }, { "code": null, "e": 13845, "s": 13794, "text": "Efficient Backtracking Approach Using Bit-Masking " }, { "code": null, "e": 14535, "s": 13845, "text": "Algorithm: There is always only one queen in each row and each column, so idea of backtracking is to start placing queen from the leftmost column of each row and find a column where the queen could be placed without collision with previously placed queens. It is repeated from the first row till the last row. While placing a queen, it is tracked as if it is not making a collision (row-wise, column-wise and diagonally) with queens placed in previous rows. Once it is found that the queen can’t be placed at a particular column index in a row, the algorithm backtracks and change the position of the queen placed in the previous row then moves forward to place the queen in the next row. " }, { "code": null, "e": 15498, "s": 14535, "text": "Start with three-bit vector which is used to track safe place for queen placement row-wise, column-wise and diagonally in each iteration.Three-bit vector will contain information as bellow:rowmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row.ldmask: set bit index (i) of this bit vector will indicate, the queen can’t e placed at ith column of next row. It represents the unsafe column index for next row falls under left diagonal of queens placed in previous rows.rdmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. It represents the unsafe column index for next row falls right diagonal of queens placed in previous rows.There is a 2-D (NxN) matrix (board), which will have ‘ ‘ character at all indexes in beginning and it gets filled by ‘Q’ row-by-row. Once all rows are filled by ‘Q’, the current solution is pushed into the result list." }, { "code": null, "e": 15636, "s": 15498, "text": "Start with three-bit vector which is used to track safe place for queen placement row-wise, column-wise and diagonally in each iteration." }, { "code": null, "e": 16244, "s": 15636, "text": "Three-bit vector will contain information as bellow:rowmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row.ldmask: set bit index (i) of this bit vector will indicate, the queen can’t e placed at ith column of next row. It represents the unsafe column index for next row falls under left diagonal of queens placed in previous rows.rdmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. It represents the unsafe column index for next row falls right diagonal of queens placed in previous rows." }, { "code": null, "e": 16358, "s": 16244, "text": "rowmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row." }, { "code": null, "e": 16582, "s": 16358, "text": "ldmask: set bit index (i) of this bit vector will indicate, the queen can’t e placed at ith column of next row. It represents the unsafe column index for next row falls under left diagonal of queens placed in previous rows." }, { "code": null, "e": 16802, "s": 16582, "text": "rdmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. It represents the unsafe column index for next row falls right diagonal of queens placed in previous rows." }, { "code": null, "e": 17021, "s": 16802, "text": "There is a 2-D (NxN) matrix (board), which will have ‘ ‘ character at all indexes in beginning and it gets filled by ‘Q’ row-by-row. Once all rows are filled by ‘Q’, the current solution is pushed into the result list." }, { "code": null, "e": 17073, "s": 17021, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 17077, "s": 17073, "text": "C++" }, { "code": null, "e": 17082, "s": 17077, "text": "Java" }, { "code": null, "e": 17090, "s": 17082, "text": "Python3" }, { "code": null, "e": 17093, "s": 17090, "text": "C#" }, { "code": "// CPP program for above approach#include <bits/stdc++.h> using namespace std; vector<vector<int> > result;// Program to solve N Queens problemvoid solveBoard(vector<vector<char> >& board, int row, int rowmask, int ldmask, int rdmask, int& ways){ int n = board.size(); // All_rows_filled is a bit mask having all N bits set int all_rows_filled = (1 << n) - 1; // If rowmask will have all bits set, means queen has // been placed successfully in all rows and board is // displayed if (rowmask == all_rows_filled) { vector<int> v; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board.size(); j++) { if (board[i][j] == 'Q') v.push_back(j + 1); } } result.push_back(v); return; } // We extract a bit mask(safe) by rowmask, // ldmask and rdmask. all set bits of 'safe' // indicates the safe column index for queen // placement of this iteration for row index(row). int safe = all_rows_filled & (~(rowmask | ldmask | rdmask)); while (safe) { // Extracts the right-most set bit // (safe column index) where queen // can be placed for this row int p = safe & (-safe); int col = (int)log2(p); board[row][col] = 'Q'; // This is very important: // we need to update rowmask, ldmask and rdmask // for next row as safe index for queen placement // will be decided by these three bit masks. // We have all three rowmask, ldmask and // rdmask as 0 in beginning. Suppose, we are placing // queen at 1st column index at 0th row. rowmask, // ldmask and rdmask will change for next row as // below: // rowmask's 1st bit will be set by OR operation // rowmask = 00000000000000000000000000000010 // ldmask will change by setting 1st // bit by OR operation and left shifting // by 1 as it has to block the next column // of next row because that will fall on left // diagonal. ldmask = // 00000000000000000000000000000100 // rdmask will change by setting 1st bit // by OR operation and right shifting by 1 // as it has to block the previous column // of next row because that will fall on right // diagonal. rdmask = // 00000000000000000000000000000001 // these bit masks will keep updated in each // iteration for next row solveBoard(board, row + 1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1, ways); // Reset right-most set bit to 0 so, // next iteration will continue by placing the queen // at another safe column index of this row safe = safe & (safe - 1); // Backtracking, replace 'Q' by ' ' board[row][col] = ' '; } return;} // Driver Codeint main(){ // Board size int n = 4; int ways = 0; vector<vector<char> > board; for (int i = 0; i < n; i++) { vector<char> tmp; for (int j = 0; j < n; j++) { tmp.push_back(' '); } board.push_back(tmp); } int rowmask = 0, ldmask = 0, rdmask = 0; int row = 0; // Function Call result.clear(); solveBoard(board, row, rowmask, ldmask, rdmask, ways); sort(result.begin(),result.end()); for (auto ar : result) { cout << \"[\"; for (auto it : ar) cout << it << \" \"; cout << \"]\"; } return 0;}// This code is contributed by Nikhil Vinay", "e": 20676, "s": 17093, "text": null }, { "code": "// Java Program for above approachimport java.util.*;public class NQueenSolution { static List<List<Integer> > result = new ArrayList<List<Integer> >(); // Program to solve N-Queens Problem public void solveBoard(char[][] board, int row, int rowmask, int ldmask, int rdmask) { int n = board.length; // All_rows_filled is a bit mask // having all N bits set int all_rows_filled = (1 << n) - 1; // If rowmask will have all bits set, // means queen has been placed successfully // in all rows and board is displayed if (rowmask == all_rows_filled) { List<Integer> v = new ArrayList<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'Q') v.add(j + 1); } } result.add(v); return; } // We extract a bit mask(safe) by rowmask, // ldmask and rdmask. all set bits of 'safe' // indicates the safe column index for queen // placement of this iteration for row index(row). int safe = all_rows_filled & (~(rowmask | ldmask | rdmask)); while (safe > 0) { // Extracts the right-most set bit // (safe column index) where queen // can be placed for this row int p = safe & (-safe); int col = (int)(Math.log(p) / Math.log(2)); board[row][col] = 'Q'; // This is very important: // we need to update rowmask, ldmask and rdmask // for next row as safe index for queen // placement will be decided by these three bit // masks. // We have all three rowmask, ldmask and // rdmask as 0 in beginning. Suppose, we are // placing queen at 1st column index at 0th row. // rowmask, ldmask and rdmask will change for // next row as below: // rowmask's 1st bit will be set by OR operation // rowmask = 00000000000000000000000000000010 // ldmask will change by setting 1st // bit by OR operation and left shifting // by 1 as it has to block the next column // of next row because that will fall on left // diagonal. ldmask = // 00000000000000000000000000000100 // rdmask will change by setting 1st bit // by OR operation and right shifting by 1 // as it has to block the previous column // of next row because that will fall on right // diagonal. rdmask = // 00000000000000000000000000000001 // these bit masks will keep updated in each // iteration for next row solveBoard(board, row + 1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1); // Reset right-most set bit to 0 so, // next iteration will continue by placing the // queen at another safe column index of this // row safe = safe & (safe - 1); // Backtracking, replace 'Q' by ' ' board[row][col] = ' '; } } // Program to print board public void printBoard(char[][] board) { for (int i = 0; i < board.length; i++) { System.out.print(\"|\"); for (int j = 0; j < board[i].length; j++) { System.out.print(board[i][j] + \"|\"); } System.out.println(); } } // Driver Code public static void main(String args[]) { // Board size int n = 4; char board[][] = new char[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i][j] = ' '; } } int rowmask = 0, ldmask = 0, rdmask = 0; int row = 0; NQueenSolution solution = new NQueenSolution(); // Function Call result.clear(); solution.solveBoard(board, row, rowmask, ldmask, rdmask); System.out.println(result); }} // This code is contributed by Nikhil Vinay", "e": 24933, "s": 20676, "text": null }, { "code": "# Python program for above approachimport math result = [] # Program to solve N-Queens Problem def solveBoard(board, row, rowmask, ldmask, rdmask): n = len(board) # All_rows_filled is a bit mask # having all N bits set all_rows_filled = (1 << n) - 1 # If rowmask will have all bits set, means # queen has been placed successfully # in all rows and board is displayed if (rowmask == all_rows_filled): v = [] for i in board: for j in range(len(i)): if i[j] == 'Q': v.append(j+1) result.append(v) # We extract a bit mask(safe) by rowmask, # ldmask and rdmask. all set bits of 'safe' # indicates the safe column index for queen # placement of this iteration for row index(row). safe = all_rows_filled & (~(rowmask | ldmask | rdmask)) while (safe > 0): # Extracts the right-most set bit # (safe column index) where queen # can be placed for this row p = safe & (-safe) col = (int)(math.log(p)/math.log(2)) board[row][col] = 'Q' # This is very important: # we need to update rowmask, ldmask and rdmask # for next row as safe index for queen placement # will be decided by these three bit masks. # We have all three rowmask, ldmask and # rdmask as 0 in beginning. Suppose, we are placing # queen at 1st column index at 0th row. rowmask, ldmask # and rdmask will change for next row as below: # rowmask's 1st bit will be set by OR operation # rowmask = 00000000000000000000000000000010 # ldmask will change by setting 1st # bit by OR operation and left shifting # by 1 as it has to block the next column # of next row because that will fall on left diagonal. # ldmask = 00000000000000000000000000000100 # rdmask will change by setting 1st bit # by OR operation and right shifting by 1 # as it has to block the previous column # of next row because that will fall on right diagonal. # rdmask = 00000000000000000000000000000001 # these bit masks will keep updated in each # iteration for next row solveBoard(board, row+1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1) # Reset right-most set bit to 0 so, next # iteration will continue by placing the queen # at another safe column index of this row safe = safe & (safe-1) # Backtracking, replace 'Q' by ' ' board[row][col] = ' ' # Program to print board def printBoard(board): for row in board: print(\"|\" + \"|\".join(row) + \"|\") # Driver Code def main(): n = 4 # board size board = [] for i in range(n): row = [] for j in range(n): row.append(' ') board.append(row) rowmask = 0 ldmask = 0 rdmask = 0 row = 0 # Function Call result.clear() solveBoard(board, row, rowmask, ldmask, rdmask) result.sort() print(result) if __name__ == \"__main__\": main() # This code is contributed by Nikhil Vinay", "e": 28090, "s": 24933, "text": null }, { "code": "// C# program to print all solutions in N-Queen Problemusing System;using System.Collections;using System.Collections.Generic; public class NQueenSolution{ static List<List<int>> result = new List<List<int>>(); public void solveBoard(char[,] board, int row,int rowmask, int ldmask,int rdmask) { int n = board.GetLength(0); // All_rows_filled is a bit mask // having all N bits set int all_rows_filled = (1 << n) - 1; // If rowmask will have all bits set, // means queen has been placed successfully // in all rows and board is displayed if (rowmask == all_rows_filled) { List<int> v = new List<int>(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i,j] == 'Q') v.Add(j + 1); } } result.Add(v); return; } // We extract a bit mask(safe) by rowmask, // ldmask and rdmask. all set bits of 'safe' // indicates the safe column index for queen // placement of this iteration for row index(row). int safe = ((all_rows_filled) & (~(rowmask | ldmask | rdmask))); while (safe > 0) { // Extracts the right-most set bit // (safe column index) where queen // can be placed for this row int p = safe & (-safe); int col = (int)(Math.Log(p) / Math.Log(2)); board[row,col] = 'Q'; // This is very important: // we need to update rowmask, ldmask and rdmask // for next row as safe index for queen // placement will be decided by these three bit // masks. // We have all three rowmask, ldmask and // rdmask as 0 in beginning. Suppose, we are // placing queen at 1st column index at 0th row. // rowmask, ldmask and rdmask will change for // next row as below: // rowmask's 1st bit will be set by OR operation // rowmask = 00000000000000000000000000000010 // ldmask will change by setting 1st // bit by OR operation and left shifting // by 1 as it has to block the next column // of next row because that will fall on left // diagonal. ldmask = // 00000000000000000000000000000100 // rdmask will change by setting 1st bit // by OR operation and right shifting by 1 // as it has to block the previous column // of next row because that will fall on right // diagonal. rdmask = // 00000000000000000000000000000001 // these bit masks will keep updated in each // iteration for next row solveBoard(board, row + 1, rowmask | p, (ldmask | p) << 1, (rdmask | p) >> 1); // Reset right-most set bit to 0 so, // next iteration will continue by placing the // queen at another safe column index of this // row safe = safe & (safe - 1); // Backtracking, replace 'Q' by ' ' board[row,col] = ' '; } } // Program to print board public void printBoard(char[,] board) { for (int i = 0; i < board.GetLength(0); i++) { Console.Write(\"|\"); for (int j = 0; j < board.GetLength(1); j++) { Console.Write(board[i,j] + \"|\"); } Console.Write(\"\\n\"); } } static public void Main (){ int n = 4; char[,] board = new char[n,n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i,j] = ' '; } } int rowmask = 0, ldmask = 0, rdmask = 0; int row = 0; NQueenSolution solution = new NQueenSolution(); // Function Call result.Clear(); solution.solveBoard(board, row, rowmask, ldmask,rdmask); foreach (var sublist in result) { Console.Write(\"[\"); foreach (int item in sublist) { Console.Write(item+\" \"); } Console.Write(\"]\"); } }} // This code is contributed by shruti456rawal", "e": 31839, "s": 28090, "text": null }, { "code": null, "e": 31860, "s": 31839, "text": "[2 4 1 3 ][3 1 4 2 ]" }, { "code": null, "e": 32158, "s": 31860, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 32170, "s": 32158, "text": "29AjayKumar" }, { "code": null, "e": 32184, "s": 32170, "text": "princiraj1992" }, { "code": null, "e": 32195, "s": 32184, "text": "YatinGupta" }, { "code": null, "e": 32202, "s": 32195, "text": "nvinay" }, { "code": null, "e": 32217, "s": 32202, "text": "UtkarshPandey6" }, { "code": null, "e": 32229, "s": 32217, "text": "moonlight23" }, { "code": null, "e": 32241, "s": 32229, "text": "anikaseth98" }, { "code": null, "e": 32259, "s": 32241, "text": "gulshankumarar231" }, { "code": null, "e": 32276, "s": 32259, "text": "akshaysingh98088" }, { "code": null, "e": 32291, "s": 32276, "text": "sagartomar9927" }, { "code": null, "e": 32308, "s": 32291, "text": "ankityadav870401" }, { "code": null, "e": 32323, "s": 32308, "text": "shruti456rawal" }, { "code": null, "e": 32340, "s": 32323, "text": "hardikkoriintern" }, { "code": null, "e": 32360, "s": 32340, "text": "chessboard-problems" }, { "code": null, "e": 32373, "s": 32360, "text": "Backtracking" }, { "code": null, "e": 32380, "s": 32373, "text": "Matrix" }, { "code": null, "e": 32387, "s": 32380, "text": "Matrix" }, { "code": null, "e": 32400, "s": 32387, "text": "Backtracking" } ]
Find pairs with given sum in doubly linked list
06 Jul, 2022 Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in a doubly-linked list whose sum is equal to given value x, without using any extra space? Example: Input : head : 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9 x = 7 Output: (6, 1), (5,2) The expected time complexity is O(n) and auxiliary space is O(1). A simple approach for this problem is to one by one pick each node and find a second element whose sum is equal to x in the remaining list by traversing in the forward direction. The time complexity for this problem will be O(n^2), n is the total number of nodes in the doubly linked list. An efficient solution for this problem is the same as this article. Here is the algorithm : Initialize two pointer variables to find the candidate elements in the sorted doubly linked list. Initialize first with the start of the doubly linked list i.e; first=head and initialize second with the last node of the doubly linked list i.e; second=last_node. We initialize first and second pointers as first and last nodes. Here we don’t have random access, so to find the second pointer, we traverse the list to initialize the second. If current sum of first and second is less than x, then we move first in forward direction. If current sum of first and second element is greater than x, then we move second in backward direction. Loop termination conditions are also different from arrays. The loop terminates when two pointers cross each other (second->next = first), or they become the same (first == second). The case when no pairs are present will be handled by the condition “first==second” Implementation: C++ Java Python3 C# Javascript // C++ program to find a pair with given sum x.#include<bits/stdc++.h>using namespace std; // structure of node of doubly linked liststruct Node{ int data; struct Node *next, *prev;}; // Function to find pair whose sum equal to given value x.void pairSum(struct Node *head, int x){ // Set two pointers, first to the beginning of DLL // and second to the end of DLL. struct Node *first = head; struct Node *second = head; while (second->next != NULL) second = second->next; // To track if we find a pair or not bool found = false; // The loop terminates when two pointers // cross each other (second->next // == first), or they become same (first == second) while (first != second && second->next != first) { // pair found if ((first->data + second->data) == x) { found = true; cout << "(" << first->data<< ", " << second->data << ")" << endl; // move first in forward direction first = first->next; // move second in backward direction second = second->prev; } else { if ((first->data + second->data) < x) first = first->next; else second = second->prev; } } // if pair is not present if (found == false) cout << "No pair found";} // A utility function to insert a new node at the// beginning of doubly linked listvoid insert(struct Node **head, int data){ struct Node *temp = new Node; temp->data = data; temp->next = temp->prev = NULL; if (!(*head)) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; }} // Driver programint main(){ struct Node *head = NULL; insert(&head, 9); insert(&head, 8); insert(&head, 6); insert(&head, 5); insert(&head, 4); insert(&head, 2); insert(&head, 1); int x = 7; pairSum(head, x); return 0;} // Java program to find a// pair with given sum x.class GFG{ // structure of node of// doubly linked liststatic class Node{ int data; Node next, prev;}; // Function to find pair whose// sum equal to given value x.static void pairSum( Node head, int x){ // Set two pointers, first // to the beginning of DLL // and second to the end of DLL. Node first = head; Node second = head; while (second.next != null) second = second.next; // To track if we find a pair or not boolean found = false; // The loop terminates when // they cross each other (second.next // == first), or they become same // (first == second) while ( first != second && second.next != first) { // pair found if ((first.data + second.data) == x) { found = true; System.out.println( "(" + first.data + ", "+ second.data + ")" ); // move first in forward direction first = first.next; // move second in backward direction second = second.prev; } else { if ((first.data + second.data) < x) first = first.next; else second = second.prev; } } // if pair is not present if (found == false) System.out.println("No pair found");} // A utility function to insert// a new node at the beginning// of doubly linked liststatic Node insert(Node head, int data){ Node temp = new Node(); temp.data = data; temp.next = temp.prev = null; if (head == null) (head) = temp; else { temp.next = head; (head).prev = temp; (head) = temp; } return temp;} // Driver Codepublic static void main(String args[]){ Node head = null; head = insert(head, 9); head = insert(head, 8); head = insert(head, 6); head = insert(head, 5); head = insert(head, 4); head = insert(head, 2); head = insert(head, 1); int x = 7; pairSum(head, x);}} // This code is contributed// by Arnab Kundu # Python3 program to find a pair with# given sum x. # Structure of node of doubly linked listclass Node: def __init__(self, x): self.data = x self.next = None self.prev = None # Function to find pair whose sum# equal to given value x.def pairSum(head, x): # Set two pointers, first to the # beginning of DLL and second to # the end of DLL. first = head second = head while (second.next != None): second = second.next # To track if we find a pair or not found = False # The loop terminates when they # cross each other (second.next == # first), or they become same # (first == second) while (first != second and second.next != first): # Pair found if ((first.data + second.data) == x): found = True print("(", first.data, ",", second.data, ")") # Move first in forward direction first = first.next # Move second in backward direction second = second.prev else: if ((first.data + second.data) < x): first = first.next else: second = second.prev # If pair is not present if (found == False): print("No pair found") # A utility function to insert a new node# at the beginning of doubly linked listdef insert(head, data): temp = Node(data) if not head: head = temp else: temp.next = head head.prev = temp head = temp return head # Driver codeif __name__ == '__main__': head = None head = insert(head, 9) head = insert(head, 8) head = insert(head, 6) head = insert(head, 5) head = insert(head, 4) head = insert(head, 2) head = insert(head, 1) x = 7 pairSum(head, x) # This code is contributed by mohit kumar 29 // C# program to find a// pair with given sum x.using System; class GFG{ // structure of node of // doubly linked list class Node { public int data; public Node next, prev; }; // Function to find pair whose // sum equal to given value x. static void pairSum( Node head, int x) { // Set two pointers, first // to the beginning of DLL // and second to the end of DLL. Node first = head; Node second = head; while (second.next != null) second = second.next; // To track if we find a pair or not bool found = false; // The loop terminates when // they cross each other (second.next // == first), or they become same // (first == second) while (first != second && second.next != first) { // pair found if ((first.data + second.data) == x) { found = true; Console.WriteLine( "(" + first.data + ", "+ second.data + ")" ); // move first in forward direction first = first.next; // move second in backward direction second = second.prev; } else { if ((first.data + second.data) < x) first = first.next; else second = second.prev; } } // if pair is not present if (found == false) Console.WriteLine("No pair found"); } // A utility function to insert // a new node at the beginning // of doubly linked list static Node insert(Node head, int data) { Node temp = new Node(); temp.data = data; temp.next = temp.prev = null; if (head == null) (head) = temp; else { temp.next = head; (head).prev = temp; (head) = temp; } return temp; } // Driver Code public static void Main(String []args) { Node head = null; head = insert(head, 9); head = insert(head, 8); head = insert(head, 6); head = insert(head, 5); head = insert(head, 4); head = insert(head, 2); head = insert(head, 1); int x = 7; pairSum(head, x); }} // This code is contributed by 29AjayKumar <script>// Javascript program to find a// pair with given sum x. // structure of node of// doubly linked listclass Node{ constructor() { this.data = 0; this.next = this.prev = null; }} // Function to find pair whose// sum equal to given value x.function pairSum(head, x){ // Set two pointers, first // to the beginning of DLL // and second to the end of DLL. let first = head; let second = head; while (second.next != null) second = second.next; // To track if we find a pair or not let found = false; // The loop terminates when // they cross each other (second.next // == first), or they become same // (first == second) while ( first != second && second.next != first) { // pair found if ((first.data + second.data) == x) { found = true; document.write( "(" + first.data + ", "+ second.data + ")<br>" ); // move first in forward direction first = first.next; // move second in backward direction second = second.prev; } else { if ((first.data + second.data) < x) first = first.next; else second = second.prev; } } // if pair is not present if (found == false) document.write("No pair found<br>");} // A utility function to insert// a new node at the beginning// of doubly linked listfunction insert(head,data){ let temp = new Node(); temp.data = data; temp.next = temp.prev = null; if (head == null) (head) = temp; else { temp.next = head; (head).prev = temp; (head) = temp; } return temp;} // Driver Codelet head = null;head = insert(head, 9);head = insert(head, 8);head = insert(head, 6);head = insert(head, 5);head = insert(head, 4);head = insert(head, 2);head = insert(head, 1);let x = 7; pairSum(head, x); // This code is contributed by avanitrachhadiya2155</script> (1, 6) (2, 5) Time complexity : O(n) Auxiliary space : O(1) If linked list is not sorted, then we can sort the list as a first step. But in that case overall time complexity would become O(n Log n). We can use Hashing in such cases if extra space is not a constraint. The hashing based solution is same as method 2 here. This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. andrew1234 29AjayKumar abhishek gupta 47 tapassaha699 mohit kumar 29 kathanvakharia avanitrachhadiya2155 hardikkoriintern doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Detect loop in a linked list Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Find the middle of a given linked list Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive)
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 236, "s": 52, "text": "Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in a doubly-linked list whose sum is equal to given value x, without using any extra space? " }, { "code": null, "e": 247, "s": 236, "text": "Example: " }, { "code": null, "e": 336, "s": 247, "text": "Input : head : 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9\n x = 7\nOutput: (6, 1), (5,2)" }, { "code": null, "e": 402, "s": 336, "text": "The expected time complexity is O(n) and auxiliary space is O(1)." }, { "code": null, "e": 692, "s": 402, "text": "A simple approach for this problem is to one by one pick each node and find a second element whose sum is equal to x in the remaining list by traversing in the forward direction. The time complexity for this problem will be O(n^2), n is the total number of nodes in the doubly linked list." }, { "code": null, "e": 786, "s": 692, "text": "An efficient solution for this problem is the same as this article. Here is the algorithm : " }, { "code": null, "e": 1048, "s": 786, "text": "Initialize two pointer variables to find the candidate elements in the sorted doubly linked list. Initialize first with the start of the doubly linked list i.e; first=head and initialize second with the last node of the doubly linked list i.e; second=last_node." }, { "code": null, "e": 1225, "s": 1048, "text": "We initialize first and second pointers as first and last nodes. Here we don’t have random access, so to find the second pointer, we traverse the list to initialize the second." }, { "code": null, "e": 1422, "s": 1225, "text": "If current sum of first and second is less than x, then we move first in forward direction. If current sum of first and second element is greater than x, then we move second in backward direction." }, { "code": null, "e": 1604, "s": 1422, "text": "Loop termination conditions are also different from arrays. The loop terminates when two pointers cross each other (second->next = first), or they become the same (first == second)." }, { "code": null, "e": 1688, "s": 1604, "text": "The case when no pairs are present will be handled by the condition “first==second”" }, { "code": null, "e": 1704, "s": 1688, "text": "Implementation:" }, { "code": null, "e": 1708, "s": 1704, "text": "C++" }, { "code": null, "e": 1713, "s": 1708, "text": "Java" }, { "code": null, "e": 1721, "s": 1713, "text": "Python3" }, { "code": null, "e": 1724, "s": 1721, "text": "C#" }, { "code": null, "e": 1735, "s": 1724, "text": "Javascript" }, { "code": "// C++ program to find a pair with given sum x.#include<bits/stdc++.h>using namespace std; // structure of node of doubly linked liststruct Node{ int data; struct Node *next, *prev;}; // Function to find pair whose sum equal to given value x.void pairSum(struct Node *head, int x){ // Set two pointers, first to the beginning of DLL // and second to the end of DLL. struct Node *first = head; struct Node *second = head; while (second->next != NULL) second = second->next; // To track if we find a pair or not bool found = false; // The loop terminates when two pointers // cross each other (second->next // == first), or they become same (first == second) while (first != second && second->next != first) { // pair found if ((first->data + second->data) == x) { found = true; cout << \"(\" << first->data<< \", \" << second->data << \")\" << endl; // move first in forward direction first = first->next; // move second in backward direction second = second->prev; } else { if ((first->data + second->data) < x) first = first->next; else second = second->prev; } } // if pair is not present if (found == false) cout << \"No pair found\";} // A utility function to insert a new node at the// beginning of doubly linked listvoid insert(struct Node **head, int data){ struct Node *temp = new Node; temp->data = data; temp->next = temp->prev = NULL; if (!(*head)) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; }} // Driver programint main(){ struct Node *head = NULL; insert(&head, 9); insert(&head, 8); insert(&head, 6); insert(&head, 5); insert(&head, 4); insert(&head, 2); insert(&head, 1); int x = 7; pairSum(head, x); return 0;}", "e": 3728, "s": 1735, "text": null }, { "code": "// Java program to find a// pair with given sum x.class GFG{ // structure of node of// doubly linked liststatic class Node{ int data; Node next, prev;}; // Function to find pair whose// sum equal to given value x.static void pairSum( Node head, int x){ // Set two pointers, first // to the beginning of DLL // and second to the end of DLL. Node first = head; Node second = head; while (second.next != null) second = second.next; // To track if we find a pair or not boolean found = false; // The loop terminates when // they cross each other (second.next // == first), or they become same // (first == second) while ( first != second && second.next != first) { // pair found if ((first.data + second.data) == x) { found = true; System.out.println( \"(\" + first.data + \", \"+ second.data + \")\" ); // move first in forward direction first = first.next; // move second in backward direction second = second.prev; } else { if ((first.data + second.data) < x) first = first.next; else second = second.prev; } } // if pair is not present if (found == false) System.out.println(\"No pair found\");} // A utility function to insert// a new node at the beginning// of doubly linked liststatic Node insert(Node head, int data){ Node temp = new Node(); temp.data = data; temp.next = temp.prev = null; if (head == null) (head) = temp; else { temp.next = head; (head).prev = temp; (head) = temp; } return temp;} // Driver Codepublic static void main(String args[]){ Node head = null; head = insert(head, 9); head = insert(head, 8); head = insert(head, 6); head = insert(head, 5); head = insert(head, 4); head = insert(head, 2); head = insert(head, 1); int x = 7; pairSum(head, x);}} // This code is contributed// by Arnab Kundu", "e": 5797, "s": 3728, "text": null }, { "code": "# Python3 program to find a pair with# given sum x. # Structure of node of doubly linked listclass Node: def __init__(self, x): self.data = x self.next = None self.prev = None # Function to find pair whose sum# equal to given value x.def pairSum(head, x): # Set two pointers, first to the # beginning of DLL and second to # the end of DLL. first = head second = head while (second.next != None): second = second.next # To track if we find a pair or not found = False # The loop terminates when they # cross each other (second.next == # first), or they become same # (first == second) while (first != second and second.next != first): # Pair found if ((first.data + second.data) == x): found = True print(\"(\", first.data, \",\", second.data, \")\") # Move first in forward direction first = first.next # Move second in backward direction second = second.prev else: if ((first.data + second.data) < x): first = first.next else: second = second.prev # If pair is not present if (found == False): print(\"No pair found\") # A utility function to insert a new node# at the beginning of doubly linked listdef insert(head, data): temp = Node(data) if not head: head = temp else: temp.next = head head.prev = temp head = temp return head # Driver codeif __name__ == '__main__': head = None head = insert(head, 9) head = insert(head, 8) head = insert(head, 6) head = insert(head, 5) head = insert(head, 4) head = insert(head, 2) head = insert(head, 1) x = 7 pairSum(head, x) # This code is contributed by mohit kumar 29", "e": 7707, "s": 5797, "text": null }, { "code": "// C# program to find a// pair with given sum x.using System; class GFG{ // structure of node of // doubly linked list class Node { public int data; public Node next, prev; }; // Function to find pair whose // sum equal to given value x. static void pairSum( Node head, int x) { // Set two pointers, first // to the beginning of DLL // and second to the end of DLL. Node first = head; Node second = head; while (second.next != null) second = second.next; // To track if we find a pair or not bool found = false; // The loop terminates when // they cross each other (second.next // == first), or they become same // (first == second) while (first != second && second.next != first) { // pair found if ((first.data + second.data) == x) { found = true; Console.WriteLine( \"(\" + first.data + \", \"+ second.data + \")\" ); // move first in forward direction first = first.next; // move second in backward direction second = second.prev; } else { if ((first.data + second.data) < x) first = first.next; else second = second.prev; } } // if pair is not present if (found == false) Console.WriteLine(\"No pair found\"); } // A utility function to insert // a new node at the beginning // of doubly linked list static Node insert(Node head, int data) { Node temp = new Node(); temp.data = data; temp.next = temp.prev = null; if (head == null) (head) = temp; else { temp.next = head; (head).prev = temp; (head) = temp; } return temp; } // Driver Code public static void Main(String []args) { Node head = null; head = insert(head, 9); head = insert(head, 8); head = insert(head, 6); head = insert(head, 5); head = insert(head, 4); head = insert(head, 2); head = insert(head, 1); int x = 7; pairSum(head, x); }} // This code is contributed by 29AjayKumar", "e": 10111, "s": 7707, "text": null }, { "code": "<script>// Javascript program to find a// pair with given sum x. // structure of node of// doubly linked listclass Node{ constructor() { this.data = 0; this.next = this.prev = null; }} // Function to find pair whose// sum equal to given value x.function pairSum(head, x){ // Set two pointers, first // to the beginning of DLL // and second to the end of DLL. let first = head; let second = head; while (second.next != null) second = second.next; // To track if we find a pair or not let found = false; // The loop terminates when // they cross each other (second.next // == first), or they become same // (first == second) while ( first != second && second.next != first) { // pair found if ((first.data + second.data) == x) { found = true; document.write( \"(\" + first.data + \", \"+ second.data + \")<br>\" ); // move first in forward direction first = first.next; // move second in backward direction second = second.prev; } else { if ((first.data + second.data) < x) first = first.next; else second = second.prev; } } // if pair is not present if (found == false) document.write(\"No pair found<br>\");} // A utility function to insert// a new node at the beginning// of doubly linked listfunction insert(head,data){ let temp = new Node(); temp.data = data; temp.next = temp.prev = null; if (head == null) (head) = temp; else { temp.next = head; (head).prev = temp; (head) = temp; } return temp;} // Driver Codelet head = null;head = insert(head, 9);head = insert(head, 8);head = insert(head, 6);head = insert(head, 5);head = insert(head, 4);head = insert(head, 2);head = insert(head, 1);let x = 7; pairSum(head, x); // This code is contributed by avanitrachhadiya2155</script>", "e": 12140, "s": 10111, "text": null }, { "code": null, "e": 12154, "s": 12140, "text": "(1, 6)\n(2, 5)" }, { "code": null, "e": 12200, "s": 12154, "text": "Time complexity : O(n) Auxiliary space : O(1)" }, { "code": null, "e": 12461, "s": 12200, "text": "If linked list is not sorted, then we can sort the list as a first step. But in that case overall time complexity would become O(n Log n). We can use Hashing in such cases if extra space is not a constraint. The hashing based solution is same as method 2 here." }, { "code": null, "e": 12776, "s": 12461, "text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 12787, "s": 12776, "text": "andrew1234" }, { "code": null, "e": 12799, "s": 12787, "text": "29AjayKumar" }, { "code": null, "e": 12817, "s": 12799, "text": "abhishek gupta 47" }, { "code": null, "e": 12830, "s": 12817, "text": "tapassaha699" }, { "code": null, "e": 12845, "s": 12830, "text": "mohit kumar 29" }, { "code": null, "e": 12860, "s": 12845, "text": "kathanvakharia" }, { "code": null, "e": 12881, "s": 12860, "text": "avanitrachhadiya2155" }, { "code": null, "e": 12898, "s": 12881, "text": "hardikkoriintern" }, { "code": null, "e": 12917, "s": 12898, "text": "doubly linked list" }, { "code": null, "e": 12929, "s": 12917, "text": "Linked List" }, { "code": null, "e": 12941, "s": 12929, "text": "Linked List" }, { "code": null, "e": 13039, "s": 12941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13058, "s": 13039, "text": "LinkedList in Java" }, { "code": null, "e": 13090, "s": 13058, "text": "Introduction to Data Structures" }, { "code": null, "e": 13119, "s": 13090, "text": "Detect loop in a linked list" }, { "code": null, "e": 13149, "s": 13119, "text": "Merge two sorted linked lists" }, { "code": null, "e": 13213, "s": 13149, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 13252, "s": 13213, "text": "Find the middle of a given linked list" }, { "code": null, "e": 13273, "s": 13252, "text": "Linked List vs Array" }, { "code": null, "e": 13301, "s": 13273, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 13348, "s": 13301, "text": "Implementing a Linked List in Java using Class" } ]
Type Inference in C++ (auto and decltype)
02 Mar, 2022 Type Inference refers to automatic deduction of the data type of an expression in a programming language. Before C++ 11, each data type needed to be explicitly declared at compile-time, limiting the values of an expression at runtime but after the new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself. With type inference capabilities, we can spend less time having to write out things the compiler already knows. As all the types are deduced in the compiler phase only, the time for compilation increases slightly but it does not affect the run time of the program. 1) auto keyword: The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In the case of functions, if their return type is auto then that will be evaluated by return type expression at runtime. Good use of auto is to avoid long initializations when creating iterators for containers. Note: The variable declared with auto keyword should be initialized at the time of its declaration only or else there will be a compile-time error. CPP // C++ program to demonstrate working of auto// and type inference #include <bits/stdc++.h>using namespace std; int main(){ // auto a; this line will give error // because 'a' is not initialized at // the time of declaration // a=33; // see here x ,y,ptr are // initialised at the time of // declaration hence there is // no error in them auto x = 4; auto y = 3.37; auto ptr = &x; cout << typeid(x).name() << endl << typeid(y).name() << endl << typeid(ptr).name() << endl; return 0;} i d Pi Note: We have used typeid for getting the type of the variables. Typeid is an operator which is used where the dynamic type of an object needs to be known. typeid(x).name() returns the data type of x, for example, it return ‘i’ for integers, ‘d’ for doubles, ‘Pi’ for the pointer to integer etc. But the actual name returned is mostly compiler dependent. Good use of auto is to avoid long initializations when creating iterators for containers. C++ // C++ program to demonstrate that we can use auto to// save time when creating iterators #include <bits/stdc++.h>using namespace std; int main(){ // Create a set of strings set<string> st; st.insert({ "geeks", "for", "geeks", "org" }); // 'it' evaluates to iterator to set of string // type automatically for (auto it = st.begin(); it != st.end(); it++) cout << *it << " "; return 0;} for geeks org Note: auto becomes int type if even an integer reference is assigned to it. To make it reference type, we use auto &. Function that returns a ‘reference to int’ type : int& fun() {}; m will default to int type instead of int& type : auto m = fun(); n will be of int& type because of use of extra & with auto keyword : auto& n = fun(); 2) decltype Keyword: It inspects the declared type of an entity or the type of an expression. ‘auto’ lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression. Explanation of the above keywords and their uses is given below: CPP // C++ program to demonstrate use of decltype#include <bits/stdc++.h>using namespace std; int fun1() { return 10; }char fun2() { return 'g'; } int main(){ // Data type of x is same as return type of fun1() // and type of y is same as return type of fun2() decltype(fun1()) x; decltype(fun2()) y; cout << typeid(x).name() << endl; cout << typeid(y).name() << endl; return 0;} i c Below is one more example to demonstrate the use of decltype, CPP // C++ program to demonstrate use of decltype#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int x = 5; // j will be of type int : data type of x decltype(x) j = x + 5; cout << typeid(j).name(); return 0;} i Below is a C++ template function min_type() that returns the minimum of two numbers. The two numbers can be of any integral type. The return type is determined using the type of minimum of two. CPP // C++ program to demonstrate use of decltype in functions#include <bits/stdc++.h>using namespace std; // A generic function which finds minimum of two values// return type is type of variable which is minimumtemplate <class A, class B>auto findMin(A a, B b) -> decltype(a < b ? a : b){ return (a < b) ? a : b;} // driver function to test various inferenceint main(){ // This call returns 3.44 of double type cout << findMin(4, 3.44) << endl; // This call returns 3 of double type cout << findMin(5.4, 3) << endl; return 0;} 3.44 3 decltype vs typeid Decltype gives the type information at compile time while typeid gives at runtime. So, if we have a base class reference (or pointer) referring to (or pointing to) a derived class object, the decltype would give type as base class reference (or pointer, but typeid would give the derived type reference (or pointer). This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Avesh_Agrawal KundanSingh4 prakhar_11704180 anshikajain26 surinderdawra388 cpp-data-types STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Mar, 2022" }, { "code": null, "e": 690, "s": 52, "text": "Type Inference refers to automatic deduction of the data type of an expression in a programming language. Before C++ 11, each data type needed to be explicitly declared at compile-time, limiting the values of an expression at runtime but after the new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself. With type inference capabilities, we can spend less time having to write out things the compiler already knows. As all the types are deduced in the compiler phase only, the time for compilation increases slightly but it does not affect the run time of the program." }, { "code": null, "e": 1054, "s": 690, "text": "1) auto keyword: The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In the case of functions, if their return type is auto then that will be evaluated by return type expression at runtime. Good use of auto is to avoid long initializations when creating iterators for containers. " }, { "code": null, "e": 1203, "s": 1054, "text": "Note: The variable declared with auto keyword should be initialized at the time of its declaration only or else there will be a compile-time error. " }, { "code": null, "e": 1207, "s": 1203, "text": "CPP" }, { "code": "// C++ program to demonstrate working of auto// and type inference #include <bits/stdc++.h>using namespace std; int main(){ // auto a; this line will give error // because 'a' is not initialized at // the time of declaration // a=33; // see here x ,y,ptr are // initialised at the time of // declaration hence there is // no error in them auto x = 4; auto y = 3.37; auto ptr = &x; cout << typeid(x).name() << endl << typeid(y).name() << endl << typeid(ptr).name() << endl; return 0;}", "e": 1748, "s": 1207, "text": null }, { "code": null, "e": 1755, "s": 1748, "text": "i\nd\nPi" }, { "code": null, "e": 1821, "s": 1755, "text": "Note: We have used typeid for getting the type of the variables. " }, { "code": null, "e": 1913, "s": 1821, "text": "Typeid is an operator which is used where the dynamic type of an object needs to be known. " }, { "code": null, "e": 2113, "s": 1913, "text": "typeid(x).name() returns the data type of x, for example, it return ‘i’ for integers, ‘d’ for doubles, ‘Pi’ for the pointer to integer etc. But the actual name returned is mostly compiler dependent. " }, { "code": null, "e": 2203, "s": 2113, "text": "Good use of auto is to avoid long initializations when creating iterators for containers." }, { "code": null, "e": 2207, "s": 2203, "text": "C++" }, { "code": "// C++ program to demonstrate that we can use auto to// save time when creating iterators #include <bits/stdc++.h>using namespace std; int main(){ // Create a set of strings set<string> st; st.insert({ \"geeks\", \"for\", \"geeks\", \"org\" }); // 'it' evaluates to iterator to set of string // type automatically for (auto it = st.begin(); it != st.end(); it++) cout << *it << \" \"; return 0;}", "e": 2623, "s": 2207, "text": null }, { "code": null, "e": 2638, "s": 2623, "text": "for geeks org " }, { "code": null, "e": 2757, "s": 2638, "text": "Note: auto becomes int type if even an integer reference is assigned to it. To make it reference type, we use auto &. " }, { "code": null, "e": 2822, "s": 2757, "text": "Function that returns a ‘reference to int’ type : int& fun() {};" }, { "code": null, "e": 2888, "s": 2822, "text": "m will default to int type instead of int& type : auto m = fun();" }, { "code": null, "e": 2974, "s": 2888, "text": "n will be of int& type because of use of extra & with auto keyword : auto& n = fun();" }, { "code": null, "e": 3334, "s": 2974, "text": "2) decltype Keyword: It inspects the declared type of an entity or the type of an expression. ‘auto’ lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression. Explanation of the above keywords and their uses is given below: " }, { "code": null, "e": 3338, "s": 3334, "text": "CPP" }, { "code": "// C++ program to demonstrate use of decltype#include <bits/stdc++.h>using namespace std; int fun1() { return 10; }char fun2() { return 'g'; } int main(){ // Data type of x is same as return type of fun1() // and type of y is same as return type of fun2() decltype(fun1()) x; decltype(fun2()) y; cout << typeid(x).name() << endl; cout << typeid(y).name() << endl; return 0;}", "e": 3736, "s": 3338, "text": null }, { "code": null, "e": 3740, "s": 3736, "text": "i\nc" }, { "code": null, "e": 3802, "s": 3740, "text": "Below is one more example to demonstrate the use of decltype," }, { "code": null, "e": 3806, "s": 3802, "text": "CPP" }, { "code": "// C++ program to demonstrate use of decltype#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int x = 5; // j will be of type int : data type of x decltype(x) j = x + 5; cout << typeid(j).name(); return 0;}", "e": 4053, "s": 3806, "text": null }, { "code": null, "e": 4055, "s": 4053, "text": "i" }, { "code": null, "e": 4249, "s": 4055, "text": "Below is a C++ template function min_type() that returns the minimum of two numbers. The two numbers can be of any integral type. The return type is determined using the type of minimum of two." }, { "code": null, "e": 4253, "s": 4249, "text": "CPP" }, { "code": "// C++ program to demonstrate use of decltype in functions#include <bits/stdc++.h>using namespace std; // A generic function which finds minimum of two values// return type is type of variable which is minimumtemplate <class A, class B>auto findMin(A a, B b) -> decltype(a < b ? a : b){ return (a < b) ? a : b;} // driver function to test various inferenceint main(){ // This call returns 3.44 of double type cout << findMin(4, 3.44) << endl; // This call returns 3 of double type cout << findMin(5.4, 3) << endl; return 0;}", "e": 4798, "s": 4253, "text": null }, { "code": null, "e": 4805, "s": 4798, "text": "3.44\n3" }, { "code": null, "e": 4824, "s": 4805, "text": "decltype vs typeid" }, { "code": null, "e": 4907, "s": 4824, "text": "Decltype gives the type information at compile time while typeid gives at runtime." }, { "code": null, "e": 5141, "s": 4907, "text": "So, if we have a base class reference (or pointer) referring to (or pointing to) a derived class object, the decltype would give type as base class reference (or pointer, but typeid would give the derived type reference (or pointer)." }, { "code": null, "e": 5315, "s": 5141, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5329, "s": 5315, "text": "Avesh_Agrawal" }, { "code": null, "e": 5342, "s": 5329, "text": "KundanSingh4" }, { "code": null, "e": 5359, "s": 5342, "text": "prakhar_11704180" }, { "code": null, "e": 5373, "s": 5359, "text": "anshikajain26" }, { "code": null, "e": 5390, "s": 5373, "text": "surinderdawra388" }, { "code": null, "e": 5405, "s": 5390, "text": "cpp-data-types" }, { "code": null, "e": 5409, "s": 5405, "text": "STL" }, { "code": null, "e": 5420, "s": 5409, "text": "C Language" }, { "code": null, "e": 5424, "s": 5420, "text": "C++" }, { "code": null, "e": 5428, "s": 5424, "text": "STL" }, { "code": null, "e": 5432, "s": 5428, "text": "CPP" } ]
Singleton Class in Java
13 Jun, 2022 In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, affects the variable of the single instance created and is visible if we access that variable through any variable of that class type defined. Remember the key points while defining class as a singleton class that is while designing a singleton class: Make a constructor private.Write a static method that has the return type object of this singleton class. Here, the concept of Lazy initialization is used to write this static method. Make a constructor private. Write a static method that has the return type object of this singleton class. Here, the concept of Lazy initialization is used to write this static method. The primary purpose of a Singleton class is to restrict the limit of the number of object creation to only one. This often ensures that there is access control to resources, for example, socket or database connection. The memory space wastage does not occur with the use of the singleton class because it restricts the instance creation. As the object creation will take place only once instead of creating it each time a new request is made. We can use this single object repeatedly as per the requirements. This is the reason why the multi-threaded and database applications mostly make use of the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and much more. For example, there is a license with us, and we have only one database connection or suppose if our JDBC driver does not allow us to do multithreading, then Singleton class comes into the picture and makes sure that at a time, only a single connection or a single thread can access the connection. To create a singleton class, we must follow the steps, given below: 1. Ensure that only one instance of the class exists. 2. Provide global access to that instance by Declaring all constructors of the class to be private. Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods. The instance is stored as a private static variable. Example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class. We can distinguish a Singleton class from the usual classes with respect to the process of instantiating the object of the class. To instantiate a normal class, we use a java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method. The other difference is that a normal class vanishes at the end of the lifecycle of the application while the singleton class does not destroy with the completion of an application. There are two forms of singleton design pattern, which are: Early Instantiation: The object creation takes place at the load time. Lazy Instantiation: The object creation is done according to the requirement. Implementation: Let us brief how the singleton class varies from the normal class in java. Here the difference is in terms of instantiation as for normal class we use constructor, whereas for singleton class we use getInstance() method which we will be peeking out in example 1 as depicted below. In general, in order to avoid confusion, we may also use the class name as method name while defining this method which will be as depicted in example 2 below as follows. Example 1: Java // Java program implementing Singleton class// with using getInstance() method // Class 1// Helper classclass Singleton { // Static variable reference of single_instance // of type Singleton private static Singleton single_instance = null; // Declaring a variable of type String public String s; // Constructor // Here we will be creating private constructor // restricted to this class itself private Singleton() { s = "Hello I am a string part of Singleton class"; } // Static method // Static method to create instance of Singleton class public static Singleton getInstance() { if (single_instance == null) single_instance = new Singleton(); return single_instance; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Instantiating Singleton class with variable x Singleton x = Singleton.getInstance(); // Instantiating Singleton class with variable y Singleton y = Singleton.getInstance(); // Instantiating Singleton class with variable z Singleton z = Singleton.getInstance(); // Printing the hash code for above variable as // declared System.out.println("Hashcode of x is " + x.hashCode()); System.out.println("Hashcode of y is " + y.hashCode()); System.out.println("Hashcode of z is " + z.hashCode()); // Condition check if (x == y && y == z) { // Print statement System.out.println( "Three objects point to the same memory location on the heap i.e, to the same object"); } else { // Print statement System.out.println( "Three objects DO NOT point to the same memory location on the heap"); } }} Hashcode of x is 558638686 Hashcode of y is 558638686 Hashcode of z is 558638686 Three objects point to the same memory location on the heap i.e, to the same object Output explanation: In a singleton class, when we first-time call the getInstance() method, it creates an object of the class with the name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object. Next time, if we try to call the getInstance() method since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again. This part is done by if condition. In the main class, we instantiate the singleton class with 3 objects x, y, z by calling the static method getInstance(). But actually, after the creation of object x, variables y and z are pointed to object x as shown in the diagram. Hence, if we change the variables of object x, that is reflected when we access the variables of objects y and z. Also if we change the variables of object z, that is reflected when we access the variables of objects x and y. Now we are done with covering all aspects of example 1 and have implemented the same, now we will be implementing Singleton class with method name as that of the class name. Example 2: Java // Java program implementing Singleton class// with method name as that of class // Class 1// Helper classclass Singleton { // Static variable single_instance of type Singleton private static Singleton single_instance = null; // Declaring a variable of type String public String s; // Constructor of this class // Here private constructor is used to // restricted to this class itself private Singleton() { s = "Hello I am a string part of Singleton class"; } // Method // Static method to create instance of Singleton class public static Singleton Singleton() { // To ensure only one instance is created if (single_instance == null) { single_instance = new Singleton(); } return single_instance; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Instantiating Singleton class with variable x Singleton x = Singleton.Singleton(); // Instantiating Singleton class with variable y Singleton y = Singleton.Singleton(); // instantiating Singleton class with variable z Singleton z = Singleton.Singleton(); // Now changing variable of instance x // via toUpperCase() method x.s = (x.s).toUpperCase(); // Print and display commands System.out.println("String from x is " + x.s); System.out.println("String from y is " + y.s); System.out.println("String from z is " + z.s); System.out.println("\n"); // Now again changing variable of instance x z.s = (z.s).toLowerCase(); System.out.println("String from x is " + x.s); System.out.println("String from y is " + y.s); System.out.println("String from z is " + z.s); }} String from x is HELLO I AM A STRING PART OF SINGLETON CLASS String from y is HELLO I AM A STRING PART OF SINGLETON CLASS String from z is HELLO I AM A STRING PART OF SINGLETON CLASS String from x is hello i am a string part of singleton class String from y is hello i am a string part of singleton class String from z is hello i am a string part of singleton class Output explanation: In the singleton class, when we first time call Singleton() method, it creates an object of class Singleton with the name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object. Next time if we try to call Singleton() method, since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again. This article is contributed by Pavan Gopal Rayapati. 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. baker6romeo mahesholtrainings surindertarika1234 devilchandra nishkarshgandhi surinderdawra388 fasiabbu Design Pattern Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 540, "s": 52, "text": "In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, affects the variable of the single instance created and is visible if we access that variable through any variable of that class type defined. " }, { "code": null, "e": 650, "s": 540, "text": "Remember the key points while defining class as a singleton class that is while designing a singleton class: " }, { "code": null, "e": 834, "s": 650, "text": "Make a constructor private.Write a static method that has the return type object of this singleton class. Here, the concept of Lazy initialization is used to write this static method." }, { "code": null, "e": 862, "s": 834, "text": "Make a constructor private." }, { "code": null, "e": 1019, "s": 862, "text": "Write a static method that has the return type object of this singleton class. Here, the concept of Lazy initialization is used to write this static method." }, { "code": null, "e": 1237, "s": 1019, "text": "The primary purpose of a Singleton class is to restrict the limit of the number of object creation to only one. This often ensures that there is access control to resources, for example, socket or database connection." }, { "code": null, "e": 1462, "s": 1237, "text": "The memory space wastage does not occur with the use of the singleton class because it restricts the instance creation. As the object creation will take place only once instead of creating it each time a new request is made." }, { "code": null, "e": 1722, "s": 1462, "text": "We can use this single object repeatedly as per the requirements. This is the reason why the multi-threaded and database applications mostly make use of the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and much more." }, { "code": null, "e": 2020, "s": 1722, "text": "For example, there is a license with us, and we have only one database connection or suppose if our JDBC driver does not allow us to do multithreading, then Singleton class comes into the picture and makes sure that at a time, only a single connection or a single thread can access the connection." }, { "code": null, "e": 2088, "s": 2020, "text": "To create a singleton class, we must follow the steps, given below:" }, { "code": null, "e": 2142, "s": 2088, "text": "1. Ensure that only one instance of the class exists." }, { "code": null, "e": 2187, "s": 2142, "text": "2. Provide global access to that instance by" }, { "code": null, "e": 2242, "s": 2187, "text": "Declaring all constructors of the class to be private." }, { "code": null, "e": 2379, "s": 2242, "text": "Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods." }, { "code": null, "e": 2432, "s": 2379, "text": "The instance is stored as a private static variable." }, { "code": null, "e": 2597, "s": 2432, "text": "Example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class." }, { "code": null, "e": 2871, "s": 2597, "text": "We can distinguish a Singleton class from the usual classes with respect to the process of instantiating the object of the class. To instantiate a normal class, we use a java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method." }, { "code": null, "e": 3053, "s": 2871, "text": "The other difference is that a normal class vanishes at the end of the lifecycle of the application while the singleton class does not destroy with the completion of an application." }, { "code": null, "e": 3113, "s": 3053, "text": "There are two forms of singleton design pattern, which are:" }, { "code": null, "e": 3184, "s": 3113, "text": "Early Instantiation: The object creation takes place at the load time." }, { "code": null, "e": 3262, "s": 3184, "text": "Lazy Instantiation: The object creation is done according to the requirement." }, { "code": null, "e": 3730, "s": 3262, "text": "Implementation: Let us brief how the singleton class varies from the normal class in java. Here the difference is in terms of instantiation as for normal class we use constructor, whereas for singleton class we use getInstance() method which we will be peeking out in example 1 as depicted below. In general, in order to avoid confusion, we may also use the class name as method name while defining this method which will be as depicted in example 2 below as follows." }, { "code": null, "e": 3741, "s": 3730, "text": "Example 1:" }, { "code": null, "e": 3746, "s": 3741, "text": "Java" }, { "code": "// Java program implementing Singleton class// with using getInstance() method // Class 1// Helper classclass Singleton { // Static variable reference of single_instance // of type Singleton private static Singleton single_instance = null; // Declaring a variable of type String public String s; // Constructor // Here we will be creating private constructor // restricted to this class itself private Singleton() { s = \"Hello I am a string part of Singleton class\"; } // Static method // Static method to create instance of Singleton class public static Singleton getInstance() { if (single_instance == null) single_instance = new Singleton(); return single_instance; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Instantiating Singleton class with variable x Singleton x = Singleton.getInstance(); // Instantiating Singleton class with variable y Singleton y = Singleton.getInstance(); // Instantiating Singleton class with variable z Singleton z = Singleton.getInstance(); // Printing the hash code for above variable as // declared System.out.println(\"Hashcode of x is \" + x.hashCode()); System.out.println(\"Hashcode of y is \" + y.hashCode()); System.out.println(\"Hashcode of z is \" + z.hashCode()); // Condition check if (x == y && y == z) { // Print statement System.out.println( \"Three objects point to the same memory location on the heap i.e, to the same object\"); } else { // Print statement System.out.println( \"Three objects DO NOT point to the same memory location on the heap\"); } }}", "e": 5669, "s": 3746, "text": null }, { "code": null, "e": 5834, "s": 5669, "text": "Hashcode of x is 558638686\nHashcode of y is 558638686\nHashcode of z is 558638686\nThree objects point to the same memory location on the heap i.e, to the same object" }, { "code": null, "e": 5855, "s": 5834, "text": "Output explanation: " }, { "code": null, "e": 6938, "s": 5855, "text": "In a singleton class, when we first-time call the getInstance() method, it creates an object of the class with the name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object. Next time, if we try to call the getInstance() method since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again. This part is done by if condition. In the main class, we instantiate the singleton class with 3 objects x, y, z by calling the static method getInstance(). But actually, after the creation of object x, variables y and z are pointed to object x as shown in the diagram. Hence, if we change the variables of object x, that is reflected when we access the variables of objects y and z. Also if we change the variables of object z, that is reflected when we access the variables of objects x and y. Now we are done with covering all aspects of example 1 and have implemented the same, now we will be implementing Singleton class with method name as that of the class name." }, { "code": null, "e": 6949, "s": 6938, "text": "Example 2:" }, { "code": null, "e": 6954, "s": 6949, "text": "Java" }, { "code": "// Java program implementing Singleton class// with method name as that of class // Class 1// Helper classclass Singleton { // Static variable single_instance of type Singleton private static Singleton single_instance = null; // Declaring a variable of type String public String s; // Constructor of this class // Here private constructor is used to // restricted to this class itself private Singleton() { s = \"Hello I am a string part of Singleton class\"; } // Method // Static method to create instance of Singleton class public static Singleton Singleton() { // To ensure only one instance is created if (single_instance == null) { single_instance = new Singleton(); } return single_instance; }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Instantiating Singleton class with variable x Singleton x = Singleton.Singleton(); // Instantiating Singleton class with variable y Singleton y = Singleton.Singleton(); // instantiating Singleton class with variable z Singleton z = Singleton.Singleton(); // Now changing variable of instance x // via toUpperCase() method x.s = (x.s).toUpperCase(); // Print and display commands System.out.println(\"String from x is \" + x.s); System.out.println(\"String from y is \" + y.s); System.out.println(\"String from z is \" + z.s); System.out.println(\"\\n\"); // Now again changing variable of instance x z.s = (z.s).toLowerCase(); System.out.println(\"String from x is \" + x.s); System.out.println(\"String from y is \" + y.s); System.out.println(\"String from z is \" + z.s); }}", "e": 8763, "s": 6954, "text": null }, { "code": null, "e": 9131, "s": 8763, "text": "String from x is HELLO I AM A STRING PART OF SINGLETON CLASS\nString from y is HELLO I AM A STRING PART OF SINGLETON CLASS\nString from z is HELLO I AM A STRING PART OF SINGLETON CLASS\n\n\nString from x is hello i am a string part of singleton class\nString from y is hello i am a string part of singleton class\nString from z is hello i am a string part of singleton class" }, { "code": null, "e": 9561, "s": 9131, "text": "Output explanation: In the singleton class, when we first time call Singleton() method, it creates an object of class Singleton with the name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object. Next time if we try to call Singleton() method, since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again." }, { "code": null, "e": 9990, "s": 9561, "text": "This article is contributed by Pavan Gopal Rayapati. 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": 10002, "s": 9990, "text": "baker6romeo" }, { "code": null, "e": 10020, "s": 10002, "text": "mahesholtrainings" }, { "code": null, "e": 10039, "s": 10020, "text": "surindertarika1234" }, { "code": null, "e": 10052, "s": 10039, "text": "devilchandra" }, { "code": null, "e": 10068, "s": 10052, "text": "nishkarshgandhi" }, { "code": null, "e": 10085, "s": 10068, "text": "surinderdawra388" }, { "code": null, "e": 10094, "s": 10085, "text": "fasiabbu" }, { "code": null, "e": 10109, "s": 10094, "text": "Design Pattern" }, { "code": null, "e": 10114, "s": 10109, "text": "Java" }, { "code": null, "e": 10119, "s": 10114, "text": "Java" } ]
Choose Specific Columns of a Data Frame in R Programming – select() Function
19 Jun, 2020 select() function in R Language is used to choose whether a column of the data frame is selected or not. Syntax: select(x, expr) Parameters:x: Data frameexpr: condition for selection Example 1: # R program to select specific columns # Loading library library(dplyr) # Create a data framed <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # startswith() function to print only ht data select(d, starts_with("ht")) # -startswith() function to # print everything except ht data select(d, -starts_with("ht")) Output: ht 1 46 2 NA 3 NA 4 69 name age school 1 Abhi 7 yes 2 Bhavesh 5 yes 3 Chaman 9 no 4 Dimri 16 no Example 2: # R program to select specific columns # Loading library library(dplyr) # Create a data framed <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Printing column 1 to 2 select(d, 1:2) # Printing data of column heading containing 'a' select(d, contains("a")) # Printing data of column heading which matches 'na' select(d, matches("na")) Output: name age 1 Abhi 7 2 Bhavesh 5 3 Chaman 9 4 Dimri 16 name age 1 Abhi 7 2 Bhavesh 5 3 Chaman 9 4 Dimri 16 name 1 Abhi 2 Bhavesh 3 Chaman 4 Dimri R DataFrame-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jun, 2020" }, { "code": null, "e": 133, "s": 28, "text": "select() function in R Language is used to choose whether a column of the data frame is selected or not." }, { "code": null, "e": 157, "s": 133, "text": "Syntax: select(x, expr)" }, { "code": null, "e": 211, "s": 157, "text": "Parameters:x: Data frameexpr: condition for selection" }, { "code": null, "e": 222, "s": 211, "text": "Example 1:" }, { "code": "# R program to select specific columns # Loading library library(dplyr) # Create a data framed <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # startswith() function to print only ht data select(d, starts_with(\"ht\")) # -startswith() function to # print everything except ht data select(d, -starts_with(\"ht\")) ", "e": 698, "s": 222, "text": null }, { "code": null, "e": 706, "s": 698, "text": "Output:" }, { "code": null, "e": 837, "s": 706, "text": " ht\n1 46\n2 NA\n3 NA\n4 69\n name age school\n1 Abhi 7 yes\n2 Bhavesh 5 yes\n3 Chaman 9 no\n4 Dimri 16 no\n" }, { "code": null, "e": 848, "s": 837, "text": "Example 2:" }, { "code": "# R program to select specific columns # Loading library library(dplyr) # Create a data framed <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # Printing column 1 to 2 select(d, 1:2) # Printing data of column heading containing 'a' select(d, contains(\"a\")) # Printing data of column heading which matches 'na' select(d, matches(\"na\")) ", "e": 1353, "s": 848, "text": null }, { "code": null, "e": 1361, "s": 1353, "text": "Output:" }, { "code": null, "e": 1552, "s": 1361, "text": " name age\n1 Abhi 7\n2 Bhavesh 5\n3 Chaman 9\n4 Dimri 16\n name age\n1 Abhi 7\n2 Bhavesh 5\n3 Chaman 9\n4 Dimri 16\n name\n1 Abhi\n2 Bhavesh\n3 Chaman\n4 Dimri\n" }, { "code": null, "e": 1573, "s": 1552, "text": "R DataFrame-Function" }, { "code": null, "e": 1584, "s": 1573, "text": "R Language" }, { "code": null, "e": 1682, "s": 1584, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1734, "s": 1682, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1792, "s": 1734, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1827, "s": 1792, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1865, "s": 1827, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1914, "s": 1865, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1931, "s": 1914, "text": "R - if statement" }, { "code": null, "e": 1968, "s": 1931, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2011, "s": 1968, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2048, "s": 2011, "text": "How to import an Excel File into R ?" } ]
Scala Float floor() method with example
29 Oct, 2019 The floor() method is utilized to returns a float number which is less than or equal to the given float number. Method Definition: (Float_Number).floor Return Type: It returns a float number which is less than or equal to the given float number. Example #1: // Scala program of Float floor()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying floor method val result = (5.4).floor // Displays output println(result) }} 5.0 Example #2: // Scala program of Float floor()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying floor method val result = (-3.8).floor // Displays output println(result) }} -4.0 Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2019" }, { "code": null, "e": 140, "s": 28, "text": "The floor() method is utilized to returns a float number which is less than or equal to the given float number." }, { "code": null, "e": 180, "s": 140, "text": "Method Definition: (Float_Number).floor" }, { "code": null, "e": 274, "s": 180, "text": "Return Type: It returns a float number which is less than or equal to the given float number." }, { "code": null, "e": 286, "s": 274, "text": "Example #1:" }, { "code": "// Scala program of Float floor()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying floor method val result = (5.4).floor // Displays output println(result) }} ", "e": 560, "s": 286, "text": null }, { "code": null, "e": 565, "s": 560, "text": "5.0\n" }, { "code": null, "e": 577, "s": 565, "text": "Example #2:" }, { "code": "// Scala program of Float floor()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying floor method val result = (-3.8).floor // Displays output println(result) }} ", "e": 852, "s": 577, "text": null }, { "code": null, "e": 858, "s": 852, "text": "-4.0\n" }, { "code": null, "e": 864, "s": 858, "text": "Scala" }, { "code": null, "e": 877, "s": 864, "text": "Scala-Method" }, { "code": null, "e": 883, "s": 877, "text": "Scala" } ]
Java Examples - Multithreaded Server
How to create a multithreaded server ? Following example demonstrates how to create a multithreaded server by using ssock.accept() method of Socket class and MultiThreadServer(socketname) method of ServerSocket class. import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class MultiThreadServer implements Runnable { Socket csocket; MultiThreadServer(Socket csocket) { this.csocket = csocket; } public static void main(String args[]) throws Exception { ServerSocket ssock = new ServerSocket(1234); System.out.println("Listening"); while (true) { Socket sock = ssock.accept(); System.out.println("Connected"); new Thread(new MultiThreadServer(sock)).start(); } } public void run() { try { PrintStream pstream = new PrintStream(csocket.getOutputStream()); for (int i = 100; i >= 0; i--) { pstream.println(i + " bottles of beer on the wall"); } pstream.close(); csocket.close(); } catch (IOException e) { System.out.println(e); } } } The above code sample will produce the following result. Listening Connected Following is an another example of how to create a multithreaded server. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Calendar; public class NewClass { ServerSocket myServerSocket; boolean ServerOn = true; public NewClass() { try { myServerSocket = new ServerSocket(8888); } catch(IOException ioe) { System.out.println("Could not create server socket on port 8888. Quitting."); System.exit(-1); } Calendar now = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat( "E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("It is now : " + formatter.format(now.getTime())); while(ServerOn) { try { Socket clientSocket = myServerSocket.accept(); ClientServiceThread cliThread = new ClientServiceThread(clientSocket); cliThread.start(); } catch(IOException ioe) { System.out.println("Exception found on accept. Ignoring. Stack Trace :"); ioe.printStackTrace(); } } try { myServerSocket.close(); System.out.println("Server Stopped"); } catch(Exception ioe) { System.out.println("Error Found stopping server socket"); System.exit(-1); } } public static void main (String[] args) { new NewClass(); } class ClientServiceThread extends Thread { Socket myClientSocket; boolean m_bRunThread = true; public ClientServiceThread() { super(); } ClientServiceThread(Socket s) { myClientSocket = s; } public void run() { BufferedReader in = null; PrintWriter out = null; System.out.println( "Accepted Client Address - " + myClientSocket.getInetAddress().getHostName()); try { in = new BufferedReader( new InputStreamReader(myClientSocket.getInputStream())); out = new PrintWriter( new OutputStreamWriter(myClientSocket.getOutputStream())); while(m_bRunThread) { String clientCommand = in.readLine(); System.out.println("Client Says :" + clientCommand); if(!ServerOn) { System.out.print("Server has already stopped"); out.println("Server has already stopped"); out.flush(); m_bRunThread = false; } if(clientCommand.equalsIgnoreCase("quit")) { m_bRunThread = false; System.out.print("Stopping client thread for client : "); } else if(clientCommand.equalsIgnoreCase("end")) { m_bRunThread = false; System.out.print("Stopping client thread for client : "); ServerOn = false; } else { out.println("Server Says : " + clientCommand); out.flush(); } } } catch(Exception e) { e.printStackTrace(); } finally { try { in.close(); out.close(); myClientSocket.close(); System.out.println("...Stopped"); } catch(IOException ioe) { ioe.printStackTrace(); } } } } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 2068, "text": "How to create a multithreaded server ?" }, { "code": null, "e": 2286, "s": 2107, "text": "Following example demonstrates how to create a multithreaded server by using ssock.accept() method of Socket class and MultiThreadServer(socketname) method of ServerSocket class." }, { "code": null, "e": 3234, "s": 2286, "text": "import java.io.IOException;\nimport java.io.PrintStream;\nimport java.net.ServerSocket;\nimport java.net.Socket;\n\npublic class MultiThreadServer implements Runnable {\n Socket csocket;\n MultiThreadServer(Socket csocket) {\n this.csocket = csocket;\n }\n public static void main(String args[]) throws Exception { \n ServerSocket ssock = new ServerSocket(1234);\n System.out.println(\"Listening\");\n \n while (true) {\n Socket sock = ssock.accept();\n System.out.println(\"Connected\");\n new Thread(new MultiThreadServer(sock)).start();\n }\n }\n public void run() {\n try {\n PrintStream pstream = new PrintStream(csocket.getOutputStream());\n for (int i = 100; i >= 0; i--) {\n pstream.println(i + \" bottles of beer on the wall\");\n }\n pstream.close();\n csocket.close();\n } catch (IOException e) {\n System.out.println(e);\n }\n }\n}" }, { "code": null, "e": 3291, "s": 3234, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3312, "s": 3291, "text": "Listening\nConnected\n" }, { "code": null, "e": 3385, "s": 3312, "text": "Following is an another example of how to create a multithreaded server." }, { "code": null, "e": 7025, "s": 3385, "text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\n\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\n \npublic class NewClass {\n ServerSocket myServerSocket;\n boolean ServerOn = true;\n public NewClass() { \n try {\n myServerSocket = new ServerSocket(8888);\n } catch(IOException ioe) { \n System.out.println(\"Could not create server socket on port 8888. Quitting.\");\n System.exit(-1);\n } \n\t\t\n Calendar now = Calendar.getInstance();\n SimpleDateFormat formatter = new SimpleDateFormat(\n \"E yyyy.MM.dd 'at' hh:mm:ss a zzz\");\n System.out.println(\"It is now : \" + formatter.format(now.getTime()));\n \n while(ServerOn) { \n try { \n Socket clientSocket = myServerSocket.accept();\n ClientServiceThread cliThread = new ClientServiceThread(clientSocket);\n cliThread.start(); \n } catch(IOException ioe) { \n System.out.println(\"Exception found on accept. Ignoring. Stack Trace :\"); \n ioe.printStackTrace(); \n } \n } \n try { \n myServerSocket.close(); \n System.out.println(\"Server Stopped\"); \n } catch(Exception ioe) { \n System.out.println(\"Error Found stopping server socket\"); \n System.exit(-1); \n } \n }\n\t\n public static void main (String[] args) { \n new NewClass(); \n } \n\t\n class ClientServiceThread extends Thread { \n Socket myClientSocket;\n boolean m_bRunThread = true; \n public ClientServiceThread() { \n super(); \n } \n\t\t\n ClientServiceThread(Socket s) { \n myClientSocket = s; \n } \n\t\t\n public void run() { \n BufferedReader in = null; \n PrintWriter out = null; \n System.out.println(\n \"Accepted Client Address - \" + myClientSocket.getInetAddress().getHostName());\n try { \n in = new BufferedReader(\n new InputStreamReader(myClientSocket.getInputStream()));\n out = new PrintWriter(\n new OutputStreamWriter(myClientSocket.getOutputStream()));\n \n while(m_bRunThread) { \n String clientCommand = in.readLine(); \n System.out.println(\"Client Says :\" + clientCommand);\n \n if(!ServerOn) { \n System.out.print(\"Server has already stopped\"); \n out.println(\"Server has already stopped\"); \n out.flush(); \n m_bRunThread = false;\n } \n if(clientCommand.equalsIgnoreCase(\"quit\")) {\n m_bRunThread = false;\n System.out.print(\"Stopping client thread for client : \");\n } else if(clientCommand.equalsIgnoreCase(\"end\")) {\n m_bRunThread = false;\n System.out.print(\"Stopping client thread for client : \");\n ServerOn = false;\n } else {\n out.println(\"Server Says : \" + clientCommand);\n out.flush(); \n } \n } \n } catch(Exception e) { \n e.printStackTrace(); \n } \n finally { \n try { \n in.close(); \n out.close(); \n myClientSocket.close(); \n System.out.println(\"...Stopped\"); \n } catch(IOException ioe) { \n ioe.printStackTrace(); \n } \n } \n } \n } \n}" }, { "code": null, "e": 7032, "s": 7025, "text": " Print" }, { "code": null, "e": 7043, "s": 7032, "text": " Add Notes" } ]
Julia Programming - Working with Graphics
This chapter discusses how to plot, visualize and perform other (graphic) operations on data using various tools in Julia. Cairo, a 2D graphics library, implements a device context to the display system. It works with Linux, Windows, OS X and can create disk files in PDF, PostScript, and SVG formats also. The Julia file of Cairo i.e. Cairo.jl is authentic to its C API. The following is an example to draw a line − First, we will create a cr context. julia> using Cairo julia> img = CairoRGBSurface(512, 128); julia> img = CairoRGBSurface(512, 128); julia> cr = CairoContext(img); julia> save(cr); Now, we will add a rectangle − julia> set_source_rgb(cr, 0.5, 0.5, 0.5); julia> rectangle(cr, 0.0, 0.0, 512.0, 128.0); julia> fill(cr); julia> restore(cr); julia> save(cr); Now, we will define the points and draw a line through those points − julia> x0=61.2; y0=74.0; julia> x1=214.8; y1=125.4; julia> x2=317.2; y2=22.8; julia> x3=470.8; y3=74.0; julia> move_to(cr, x0, y0); julia> curve_to(cr, x1, y1, x2, y2, x3, y3); julia> set_line_width(cr, 10.0); julia> stroke_preserve(cr); julia> restore(cr); Finally, writing the resulting graphics to the disk − julia> move_to(cr, 12.0, 12.0); julia> set_source_rgb(cr, 0, 0, 0); julia> show_text(cr,"Line_Figure") julia> write_to_png(c,"Line_Figure.png"); Winston is also a 2D graphics library. It resembles the built-in graphics available within MATLAB. julia> x = range(0, stop=3pi, length=100); julia> c = cos.(x); julia> s = sin.(x); julia> p = FramedPlot( title="Winston Graphics!", xlabel="\\Sigma x^2_i", ylabel="\\Theta_i") julia> add(p, FillBetween(x, c, x, s)) julia> add(p, Curve(x, c, color="black")) julia> add(p, Curve(x, s, color="red")) Data visualization may be defined as the presentation of data in a variety of graphical as well as pictorial formats such as pie and bar charts. Gadfly is a powerful Julia package for data visualization and an implementation of the “grammar of graphics” style. It is based on the same principal as ggplot2 in R. For using it, we need to first add it with the help of Julia package manager. To use Gadfly, we first need to use RDatasets package so that we can get some datasets to work with. In this example, we will be using iris dataset − julia> using Gadfly julia> using RDatasets julia> iris = dataset("datasets", "iris"); julia> first(iris,10) 10×5 DataFrame │ Row │ SepalLength │ SepalWidth │ PetalLength │ PetalWidth │ Species │ │ │ Float64 │ Float64 │ Float64 │ Float64 │ Cat... │ ├─────┼─────────────┼────────────┼─────────────┼────────────┼─────────┤ │ 1 │ 5.1 │ 3.5 │ 1.4 │ 0.2 │ setosa │ │ 2 │ 4.9 │ 3.0 │ 1.4 │ 0.2 │ setosa │ │ 3 │ 4.7 │ 3.2 │ 1.3 │ 0.2 │ setosa │ │ 4 │ 4.6 │ 3.1 │ 1.5 │ 0.2 │ setosa │ │ 5 │ 5.0 │ 3.6 │ 1.4 │ 0.2 │ setosa │ │ 6 │ 5.4 │ 3.9 │ 1.7 │ 0.4 │ setosa │ │ 7 │ 4.6 │ 3.4 │ 1.4 │ 0.3 │ setosa │ │ 8 │ 5.0 │ 3.4 │ 1.5 │ 0.2 │ setosa │ │ 9 │ 4.4 │ 2.9 │ 1.4 │ 0.2 │ setosa │ │ 10 │ 4.9 │ 3.1 │ 1.5 │ 0.1 │ setosa │ Now let us plot a scatter plot. We will be using the variables namely SepalLength and SepalWidth. For this, we need to set the geometry element using Geom.point as follows − julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, Geom.point) Similarly we can add some more geometries like geom.line to produce more layers in the plot − julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, Geom.point, Geom.line) We can also set the color of keyword argument as follows − julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, color = :Species, Geom.point) Compose is a declarative vector graphics system. It is also written by Daniel Jones as a part of the Gadfly system. In Compose, the graphics are defined using a tree structure and the primitives can be classified as follows − Context − It represents an internal node. Context − It represents an internal node. Form − It represents a leaf node which defines some geometry such as a circle or line. Form − It represents a leaf node which defines some geometry such as a circle or line. Property − It represents a leaf node that modifies how its parent’s subtree is drawn. For example, fill color and line width. Property − It represents a leaf node that modifies how its parent’s subtree is drawn. For example, fill color and line width. Compose(x,y) − It returns a new tree rooted at x and with y attached as child. Compose(x,y) − It returns a new tree rooted at x and with y attached as child. The below example will draw a simple image − julia> using Compose julia> composition = compose(compose(context(), rectangle()), fill("tomato")) julia> draw(SVG("simple.svg", 6cm, 6cm), composition) Now let us form more complex trees by grouping subtrees with brackets − julia> composition = compose(context(), (context(), circle(), fill("bisque")), (context(), rectangle(), fill("tomato"))) julia> composition |> SVG("simple2.svg") In this section, we shall discuss various graphic engines used in Julia. PyPlot, arose from the previous development of the PyCall module, provides a Julia interface to the Matplotlib plotting library from Python. It uses the PyCall package to call Matplotlib directly from Julia. To work with PytPlot, we need to do the following setup − julia> using Pkg julia> pkg"up; add PyPlot Conda" julia> using Conda julia> Conda.add("matplotlib") Once you are done with this setup, you can simply import PyPlot by using PyPlot command. It will let you make calling functions in matplotlib.pyplot. This example, from PyPlot documentation, will create a sinusoidally modulated sinusoid − julia> using PyPlot julia> x = range(0; stop=2*pi, length=500); julia> y = sin.(3 * x + 4 * cos.(2 * x)); julia> plot(x, y, color="blue", linewidth=1.0, linestyle="--") 1-element Array{PyCall.PyObject,1}: PyObject <matplotlib.lines.Line2D object at 0x00000000323405E0> julia> title("A sinusoidally modulated sinusoid") PyObject Text(0.5, 1.0, 'A sinusoidally modulated sinusoid') The PyPlot package can also be used for 3d plotting and for this it can import functions from Matplotlib’s mplot3d toolkit. We can create 3d plots directly also by calling some corresponding methods such as bar3d, plot_surface, plot3d, etc., of Axes3d. For example, we can plot a random surface mesh as follows − julia> surf(rand(20,30)) PyObject <mpl_toolkits.mplot3d.art3d.Poly3DCollection object at 0x00000000019BD550> Gaston is another useful package for plotting. This plotting package provides an interface to gnuplot. Some of the features of Gaston are as follows − It can plot using graphical windows, and with mouse interaction, it can keep multiple plots active at one time. It can plot using graphical windows, and with mouse interaction, it can keep multiple plots active at one time. It can plot directly to the REPL. It can plot directly to the REPL. It can also plot in Jupyter and Juno. It can also plot in Jupyter and Juno. It supports popular 2-dimensional plots such as stem, step, histograms, etc. It supports popular 2-dimensional plots such as stem, step, histograms, etc. It also supports popular 3-dimensional plots such as surface, contour, and heatmap. It also supports popular 3-dimensional plots such as surface, contour, and heatmap. It takes around five seconds to load package, plot, and save to pdf. It takes around five seconds to load package, plot, and save to pdf. A simple 2-D plot with the help of Gaston is shown below − julia> x = 0:0.01:1 0.0:0.01:1.0 julia> plot(x, sin.(2π*5*t)) Now, we can add another curve as follows − julia> plot!(x, cos.(2π*5*t)) PyPlot can also be used to plot 3-d plots. Example is given below: julia> a = b = -10:0.30:10 -10.0:0.3:9.8 julia> surf(a, b, (a,b)->sin.(sqrt.(a.*a+b.*b))./sqrt.(a.*a+b.*b), title="Sombrero", plotstyle="pm3d") PGFPlots, unlike Gaston, is relatively a new package for plotting. This plotting package uses the pgfplots LaTex routines to produce the plots. It can easily integrate with IJulia, outputting SVG images to notebook. To work with it, we need to install the following dependencies − Pdf2svg, which is required by TikzPictures. Pdf2svg, which is required by TikzPictures. Pgfplots, which you can install using latex package manager. Pgfplots, which you can install using latex package manager. GNUPlot, which you need to plot contours GNUPlot, which you need to plot contours Once you are done with these installations, you are ready to use PGFPlots. In this example, we will be generating multiple curves on the same axis and assign their legend entries in LaTex format − julia> using PGFPlots julia> R = Axis( [ Plots.Linear(x->sin(3x)*exp(-0.3x), (0,8), legendentry = L"$\sin(3x)*exp(-0.3x)$"), Plots.Linear(x->sqrt(x)/(1+x^2), (0,8), legendentry = L"$\sqrt{2x}/(1+x^2)$") ]); julia> save("Plot_LinearPGF.svg", R); 73 Lectures 4 hours Lemuel Ogbunude 24 Lectures 3 hours Mohammad Nauman 29 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2201, "s": 2078, "text": "This chapter discusses how to plot, visualize and perform other (graphic) operations on data using various tools in Julia." }, { "code": null, "e": 2450, "s": 2201, "text": "Cairo, a 2D graphics library, implements a device context to the display system. It works with Linux, Windows, OS X and can create disk files in PDF, PostScript, and SVG formats also. The Julia file of Cairo i.e. Cairo.jl is authentic to its C API." }, { "code": null, "e": 2495, "s": 2450, "text": "The following is an example to draw a line −" }, { "code": null, "e": 2531, "s": 2495, "text": "First, we will create a cr context." }, { "code": null, "e": 2682, "s": 2531, "text": "julia> using Cairo\n\njulia> img = CairoRGBSurface(512, 128);\n\njulia> img = CairoRGBSurface(512, 128);\n\njulia> cr = CairoContext(img);\n\njulia> save(cr);" }, { "code": null, "e": 2713, "s": 2682, "text": "Now, we will add a rectangle −" }, { "code": null, "e": 2859, "s": 2713, "text": "julia> set_source_rgb(cr, 0.5, 0.5, 0.5);\n\njulia> rectangle(cr, 0.0, 0.0, 512.0, 128.0);\n\njulia> fill(cr);\n\njulia> restore(cr);\n\njulia> save(cr);" }, { "code": null, "e": 2929, "s": 2859, "text": "Now, we will define the points and draw a line through those points −" }, { "code": null, "e": 3195, "s": 2929, "text": "julia> x0=61.2; y0=74.0;\n\njulia> x1=214.8; y1=125.4;\n\njulia> x2=317.2; y2=22.8;\n\njulia> x3=470.8; y3=74.0;\n\njulia> move_to(cr, x0, y0);\n\njulia> curve_to(cr, x1, y1, x2, y2, x3, y3);\n\njulia> set_line_width(cr, 10.0);\n\njulia> stroke_preserve(cr);\n\njulia> restore(cr);" }, { "code": null, "e": 3249, "s": 3195, "text": "Finally, writing the resulting graphics to the disk −" }, { "code": null, "e": 3397, "s": 3249, "text": "julia> move_to(cr, 12.0, 12.0);\n\njulia> set_source_rgb(cr, 0, 0, 0);\n\njulia> show_text(cr,\"Line_Figure\")\n\njulia> write_to_png(c,\"Line_Figure.png\");" }, { "code": null, "e": 3496, "s": 3397, "text": "Winston is also a 2D graphics library. It resembles the built-in graphics available within MATLAB." }, { "code": null, "e": 3896, "s": 3496, "text": "julia> x = range(0, stop=3pi, length=100);\n\njulia> c = cos.(x);\n\njulia> s = sin.(x);\n\njulia> p = FramedPlot(\n title=\"Winston Graphics!\",\n xlabel=\"\\\\Sigma x^2_i\",\n ylabel=\"\\\\Theta_i\")\n \njulia> add(p, FillBetween(x, c, x, s))\n\njulia> add(p, Curve(x, c, color=\"black\"))\n\njulia> add(p, Curve(x, s, color=\"red\"))" }, { "code": null, "e": 4041, "s": 3896, "text": "Data visualization may be defined as the presentation of data in a variety of graphical as well as pictorial formats such as pie and bar charts." }, { "code": null, "e": 4286, "s": 4041, "text": "Gadfly is a powerful Julia package for data visualization and an implementation of the “grammar of graphics” style. It is based on the same principal as ggplot2 in R. For using it, we need to first add it with the help of Julia package manager." }, { "code": null, "e": 4436, "s": 4286, "text": "To use Gadfly, we first need to use RDatasets package so that we can get some datasets to work with. In this example, we will be using iris dataset −" }, { "code": null, "e": 5500, "s": 4436, "text": "julia> using Gadfly\n\njulia> using RDatasets\n\njulia> iris = dataset(\"datasets\", \"iris\");\n\njulia> first(iris,10)\n10×5 DataFrame\n│ Row │ SepalLength │ SepalWidth │ PetalLength │ PetalWidth │ Species │\n│ │ Float64 │ Float64 │ Float64 │ Float64 │ Cat... │\n├─────┼─────────────┼────────────┼─────────────┼────────────┼─────────┤\n│ 1 │ 5.1 │ 3.5 │ 1.4 │ 0.2 │ setosa │\n│ 2 │ 4.9 │ 3.0 │ 1.4 │ 0.2 │ setosa │\n│ 3 │ 4.7 │ 3.2 │ 1.3 │ 0.2 │ setosa │\n│ 4 │ 4.6 │ 3.1 │ 1.5 │ 0.2 │ setosa │\n│ 5 │ 5.0 │ 3.6 │ 1.4 │ 0.2 │ setosa │\n│ 6 │ 5.4 │ 3.9 │ 1.7 │ 0.4 │ setosa │\n│ 7 │ 4.6 │ 3.4 │ 1.4 │ 0.3 │ setosa │\n│ 8 │ 5.0 │ 3.4 │ 1.5 │ 0.2 │ setosa │\n│ 9 │ 4.4 │ 2.9 │ 1.4 │ 0.2 │ setosa │\n│ 10 │ 4.9 │ 3.1 │ 1.5 │ 0.1 │ setosa │" }, { "code": null, "e": 5674, "s": 5500, "text": "Now let us plot a scatter plot. We will be using the variables namely SepalLength and SepalWidth. For this, we need to set the geometry element using Geom.point as follows −" }, { "code": null, "e": 5746, "s": 5674, "text": "julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, Geom.point)" }, { "code": null, "e": 5840, "s": 5746, "text": "Similarly we can add some more geometries like geom.line to produce more layers in the plot −" }, { "code": null, "e": 5923, "s": 5840, "text": "julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, Geom.point, Geom.line)" }, { "code": null, "e": 5982, "s": 5923, "text": "We can also set the color of keyword argument as follows −" }, { "code": null, "e": 6072, "s": 5982, "text": "julia> Gadfly.plot(iris, x = :SepalLength, y = :SepalWidth, color = :Species, Geom.point)" }, { "code": null, "e": 6298, "s": 6072, "text": "Compose is a declarative vector graphics system. It is also written by Daniel Jones as a part of the Gadfly system. In Compose, the graphics are defined using a tree structure and the primitives can be classified as follows −" }, { "code": null, "e": 6340, "s": 6298, "text": "Context − It represents an internal node." }, { "code": null, "e": 6382, "s": 6340, "text": "Context − It represents an internal node." }, { "code": null, "e": 6469, "s": 6382, "text": "Form − It represents a leaf node which defines some geometry such as a circle or line." }, { "code": null, "e": 6556, "s": 6469, "text": "Form − It represents a leaf node which defines some geometry such as a circle or line." }, { "code": null, "e": 6682, "s": 6556, "text": "Property − It represents a leaf node that modifies how its parent’s subtree is drawn. For example, fill color and line width." }, { "code": null, "e": 6808, "s": 6682, "text": "Property − It represents a leaf node that modifies how its parent’s subtree is drawn. For example, fill color and line width." }, { "code": null, "e": 6887, "s": 6808, "text": "Compose(x,y) − It returns a new tree rooted at x and with y attached as child." }, { "code": null, "e": 6966, "s": 6887, "text": "Compose(x,y) − It returns a new tree rooted at x and with y attached as child." }, { "code": null, "e": 7011, "s": 6966, "text": "The below example will draw a simple image −" }, { "code": null, "e": 7166, "s": 7011, "text": "julia> using Compose\n\njulia> composition = compose(compose(context(), rectangle()), fill(\"tomato\"))\n\njulia> draw(SVG(\"simple.svg\", 6cm, 6cm), composition)" }, { "code": null, "e": 7238, "s": 7166, "text": "Now let us form more complex trees by grouping subtrees with brackets −" }, { "code": null, "e": 7430, "s": 7238, "text": "julia> composition = compose(context(),\n (context(), circle(), fill(\"bisque\")),\n (context(), rectangle(), fill(\"tomato\")))\njulia> composition |> SVG(\"simple2.svg\")" }, { "code": null, "e": 7503, "s": 7430, "text": "In this section, we shall discuss various graphic engines used in Julia." }, { "code": null, "e": 7769, "s": 7503, "text": "PyPlot, arose from the previous development of the PyCall module, provides a Julia interface to the Matplotlib plotting library from Python. It uses the PyCall package to call Matplotlib directly from Julia. To work with PytPlot, we need to do the following setup −" }, { "code": null, "e": 7872, "s": 7769, "text": "julia> using Pkg\n\njulia> pkg\"up; add PyPlot Conda\"\n\njulia> using Conda\n\njulia> Conda.add(\"matplotlib\")" }, { "code": null, "e": 8022, "s": 7872, "text": "Once you are done with this setup, you can simply import PyPlot by using PyPlot command. It will let you make calling functions in matplotlib.pyplot." }, { "code": null, "e": 8111, "s": 8022, "text": "This example, from PyPlot documentation, will create a sinusoidally modulated sinusoid −" }, { "code": null, "e": 8497, "s": 8111, "text": "julia> using PyPlot\n\njulia> x = range(0; stop=2*pi, length=500);\n\njulia> y = sin.(3 * x + 4 * cos.(2 * x));\n\njulia> plot(x, y, color=\"blue\", linewidth=1.0, linestyle=\"--\")\n\n1-element Array{PyCall.PyObject,1}:\nPyObject <matplotlib.lines.Line2D object at 0x00000000323405E0>\n\njulia> title(\"A sinusoidally modulated sinusoid\")\n\nPyObject Text(0.5, 1.0, 'A sinusoidally modulated sinusoid')" }, { "code": null, "e": 8750, "s": 8497, "text": "The PyPlot package can also be used for 3d plotting and for this it can import functions from Matplotlib’s mplot3d toolkit. We can create 3d plots directly also by calling some corresponding methods such as bar3d, plot_surface, plot3d, etc., of Axes3d." }, { "code": null, "e": 8810, "s": 8750, "text": "For example, we can plot a random surface mesh as follows −" }, { "code": null, "e": 8920, "s": 8810, "text": "julia> surf(rand(20,30))\n\nPyObject <mpl_toolkits.mplot3d.art3d.Poly3DCollection object at 0x00000000019BD550>" }, { "code": null, "e": 9023, "s": 8920, "text": "Gaston is another useful package for plotting. This plotting package provides an interface to gnuplot." }, { "code": null, "e": 9071, "s": 9023, "text": "Some of the features of Gaston are as follows −" }, { "code": null, "e": 9183, "s": 9071, "text": "It can plot using graphical windows, and with mouse interaction, it can keep multiple plots active at one time." }, { "code": null, "e": 9295, "s": 9183, "text": "It can plot using graphical windows, and with mouse interaction, it can keep multiple plots active at one time." }, { "code": null, "e": 9329, "s": 9295, "text": "It can plot directly to the REPL." }, { "code": null, "e": 9363, "s": 9329, "text": "It can plot directly to the REPL." }, { "code": null, "e": 9401, "s": 9363, "text": "It can also plot in Jupyter and Juno." }, { "code": null, "e": 9439, "s": 9401, "text": "It can also plot in Jupyter and Juno." }, { "code": null, "e": 9516, "s": 9439, "text": "It supports popular 2-dimensional plots such as stem, step, histograms, etc." }, { "code": null, "e": 9593, "s": 9516, "text": "It supports popular 2-dimensional plots such as stem, step, histograms, etc." }, { "code": null, "e": 9677, "s": 9593, "text": "It also supports popular 3-dimensional plots such as surface, contour, and heatmap." }, { "code": null, "e": 9761, "s": 9677, "text": "It also supports popular 3-dimensional plots such as surface, contour, and heatmap." }, { "code": null, "e": 9830, "s": 9761, "text": "It takes around five seconds to load package, plot, and save to pdf." }, { "code": null, "e": 9899, "s": 9830, "text": "It takes around five seconds to load package, plot, and save to pdf." }, { "code": null, "e": 9958, "s": 9899, "text": "A simple 2-D plot with the help of Gaston is shown below −" }, { "code": null, "e": 10020, "s": 9958, "text": "julia> x = 0:0.01:1\n0.0:0.01:1.0\njulia> plot(x, sin.(2π*5*t))" }, { "code": null, "e": 10063, "s": 10020, "text": "Now, we can add another curve as follows −" }, { "code": null, "e": 10093, "s": 10063, "text": "julia> plot!(x, cos.(2π*5*t))" }, { "code": null, "e": 10313, "s": 10093, "text": "PyPlot can also be used to plot 3-d plots. Example is given below:\njulia> a = b = -10:0.30:10\n-10.0:0.3:9.8\njulia> surf(a, b, (a,b)->sin.(sqrt.(a.*a+b.*b))./sqrt.(a.*a+b.*b),\n title=\"Sombrero\", plotstyle=\"pm3d\")" }, { "code": null, "e": 10594, "s": 10313, "text": "PGFPlots, unlike Gaston, is relatively a new package for plotting. This plotting package uses the pgfplots LaTex routines to produce the plots. It can easily integrate with IJulia, outputting SVG images to notebook. To work with it, we need to install the following dependencies −" }, { "code": null, "e": 10638, "s": 10594, "text": "Pdf2svg, which is required by TikzPictures." }, { "code": null, "e": 10682, "s": 10638, "text": "Pdf2svg, which is required by TikzPictures." }, { "code": null, "e": 10743, "s": 10682, "text": "Pgfplots, which you can install using latex package manager." }, { "code": null, "e": 10804, "s": 10743, "text": "Pgfplots, which you can install using latex package manager." }, { "code": null, "e": 10845, "s": 10804, "text": "GNUPlot, which you need to plot contours" }, { "code": null, "e": 10886, "s": 10845, "text": "GNUPlot, which you need to plot contours" }, { "code": null, "e": 10961, "s": 10886, "text": "Once you are done with these installations, you are ready to use PGFPlots." }, { "code": null, "e": 11083, "s": 10961, "text": "In this example, we will be generating multiple curves on the same axis and assign their legend entries in LaTex format −" }, { "code": null, "e": 11354, "s": 11083, "text": "julia> using PGFPlots\n\njulia> R = Axis( [ Plots.Linear(x->sin(3x)*exp(-0.3x), (0,8),\n legendentry = L\"$\\sin(3x)*exp(-0.3x)$\"),\n Plots.Linear(x->sqrt(x)/(1+x^2), (0,8),\n legendentry = L\"$\\sqrt{2x}/(1+x^2)$\") ]);\n \njulia> save(\"Plot_LinearPGF.svg\", R);" }, { "code": null, "e": 11387, "s": 11354, "text": "\n 73 Lectures \n 4 hours \n" }, { "code": null, "e": 11404, "s": 11387, "text": " Lemuel Ogbunude" }, { "code": null, "e": 11437, "s": 11404, "text": "\n 24 Lectures \n 3 hours \n" }, { "code": null, "e": 11454, "s": 11437, "text": " Mohammad Nauman" }, { "code": null, "e": 11489, "s": 11454, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11512, "s": 11489, "text": " Stone River ELearning" }, { "code": null, "e": 11519, "s": 11512, "text": " Print" }, { "code": null, "e": 11530, "s": 11519, "text": " Add Notes" } ]
Develop a Slack-bot using Golang. Learn how to build a Slack bot in... | by Percy Bolmér | Towards Data Science
Slack is a communication tool used by developers and companies to share information and communicate. It has grown very popular in recent years. In this article, we will cover how to set up and build a bot that can interact with the Slack workspace and channels. We will look into how to create slash commands and visualized requests such as buttons. The bot application will be sending requests to a Go backend via Websocket, something called Socket-Mode in the slack world. If you don’t already have a workspace to use, make sure to create a new one by visiting slack and press Create a new Workspace. Go ahead and fill all the forms, you will need to provide a name for the team or company, a new channel name, and eventually invite other teammates. The first thing we need to do is to create the Slack application. Visit the slack website to create the application. Select the From scratch option. You will be presented with the option to add a Name to the application and the Workspace to allow the application to be used. You should be able to see all workspaces that you are connected to. Select the appropriate workspace. There are many different use cases for an Application. You will be asked to select what features to add, we will create a bot so select the Bot option. After clicking Bots you will be redirected to a Help information page, select the option to add scopes. The first thing we need to add to the application is the actual permissions to perform anything. After pressing Review Scopes to Add, scroll down to Bot scopes and start adding the 4 scopes I’ve added. The explanation of the scopes is present in the image. After adding the scopes we are ready to install the application. If you’re the owner of the application you can simply install it, otherwise, like in my case, I have to request permission from an Admin. If you can Install or are allowed to install you will see yet another screen with information, select the appropriate channels the bot can use to post on as an application. Once you click Allow you will see long strings, one OAuth token, and one Webhook URL. Remember the location of these, or save them on another safe storage. Open your slack client and log in to the workspace. We need to invite the Application into a channel that we want him to be available in. I’ve used a channel named percybot. Go there and start typing a command message which is done by starting the message with /. We can invite the bot by typing /invite @NameOfYourbot. Now that we have the Slack application up and the authentication token we can start communicating with the Slack channel. We will be using go-slack which is a library that supports the regular REST API, WebSockets, RTM, and Events. We will also use godotenv to read environment variables. Let’s create a new golang package and download it. mkdir slack-botcd slack-botgo mod init programmingpercy/slack-botgo get -u github.com/slack-go/slackgo get -u github.com/joho/godotenv First of all, we will create a .env file that can be used to store your secret token. We will also store a channel ID here. You can find the Token in the web UI where you created the application, the channel can be found in the UI if you select the channel and go to Get channel details by pressing the carrot arrow. Create main.go so we can start coding. We will begin by simply connecting to the workspace and posting a simple message to make sure everything is working. We will use godotenv to read in the .env file. Then create a Slack Attachment, which is a message that is sent to the channel. What’s important to understand is that the Slack package leverages a pattern where most functions take a Configuration slice. What this means is that there are Option functions that can be added in each request, and a variable amount. We will also add some Fields to the message which can be used to send extra contextual data. Execute the program by running the main function, you should then see a new message in the slack channel. go run main.go The slack events API is a way to handle events that occur in the Slack channels. There are many events, but for our bot, we want to listen to the mentions event. This means that whenever somebody mentions the bot it will receive an Event to trigger on. The events are delivered via WebSocket. You can find all the event types available in the documentation. The first thing you need to do is attend your Application in the web UI. We will activate something called Socket Mode, this allows the bot to connect via WebSocket. The alternative is to have the bot host a public endpoint, but then you need a domain to host on. Then we also need to add Event Subscriptions. You can find it in the Features tab, enter it, and activate it. Then add the app_mentions scope to the Event subscriptions. This will make mentions trigger a new event to the application The final thing we need to do is generate an Application token. Right now we only have a Bot token, but for the Events, we need an Application token. Go into Settings->Basic Information and scroll down to the chapter called App-Level Tokens and press Generate Tokens and Scope and fill in a name for your Token. I’ve added the connections:write scope to that token, make sure you save the Token as well by adding it to the .env file as SLACK_APP_TOKEN. To use Socket Mode we also need to get a sub package of slack-go which is called socket mode. go get github.com/slack-go/slack/socketmode The slack package will need to create a new Client for the socket mode, so we will have two clients. One that uses the regular API and one for the websocket events. Let’s begin by connecting to make sure all permissions are correct. Notice how the Websocket client is created by calling socketmode.New and given the regular client as input. I’ve also added a OptionAppLevelToken to the creation of the regular client since that is now needed to connect to the Socket. Make sure to run the program and verify the output that is connected, there will be a ping hello sent. It’s time to start selecting all events to listen for. At the end of the program, we call socketClient.Run() which will be blocking and ingesting new Websocket messages on a channel at socketClient.Events. So we can use a for loop to continuously wait for new events, also the slack-go library comes with predefined Event types, so we can use a type switch to handle different types of Events easily. All events can be found here. Since socketClient.Run() is blocking, we will spawn a goroutine that handles incoming messages in the background. We will begin by simply logging in whenever an Event on the EventAPI is triggered in Slack. Since we first need to type switch the message on the websocket if it’s an EventsAPI type, then switch again based on the actual Event that occurred we will break the Event handling out into a separate function to avoid deeply nested switches. If you want to test it, run the program and then enter Slack and mention by bot by using @yourbotname. go run main.go You should be able to see the Event being logged in the command line running the bot. Look at the Event printed and you will understand why we need to use multiple type switches. The event we get is of the type event_callback, and that event contains a payload with the actual event that was performed. So first we need to test if it’s a Callback event and then if it’s an app_mention payload event. Let’s implement the handleEventMessage that will continue the type switching. We can use the type field to know how to handle the Event. Then we can reach the payload event by using the InnerEvent field. Replace the previous log in the main function that printed the event with the new handleEventMessage function instead. Now logging the event does not make a fun bot. We should make the bot respond to the user who mentioned him and if they said hello it should also greet them. Begin by logging into the application and adding the users:read scope to the bot token. I trust you to make that without guidance now, or go back and read how we did before. Once that’s done we will create the handleAppMentionEvent function. This function will take a *slackevents.AppMentionEvent and a slack.Client as input so it can respond. The event does contain the user ID in the event.User so we can use that ID to grab user information. The channel to respond to is also available in the event.Channel. The final piece of information we need is the actual message the user sent when mentioning, which is found in the event.Text. To begin using this function we need to add the Client as an input parameter as well. So we have to update handleEventMessage to accept it. Restart the program and try saying Hello and also saying something else to see that it works as expected. If you get a “missing_scope” error you have missed some scope. Here is the output of my currently running bot It’s time to move forward and looking at how to add Slash commands. Most commonly I’ve seen slash commands being used by Slack bots. What this means is you can type /send a special command. There are many built-in commands such as /call which allows you to start a call etc. We will be adding a custom command which will be /hello. When this command is triggered we will make the bot send a greetings message. Again, you need to add the command in the web UI. Visit the website and select the Slash Command in the features tab. We will make a command that accepts a single parameter which is the username to greet. Fill in the fields asked for, note that we are using socket-mode so we don’t need to provide a request URL. Don’t forget to reinstall the application after we have added the command. This is needed since we have changed the application. If you have forgotten how then revisit the earlier part of the article where we installed the application. You can verify that everything has been installed by opening up the slack and the channel where the application is invited and type the /hello command. That was easy enough, let’s also redo what we did with the EventsAPI, but this time we will add a type switch for EventTypeSlashCommand. We will find the command called in the SlashCommand.Command and the input text in SlashCommand.Text. So we will first route the command based on the input of the command and then return greetings to the text field. Begin by updating the main.go file to include the listener for the new type of message events on the websocket. Do not forget to send the Acknowledgement, or else you will see an error message in slack that the message was not dispatched properly. We will have a router function called handleSlashCommand which will simply redirect to another function. This might seem overkill for now, but if you plan to add more functions it’s easier to make multiple small functions. Especially if you are using unit tests. The actual response will come from handleHelloCommand which will simply take the username set after the /hello command and send a greeting in the channel. Restart the program and try sending a command from the slack client. When I input /hello reader I see the following output. We will look at how we can implement a slash command which triggers the bot to ask a question that we can answer with a Yes and No button. Begin by adding the new command in the Slack web UI so we can trigger it. We will make a small change to the main function first, In the type switch that accepts the Slash commands events, we currently acknowledge before we process the message. We will change this and return the response in the Acknowledge since this is possible. Now you will see how easily we can add new commands, all we need to do is add a new case option in handleSlashCommand to check for. Of course, we need to handle the actual command as well, but the structure is easily scaled. We will update handleSlashCommand so that it returns an interface{} also. This is the payload response that will be included in the acknowledgment. We will route to a function called handleIsArticleGood that will trigger a two-button questionnaire to the user using something called Block-Kit. It’s a Slack implementation that allows us to send HTML components. There are a ton of options and components to send, but let’s stick to buttons for now. The blocks are added to the slack.Attachment that we used previously to send simple messages. It has a field called Blocks which accepts an array of blocks to send. Each block is a visual component to send. We will be using a Section block, and the Slack library helps us create one using the NewSectionBlock() which will accept a few parameters. The first parameter is a slack.TextBlockObject which is a standard way of sending text contains the type to use, in which we will use markdown. It also contains the value to display in the text block. The second parameter is fields to add, such as we used before to add contextual data, let’s leave it as nil. The third parameter is a slack.Accessory which a container for a block element, you can find the JSON layout in the slack documentation. We will add a Checkbox element to the Accessory, which contains two options, [Yes, No]. Remember that we simply return the response, in this case, we don’t send it as in the hello handler. Notice the answer in the CheckBoxGroupsBlockElement, this is the action that is used to identify what kind of interaction was performed. Restart your bot and try executing the command in slack. When you select something nothing will happen since we don’t accept the response in the backend yet. The response is will trigger an InteractionEvent, so if we want to accept the response we need to listen for this event in the main function. The process is the same as before, typecast into the correct message type. In this case, it’s an InteractionCallback. We will add a handleInteractionEvent that will simply print information about the interaction and the selected option. Try executing the command, and select an option. We have covered most of the items needed to get started with building your bot. We have covered these topics How to set up a Slack-Bot application Connecting to the application from a Golang service Listening for bot mentions in a channel Adding slash commands to the bot Using the Slack Events API Sending visualized blocks to Slack Listening for User interactions This is it for this time, hopefully you have enjoyed the article. As always feel free to reach out and give me feedback or questions. Now go out there and build some bots!
[ { "code": null, "e": 316, "s": 172, "text": "Slack is a communication tool used by developers and companies to share information and communicate. It has grown very popular in recent years." }, { "code": null, "e": 647, "s": 316, "text": "In this article, we will cover how to set up and build a bot that can interact with the Slack workspace and channels. We will look into how to create slash commands and visualized requests such as buttons. The bot application will be sending requests to a Go backend via Websocket, something called Socket-Mode in the slack world." }, { "code": null, "e": 775, "s": 647, "text": "If you don’t already have a workspace to use, make sure to create a new one by visiting slack and press Create a new Workspace." }, { "code": null, "e": 924, "s": 775, "text": "Go ahead and fill all the forms, you will need to provide a name for the team or company, a new channel name, and eventually invite other teammates." }, { "code": null, "e": 1073, "s": 924, "text": "The first thing we need to do is to create the Slack application. Visit the slack website to create the application. Select the From scratch option." }, { "code": null, "e": 1301, "s": 1073, "text": "You will be presented with the option to add a Name to the application and the Workspace to allow the application to be used. You should be able to see all workspaces that you are connected to. Select the appropriate workspace." }, { "code": null, "e": 1453, "s": 1301, "text": "There are many different use cases for an Application. You will be asked to select what features to add, we will create a bot so select the Bot option." }, { "code": null, "e": 1654, "s": 1453, "text": "After clicking Bots you will be redirected to a Help information page, select the option to add scopes. The first thing we need to add to the application is the actual permissions to perform anything." }, { "code": null, "e": 1814, "s": 1654, "text": "After pressing Review Scopes to Add, scroll down to Bot scopes and start adding the 4 scopes I’ve added. The explanation of the scopes is present in the image." }, { "code": null, "e": 2017, "s": 1814, "text": "After adding the scopes we are ready to install the application. If you’re the owner of the application you can simply install it, otherwise, like in my case, I have to request permission from an Admin." }, { "code": null, "e": 2190, "s": 2017, "text": "If you can Install or are allowed to install you will see yet another screen with information, select the appropriate channels the bot can use to post on as an application." }, { "code": null, "e": 2346, "s": 2190, "text": "Once you click Allow you will see long strings, one OAuth token, and one Webhook URL. Remember the location of these, or save them on another safe storage." }, { "code": null, "e": 2666, "s": 2346, "text": "Open your slack client and log in to the workspace. We need to invite the Application into a channel that we want him to be available in. I’ve used a channel named percybot. Go there and start typing a command message which is done by starting the message with /. We can invite the bot by typing /invite @NameOfYourbot." }, { "code": null, "e": 2788, "s": 2666, "text": "Now that we have the Slack application up and the authentication token we can start communicating with the Slack channel." }, { "code": null, "e": 2955, "s": 2788, "text": "We will be using go-slack which is a library that supports the regular REST API, WebSockets, RTM, and Events. We will also use godotenv to read environment variables." }, { "code": null, "e": 3006, "s": 2955, "text": "Let’s create a new golang package and download it." }, { "code": null, "e": 3141, "s": 3006, "text": "mkdir slack-botcd slack-botgo mod init programmingpercy/slack-botgo get -u github.com/slack-go/slackgo get -u github.com/joho/godotenv" }, { "code": null, "e": 3458, "s": 3141, "text": "First of all, we will create a .env file that can be used to store your secret token. We will also store a channel ID here. You can find the Token in the web UI where you created the application, the channel can be found in the UI if you select the channel and go to Get channel details by pressing the carrot arrow." }, { "code": null, "e": 3614, "s": 3458, "text": "Create main.go so we can start coding. We will begin by simply connecting to the workspace and posting a simple message to make sure everything is working." }, { "code": null, "e": 3976, "s": 3614, "text": "We will use godotenv to read in the .env file. Then create a Slack Attachment, which is a message that is sent to the channel. What’s important to understand is that the Slack package leverages a pattern where most functions take a Configuration slice. What this means is that there are Option functions that can be added in each request, and a variable amount." }, { "code": null, "e": 4069, "s": 3976, "text": "We will also add some Fields to the message which can be used to send extra contextual data." }, { "code": null, "e": 4175, "s": 4069, "text": "Execute the program by running the main function, you should then see a new message in the slack channel." }, { "code": null, "e": 4190, "s": 4175, "text": "go run main.go" }, { "code": null, "e": 4483, "s": 4190, "text": "The slack events API is a way to handle events that occur in the Slack channels. There are many events, but for our bot, we want to listen to the mentions event. This means that whenever somebody mentions the bot it will receive an Event to trigger on. The events are delivered via WebSocket." }, { "code": null, "e": 4548, "s": 4483, "text": "You can find all the event types available in the documentation." }, { "code": null, "e": 4621, "s": 4548, "text": "The first thing you need to do is attend your Application in the web UI." }, { "code": null, "e": 4812, "s": 4621, "text": "We will activate something called Socket Mode, this allows the bot to connect via WebSocket. The alternative is to have the bot host a public endpoint, but then you need a domain to host on." }, { "code": null, "e": 5045, "s": 4812, "text": "Then we also need to add Event Subscriptions. You can find it in the Features tab, enter it, and activate it. Then add the app_mentions scope to the Event subscriptions. This will make mentions trigger a new event to the application" }, { "code": null, "e": 5195, "s": 5045, "text": "The final thing we need to do is generate an Application token. Right now we only have a Bot token, but for the Events, we need an Application token." }, { "code": null, "e": 5357, "s": 5195, "text": "Go into Settings->Basic Information and scroll down to the chapter called App-Level Tokens and press Generate Tokens and Scope and fill in a name for your Token." }, { "code": null, "e": 5498, "s": 5357, "text": "I’ve added the connections:write scope to that token, make sure you save the Token as well by adding it to the .env file as SLACK_APP_TOKEN." }, { "code": null, "e": 5592, "s": 5498, "text": "To use Socket Mode we also need to get a sub package of slack-go which is called socket mode." }, { "code": null, "e": 5636, "s": 5592, "text": "go get github.com/slack-go/slack/socketmode" }, { "code": null, "e": 6104, "s": 5636, "text": "The slack package will need to create a new Client for the socket mode, so we will have two clients. One that uses the regular API and one for the websocket events. Let’s begin by connecting to make sure all permissions are correct. Notice how the Websocket client is created by calling socketmode.New and given the regular client as input. I’ve also added a OptionAppLevelToken to the creation of the regular client since that is now needed to connect to the Socket." }, { "code": null, "e": 6207, "s": 6104, "text": "Make sure to run the program and verify the output that is connected, there will be a ping hello sent." }, { "code": null, "e": 6638, "s": 6207, "text": "It’s time to start selecting all events to listen for. At the end of the program, we call socketClient.Run() which will be blocking and ingesting new Websocket messages on a channel at socketClient.Events. So we can use a for loop to continuously wait for new events, also the slack-go library comes with predefined Event types, so we can use a type switch to handle different types of Events easily. All events can be found here." }, { "code": null, "e": 6752, "s": 6638, "text": "Since socketClient.Run() is blocking, we will spawn a goroutine that handles incoming messages in the background." }, { "code": null, "e": 7088, "s": 6752, "text": "We will begin by simply logging in whenever an Event on the EventAPI is triggered in Slack. Since we first need to type switch the message on the websocket if it’s an EventsAPI type, then switch again based on the actual Event that occurred we will break the Event handling out into a separate function to avoid deeply nested switches." }, { "code": null, "e": 7191, "s": 7088, "text": "If you want to test it, run the program and then enter Slack and mention by bot by using @yourbotname." }, { "code": null, "e": 7206, "s": 7191, "text": "go run main.go" }, { "code": null, "e": 7292, "s": 7206, "text": "You should be able to see the Event being logged in the command line running the bot." }, { "code": null, "e": 7509, "s": 7292, "text": "Look at the Event printed and you will understand why we need to use multiple type switches. The event we get is of the type event_callback, and that event contains a payload with the actual event that was performed." }, { "code": null, "e": 7606, "s": 7509, "text": "So first we need to test if it’s a Callback event and then if it’s an app_mention payload event." }, { "code": null, "e": 7810, "s": 7606, "text": "Let’s implement the handleEventMessage that will continue the type switching. We can use the type field to know how to handle the Event. Then we can reach the payload event by using the InnerEvent field." }, { "code": null, "e": 7929, "s": 7810, "text": "Replace the previous log in the main function that printed the event with the new handleEventMessage function instead." }, { "code": null, "e": 8087, "s": 7929, "text": "Now logging the event does not make a fun bot. We should make the bot respond to the user who mentioned him and if they said hello it should also greet them." }, { "code": null, "e": 8261, "s": 8087, "text": "Begin by logging into the application and adding the users:read scope to the bot token. I trust you to make that without guidance now, or go back and read how we did before." }, { "code": null, "e": 8724, "s": 8261, "text": "Once that’s done we will create the handleAppMentionEvent function. This function will take a *slackevents.AppMentionEvent and a slack.Client as input so it can respond. The event does contain the user ID in the event.User so we can use that ID to grab user information. The channel to respond to is also available in the event.Channel. The final piece of information we need is the actual message the user sent when mentioning, which is found in the event.Text." }, { "code": null, "e": 8864, "s": 8724, "text": "To begin using this function we need to add the Client as an input parameter as well. So we have to update handleEventMessage to accept it." }, { "code": null, "e": 9033, "s": 8864, "text": "Restart the program and try saying Hello and also saying something else to see that it works as expected. If you get a “missing_scope” error you have missed some scope." }, { "code": null, "e": 9080, "s": 9033, "text": "Here is the output of my currently running bot" }, { "code": null, "e": 9148, "s": 9080, "text": "It’s time to move forward and looking at how to add Slash commands." }, { "code": null, "e": 9355, "s": 9148, "text": "Most commonly I’ve seen slash commands being used by Slack bots. What this means is you can type /send a special command. There are many built-in commands such as /call which allows you to start a call etc." }, { "code": null, "e": 9490, "s": 9355, "text": "We will be adding a custom command which will be /hello. When this command is triggered we will make the bot send a greetings message." }, { "code": null, "e": 9608, "s": 9490, "text": "Again, you need to add the command in the web UI. Visit the website and select the Slash Command in the features tab." }, { "code": null, "e": 9695, "s": 9608, "text": "We will make a command that accepts a single parameter which is the username to greet." }, { "code": null, "e": 9803, "s": 9695, "text": "Fill in the fields asked for, note that we are using socket-mode so we don’t need to provide a request URL." }, { "code": null, "e": 10039, "s": 9803, "text": "Don’t forget to reinstall the application after we have added the command. This is needed since we have changed the application. If you have forgotten how then revisit the earlier part of the article where we installed the application." }, { "code": null, "e": 10191, "s": 10039, "text": "You can verify that everything has been installed by opening up the slack and the channel where the application is invited and type the /hello command." }, { "code": null, "e": 10328, "s": 10191, "text": "That was easy enough, let’s also redo what we did with the EventsAPI, but this time we will add a type switch for EventTypeSlashCommand." }, { "code": null, "e": 10543, "s": 10328, "text": "We will find the command called in the SlashCommand.Command and the input text in SlashCommand.Text. So we will first route the command based on the input of the command and then return greetings to the text field." }, { "code": null, "e": 10655, "s": 10543, "text": "Begin by updating the main.go file to include the listener for the new type of message events on the websocket." }, { "code": null, "e": 10791, "s": 10655, "text": "Do not forget to send the Acknowledgement, or else you will see an error message in slack that the message was not dispatched properly." }, { "code": null, "e": 11054, "s": 10791, "text": "We will have a router function called handleSlashCommand which will simply redirect to another function. This might seem overkill for now, but if you plan to add more functions it’s easier to make multiple small functions. Especially if you are using unit tests." }, { "code": null, "e": 11209, "s": 11054, "text": "The actual response will come from handleHelloCommand which will simply take the username set after the /hello command and send a greeting in the channel." }, { "code": null, "e": 11333, "s": 11209, "text": "Restart the program and try sending a command from the slack client. When I input /hello reader I see the following output." }, { "code": null, "e": 11472, "s": 11333, "text": "We will look at how we can implement a slash command which triggers the bot to ask a question that we can answer with a Yes and No button." }, { "code": null, "e": 11546, "s": 11472, "text": "Begin by adding the new command in the Slack web UI so we can trigger it." }, { "code": null, "e": 11804, "s": 11546, "text": "We will make a small change to the main function first, In the type switch that accepts the Slash commands events, we currently acknowledge before we process the message. We will change this and return the response in the Acknowledge since this is possible." }, { "code": null, "e": 12177, "s": 11804, "text": "Now you will see how easily we can add new commands, all we need to do is add a new case option in handleSlashCommand to check for. Of course, we need to handle the actual command as well, but the structure is easily scaled. We will update handleSlashCommand so that it returns an interface{} also. This is the payload response that will be included in the acknowledgment." }, { "code": null, "e": 12478, "s": 12177, "text": "We will route to a function called handleIsArticleGood that will trigger a two-button questionnaire to the user using something called Block-Kit. It’s a Slack implementation that allows us to send HTML components. There are a ton of options and components to send, but let’s stick to buttons for now." }, { "code": null, "e": 12685, "s": 12478, "text": "The blocks are added to the slack.Attachment that we used previously to send simple messages. It has a field called Blocks which accepts an array of blocks to send. Each block is a visual component to send." }, { "code": null, "e": 12825, "s": 12685, "text": "We will be using a Section block, and the Slack library helps us create one using the NewSectionBlock() which will accept a few parameters." }, { "code": null, "e": 13026, "s": 12825, "text": "The first parameter is a slack.TextBlockObject which is a standard way of sending text contains the type to use, in which we will use markdown. It also contains the value to display in the text block." }, { "code": null, "e": 13135, "s": 13026, "text": "The second parameter is fields to add, such as we used before to add contextual data, let’s leave it as nil." }, { "code": null, "e": 13598, "s": 13135, "text": "The third parameter is a slack.Accessory which a container for a block element, you can find the JSON layout in the slack documentation. We will add a Checkbox element to the Accessory, which contains two options, [Yes, No]. Remember that we simply return the response, in this case, we don’t send it as in the hello handler. Notice the answer in the CheckBoxGroupsBlockElement, this is the action that is used to identify what kind of interaction was performed." }, { "code": null, "e": 13655, "s": 13598, "text": "Restart your bot and try executing the command in slack." }, { "code": null, "e": 13898, "s": 13655, "text": "When you select something nothing will happen since we don’t accept the response in the backend yet. The response is will trigger an InteractionEvent, so if we want to accept the response we need to listen for this event in the main function." }, { "code": null, "e": 14016, "s": 13898, "text": "The process is the same as before, typecast into the correct message type. In this case, it’s an InteractionCallback." }, { "code": null, "e": 14135, "s": 14016, "text": "We will add a handleInteractionEvent that will simply print information about the interaction and the selected option." }, { "code": null, "e": 14184, "s": 14135, "text": "Try executing the command, and select an option." }, { "code": null, "e": 14264, "s": 14184, "text": "We have covered most of the items needed to get started with building your bot." }, { "code": null, "e": 14293, "s": 14264, "text": "We have covered these topics" }, { "code": null, "e": 14331, "s": 14293, "text": "How to set up a Slack-Bot application" }, { "code": null, "e": 14383, "s": 14331, "text": "Connecting to the application from a Golang service" }, { "code": null, "e": 14423, "s": 14383, "text": "Listening for bot mentions in a channel" }, { "code": null, "e": 14456, "s": 14423, "text": "Adding slash commands to the bot" }, { "code": null, "e": 14483, "s": 14456, "text": "Using the Slack Events API" }, { "code": null, "e": 14518, "s": 14483, "text": "Sending visualized blocks to Slack" }, { "code": null, "e": 14550, "s": 14518, "text": "Listening for User interactions" }, { "code": null, "e": 14684, "s": 14550, "text": "This is it for this time, hopefully you have enjoyed the article. As always feel free to reach out and give me feedback or questions." } ]
Naive Pattern Searching
Naïve pattern searching is the simplest method among other pattern searching algorithms. It checks for all character of the main string to the pattern. This algorithm is helpful for smaller texts. It does not need any pre-processing phases. We can find substring by checking once for the string. It also does not occupy extra space to perform the operation. The time complexity of Naïve Pattern Search method is O(m*n). The m is the size of pattern and n is the size of the main string. Input: Main String: “ABAAABCDBBABCDDEBCABC”, pattern: “ABC” Output: Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18 naivePatternSearch(pattern, text) Input − The text and the pattern Output − location, where patterns are present in the text Begin patLen := pattern Size strLen := string size for i := 0 to (strLen - patLen), do for j := 0 to patLen, do if text[i+j] ≠ pattern[j], then break the loop done if j == patLen, then display the position i, as there pattern found done End #include<iostream> using namespace std; void naivePatternSearch(string mainString, string pattern, int array[], int *index) { int patLen = pattern.size(); int strLen = mainString.size(); for(int i = 0; i<=(strLen - patLen); i++) { int j; for(j = 0; j<patLen; j++) { //check for each character of pattern if it is matched if(mainString[i+j] != pattern[j]) break; } if(j == patLen) { //the pattern is found (*index)++; array[(*index)] = i; } } } int main() { string mainString = "ABAAABCDBBABCDDEBCABC"; string pattern = "ABC"; int locArray[mainString.size()]; int index = -1; naivePatternSearch(mainString, pattern, locArray, &index); for(int i = 0; i <= index; i++) { cout << "Pattern found at position: " << locArray[i]<<endl; } } Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18
[ { "code": null, "e": 1421, "s": 1062, "text": "Naïve pattern searching is the simplest method among other pattern searching algorithms. It checks for all character of the main string to the pattern. This algorithm is helpful for smaller texts. It does not need any pre-processing phases. We can find substring by checking once for the string. It also does not occupy extra space to perform the operation." }, { "code": null, "e": 1551, "s": 1421, "text": "The time complexity of Naïve Pattern Search method is O(m*n). The m is the size of pattern and n is the size of the main string." }, { "code": null, "e": 1708, "s": 1551, "text": "Input:\nMain String: “ABAAABCDBBABCDDEBCABC”, pattern: “ABC”\nOutput:\nPattern found at position: 4\nPattern found at position: 10\nPattern found at position: 18" }, { "code": null, "e": 1742, "s": 1708, "text": "naivePatternSearch(pattern, text)" }, { "code": null, "e": 1775, "s": 1742, "text": "Input − The text and the pattern" }, { "code": null, "e": 1833, "s": 1775, "text": "Output − location, where patterns are present in the text" }, { "code": null, "e": 2137, "s": 1833, "text": "Begin\n patLen := pattern Size\n strLen := string size\n\n for i := 0 to (strLen - patLen), do\n for j := 0 to patLen, do\n if text[i+j] ≠ pattern[j], then\n break the loop\n done\n\n if j == patLen, then\n display the position i, as there pattern found\n done\nEnd" }, { "code": null, "e": 2991, "s": 2137, "text": "#include<iostream>\nusing namespace std;\n\nvoid naivePatternSearch(string mainString, string pattern, int array[], int *index) {\n int patLen = pattern.size();\n int strLen = mainString.size();\n\n for(int i = 0; i<=(strLen - patLen); i++) {\n int j;\n for(j = 0; j<patLen; j++) { //check for each character of pattern if it is matched\n if(mainString[i+j] != pattern[j])\n break;\n }\n\n if(j == patLen) { //the pattern is found\n (*index)++;\n array[(*index)] = i;\n }\n }\n}\n\nint main() {\n string mainString = \"ABAAABCDBBABCDDEBCABC\";\n string pattern = \"ABC\";\n int locArray[mainString.size()];\n int index = -1;\n naivePatternSearch(mainString, pattern, locArray, &index);\n\n for(int i = 0; i <= index; i++) {\n cout << \"Pattern found at position: \" << locArray[i]<<endl;\n }\n}" }, { "code": null, "e": 3080, "s": 2991, "text": "Pattern found at position: 4\nPattern found at position: 10\nPattern found at position: 18" } ]
Identify your Data’s Distribution | by Abhishek Mungoli | Towards Data Science
Every day we come across a variety of Data like Sensor Data, Sales Data, Customer Data, Traffic Data, etc. Further, depending on the use case, we do a variety of processing and try out several algorithms on it. Have you ever wondered these questions about your Data: What your Data look like? Is there any confidence you can attach to the values it can take? What is the possibility of an extreme value ‘x’ to occur? The algorithm you are applying on it may make some assumption about Data distribution, are those assumptions correct? Can the Data distribution change over time or during special seasons? Data Distribution is a function that lists out all possible values the Data can take. It can be a continuous or discrete Data distribution. Several known standard Probability Distribution functions provide probabilities of occurrence of different possible outcomes in an experiment. Some well-known probability distributions are Normal, Log-Normal, Beta, Gamma, etc. which have a standard form. But, the challenge is the real-world Data may not follow any well-known Probability Distributions. In this case, we can approximate the most probable Probability Distribution and check it’s Goodness of fit. Through this blog post, I intend to highlight the benefits of knowing your Data and approximating its’s Probability distribution. I will also show practical examples of how to do that and measure the Goodness of fit of the fitted distribution to that of the observed. The Dataset used in the blog is Kaggle’s Used Car Dataset. The code used in this blog post can be downloaded from here. It’s a good practice to know your Data once you start working on it. Many Algorithms, like Linear Regression, assumes variables to follow a particular distribution. The cost of not meeting the assumptions could be high at times. Knowing the underlying probability distribution, we can find it’s Probability density function. This helps us in attaching confidence intervals to the range of values Data is likely to take. We can also find the probability of extreme value to occur. Distribution has parameters. With these parameters, we can keep track of how the Distribution has changed over time or during a particular season/event. The standard probability distributions have well known statistical properties that simplify the job for us. We can explain the Data and its behaviour with just a few parameters. For this blog, I will be using the Kaggle Used Car Dataset. We will try to approximate the distributions of various variables and also check its Goodness of fit. I have filtered out a few columns. Let’s have a look at the data : Id: A unique identifier, identifying the vehicle Price: Selling Price of the vehicle Year: Year of Manufacturing Manufacturer: The Brand of the Car Condition: Car’s condition Odometer: Odometer reading denotes the distance traveled The Dataset has 539K records. We will try to identify/approximate the Distribution of ‘price’ and ‘odometer’ variables. Scipy Library of Python allows estimating the parameters of 200+ distributions. Further, the Goodness of fit can be tested by various metrics like Chi-square statistics, Kolmogorov–Smirnov test, QQ plots, etc. As per blog of Adam Hayes, A chi-square (χ2) statistic is a test that measures how expectations compare to actual observed data (or model results). The data used in calculating a chi-square statistic must be random, raw, mutually exclusive, drawn from independent variables, and drawn from a large enough sample. For example, the results of tossing a coin 100 times meet these criteria. [[Source Investopedia]] The formula for chi-square statistics is given as - where c is the degree of freedom, O is the observed value and E is the expected value. Article Link www.investopedia.com Do check out my blog on the Chi-square statistical test to decide on the winner of a Bet. medium.com Commonly known as the K-S Test, it is used to check the Goodness of fit of the observed Distribution with the theoretical Distribution. Here’s a great article on the topic. www.tutorialspoint.com As per Wikipedia, QQ plots is a graphical method for comparing two probability distributions by plotting their quantiles against each other. Here’s an interesting StatQuest video on QQ plots With a good enough refresher, we are all set to our primary task of Distribution fitting. We will try to approximate ‘price’ using the following Distributions and see which performs the best in terms of Chi-square Statistics - dist_names = [‘weibull_min’,’norm’,’weibull_max’,’beta’, ‘invgauss’,’uniform’,’gamma’,’expon’, ‘lognorm’,’pearson3',’triang’] For stable results, I removed extreme outliers (1% data on both ends). Fitting the distributions : Python code using the Scipy Library to fit the Distribution Fitting different Distributions and checking Goodness of fit based on Chi-square Statistics The output sorted in order of Goodness of fit looks like: Top-2 distributions in terms of Goodness of fit are Exponential and Inverse Gaussian Distribution The parameters of the two distributions are : Parameters of Exponential Distribution<scipy.stats._continuous_distns.expon_gen object at 0x12abd2390>(loc = -1.19, scale = 1.19)where Lambda = 1/scaleParameters of Inverse Gaussian Distribution<scipy.stats._continuous_distns.invgauss_gen object at 0x12ac90c50>(mu = 0.45, loc = -1.64, scale = 3.61) The Scipy Library apart of distribution parameters also provides loc and scale parameters. Loc parameters shift the distribution by the appropriate amount and Scale parameters stretches the distribution as required. docs.scipy.org Let’s visualise the Results : fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 5))# Histogram Plot of Observed Dataaxes[0].hist(y)#Exponential Distribution Fittingaxes[1].plot(y,expon.pdf(y_std,-1.19, 1.19))#Inverse-Gaussian Distribution Fittingaxes[2].plot(y,invgauss.pdf(y_std,0.45, -1.64, 3.61))fig.tight_layout() Both the distribution performs fairly good. Exponential Distribution has a slight edge over Inverse-Gaussian. Chi-square statistics also suggests the same. Let’s analyse the QQ plot, as well Both the distributions do fairly well. Exponential is slightly better than Inverse Gaussian in approximating ‘Price’ Data. We will try to approximate ‘odometer’ using the following Distributions and see which performs the best in terms of Chi-square Statistics - dist_names = [‘weibull_min’,’norm’,’weibull_max’,’beta’, ‘invgauss’,’uniform’,’gamma’,’expon’, ‘lognorm’,’pearson3',’triang’] For stable results, I removed extreme outliers (1% data on both ends). Fitting the distributions : Python code using the Scipy Library to fit the Distribution Fitting different Distributions and checking Goodness of fit based on Chi-square Statistics The output sorted in order of Goodness of fit looks like: Top-2 distributions in terms of Goodness of fit are Beta and Triangular Distribution. However, the difference in Chi-square statistics is significantly high and Beta seems to be a clear winner. The parameters of the two distributions are : Parameters of Beta Distribution<scipy.stats._continuous_distns.beta_gen object at 0x12abb72d0>(a = 1.51, b = 2.94, loc = -1.71, scale = 5.02)Parameters of Triangular Distribution<scipy.stats._continuous_distns.triang_gen object at 0x12acf4050>(c = 0.12, loc = -1.79, scale = 4.90) The Scipy Library apart of distribution parameters also provides loc and scale parameters. Loc parameters shift the distribution by the appropriate amount and Scale parameters stretches the distribution as required. docs.scipy.org Let’s visualise the Results : Beta Distribution performs much better than Triangular distribution. Visually its clear and Chi-square statistics also suggests the same. Let’s analyse the QQ plot, as well QQ plot also makes it clear that Beta Distribution approximates the ‘Odometer’ (Distance) Data well. With this blog post, I covered the advantage of knowing Data prior to analysing or applying algorithms on it. Knowing/Approximating the Data’s probability distribution also helps us to use its statistical properties and attach confidence interval to the values it can take. I also covered how to do that using Python and introduced various metrics to check the Goodness of fit. The Kaggle Dataset used can be downloaded from here. The code of the project can be downloaded from here. If you have any doubts or queries, do reach out to me. I will be interested to know if you have some interesting problem to solve and feel that approximating the Data’s Probability distribution can be helpful. My Youtube channel for more content: www.youtube.com About the author-: Abhishek Mungoli is a seasoned Data Scientist with experience in ML field and Computer Science background, spanning over various domains and problem-solving mindset. Excelled in various Machine learning and Optimization problems specific to Retail. Enthusiastic about implementing Machine Learning models at scale and knowledge sharing via blogs, talks, meetups, and papers, etc. My motive always is to simplify the toughest of the things to its most simplified version. I love problem-solving, data science, product development, and scaling solutions. I love to explore new places and working out in my leisure time. Follow me up at Medium, Linkedin or Instagram and check out my previous posts. I welcome feedback and constructive criticism. Some of my blogs - 5 Mistakes every Data Scientist should avoid Decomposing Time Series in a simple & intuitive way How GPU Computing literally saved me at work? Information Theory & KL Divergence Part I and Part II Process Wikipedia Using Apache Spark to Create Spicy Hot Datasets A Semi-Supervised Embedding based Fuzzy Clustering Compare which Machine Learning Model performs Better
[ { "code": null, "e": 438, "s": 171, "text": "Every day we come across a variety of Data like Sensor Data, Sales Data, Customer Data, Traffic Data, etc. Further, depending on the use case, we do a variety of processing and try out several algorithms on it. Have you ever wondered these questions about your Data:" }, { "code": null, "e": 464, "s": 438, "text": "What your Data look like?" }, { "code": null, "e": 588, "s": 464, "text": "Is there any confidence you can attach to the values it can take? What is the possibility of an extreme value ‘x’ to occur?" }, { "code": null, "e": 706, "s": 588, "text": "The algorithm you are applying on it may make some assumption about Data distribution, are those assumptions correct?" }, { "code": null, "e": 776, "s": 706, "text": "Can the Data distribution change over time or during special seasons?" }, { "code": null, "e": 1171, "s": 776, "text": "Data Distribution is a function that lists out all possible values the Data can take. It can be a continuous or discrete Data distribution. Several known standard Probability Distribution functions provide probabilities of occurrence of different possible outcomes in an experiment. Some well-known probability distributions are Normal, Log-Normal, Beta, Gamma, etc. which have a standard form." }, { "code": null, "e": 1378, "s": 1171, "text": "But, the challenge is the real-world Data may not follow any well-known Probability Distributions. In this case, we can approximate the most probable Probability Distribution and check it’s Goodness of fit." }, { "code": null, "e": 1766, "s": 1378, "text": "Through this blog post, I intend to highlight the benefits of knowing your Data and approximating its’s Probability distribution. I will also show practical examples of how to do that and measure the Goodness of fit of the fitted distribution to that of the observed. The Dataset used in the blog is Kaggle’s Used Car Dataset. The code used in this blog post can be downloaded from here." }, { "code": null, "e": 1995, "s": 1766, "text": "It’s a good practice to know your Data once you start working on it. Many Algorithms, like Linear Regression, assumes variables to follow a particular distribution. The cost of not meeting the assumptions could be high at times." }, { "code": null, "e": 2246, "s": 1995, "text": "Knowing the underlying probability distribution, we can find it’s Probability density function. This helps us in attaching confidence intervals to the range of values Data is likely to take. We can also find the probability of extreme value to occur." }, { "code": null, "e": 2399, "s": 2246, "text": "Distribution has parameters. With these parameters, we can keep track of how the Distribution has changed over time or during a particular season/event." }, { "code": null, "e": 2577, "s": 2399, "text": "The standard probability distributions have well known statistical properties that simplify the job for us. We can explain the Data and its behaviour with just a few parameters." }, { "code": null, "e": 2806, "s": 2577, "text": "For this blog, I will be using the Kaggle Used Car Dataset. We will try to approximate the distributions of various variables and also check its Goodness of fit. I have filtered out a few columns. Let’s have a look at the data :" }, { "code": null, "e": 2855, "s": 2806, "text": "Id: A unique identifier, identifying the vehicle" }, { "code": null, "e": 2891, "s": 2855, "text": "Price: Selling Price of the vehicle" }, { "code": null, "e": 2919, "s": 2891, "text": "Year: Year of Manufacturing" }, { "code": null, "e": 2954, "s": 2919, "text": "Manufacturer: The Brand of the Car" }, { "code": null, "e": 2981, "s": 2954, "text": "Condition: Car’s condition" }, { "code": null, "e": 3038, "s": 2981, "text": "Odometer: Odometer reading denotes the distance traveled" }, { "code": null, "e": 3158, "s": 3038, "text": "The Dataset has 539K records. We will try to identify/approximate the Distribution of ‘price’ and ‘odometer’ variables." }, { "code": null, "e": 3368, "s": 3158, "text": "Scipy Library of Python allows estimating the parameters of 200+ distributions. Further, the Goodness of fit can be tested by various metrics like Chi-square statistics, Kolmogorov–Smirnov test, QQ plots, etc." }, { "code": null, "e": 3779, "s": 3368, "text": "As per blog of Adam Hayes, A chi-square (χ2) statistic is a test that measures how expectations compare to actual observed data (or model results). The data used in calculating a chi-square statistic must be random, raw, mutually exclusive, drawn from independent variables, and drawn from a large enough sample. For example, the results of tossing a coin 100 times meet these criteria. [[Source Investopedia]]" }, { "code": null, "e": 3831, "s": 3779, "text": "The formula for chi-square statistics is given as -" }, { "code": null, "e": 3918, "s": 3831, "text": "where c is the degree of freedom, O is the observed value and E is the expected value." }, { "code": null, "e": 3931, "s": 3918, "text": "Article Link" }, { "code": null, "e": 3952, "s": 3931, "text": "www.investopedia.com" }, { "code": null, "e": 4042, "s": 3952, "text": "Do check out my blog on the Chi-square statistical test to decide on the winner of a Bet." }, { "code": null, "e": 4053, "s": 4042, "text": "medium.com" }, { "code": null, "e": 4189, "s": 4053, "text": "Commonly known as the K-S Test, it is used to check the Goodness of fit of the observed Distribution with the theoretical Distribution." }, { "code": null, "e": 4226, "s": 4189, "text": "Here’s a great article on the topic." }, { "code": null, "e": 4249, "s": 4226, "text": "www.tutorialspoint.com" }, { "code": null, "e": 4390, "s": 4249, "text": "As per Wikipedia, QQ plots is a graphical method for comparing two probability distributions by plotting their quantiles against each other." }, { "code": null, "e": 4440, "s": 4390, "text": "Here’s an interesting StatQuest video on QQ plots" }, { "code": null, "e": 4530, "s": 4440, "text": "With a good enough refresher, we are all set to our primary task of Distribution fitting." }, { "code": null, "e": 4667, "s": 4530, "text": "We will try to approximate ‘price’ using the following Distributions and see which performs the best in terms of Chi-square Statistics -" }, { "code": null, "e": 4822, "s": 4667, "text": "dist_names = [‘weibull_min’,’norm’,’weibull_max’,’beta’, ‘invgauss’,’uniform’,’gamma’,’expon’, ‘lognorm’,’pearson3',’triang’]" }, { "code": null, "e": 4921, "s": 4822, "text": "For stable results, I removed extreme outliers (1% data on both ends). Fitting the distributions :" }, { "code": null, "e": 4981, "s": 4921, "text": "Python code using the Scipy Library to fit the Distribution" }, { "code": null, "e": 5073, "s": 4981, "text": "Fitting different Distributions and checking Goodness of fit based on Chi-square Statistics" }, { "code": null, "e": 5131, "s": 5073, "text": "The output sorted in order of Goodness of fit looks like:" }, { "code": null, "e": 5229, "s": 5131, "text": "Top-2 distributions in terms of Goodness of fit are Exponential and Inverse Gaussian Distribution" }, { "code": null, "e": 5275, "s": 5229, "text": "The parameters of the two distributions are :" }, { "code": null, "e": 5575, "s": 5275, "text": "Parameters of Exponential Distribution<scipy.stats._continuous_distns.expon_gen object at 0x12abd2390>(loc = -1.19, scale = 1.19)where Lambda = 1/scaleParameters of Inverse Gaussian Distribution<scipy.stats._continuous_distns.invgauss_gen object at 0x12ac90c50>(mu = 0.45, loc = -1.64, scale = 3.61)" }, { "code": null, "e": 5791, "s": 5575, "text": "The Scipy Library apart of distribution parameters also provides loc and scale parameters. Loc parameters shift the distribution by the appropriate amount and Scale parameters stretches the distribution as required." }, { "code": null, "e": 5806, "s": 5791, "text": "docs.scipy.org" }, { "code": null, "e": 5836, "s": 5806, "text": "Let’s visualise the Results :" }, { "code": null, "e": 6129, "s": 5836, "text": "fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 5))# Histogram Plot of Observed Dataaxes[0].hist(y)#Exponential Distribution Fittingaxes[1].plot(y,expon.pdf(y_std,-1.19, 1.19))#Inverse-Gaussian Distribution Fittingaxes[2].plot(y,invgauss.pdf(y_std,0.45, -1.64, 3.61))fig.tight_layout()" }, { "code": null, "e": 6285, "s": 6129, "text": "Both the distribution performs fairly good. Exponential Distribution has a slight edge over Inverse-Gaussian. Chi-square statistics also suggests the same." }, { "code": null, "e": 6320, "s": 6285, "text": "Let’s analyse the QQ plot, as well" }, { "code": null, "e": 6443, "s": 6320, "text": "Both the distributions do fairly well. Exponential is slightly better than Inverse Gaussian in approximating ‘Price’ Data." }, { "code": null, "e": 6583, "s": 6443, "text": "We will try to approximate ‘odometer’ using the following Distributions and see which performs the best in terms of Chi-square Statistics -" }, { "code": null, "e": 6738, "s": 6583, "text": "dist_names = [‘weibull_min’,’norm’,’weibull_max’,’beta’, ‘invgauss’,’uniform’,’gamma’,’expon’, ‘lognorm’,’pearson3',’triang’]" }, { "code": null, "e": 6837, "s": 6738, "text": "For stable results, I removed extreme outliers (1% data on both ends). Fitting the distributions :" }, { "code": null, "e": 6897, "s": 6837, "text": "Python code using the Scipy Library to fit the Distribution" }, { "code": null, "e": 6989, "s": 6897, "text": "Fitting different Distributions and checking Goodness of fit based on Chi-square Statistics" }, { "code": null, "e": 7047, "s": 6989, "text": "The output sorted in order of Goodness of fit looks like:" }, { "code": null, "e": 7241, "s": 7047, "text": "Top-2 distributions in terms of Goodness of fit are Beta and Triangular Distribution. However, the difference in Chi-square statistics is significantly high and Beta seems to be a clear winner." }, { "code": null, "e": 7287, "s": 7241, "text": "The parameters of the two distributions are :" }, { "code": null, "e": 7568, "s": 7287, "text": "Parameters of Beta Distribution<scipy.stats._continuous_distns.beta_gen object at 0x12abb72d0>(a = 1.51, b = 2.94, loc = -1.71, scale = 5.02)Parameters of Triangular Distribution<scipy.stats._continuous_distns.triang_gen object at 0x12acf4050>(c = 0.12, loc = -1.79, scale = 4.90)" }, { "code": null, "e": 7784, "s": 7568, "text": "The Scipy Library apart of distribution parameters also provides loc and scale parameters. Loc parameters shift the distribution by the appropriate amount and Scale parameters stretches the distribution as required." }, { "code": null, "e": 7799, "s": 7784, "text": "docs.scipy.org" }, { "code": null, "e": 7829, "s": 7799, "text": "Let’s visualise the Results :" }, { "code": null, "e": 7967, "s": 7829, "text": "Beta Distribution performs much better than Triangular distribution. Visually its clear and Chi-square statistics also suggests the same." }, { "code": null, "e": 8002, "s": 7967, "text": "Let’s analyse the QQ plot, as well" }, { "code": null, "e": 8103, "s": 8002, "text": "QQ plot also makes it clear that Beta Distribution approximates the ‘Odometer’ (Distance) Data well." }, { "code": null, "e": 8587, "s": 8103, "text": "With this blog post, I covered the advantage of knowing Data prior to analysing or applying algorithms on it. Knowing/Approximating the Data’s probability distribution also helps us to use its statistical properties and attach confidence interval to the values it can take. I also covered how to do that using Python and introduced various metrics to check the Goodness of fit. The Kaggle Dataset used can be downloaded from here. The code of the project can be downloaded from here." }, { "code": null, "e": 8797, "s": 8587, "text": "If you have any doubts or queries, do reach out to me. I will be interested to know if you have some interesting problem to solve and feel that approximating the Data’s Probability distribution can be helpful." }, { "code": null, "e": 8834, "s": 8797, "text": "My Youtube channel for more content:" }, { "code": null, "e": 8850, "s": 8834, "text": "www.youtube.com" }, { "code": null, "e": 8869, "s": 8850, "text": "About the author-:" }, { "code": null, "e": 9249, "s": 8869, "text": "Abhishek Mungoli is a seasoned Data Scientist with experience in ML field and Computer Science background, spanning over various domains and problem-solving mindset. Excelled in various Machine learning and Optimization problems specific to Retail. Enthusiastic about implementing Machine Learning models at scale and knowledge sharing via blogs, talks, meetups, and papers, etc." }, { "code": null, "e": 9632, "s": 9249, "text": "My motive always is to simplify the toughest of the things to its most simplified version. I love problem-solving, data science, product development, and scaling solutions. I love to explore new places and working out in my leisure time. Follow me up at Medium, Linkedin or Instagram and check out my previous posts. I welcome feedback and constructive criticism. Some of my blogs -" }, { "code": null, "e": 9677, "s": 9632, "text": "5 Mistakes every Data Scientist should avoid" }, { "code": null, "e": 9729, "s": 9677, "text": "Decomposing Time Series in a simple & intuitive way" }, { "code": null, "e": 9775, "s": 9729, "text": "How GPU Computing literally saved me at work?" }, { "code": null, "e": 9829, "s": 9775, "text": "Information Theory & KL Divergence Part I and Part II" }, { "code": null, "e": 9895, "s": 9829, "text": "Process Wikipedia Using Apache Spark to Create Spicy Hot Datasets" }, { "code": null, "e": 9946, "s": 9895, "text": "A Semi-Supervised Embedding based Fuzzy Clustering" } ]
How to import java.lang.String class in Java?
To import any package in the current class you need to use the import keyword as import packagename; Live Demo import java.lang.String; public class Sample { public static void main(String args[]) { String s = new String("Hello"); System.out.println(s); } } Hello
[ { "code": null, "e": 1143, "s": 1062, "text": "To import any package in the current class you need to use the import keyword as" }, { "code": null, "e": 1163, "s": 1143, "text": "import packagename;" }, { "code": null, "e": 1173, "s": 1163, "text": "Live Demo" }, { "code": null, "e": 1338, "s": 1173, "text": "import java.lang.String;\npublic class Sample {\n public static void main(String args[]) {\n String s = new String(\"Hello\");\n System.out.println(s);\n }\n}" }, { "code": null, "e": 1344, "s": 1338, "text": "Hello" } ]
What are undefined reference/unresolved external symbol errors in C++?
As the name suggests, a symbol you declared was not defined by you. This may occur due to many cases. Let's have a look at three of them − You forgot to define the declared name. For example, you declared a function in a file and used it somewhere. But you did not provide its definition. Code − You forgot to define the declared name. For example, you declared a function in a file and used it somewhere. But you did not provide its definition. Code − #include<iostream> void foo(); int main() { foo(); // Declared but not defined } You defined it but did not use the qualified name. Say you created a class with a method and defined that method but forgot using scope resolution to link that function to that definition and used that function somewhere. For example, You defined it but did not use the qualified name. Say you created a class with a method and defined that method but forgot using scope resolution to link that function to that definition and used that function somewhere. For example, #include<iostream> class A { void foo(); }; void foo() { } // should have used A::foo int main() { A a; a.foo(); // Not defined! } You did not include dependencies in incorrect order. The linker tries to link in the order you specify to it. So in case you use a method before its definition, it will likely give this error. You did not include dependencies in incorrect order. The linker tries to link in the order you specify to it. So in case you use a method before its definition, it will likely give this error. Creating an exhaustive list of conditions that can cause this error is not possible. But you can refer to this post for a very well-curated list of likely reasons − https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix
[ { "code": null, "e": 1201, "s": 1062, "text": "As the name suggests, a symbol you declared was not defined by you. This may occur due to many cases. Let's have a look at three of them −" }, { "code": null, "e": 1358, "s": 1201, "text": "You forgot to define the declared name. For example, you declared a function in a file and used it somewhere. But you did not provide its definition. Code −" }, { "code": null, "e": 1515, "s": 1358, "text": "You forgot to define the declared name. For example, you declared a function in a file and used it somewhere. But you did not provide its definition. Code −" }, { "code": null, "e": 1599, "s": 1515, "text": "#include<iostream>\nvoid foo();\nint main() {\n foo(); // Declared but not defined\n}" }, { "code": null, "e": 1834, "s": 1599, "text": "You defined it but did not use the qualified name. Say you created a class with a method and defined that method but forgot using scope resolution to link that function to that definition and used that function somewhere. For example," }, { "code": null, "e": 2069, "s": 1834, "text": "You defined it but did not use the qualified name. Say you created a class with a method and defined that method but forgot using scope resolution to link that function to that definition and used that function somewhere. For example," }, { "code": null, "e": 2209, "s": 2069, "text": "#include<iostream>\nclass A {\n void foo();\n};\nvoid foo() { } // should have used A::foo\nint main() {\n A a;\n a.foo(); // Not defined!\n}" }, { "code": null, "e": 2402, "s": 2209, "text": "You did not include dependencies in incorrect order. The linker tries to link in the order you specify to it. So in case you use a method before its definition, it will likely give this error." }, { "code": null, "e": 2595, "s": 2402, "text": "You did not include dependencies in incorrect order. The linker tries to link in the order you specify to it. So in case you use a method before its definition, it will likely give this error." }, { "code": null, "e": 2886, "s": 2595, "text": "Creating an exhaustive list of conditions that can cause this error is not possible. But you can refer to this post for a very well-curated list of likely reasons − https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix" } ]
Example of a nested table in HTML
The following is an example of a nested table in HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Example</title> </head> <body> <table> <tbody> <tr> <td> <table> <tbody> <tr> <td>My</td> <td>Table</td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </body> </html>
[ { "code": null, "e": 1117, "s": 1062, "text": "The following is an example of a nested table in HTML:" }, { "code": null, "e": 1640, "s": 1117, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>Example</title>\n </head>\n <body>\n <table>\n <tbody>\n <tr>\n <td>\n <table>\n <tbody>\n <tr>\n <td>My</td>\n <td>Table</td>\n </tr>\n </tbody>\n </table>\n </td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>" } ]
Bootstrap .btn class
Use the .btn class in Bootstrap to add a button to the web page. You can try to run the following code to implement a .btn class Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <!-- Standard button --> <button type = "button" class = "btn btn-default"> Result</button> </body> </html>
[ { "code": null, "e": 1127, "s": 1062, "text": "Use the .btn class in Bootstrap to add a button to the web page." }, { "code": null, "e": 1191, "s": 1127, "text": "You can try to run the following code to implement a .btn class" }, { "code": null, "e": 1201, "s": 1191, "text": "Live Demo" }, { "code": null, "e": 1812, "s": 1201, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <!-- Standard button -->\n <button type = \"button\" class = \"btn btn-default\"> Result</button>\n </body>\n</html>" } ]
Exploring NYC Bike Share Data. How to access trip data from Citi Bike... | by Clif Kranish | Towards Data Science
Many bike share systems make available their trip data for those who want to understand how their systems are used. The bike share system in New York City, Citi Bike, is one of them, but they don’t provide much more than the data. I’ve got some experience in obtaining and preparing their data for visualization, so in this article I will show you how to get started with this rich data source. In the Before Times I commuted from suburban New Jersey to my job as a Product Manager in New York City at an office, now shuttered, above Penn Station. To get around in the City at lunch or after work I often relied on Citi Bike, New York’s bike share system. I found I could get to destinations in midtown and even further afield faster than walking and cheaper than the bus or subway. When I discovered that Citi Bike made trip data publicly available I thought that it might provide an interesting use case for the data preparation product that I managed. Using real data turned out to be much more interesting then the sample files that we had been using because there were actual anomalies that needed to be cleaned up to make the data useful for analysis, and there were interesting stories to tell from the data. The trip data files contain one record for each ride, around two million records per month, depending on the season. It’s a traditional bike share system with fixed stations where a user picks up a bike at one dock, using a key fob or a code, and returns it at another. The station and time when the ride started and stopped is recorded for each ride. Some limited information about the rider is also recorded: their gender and year of birth. Citi Bike also distinguishes between what they call Subscribers who buy an annual pass (current cost is $179 for unlimited rides up to 45 minutes) and Customers who buy a day pass ($15 for unlimited 30 minute rides) or a single ride pass ($3). For each user type there are overage fees for longer rides. For Customers it’s $4 per 15 minutes; for Subscribers it’s $0.15 per minute. These fees seem to be designed to discourage longer rides, more so than to increase revenue. The Citi Bike System Data page describes the information provided. The specific information for each ride is: Trip Duration (seconds) Start Time and Date Stop Time and Date Start Station Name End Station Name Station ID Station Lat/Long Bike ID User Type (Customer = 24-hour pass or single ride user; Subscriber = Annual Member) Gender (Zero=unknown; 1=male; 2=female) Year of Birth The kinds of questions we wanted to answer included ones like these: What’s the most common ride duration? What times of the day does the system get the most usage? How much does ridership vary over the course of a month? What are the most used stations? How old are the riders? While the answers to these questions can be found in the trip data files, the data needs to be augmented to provide easy answers. For example the trip duration in seconds is too granular; minutes would be more useful. Over the years I used this data for numerous presentations to customers and at user group meetings. And the cleansed data I created was used by the product managers for a visualization tool for their own presentations. When I happened to use Jupyter Notebook, Python and Pandas for another project I decided to see what it would take to prepare the Citi Bike trip data using these tools. Jupyter Notebook is an open-source web-based application that allows you to create and share documents that contain code, visualizations and narrative text. It’s commonly used for data preparation and visualization but has many other uses as well. Python is the programming language used by default and Pandas is a software library widely used for data manipulation and analysis. I also used Seaborn as an easy way to visualize the data. The Jupyter Notebook with all the code and output can be found on github. The data can be downloaded from a link on the page referenced above to downloadable files for Citibike tripdata . There’s a file for each month, a zip file containing a single csv file. The files are in chronological order starting in 2013, so to find the recent ones you have to scroll down. Don’t scroll down all the way to the bottom though; the files with JC in the name are for Jersey City, not New York. For this tutorial I’m using the file for March 2020 which for reasons that will become clear is a smaller file than most. Find the file with the name starting with 202003. On a Windows system download the file, unzip it to a new directory under your user directory. On Linux you’ll need to use the wget command to download the file and unzip to expand it. If you don’t have them installed you can install them using the command for your Linux distribution as shown: sudo apt-get install wget unzip # Ubuntu sudo yum install wget unzip # RHEL and CentOS 7 and earliersudo dnf install wget unzip # RHEL and CentOS 8 To get the file on a Linux system all you need from the web page is the URL. Right click on the file with the name starting 202003 and select Copy link address. From a Linux command prompt create a directory for these files and switch to it. Type wget and right click to copy the address from clipboard. Then unzip archive and delete it. mkdir bikesharecd bikesharewget https://s3.amazonaws.com/tripdata/202003-citibike-tripdata.csv.zipunzip 202003-citibike-tripdata.csv.ziprm 202003-citibike-tripdata.csv.zip There are multiple ways to install Jupyter but first you need to install Anaconda, a data science platform, and there are multiple options here too. I used Miniconda, “a free minimal installer for conda” which can be downloaded from miniconda. Be sure to get miniconda3 which is Python 3 based. On Linux you can use wget to download a shell script, then make it executable and run it. wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.shchmod +x Miniconda3-latest-Linux-x86_64.sh./Miniconda3-latest-Linux-x86_64.sh Then add the location where minconda3 was installed to your PATH, either in the current session or to your profile. For example: export PATH=~/miniconda3/bin:$PATH Once that is done you can install Jupyter and other libraries used here. I chose to use the classic Jupyter Notebook. See Installing the Jupyter Software for more information. conda install -c conda-forge notebook pyarrow conda install pandas seaborn Then start the notebook and you can connect to it from a web browser. jupyter notebook On the Jupyter home page click on the bikeshare directory created earlier to select it. You should see the Citi Bike Trip data file there. Click on New to create a new notebook. Then in the first cell enter the commands below to import the libraries needed. Click Ctrl-Enter to execute the command. These commands have no output, the bracketed number turns to an asterisk while the command is running, and back to the number when it completes. import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np Read the trip data file into a DataFrame which is an in-memory object like a table with rows and columns. If the file is in the same directory as your notebook you can just use the file name as shown. If it’s anywhere else use the full path to the file name. df = pd.read_csv('202003-citibike-tripdata.csv') You can view the first five rows in the data frame with the head() method. df.head() You can get some more information about the columns with the info() method. df.info() The output shows the number of rows (just over a million) and the number of columns. The values for Count are all the same, telling us there are no missing values for any columns. The Dtype column shows the data types of each of the columns. The types int64 and float64 indicate 64-bit integer and floating type values, object indicates strings. <class 'pandas.core.frame.DataFrame'>RangeIndex: 1068457 entries, 0 to 1068456Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 tripduration 1068457 non-null int64 1 starttime 1068457 non-null object 2 stoptime 1068457 non-null object 3 start station id 1068457 non-null int64 4 start station name 1068457 non-null object 5 start station latitude 1068457 non-null float64 6 start station longitude 1068457 non-null float64 7 end station id 1068457 non-null int64 8 end station name 1068457 non-null object 9 end station latitude 1068457 non-null float64 10 end station longitude 1068457 non-null float64 11 bikeid 1068457 non-null int64 12 usertype 1068457 non-null object 13 birth year 1068457 non-null int64 14 gender 1068457 non-null int64 dtypes: float64(4), int64(6), object(5)memory usage: 122.3+ MBNone For the numeric fields you can also see how the data is distributed using the describe()method. It shows the minimum and maximum values, the mean and median (50th percentile) and quartiles. By default the values display in scientific notation which is hard to read, but they can be rounded to two decimal places using the the round method. df.describe().round(2) Just from this summary we can see that we need to clean up the data to make it useful for analysis. For example: tripduration. Here we can see shortest trips were 61 seconds (Citi Bike ignores trips that are 60 seconds or less). The longest was 3247190 seconds (or 902 hours) which sounds like someone didn’t dock their bike. Numbers that large will throw off the mean, so we’ll want to address that. birth year. The earliest year is 1885. I don’t think anyone born then is still alive, let alone riding a bicycle! starttime/stoptime. These columns are loaded with data type object. In order for use to use the components (date or time) we need to convert them to timestamps. We saw above the column names and data types, we can get additional information about the data in the data frame with an expression like this that shows for each column its name, number of unique values, its data type and the amount of memory the column uses. pd.DataFrame.from_records([(col, df[col].nunique(), df[col].dtype, df[col].memory_usage(deep=True) ) for col in df.columns], columns=['Column Name', 'Unique', 'Data Type','Memory Usage']) Here we can see that the columns stored with a data type of object take up around ten times the space in memory as the integer or float data types. As long as we’re just looking at one month’s data that’s not so much a problem, but for a year’s data it would be. We can easily convert the start and end time columns from object to to timestamp: df['starttime'] = pd.to_datetime(df['starttime'])df['stoptime'] = pd.to_datetime(df['stoptime']) We can also reduce the amount of memory used for some of the other columns by using the category data type. Categories are useful when there are a limited number of unique values for a column compared to the number of rows. The actual values are stored just once, and instead of storing a long string in each row, just an integer is stored that points to the actual value. This file contains over a million rows, but from the unique count for the start and end station names we see that there 899 stations for this month, so they are good candidates to store as categorical data. The usertype column with only two unique values should get similar treatment, as should gender with three values. Bikeid could also be treated similarly. cols = ['start station name', 'end station name', 'bikeid', 'usertype', 'gender']for col in cols: df[col] = df[col].astype('category') Now if we run the same report as before we can see that the data types have been changed and that the memory used by these columns has been greatly reduced. This will also speed up processing that uses these columns. We’d like to know what the most common trip duration times are. But the tripduration column is stored in seconds which is too precise for this purpose so we’ll create an additional column tripminutes that has the trip duration in minutes. Then we can use Seaborn displot to show the count of rides for each duration trip duration. The parameters used are: data — The name of the Data Frame.x — The name of the column to chart.bins — A list of values. Because of the overage fees for rides more than 30 or 45 minutes the number of longer rides is small, so we will only count rides up to an hour. aspect — The ration of height to width. The value 10/5 gives a a wider chart than the default The semi-colon at the end of the line prevents a spurious line of text from appearing above the chart. df['tripminutes'] = df['tripduration'] // 60sns.displot(data=df,x="tripminutes", bins=range(1,61), aspect=10/5); This chart shows that the most common trip is five minutes long (the tallest bar) followed by four and six minutes (the bars before and after that one). After that the chart shows a classic “long tail” of fewer trips for longer rides. Next we’d like to see hour the rides are distributed across the day and the month. Since we converted the starttime column to a datetime value we can use its methods to extract the hour, day and day of week. With just 24, 31 or seven possible values these are good columns to store as categories. df['start hour']=df['starttime'].dt.hour.astype('category')df['start day']=df['starttime'].dt.day.astype('category') df['weekday']=df['starttime'].dt.weekday.astype('category') Then we can plot the rides per hour using seaborn countplot. Here the figsize setting allows for a wider chart than the default. plt.figure(figsize=(12,5))sns.countplot(data=df, x="start hour" ) ; Here we can see a morning rush hour and an evening rush hour. Next let’s look at rides per day. It’s helpful to highlight the weekends to understand the data so I’ll create an additional column that weekendthat indicates if a day is a weekend day. The additional parameters used for countplotare hue— the name of the column that controls the color of the bardodge — show a single column for the multiple hue values df['weekend'] = [if d >= 5 for d in df['weekday']] # 0=mondayplt.figure(figsize=(12,6))sns.set_palette("Set2")sns.countplot(data=df,x="start day", hue='weekend', dodge=False) ; Here we can clearly see the effect the pandemic had on Citi Bike usage in March. The number of daily rides peaked on March 9th. After it was announced that Broadway theaters would be closed on March 12th the number of daily rides decreased further, and remained so for the rest of the month. Next we’d like to know: which stations get the most use? We can use the data frame method value_counts() which for a column returns a series of indexes (here, the station names) and the values (the counts). The counts are conveniently in descending order of frequency so if we select the first 20 values we will get the 20 most frequently used stations. For readability I’ll make this chart taller by using a higher figsize value. startstation = df['start station name'].value_counts()[:20]plt.figure(figsize=(12,10))sns.barplot( x=startstation.values , y=list(startstation.index), orient="h" ) ; This shows the most frequently used station is Pershing Square North. That’s one of the largest stations in the system, and it’s just South of Grand Central Terminal, a major railroad and subway hub, so it makes sense that should be number one. Citi Bike provides limited data about who rode the bikes: their birth year, gender and if they were an (annual) Subscriber or (daily) Customer. Still it would be interesting to know how old the riders are. As we saw the birth year column has year values are impossible or at best unlikely, so it makes sense to restrict our analysis. I’m going to use 1946 as a cut-off which is generally considered to be the first year of the Baby Boom generation. sns.displot(data=df, x="birth year" , bins=range(1946,2004), aspect=10/5) ; The first thing we notice about this chart is that 1969 sticks out like the proverbial sore thumb: I suspect that it might have something to do with the user type. Citi Bike has profiles for their Subscribers who sign-up online, but Customers buy a day pass at a Kiosk, and may not be inclined to key in their actual year of birth. Indeed if I color the bars by User Type then I see that most of riders with a birth year of 1969 were Customers. sns.displot(data=df,x="birth year", bins=range(1946,2004), hue='usertype', multiple='stack' , hue_order=["Subscriber","Customer"], aspect=10/5); But even if we remove the Customers the value for 1969 still looks too high. What about the value for gender? A value of zero indicates a missing value. Here the bars are colored by gender in order 0 (undeclared), 1 (male), 2 (female). So when calculating the rider’s age I want to omit rides where the rider was born before 1946 or where gender is zero. I create a mask that is True when those conditions are met. Then I create a new age column in the data flow that’s set to 2020 minus the birth year unless the mask is True and then it’s set to None which indicates a missing value. skip = (df['birth year'] < 1946) | (df['gender'] == 0) df['age'] = (2020 - df['birth year']).mask(skip,None) Finally I can do a plot by the rider’s age, still showing the rider’s gender. sns.displot(data=df, x='age', hue='gender', multiple='stack', aspect=10/5) ; From here we can see the most common age (the mode) is 30, and indeed the most common ages cluster around it. We also now see that there are far more men than women using Citi Bike. Unlike some “dockless” bike share systems with GPS systems on the bikes, Citi Bike doesn’t have any way to record the route taken by a rider. However with the starting and ending latitude and longitude for each trip it’s possible to at least calculate the distance “as the crow files” using the Haversine Formula which calculates the “great circle” distance between any two points on earth. When the two stations are on the same street or avenue the distance will be reasonably accurate, but otherwise not so much. Still it provides a minimum distance between two stations. Here’s a Python program that represents the formula. import numpy as npdef haversine(lat1, lon1, lat2, lon2): lon1, lat1, lon2, lat2 = \ map(np.radians ,[lon1, lat1, lon2, lat2]) h = np.sin((lat2-lat1)/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2 miles = 3959 * (2 * np.arcsin(np.sqrt(h))) return miles We can use it to create a variable to add to the data frame, and use for a chart. distance = haversine(df['start station latitude'],df['start station longitude'],df['end station latitude'],df['end station longitude'])df['distance'] = distancesns.displot(data=df, x="distance", aspect=10/5 ) ; But the chart shows us that there a lot of trips with a distance of zero! It turns out that even though Citi Bike is intended for transportation it also gets used for recreation where trips start and end at the same station. We can remove those trips from the distance variable to get a more readable chart. distance = list(filter(lambda distance: distance !=0 , distance)) sns.displot(x=distance , aspect=10/5 ) ; The combination of time and distance information offers many opportunities for further analysis, for example you could calculate the (approximate) speed for each trip and analyze it by age, gender or station. After we’ve changed the data types of some of the columns and derived new columns we’ll want to save the DataFrame to a file so that we can do additional analysis. We don’t want to write it back as a csv file because it takes a long time to load and looses the categorical columns. There are a number of options such as Pickle and Feather, but in my opinion the best choice is often Parquet, a columnar file format that is well integrated with Pandas. As a column store it provides faster retrieval times when not every column is needed. df.to_parquet('202003-citibike-tripdata.parquet') Parquet takes up less space on disk than other formats, even using the default SNAPPY compression. We can compare the sizes of the two files and see that the Parquet file takes about 17% of the space of the original csv file, even with the additional columns added. 202003-citibike-tripdata.csv 202,642,779 202003-citibike-tripdata.parquet 35,086,348 Later, to read the Parquet file into a Data Frame for further analysis use: df = pd.read_parquet('202003-citibike-tripdata.parquet') Parquet files can also be used from most visualization tools when accessed through a SQL query engine such as Apache Drill or PrestoDB. This is the first of a series of articles on this topic. Citi Bike tripdata can be combined with data from other sources to provide more insights into how the bike share system is used. For more see: Using reverse geocoding with NYC Bike Share Data The Citi Bike trip data, while useful for analysis as provided, can be made more so with some data preparation to add additional columns with more or less detail. Pandas provides the data structures and operations to facilitate data preparation and Seaborn makes it very easy to produce distribution charts to understand the data. Jupyter Notebook provides a convenient way to document the preparation steps used.
[ { "code": null, "e": 567, "s": 172, "text": "Many bike share systems make available their trip data for those who want to understand how their systems are used. The bike share system in New York City, Citi Bike, is one of them, but they don’t provide much more than the data. I’ve got some experience in obtaining and preparing their data for visualization, so in this article I will show you how to get started with this rich data source." }, { "code": null, "e": 1127, "s": 567, "text": "In the Before Times I commuted from suburban New Jersey to my job as a Product Manager in New York City at an office, now shuttered, above Penn Station. To get around in the City at lunch or after work I often relied on Citi Bike, New York’s bike share system. I found I could get to destinations in midtown and even further afield faster than walking and cheaper than the bus or subway. When I discovered that Citi Bike made trip data publicly available I thought that it might provide an interesting use case for the data preparation product that I managed." }, { "code": null, "e": 1388, "s": 1127, "text": "Using real data turned out to be much more interesting then the sample files that we had been using because there were actual anomalies that needed to be cleaned up to make the data useful for analysis, and there were interesting stories to tell from the data." }, { "code": null, "e": 1740, "s": 1388, "text": "The trip data files contain one record for each ride, around two million records per month, depending on the season. It’s a traditional bike share system with fixed stations where a user picks up a bike at one dock, using a key fob or a code, and returns it at another. The station and time when the ride started and stopped is recorded for each ride." }, { "code": null, "e": 2075, "s": 1740, "text": "Some limited information about the rider is also recorded: their gender and year of birth. Citi Bike also distinguishes between what they call Subscribers who buy an annual pass (current cost is $179 for unlimited rides up to 45 minutes) and Customers who buy a day pass ($15 for unlimited 30 minute rides) or a single ride pass ($3)." }, { "code": null, "e": 2305, "s": 2075, "text": "For each user type there are overage fees for longer rides. For Customers it’s $4 per 15 minutes; for Subscribers it’s $0.15 per minute. These fees seem to be designed to discourage longer rides, more so than to increase revenue." }, { "code": null, "e": 2415, "s": 2305, "text": "The Citi Bike System Data page describes the information provided. The specific information for each ride is:" }, { "code": null, "e": 2439, "s": 2415, "text": "Trip Duration (seconds)" }, { "code": null, "e": 2459, "s": 2439, "text": "Start Time and Date" }, { "code": null, "e": 2478, "s": 2459, "text": "Stop Time and Date" }, { "code": null, "e": 2497, "s": 2478, "text": "Start Station Name" }, { "code": null, "e": 2514, "s": 2497, "text": "End Station Name" }, { "code": null, "e": 2525, "s": 2514, "text": "Station ID" }, { "code": null, "e": 2542, "s": 2525, "text": "Station Lat/Long" }, { "code": null, "e": 2550, "s": 2542, "text": "Bike ID" }, { "code": null, "e": 2634, "s": 2550, "text": "User Type (Customer = 24-hour pass or single ride user; Subscriber = Annual Member)" }, { "code": null, "e": 2674, "s": 2634, "text": "Gender (Zero=unknown; 1=male; 2=female)" }, { "code": null, "e": 2688, "s": 2674, "text": "Year of Birth" }, { "code": null, "e": 2967, "s": 2688, "text": "The kinds of questions we wanted to answer included ones like these: What’s the most common ride duration? What times of the day does the system get the most usage? How much does ridership vary over the course of a month? What are the most used stations? How old are the riders?" }, { "code": null, "e": 3185, "s": 2967, "text": "While the answers to these questions can be found in the trip data files, the data needs to be augmented to provide easy answers. For example the trip duration in seconds is too granular; minutes would be more useful." }, { "code": null, "e": 3404, "s": 3185, "text": "Over the years I used this data for numerous presentations to customers and at user group meetings. And the cleansed data I created was used by the product managers for a visualization tool for their own presentations." }, { "code": null, "e": 3573, "s": 3404, "text": "When I happened to use Jupyter Notebook, Python and Pandas for another project I decided to see what it would take to prepare the Citi Bike trip data using these tools." }, { "code": null, "e": 4011, "s": 3573, "text": "Jupyter Notebook is an open-source web-based application that allows you to create and share documents that contain code, visualizations and narrative text. It’s commonly used for data preparation and visualization but has many other uses as well. Python is the programming language used by default and Pandas is a software library widely used for data manipulation and analysis. I also used Seaborn as an easy way to visualize the data." }, { "code": null, "e": 4085, "s": 4011, "text": "The Jupyter Notebook with all the code and output can be found on github." }, { "code": null, "e": 4495, "s": 4085, "text": "The data can be downloaded from a link on the page referenced above to downloadable files for Citibike tripdata . There’s a file for each month, a zip file containing a single csv file. The files are in chronological order starting in 2013, so to find the recent ones you have to scroll down. Don’t scroll down all the way to the bottom though; the files with JC in the name are for Jersey City, not New York." }, { "code": null, "e": 4667, "s": 4495, "text": "For this tutorial I’m using the file for March 2020 which for reasons that will become clear is a smaller file than most. Find the file with the name starting with 202003." }, { "code": null, "e": 4761, "s": 4667, "text": "On a Windows system download the file, unzip it to a new directory under your user directory." }, { "code": null, "e": 4961, "s": 4761, "text": "On Linux you’ll need to use the wget command to download the file and unzip to expand it. If you don’t have them installed you can install them using the command for your Linux distribution as shown:" }, { "code": null, "e": 5110, "s": 4961, "text": "sudo apt-get install wget unzip # Ubuntu sudo yum install wget unzip # RHEL and CentOS 7 and earliersudo dnf install wget unzip # RHEL and CentOS 8 " }, { "code": null, "e": 5448, "s": 5110, "text": "To get the file on a Linux system all you need from the web page is the URL. Right click on the file with the name starting 202003 and select Copy link address. From a Linux command prompt create a directory for these files and switch to it. Type wget and right click to copy the address from clipboard. Then unzip archive and delete it." }, { "code": null, "e": 5620, "s": 5448, "text": "mkdir bikesharecd bikesharewget https://s3.amazonaws.com/tripdata/202003-citibike-tripdata.csv.zipunzip 202003-citibike-tripdata.csv.ziprm 202003-citibike-tripdata.csv.zip" }, { "code": null, "e": 5915, "s": 5620, "text": "There are multiple ways to install Jupyter but first you need to install Anaconda, a data science platform, and there are multiple options here too. I used Miniconda, “a free minimal installer for conda” which can be downloaded from miniconda. Be sure to get miniconda3 which is Python 3 based." }, { "code": null, "e": 6005, "s": 5915, "text": "On Linux you can use wget to download a shell script, then make it executable and run it." }, { "code": null, "e": 6158, "s": 6005, "text": "wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.shchmod +x Miniconda3-latest-Linux-x86_64.sh./Miniconda3-latest-Linux-x86_64.sh " }, { "code": null, "e": 6287, "s": 6158, "text": "Then add the location where minconda3 was installed to your PATH, either in the current session or to your profile. For example:" }, { "code": null, "e": 6322, "s": 6287, "text": "export PATH=~/miniconda3/bin:$PATH" }, { "code": null, "e": 6498, "s": 6322, "text": "Once that is done you can install Jupyter and other libraries used here. I chose to use the classic Jupyter Notebook. See Installing the Jupyter Software for more information." }, { "code": null, "e": 6573, "s": 6498, "text": "conda install -c conda-forge notebook pyarrow conda install pandas seaborn" }, { "code": null, "e": 6643, "s": 6573, "text": "Then start the notebook and you can connect to it from a web browser." }, { "code": null, "e": 6661, "s": 6643, "text": "jupyter notebook " }, { "code": null, "e": 6800, "s": 6661, "text": "On the Jupyter home page click on the bikeshare directory created earlier to select it. You should see the Citi Bike Trip data file there." }, { "code": null, "e": 7105, "s": 6800, "text": "Click on New to create a new notebook. Then in the first cell enter the commands below to import the libraries needed. Click Ctrl-Enter to execute the command. These commands have no output, the bracketed number turns to an asterisk while the command is running, and back to the number when it completes." }, { "code": null, "e": 7195, "s": 7105, "text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np" }, { "code": null, "e": 7454, "s": 7195, "text": "Read the trip data file into a DataFrame which is an in-memory object like a table with rows and columns. If the file is in the same directory as your notebook you can just use the file name as shown. If it’s anywhere else use the full path to the file name." }, { "code": null, "e": 7503, "s": 7454, "text": "df = pd.read_csv('202003-citibike-tripdata.csv')" }, { "code": null, "e": 7578, "s": 7503, "text": "You can view the first five rows in the data frame with the head() method." }, { "code": null, "e": 7588, "s": 7578, "text": "df.head()" }, { "code": null, "e": 7664, "s": 7588, "text": "You can get some more information about the columns with the info() method." }, { "code": null, "e": 7674, "s": 7664, "text": "df.info()" }, { "code": null, "e": 7759, "s": 7674, "text": "The output shows the number of rows (just over a million) and the number of columns." }, { "code": null, "e": 7854, "s": 7759, "text": "The values for Count are all the same, telling us there are no missing values for any columns." }, { "code": null, "e": 8020, "s": 7854, "text": "The Dtype column shows the data types of each of the columns. The types int64 and float64 indicate 64-bit integer and floating type values, object indicates strings." }, { "code": null, "e": 9132, "s": 8020, "text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 1068457 entries, 0 to 1068456Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 tripduration 1068457 non-null int64 1 starttime 1068457 non-null object 2 stoptime 1068457 non-null object 3 start station id 1068457 non-null int64 4 start station name 1068457 non-null object 5 start station latitude 1068457 non-null float64 6 start station longitude 1068457 non-null float64 7 end station id 1068457 non-null int64 8 end station name 1068457 non-null object 9 end station latitude 1068457 non-null float64 10 end station longitude 1068457 non-null float64 11 bikeid 1068457 non-null int64 12 usertype 1068457 non-null object 13 birth year 1068457 non-null int64 14 gender 1068457 non-null int64 dtypes: float64(4), int64(6), object(5)memory usage: 122.3+ MBNone" }, { "code": null, "e": 9322, "s": 9132, "text": "For the numeric fields you can also see how the data is distributed using the describe()method. It shows the minimum and maximum values, the mean and median (50th percentile) and quartiles." }, { "code": null, "e": 9472, "s": 9322, "text": "By default the values display in scientific notation which is hard to read, but they can be rounded to two decimal places using the the round method." }, { "code": null, "e": 9495, "s": 9472, "text": "df.describe().round(2)" }, { "code": null, "e": 9608, "s": 9495, "text": "Just from this summary we can see that we need to clean up the data to make it useful for analysis. For example:" }, { "code": null, "e": 9896, "s": 9608, "text": "tripduration. Here we can see shortest trips were 61 seconds (Citi Bike ignores trips that are 60 seconds or less). The longest was 3247190 seconds (or 902 hours) which sounds like someone didn’t dock their bike. Numbers that large will throw off the mean, so we’ll want to address that." }, { "code": null, "e": 10010, "s": 9896, "text": "birth year. The earliest year is 1885. I don’t think anyone born then is still alive, let alone riding a bicycle!" }, { "code": null, "e": 10171, "s": 10010, "text": "starttime/stoptime. These columns are loaded with data type object. In order for use to use the components (date or time) we need to convert them to timestamps." }, { "code": null, "e": 10431, "s": 10171, "text": "We saw above the column names and data types, we can get additional information about the data in the data frame with an expression like this that shows for each column its name, number of unique values, its data type and the amount of memory the column uses." }, { "code": null, "e": 10621, "s": 10431, "text": "pd.DataFrame.from_records([(col, df[col].nunique(), df[col].dtype, df[col].memory_usage(deep=True) ) for col in df.columns], columns=['Column Name', 'Unique', 'Data Type','Memory Usage'])" }, { "code": null, "e": 10884, "s": 10621, "text": "Here we can see that the columns stored with a data type of object take up around ten times the space in memory as the integer or float data types. As long as we’re just looking at one month’s data that’s not so much a problem, but for a year’s data it would be." }, { "code": null, "e": 10966, "s": 10884, "text": "We can easily convert the start and end time columns from object to to timestamp:" }, { "code": null, "e": 11063, "s": 10966, "text": "df['starttime'] = pd.to_datetime(df['starttime'])df['stoptime'] = pd.to_datetime(df['stoptime'])" }, { "code": null, "e": 11436, "s": 11063, "text": "We can also reduce the amount of memory used for some of the other columns by using the category data type. Categories are useful when there are a limited number of unique values for a column compared to the number of rows. The actual values are stored just once, and instead of storing a long string in each row, just an integer is stored that points to the actual value." }, { "code": null, "e": 11643, "s": 11436, "text": "This file contains over a million rows, but from the unique count for the start and end station names we see that there 899 stations for this month, so they are good candidates to store as categorical data." }, { "code": null, "e": 11797, "s": 11643, "text": "The usertype column with only two unique values should get similar treatment, as should gender with three values. Bikeid could also be treated similarly." }, { "code": null, "e": 11935, "s": 11797, "text": "cols = ['start station name', 'end station name', 'bikeid', 'usertype', 'gender']for col in cols: df[col] = df[col].astype('category')" }, { "code": null, "e": 12152, "s": 11935, "text": "Now if we run the same report as before we can see that the data types have been changed and that the memory used by these columns has been greatly reduced. This will also speed up processing that uses these columns." }, { "code": null, "e": 12391, "s": 12152, "text": "We’d like to know what the most common trip duration times are. But the tripduration column is stored in seconds which is too precise for this purpose so we’ll create an additional column tripminutes that has the trip duration in minutes." }, { "code": null, "e": 12483, "s": 12391, "text": "Then we can use Seaborn displot to show the count of rides for each duration trip duration." }, { "code": null, "e": 12508, "s": 12483, "text": "The parameters used are:" }, { "code": null, "e": 12842, "s": 12508, "text": "data — The name of the Data Frame.x — The name of the column to chart.bins — A list of values. Because of the overage fees for rides more than 30 or 45 minutes the number of longer rides is small, so we will only count rides up to an hour. aspect — The ration of height to width. The value 10/5 gives a a wider chart than the default" }, { "code": null, "e": 12945, "s": 12842, "text": "The semi-colon at the end of the line prevents a spurious line of text from appearing above the chart." }, { "code": null, "e": 13058, "s": 12945, "text": "df['tripminutes'] = df['tripduration'] // 60sns.displot(data=df,x=\"tripminutes\", bins=range(1,61), aspect=10/5);" }, { "code": null, "e": 13293, "s": 13058, "text": "This chart shows that the most common trip is five minutes long (the tallest bar) followed by four and six minutes (the bars before and after that one). After that the chart shows a classic “long tail” of fewer trips for longer rides." }, { "code": null, "e": 13590, "s": 13293, "text": "Next we’d like to see hour the rides are distributed across the day and the month. Since we converted the starttime column to a datetime value we can use its methods to extract the hour, day and day of week. With just 24, 31 or seven possible values these are good columns to store as categories." }, { "code": null, "e": 13767, "s": 13590, "text": "df['start hour']=df['starttime'].dt.hour.astype('category')df['start day']=df['starttime'].dt.day.astype('category') df['weekday']=df['starttime'].dt.weekday.astype('category')" }, { "code": null, "e": 13896, "s": 13767, "text": "Then we can plot the rides per hour using seaborn countplot. Here the figsize setting allows for a wider chart than the default." }, { "code": null, "e": 13964, "s": 13896, "text": "plt.figure(figsize=(12,5))sns.countplot(data=df, x=\"start hour\" ) ;" }, { "code": null, "e": 14026, "s": 13964, "text": "Here we can see a morning rush hour and an evening rush hour." }, { "code": null, "e": 14212, "s": 14026, "text": "Next let’s look at rides per day. It’s helpful to highlight the weekends to understand the data so I’ll create an additional column that weekendthat indicates if a day is a weekend day." }, { "code": null, "e": 14260, "s": 14212, "text": "The additional parameters used for countplotare" }, { "code": null, "e": 14379, "s": 14260, "text": "hue— the name of the column that controls the color of the bardodge — show a single column for the multiple hue values" }, { "code": null, "e": 14556, "s": 14379, "text": "df['weekend'] = [if d >= 5 for d in df['weekday']] # 0=mondayplt.figure(figsize=(12,6))sns.set_palette(\"Set2\")sns.countplot(data=df,x=\"start day\", hue='weekend', dodge=False) ;" }, { "code": null, "e": 14848, "s": 14556, "text": "Here we can clearly see the effect the pandemic had on Citi Bike usage in March. The number of daily rides peaked on March 9th. After it was announced that Broadway theaters would be closed on March 12th the number of daily rides decreased further, and remained so for the rest of the month." }, { "code": null, "e": 15279, "s": 14848, "text": "Next we’d like to know: which stations get the most use? We can use the data frame method value_counts() which for a column returns a series of indexes (here, the station names) and the values (the counts). The counts are conveniently in descending order of frequency so if we select the first 20 values we will get the 20 most frequently used stations. For readability I’ll make this chart taller by using a higher figsize value." }, { "code": null, "e": 15447, "s": 15279, "text": "startstation = df['start station name'].value_counts()[:20]plt.figure(figsize=(12,10))sns.barplot( x=startstation.values , y=list(startstation.index), orient=\"h\" ) ;" }, { "code": null, "e": 15692, "s": 15447, "text": "This shows the most frequently used station is Pershing Square North. That’s one of the largest stations in the system, and it’s just South of Grand Central Terminal, a major railroad and subway hub, so it makes sense that should be number one." }, { "code": null, "e": 16141, "s": 15692, "text": "Citi Bike provides limited data about who rode the bikes: their birth year, gender and if they were an (annual) Subscriber or (daily) Customer. Still it would be interesting to know how old the riders are. As we saw the birth year column has year values are impossible or at best unlikely, so it makes sense to restrict our analysis. I’m going to use 1946 as a cut-off which is generally considered to be the first year of the Baby Boom generation." }, { "code": null, "e": 16218, "s": 16141, "text": "sns.displot(data=df, x=\"birth year\" , bins=range(1946,2004), aspect=10/5) ;" }, { "code": null, "e": 16317, "s": 16218, "text": "The first thing we notice about this chart is that 1969 sticks out like the proverbial sore thumb:" }, { "code": null, "e": 16550, "s": 16317, "text": "I suspect that it might have something to do with the user type. Citi Bike has profiles for their Subscribers who sign-up online, but Customers buy a day pass at a Kiosk, and may not be inclined to key in their actual year of birth." }, { "code": null, "e": 16663, "s": 16550, "text": "Indeed if I color the bars by User Type then I see that most of riders with a birth year of 1969 were Customers." }, { "code": null, "e": 16809, "s": 16663, "text": "sns.displot(data=df,x=\"birth year\", bins=range(1946,2004), hue='usertype', multiple='stack' , hue_order=[\"Subscriber\",\"Customer\"], aspect=10/5); " }, { "code": null, "e": 17045, "s": 16809, "text": "But even if we remove the Customers the value for 1969 still looks too high. What about the value for gender? A value of zero indicates a missing value. Here the bars are colored by gender in order 0 (undeclared), 1 (male), 2 (female)." }, { "code": null, "e": 17395, "s": 17045, "text": "So when calculating the rider’s age I want to omit rides where the rider was born before 1946 or where gender is zero. I create a mask that is True when those conditions are met. Then I create a new age column in the data flow that’s set to 2020 minus the birth year unless the mask is True and then it’s set to None which indicates a missing value." }, { "code": null, "e": 17504, "s": 17395, "text": "skip = (df['birth year'] < 1946) | (df['gender'] == 0) df['age'] = (2020 - df['birth year']).mask(skip,None)" }, { "code": null, "e": 17582, "s": 17504, "text": "Finally I can do a plot by the rider’s age, still showing the rider’s gender." }, { "code": null, "e": 17660, "s": 17582, "text": "sns.displot(data=df, x='age', hue='gender', multiple='stack', aspect=10/5) ;" }, { "code": null, "e": 17842, "s": 17660, "text": "From here we can see the most common age (the mode) is 30, and indeed the most common ages cluster around it. We also now see that there are far more men than women using Citi Bike." }, { "code": null, "e": 17984, "s": 17842, "text": "Unlike some “dockless” bike share systems with GPS systems on the bikes, Citi Bike doesn’t have any way to record the route taken by a rider." }, { "code": null, "e": 18416, "s": 17984, "text": "However with the starting and ending latitude and longitude for each trip it’s possible to at least calculate the distance “as the crow files” using the Haversine Formula which calculates the “great circle” distance between any two points on earth. When the two stations are on the same street or avenue the distance will be reasonably accurate, but otherwise not so much. Still it provides a minimum distance between two stations." }, { "code": null, "e": 18469, "s": 18416, "text": "Here’s a Python program that represents the formula." }, { "code": null, "e": 18757, "s": 18469, "text": "import numpy as npdef haversine(lat1, lon1, lat2, lon2): lon1, lat1, lon2, lat2 = \\ map(np.radians ,[lon1, lat1, lon2, lat2]) h = np.sin((lat2-lat1)/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2 miles = 3959 * (2 * np.arcsin(np.sqrt(h))) return miles" }, { "code": null, "e": 18839, "s": 18757, "text": "We can use it to create a variable to add to the data frame, and use for a chart." }, { "code": null, "e": 19052, "s": 18839, "text": "distance = haversine(df['start station latitude'],df['start station longitude'],df['end station latitude'],df['end station longitude'])df['distance'] = distancesns.displot(data=df, x=\"distance\", aspect=10/5 ) ;" }, { "code": null, "e": 19277, "s": 19052, "text": "But the chart shows us that there a lot of trips with a distance of zero! It turns out that even though Citi Bike is intended for transportation it also gets used for recreation where trips start and end at the same station." }, { "code": null, "e": 19360, "s": 19277, "text": "We can remove those trips from the distance variable to get a more readable chart." }, { "code": null, "e": 19469, "s": 19360, "text": "distance = list(filter(lambda distance: distance !=0 , distance)) sns.displot(x=distance , aspect=10/5 ) ;" }, { "code": null, "e": 19678, "s": 19469, "text": "The combination of time and distance information offers many opportunities for further analysis, for example you could calculate the (approximate) speed for each trip and analyze it by age, gender or station." }, { "code": null, "e": 19960, "s": 19678, "text": "After we’ve changed the data types of some of the columns and derived new columns we’ll want to save the DataFrame to a file so that we can do additional analysis. We don’t want to write it back as a csv file because it takes a long time to load and looses the categorical columns." }, { "code": null, "e": 20216, "s": 19960, "text": "There are a number of options such as Pickle and Feather, but in my opinion the best choice is often Parquet, a columnar file format that is well integrated with Pandas. As a column store it provides faster retrieval times when not every column is needed." }, { "code": null, "e": 20266, "s": 20216, "text": "df.to_parquet('202003-citibike-tripdata.parquet')" }, { "code": null, "e": 20532, "s": 20266, "text": "Parquet takes up less space on disk than other formats, even using the default SNAPPY compression. We can compare the sizes of the two files and see that the Parquet file takes about 17% of the space of the original csv file, even with the additional columns added." }, { "code": null, "e": 20628, "s": 20532, "text": "202003-citibike-tripdata.csv 202,642,779 202003-citibike-tripdata.parquet 35,086,348" }, { "code": null, "e": 20704, "s": 20628, "text": "Later, to read the Parquet file into a Data Frame for further analysis use:" }, { "code": null, "e": 20761, "s": 20704, "text": "df = pd.read_parquet('202003-citibike-tripdata.parquet')" }, { "code": null, "e": 20897, "s": 20761, "text": "Parquet files can also be used from most visualization tools when accessed through a SQL query engine such as Apache Drill or PrestoDB." }, { "code": null, "e": 21097, "s": 20897, "text": "This is the first of a series of articles on this topic. Citi Bike tripdata can be combined with data from other sources to provide more insights into how the bike share system is used. For more see:" }, { "code": null, "e": 21146, "s": 21097, "text": "Using reverse geocoding with NYC Bike Share Data" } ]
SWING - KeyEvent Class
On entering the character the Key event is generated.There are three types of key events which are represented by the integer constants. KEY_PRESSED KEY_RELASED KEY_TYPED Following is the declaration for java.awt.event.KeyEvent class − public class KeyEvent extends InputEvent Following are the fields for java.awt.InputEvent class − static char CHAR_UNDEFINED − KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value. static char CHAR_UNDEFINED − KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value. static int KEY_FIRST − The first number in the range of IDs used for key events. static int KEY_FIRST − The first number in the range of IDs used for key events. static int KEY_LAST − The last number in the range of IDs used for key events. static int KEY_LAST − The last number in the range of IDs used for key events. static int KEY_LOCATION_LEFT − A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key). static int KEY_LOCATION_LEFT − A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key). static int KEY_LOCATION_NUMPAD − A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad. static int KEY_LOCATION_NUMPAD − A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad. static int KEY_LOCATION_RIGHT − A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key). static int KEY_LOCATION_RIGHT − A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key). static int KEY_LOCATION_STANDARD − A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad). static int KEY_LOCATION_STANDARD − A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad). static int KEY_LOCATION_UNKNOWN − A constant indicating that the keyLocation is indeterminate or not relevant. static int KEY_LOCATION_UNKNOWN − A constant indicating that the keyLocation is indeterminate or not relevant. static int KEY_PRESSED − The "key pressed" event. static int KEY_PRESSED − The "key pressed" event. static int KEY_RELEASED − The "key released" event. static int KEY_RELEASED − The "key released" event. static int KEY_TYPED − The "key typed" event. static int KEY_TYPED − The "key typed" event. static int VK_0 − VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0×30 - 0×39) static int VK_0 − VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0×30 - 0×39) static int VK_1 static int VK_1 static int VK_2 static int VK_2 static int VK_3 static int VK_3 static int VK_4 static int VK_4 static int VK_5 static int VK_5 static int VK_6 static int VK_6 static int VK_7 static int VK_7 static int VK_8 static int VK_8 static int VK_9 static int VK_9 static int VK_A − VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0×41 - 0×5A) static int VK_A − VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0×41 - 0×5A) static int VK_ACCEPT − Constant for the Accept or Commit function key. static int VK_ACCEPT − Constant for the Accept or Commit function key. static int VK_ADD static int VK_ADD static int VK_AGAIN static int VK_AGAIN static int VK_ALL_CANDIDATES − Constant for the All Candidates function key. static int VK_ALL_CANDIDATES − Constant for the All Candidates function key. static int VK_ALPHANUMERIC − Constant for the Alphanumeric function key. static int VK_ALPHANUMERIC − Constant for the Alphanumeric function key. static int VK_ALT static int VK_ALT static int VK_ALT_GRAPH − Constant for the AltGraph function key. static int VK_ALT_GRAPH − Constant for the AltGraph function key. static int VK_AMPERSAND static int VK_AMPERSAND static int VK_ASTERISK static int VK_ASTERISK static int VK_AT − Constant for the "@" key. static int VK_AT − Constant for the "@" key. static int VK_B static int VK_B static int VK_BACK_QUOTE static int VK_BACK_QUOTE static int VK_BACK_SLASH − Constant for the back slash key, "\" static int VK_BACK_SLASH − Constant for the back slash key, "\" static int VK_BACK_SPACE static int VK_BACK_SPACE static int VK_BEGIN − Constant for the Begin key. static int VK_BEGIN − Constant for the Begin key. static int VK_BRACELEFT static int VK_BRACELEFT static int VK_BRACERIGHT static int VK_BRACERIGHT static int VK_C static int VK_C static int VK_CANCEL static int VK_CANCEL static int VK_CAPS_LOCK static int VK_CAPS_LOCK static int VK_CIRCUMFLEX − Constant for the "^" key. static int VK_CIRCUMFLEX − Constant for the "^" key. static int VK_CLEAR static int VK_CLEAR static int VK_CLOSE_BRACKET − Constant for the close bracket key, "]" static int VK_CLOSE_BRACKET − Constant for the close bracket key, "]" static int VK_CODE_INPUT − Constant for the Code Input function key. static int VK_CODE_INPUT − Constant for the Code Input function key. static int VK_COLON − Constant for the ":" key. static int VK_COLON − Constant for the ":" key. static int VK_COMMA − Constant for the comma key, "," static int VK_COMMA − Constant for the comma key, "," static int VK_COMPOSE − Constant for the Compose function key. static int VK_COMPOSE − Constant for the Compose function key. static int VK_CONTEXT_MENU − Constant for the Microsoft Windows Context Menu key. static int VK_CONTEXT_MENU − Constant for the Microsoft Windows Context Menu key. static int VK_CONTROL static int VK_CONTROL static int VK_CONVERT − Constant for the Convert function key. static int VK_CONVERT − Constant for the Convert function key. static int VK_COPY static int VK_COPY static int VK_CUT static int VK_CUT static int VK_D static int VK_D static int VK_DEAD_ABOVEDOT static int VK_DEAD_ABOVEDOT static int VK_DEAD_ABOVERING static int VK_DEAD_ABOVERING static int VK_DEAD_ACUTE static int VK_DEAD_ACUTE static int VK_DEAD_BREVE static int VK_DEAD_BREVE static int VK_DEAD_CARON static int VK_DEAD_CARON static int VK_DEAD_CEDILLA static int VK_DEAD_CEDILLA static int VK_DEAD_CIRCUMFLEX static int VK_DEAD_CIRCUMFLEX static int VK_DEAD_DIAERESIS static int VK_DEAD_DIAERESIS static int VK_DEAD_DOUBLEACUTE static int VK_DEAD_DOUBLEACUTE static int VK_DEAD_GRAVE static int VK_DEAD_GRAVE static int VK_DEAD_IOTA static int VK_DEAD_IOTA static int VK_DEAD_MACRON static int VK_DEAD_MACRON static int VK_DEAD_OGONEK static int VK_DEAD_OGONEK static int VK_DEAD_SEMIVOICED_SOUND static int VK_DEAD_SEMIVOICED_SOUND static int VK_DEAD_TILDE static int VK_DEAD_TILDE static int VK_DEAD_VOICED_SOUND static int VK_DEAD_VOICED_SOUND static int VK_DECIMAL static int VK_DECIMAL static int VK_DELETE static int VK_DELETE static int VK_DIVIDE static int VK_DIVIDE static int VK_DOLLAR − Constant for the "$" key. static int VK_DOLLAR − Constant for the "$" key. static int VK_DOWN − Constant for the non-numpad down arrow key. static int VK_DOWN − Constant for the non-numpad down arrow key. static int VK_E static int VK_E static int VK_END static int VK_END static int VK_ENTER static int VK_ENTER static int VK_EQUALS − Constant for the equals key, "=" static int VK_EQUALS − Constant for the equals key, "=" static int VK_ESCAPE static int VK_ESCAPE static int VK_EURO_SIGN − Constant for the Euro currency sign key. static int VK_EURO_SIGN − Constant for the Euro currency sign key. static int VK_EXCLAMATION_MARK − Constant for the "!" key. static int VK_EXCLAMATION_MARK − Constant for the "!" key. static int VK_F static int VK_F static int VK_F1 − Constant for the F1 function key. static int VK_F1 − Constant for the F1 function key. static int VK_F10 − Constant for the F10 function key. static int VK_F10 − Constant for the F10 function key. static int VK_F11 − Constant for the F11 function key. static int VK_F11 − Constant for the F11 function key. static int VK_F12 − Constant for the F12 function key. static int VK_F12 − Constant for the F12 function key. static int VK_F13 − Constant for the F13 function key. static int VK_F13 − Constant for the F13 function key. static int VK_F14 − Constant for the F14 function key. static int VK_F14 − Constant for the F14 function key. static int VK_F15 − Constant for the F15 function key. static int VK_F15 − Constant for the F15 function key. static int VK_F16 − Constant for the F16 function key. static int VK_F16 − Constant for the F16 function key. static int VK_F17 − Constant for the F17 function key. static int VK_F17 − Constant for the F17 function key. static int VK_F18 − Constant for the F18 function key. static int VK_F18 − Constant for the F18 function key. static int VK_F19 − Constant for the F19 function key. static int VK_F19 − Constant for the F19 function key. static int VK_F2 − Constant for the F2 function key. static int VK_F2 − Constant for the F2 function key. static int VK_F20 − Constant for the F20 function key. static int VK_F20 − Constant for the F20 function key. static int VK_F21 − Constant for the F21 function key. static int VK_F21 − Constant for the F21 function key. static int VK_F22 − Constant for the F22 function key. static int VK_F22 − Constant for the F22 function key. static int VK_F23 − Constant for the F23 function key. static int VK_F23 − Constant for the F23 function key. static int VK_F24 − Constant for the F24 function key. static int VK_F24 − Constant for the F24 function key. static int VK_F3 − Constant for the F3 function key. static int VK_F3 − Constant for the F3 function key. static int VK_F4 − Constant for the F4 function key. static int VK_F4 − Constant for the F4 function key. static int VK_F5 − Constant for the F5 function key. static int VK_F5 − Constant for the F5 function key. static int VK_F6 − Constant for the F6 function key. static int VK_F6 − Constant for the F6 function key. static int VK_F7 − Constant for the F7 function key. static int VK_F7 − Constant for the F7 function key. static int VK_F8 − Constant for the F8 function key. static int VK_F8 − Constant for the F8 function key. static int VK_F9 − Constant for the F9 function key. static int VK_F9 − Constant for the F9 function key. static int VK_FINAL static int VK_FINAL static int VK_FIND static int VK_FIND static int VK_FULL_WIDTH − Constant for the Full-Width Characters function key. static int VK_FULL_WIDTH − Constant for the Full-Width Characters function key. static int VK_G static int VK_G static int VK_GREATER static int VK_GREATER static int VK_H static int VK_H static int VK_HALF_WIDTH − Constant for the Half-Width Characters function key. static int VK_HALF_WIDTH − Constant for the Half-Width Characters function key. static int VK_HELP static int VK_HELP static int VK_HIRAGANA − Constant for the Hiragana function key. static int VK_HIRAGANA − Constant for the Hiragana function key. static int VK_HOME static int VK_HOME static int VK_I static int VK_I static int VK_INPUT_METHOD_ON_OFF − Constant for the input method on/off key. static int VK_INPUT_METHOD_ON_OFF − Constant for the input method on/off key. static int VK_INSERT static int VK_INSERT static int VK_INVERTED_EXCLAMATION_MARK − Constant for the inverted exclamation mark key. static int VK_INVERTED_EXCLAMATION_MARK − Constant for the inverted exclamation mark key. static int VK_J static int VK_J static int VK_JAPANESE_HIRAGANA − Constant for the Japanese-Hiragana function key. static int VK_JAPANESE_HIRAGANA − Constant for the Japanese-Hiragana function key. static int VK_JAPANESE_KATAKANA − Constant for the Japanese-Katakana function key. static int VK_JAPANESE_KATAKANA − Constant for the Japanese-Katakana function key. static int VK_JAPANESE_ROMAN − Constant for the Japanese-Roman function key. static int VK_JAPANESE_ROMAN − Constant for the Japanese-Roman function key. static int VK_K static int VK_K static int VK_KANA static int VK_KANA static int VK_KANA_LOCK − Constant for the locking Kana function key. static int VK_KANA_LOCK − Constant for the locking Kana function key. static int VK_KANJI static int VK_KANJI static int VK_KATAKANA − Constant for the Katakana function key. static int VK_KATAKANA − Constant for the Katakana function key. static int VK_KP_DOWN − Constant for the numeric keypad down arrow key. static int VK_KP_DOWN − Constant for the numeric keypad down arrow key. static int VK_KP_LEFT − Constant for the numeric keypad left arrow key. static int VK_KP_LEFT − Constant for the numeric keypad left arrow key. static int VK_KP_RIGHT − Constant for the numeric keypad right arrow key. static int VK_KP_RIGHT − Constant for the numeric keypad right arrow key. static int VK_KP_UP − Constant for the numeric keypad up arrow key. static int VK_KP_UP − Constant for the numeric keypad up arrow key. static int VK_L static int VK_L static int VK_LEFT − Constant for the non-numpad left arrow key. static int VK_LEFT − Constant for the non-numpad left arrow key. static int VK_LEFT_PARENTHESIS − Constant for the "(" key. static int VK_LEFT_PARENTHESIS − Constant for the "(" key. static int VK_LESS static int VK_LESS static int VK_M static int VK_M static int VK_META static int VK_META static int VK_MINUS − Constant for the minus key, "-" static int VK_MINUS − Constant for the minus key, "-" static int VK_MODECHANGE static int VK_MODECHANGE static int VK_MULTIPLY static int VK_MULTIPLY static int VK_N static int VK_N static int VK_NONCONVERT − Constant for the Don't Convert function key. static int VK_NONCONVERT − Constant for the Don't Convert function key. static int VK_NUM_LOCK static int VK_NUM_LOCK static int VK_NUMBER_SIGN − Constant for the "#" key. static int VK_NUMBER_SIGN − Constant for the "#" key. static int VK_NUMPAD0 static int VK_NUMPAD0 static int VK_NUMPAD1 static int VK_NUMPAD1 static int VK_NUMPAD2 static int VK_NUMPAD2 static int VK_NUMPAD3 static int VK_NUMPAD3 static int VK_NUMPAD4 static int VK_NUMPAD4 static int VK_NUMPAD5 static int VK_NUMPAD5 static int VK_NUMPAD6 static int VK_NUMPAD6 static int VK_NUMPAD7 static int VK_NUMPAD7 static int VK_NUMPAD8 static int VK_NUMPAD8 static int VK_NUMPAD9 static int VK_NUMPAD9 static int VK_O static int VK_O static int VK_OPEN_BRACKET − Constant for the open bracket key, "[" static int VK_OPEN_BRACKET − Constant for the open bracket key, "[" static int VK_P static int VK_P static int VK_PAGE_DOWN static int VK_PAGE_DOWN static int VK_PAGE_UP static int VK_PAGE_UP static int VK_PASTE static int VK_PASTE static int VK_PAUSE static int VK_PAUSE static int VK_PERIOD − Constant for the period key, "." static int VK_PERIOD − Constant for the period key, "." static int VK_PLUS − Constant for the "+" key. static int VK_PLUS − Constant for the "+" key. static int VK_PREVIOUS_CANDIDATE − Constant for the Previous Candidate function key. static int VK_PREVIOUS_CANDIDATE − Constant for the Previous Candidate function key. static int VK_PRINTSCREEN static int VK_PRINTSCREEN static int VK_PROPS static int VK_PROPS static int VK_Q static int VK_Q static int VK_QUOTE static int VK_QUOTE static int VK_QUOTEDBL static int VK_QUOTEDBL static int VK_R static int VK_R static int VK_RIGHT − Constant for the non-numpad right arrow key. static int VK_RIGHT − Constant for the non-numpad right arrow key. static int VK_RIGHT_PARENTHESIS − Constant for the ")" key. static int VK_RIGHT_PARENTHESIS − Constant for the ")" key. static int VK_ROMAN_CHARACTERS − Constant for the Roman Characters function key. static int VK_ROMAN_CHARACTERS − Constant for the Roman Characters function key. static int VK_S static int VK_S static int VK_SCROLL_LOCK static int VK_SCROLL_LOCK static int VK_SEMICOLON − Constant for the semicolon key, ";" static int VK_SEMICOLON − Constant for the semicolon key, ";" static int VK_SEPARATER − This constant is obsolete, and is included only for backwards compatibility. static int VK_SEPARATER − This constant is obsolete, and is included only for backwards compatibility. static int VK_SEPARATOR − Constant for the Numpad Separator key. static int VK_SEPARATOR − Constant for the Numpad Separator key. static int VK_SHIFT static int VK_SHIFT static int VK_SLASH − Constant for the forward slash key, "/" static int VK_SLASH − Constant for the forward slash key, "/" static int VK_SPACE static int VK_SPACE static int VK_STOP static int VK_STOP static int VK_SUBTRACT static int VK_SUBTRACT static int VK_T static int VK_T static int VK_TAB static int VK_TAB static int VK_U static int VK_U static int VK_UNDEFINED − This value is used to indicate that the keyCode is unknown. static int VK_UNDEFINED − This value is used to indicate that the keyCode is unknown. static int VK_UNDERSCORE − Constant for the "_" key. static int VK_UNDERSCORE − Constant for the "_" key. static int VK_UNDO static int VK_UNDO static int VK_UP − Constant for the non-numpad up arrow key. static int VK_UP − Constant for the non-numpad up arrow key. static int VK_V static int VK_V static int VK_W static int VK_W static int VK_WINDOWS − Constant for the Microsoft Windows "Windows" key. static int VK_WINDOWS − Constant for the Microsoft Windows "Windows" key. static int VK_X static int VK_X static int VK_Y static int VK_Y static int VK_Z static int VK_Z KeyEvent(Component source, int id, long when, int modifiers, int keyCode) Deprecated. as of JDK1.1 KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar) Constructs a KeyEvent object. KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation) char getKeyChar() Returns the character associated with the key in this event. int getKeyCode() Returns the integer keyCode associated with the key in this event. int getKeyLocation() Returns the location of the key that originated this key event. static String getKeyModifiersText(int modifiers) Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift". static String getKeyText(int keyCode) Returns a String describing the keyCode, such as "HOME", "F1" or "A". boolean isActionKey() Returns whether the key in this event is an "action" key. String paramString() Returns a parameter string identifying this event. void setKeyChar(char keyChar) Set the keyChar value to indicate a logical character. void setKeyCode(int keyCode) Set the keyCode value to indicate a physical key. void setModifiers(int modifiers) Deprecated. as of JDK1.1.4 This class inherits methods from the following classes − java.awt.event.InputEvent java.awt.event.ComponentEvent java.awt.AWTEvent java.util.EventObject java.lang.Object 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1900, "s": 1763, "text": "On entering the character the Key event is generated.There are three types of key events which are represented by the integer constants." }, { "code": null, "e": 1912, "s": 1900, "text": "KEY_PRESSED" }, { "code": null, "e": 1924, "s": 1912, "text": "KEY_RELASED" }, { "code": null, "e": 1934, "s": 1924, "text": "KEY_TYPED" }, { "code": null, "e": 1999, "s": 1934, "text": "Following is the declaration for java.awt.event.KeyEvent class −" }, { "code": null, "e": 2044, "s": 1999, "text": "public class KeyEvent\n extends InputEvent\n" }, { "code": null, "e": 2101, "s": 2044, "text": "Following are the fields for java.awt.InputEvent class −" }, { "code": null, "e": 2244, "s": 2101, "text": "static char CHAR_UNDEFINED − KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value." }, { "code": null, "e": 2387, "s": 2244, "text": "static char CHAR_UNDEFINED − KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value." }, { "code": null, "e": 2468, "s": 2387, "text": "static int KEY_FIRST − The first number in the range of IDs used for key events." }, { "code": null, "e": 2549, "s": 2468, "text": "static int KEY_FIRST − The first number in the range of IDs used for key events." }, { "code": null, "e": 2628, "s": 2549, "text": "static int KEY_LAST − The last number in the range of IDs used for key events." }, { "code": null, "e": 2707, "s": 2628, "text": "static int KEY_LAST − The last number in the range of IDs used for key events." }, { "code": null, "e": 2878, "s": 2707, "text": "static int KEY_LOCATION_LEFT − A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key)." }, { "code": null, "e": 3049, "s": 2878, "text": "static int KEY_LOCATION_LEFT − A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key)." }, { "code": null, "e": 3215, "s": 3049, "text": "static int KEY_LOCATION_NUMPAD − A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad." }, { "code": null, "e": 3381, "s": 3215, "text": "static int KEY_LOCATION_NUMPAD − A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad." }, { "code": null, "e": 3554, "s": 3381, "text": "static int KEY_LOCATION_RIGHT − A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key)." }, { "code": null, "e": 3727, "s": 3554, "text": "static int KEY_LOCATION_RIGHT − A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key)." }, { "code": null, "e": 4000, "s": 3727, "text": "static int KEY_LOCATION_STANDARD − A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad)." }, { "code": null, "e": 4273, "s": 4000, "text": "static int KEY_LOCATION_STANDARD − A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad)." }, { "code": null, "e": 4384, "s": 4273, "text": "static int KEY_LOCATION_UNKNOWN − A constant indicating that the keyLocation is indeterminate or not relevant." }, { "code": null, "e": 4495, "s": 4384, "text": "static int KEY_LOCATION_UNKNOWN − A constant indicating that the keyLocation is indeterminate or not relevant." }, { "code": null, "e": 4545, "s": 4495, "text": "static int KEY_PRESSED − The \"key pressed\" event." }, { "code": null, "e": 4595, "s": 4545, "text": "static int KEY_PRESSED − The \"key pressed\" event." }, { "code": null, "e": 4647, "s": 4595, "text": "static int KEY_RELEASED − The \"key released\" event." }, { "code": null, "e": 4699, "s": 4647, "text": "static int KEY_RELEASED − The \"key released\" event." }, { "code": null, "e": 4745, "s": 4699, "text": "static int KEY_TYPED − The \"key typed\" event." }, { "code": null, "e": 4791, "s": 4745, "text": "static int KEY_TYPED − The \"key typed\" event." }, { "code": null, "e": 4873, "s": 4791, "text": "static int VK_0 − VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0×30 - 0×39)" }, { "code": null, "e": 4955, "s": 4873, "text": "static int VK_0 − VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0×30 - 0×39)" }, { "code": null, "e": 4971, "s": 4955, "text": "static int VK_1" }, { "code": null, "e": 4987, "s": 4971, "text": "static int VK_1" }, { "code": null, "e": 5003, "s": 4987, "text": "static int VK_2" }, { "code": null, "e": 5019, "s": 5003, "text": "static int VK_2" }, { "code": null, "e": 5035, "s": 5019, "text": "static int VK_3" }, { "code": null, "e": 5051, "s": 5035, "text": "static int VK_3" }, { "code": null, "e": 5067, "s": 5051, "text": "static int VK_4" }, { "code": null, "e": 5083, "s": 5067, "text": "static int VK_4" }, { "code": null, "e": 5099, "s": 5083, "text": "static int VK_5" }, { "code": null, "e": 5115, "s": 5099, "text": "static int VK_5" }, { "code": null, "e": 5131, "s": 5115, "text": "static int VK_6" }, { "code": null, "e": 5147, "s": 5131, "text": "static int VK_6" }, { "code": null, "e": 5163, "s": 5147, "text": "static int VK_7" }, { "code": null, "e": 5179, "s": 5163, "text": "static int VK_7" }, { "code": null, "e": 5195, "s": 5179, "text": "static int VK_8" }, { "code": null, "e": 5211, "s": 5195, "text": "static int VK_8" }, { "code": null, "e": 5227, "s": 5211, "text": "static int VK_9" }, { "code": null, "e": 5243, "s": 5227, "text": "static int VK_9" }, { "code": null, "e": 5325, "s": 5243, "text": "static int VK_A − VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0×41 - 0×5A)" }, { "code": null, "e": 5407, "s": 5325, "text": "static int VK_A − VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0×41 - 0×5A)" }, { "code": null, "e": 5478, "s": 5407, "text": "static int VK_ACCEPT − Constant for the Accept or Commit function key." }, { "code": null, "e": 5549, "s": 5478, "text": "static int VK_ACCEPT − Constant for the Accept or Commit function key." }, { "code": null, "e": 5567, "s": 5549, "text": "static int VK_ADD" }, { "code": null, "e": 5585, "s": 5567, "text": "static int VK_ADD" }, { "code": null, "e": 5605, "s": 5585, "text": "static int VK_AGAIN" }, { "code": null, "e": 5625, "s": 5605, "text": "static int VK_AGAIN" }, { "code": null, "e": 5702, "s": 5625, "text": "static int VK_ALL_CANDIDATES − Constant for the All Candidates function key." }, { "code": null, "e": 5779, "s": 5702, "text": "static int VK_ALL_CANDIDATES − Constant for the All Candidates function key." }, { "code": null, "e": 5852, "s": 5779, "text": "static int VK_ALPHANUMERIC − Constant for the Alphanumeric function key." }, { "code": null, "e": 5925, "s": 5852, "text": "static int VK_ALPHANUMERIC − Constant for the Alphanumeric function key." }, { "code": null, "e": 5943, "s": 5925, "text": "static int VK_ALT" }, { "code": null, "e": 5961, "s": 5943, "text": "static int VK_ALT" }, { "code": null, "e": 6027, "s": 5961, "text": "static int VK_ALT_GRAPH − Constant for the AltGraph function key." }, { "code": null, "e": 6093, "s": 6027, "text": "static int VK_ALT_GRAPH − Constant for the AltGraph function key." }, { "code": null, "e": 6117, "s": 6093, "text": "static int VK_AMPERSAND" }, { "code": null, "e": 6141, "s": 6117, "text": "static int VK_AMPERSAND" }, { "code": null, "e": 6164, "s": 6141, "text": "static int VK_ASTERISK" }, { "code": null, "e": 6187, "s": 6164, "text": "static int VK_ASTERISK" }, { "code": null, "e": 6232, "s": 6187, "text": "static int VK_AT − Constant for the \"@\" key." }, { "code": null, "e": 6277, "s": 6232, "text": "static int VK_AT − Constant for the \"@\" key." }, { "code": null, "e": 6293, "s": 6277, "text": "static int VK_B" }, { "code": null, "e": 6309, "s": 6293, "text": "static int VK_B" }, { "code": null, "e": 6334, "s": 6309, "text": "static int VK_BACK_QUOTE" }, { "code": null, "e": 6359, "s": 6334, "text": "static int VK_BACK_QUOTE" }, { "code": null, "e": 6423, "s": 6359, "text": "static int VK_BACK_SLASH − Constant for the back slash key, \"\\\"" }, { "code": null, "e": 6487, "s": 6423, "text": "static int VK_BACK_SLASH − Constant for the back slash key, \"\\\"" }, { "code": null, "e": 6512, "s": 6487, "text": "static int VK_BACK_SPACE" }, { "code": null, "e": 6537, "s": 6512, "text": "static int VK_BACK_SPACE" }, { "code": null, "e": 6587, "s": 6537, "text": "static int VK_BEGIN − Constant for the Begin key." }, { "code": null, "e": 6637, "s": 6587, "text": "static int VK_BEGIN − Constant for the Begin key." }, { "code": null, "e": 6661, "s": 6637, "text": "static int VK_BRACELEFT" }, { "code": null, "e": 6685, "s": 6661, "text": "static int VK_BRACELEFT" }, { "code": null, "e": 6710, "s": 6685, "text": "static int VK_BRACERIGHT" }, { "code": null, "e": 6735, "s": 6710, "text": "static int VK_BRACERIGHT" }, { "code": null, "e": 6751, "s": 6735, "text": "static int VK_C" }, { "code": null, "e": 6767, "s": 6751, "text": "static int VK_C" }, { "code": null, "e": 6788, "s": 6767, "text": "static int VK_CANCEL" }, { "code": null, "e": 6809, "s": 6788, "text": "static int VK_CANCEL" }, { "code": null, "e": 6833, "s": 6809, "text": "static int VK_CAPS_LOCK" }, { "code": null, "e": 6857, "s": 6833, "text": "static int VK_CAPS_LOCK" }, { "code": null, "e": 6910, "s": 6857, "text": "static int VK_CIRCUMFLEX − Constant for the \"^\" key." }, { "code": null, "e": 6963, "s": 6910, "text": "static int VK_CIRCUMFLEX − Constant for the \"^\" key." }, { "code": null, "e": 6983, "s": 6963, "text": "static int VK_CLEAR" }, { "code": null, "e": 7003, "s": 6983, "text": "static int VK_CLEAR" }, { "code": null, "e": 7073, "s": 7003, "text": "static int VK_CLOSE_BRACKET − Constant for the close bracket key, \"]\"" }, { "code": null, "e": 7143, "s": 7073, "text": "static int VK_CLOSE_BRACKET − Constant for the close bracket key, \"]\"" }, { "code": null, "e": 7212, "s": 7143, "text": "static int VK_CODE_INPUT − Constant for the Code Input function key." }, { "code": null, "e": 7281, "s": 7212, "text": "static int VK_CODE_INPUT − Constant for the Code Input function key." }, { "code": null, "e": 7329, "s": 7281, "text": "static int VK_COLON − Constant for the \":\" key." }, { "code": null, "e": 7377, "s": 7329, "text": "static int VK_COLON − Constant for the \":\" key." }, { "code": null, "e": 7431, "s": 7377, "text": "static int VK_COMMA − Constant for the comma key, \",\"" }, { "code": null, "e": 7485, "s": 7431, "text": "static int VK_COMMA − Constant for the comma key, \",\"" }, { "code": null, "e": 7548, "s": 7485, "text": "static int VK_COMPOSE − Constant for the Compose function key." }, { "code": null, "e": 7611, "s": 7548, "text": "static int VK_COMPOSE − Constant for the Compose function key." }, { "code": null, "e": 7693, "s": 7611, "text": "static int VK_CONTEXT_MENU − Constant for the Microsoft Windows Context Menu key." }, { "code": null, "e": 7775, "s": 7693, "text": "static int VK_CONTEXT_MENU − Constant for the Microsoft Windows Context Menu key." }, { "code": null, "e": 7797, "s": 7775, "text": "static int VK_CONTROL" }, { "code": null, "e": 7819, "s": 7797, "text": "static int VK_CONTROL" }, { "code": null, "e": 7882, "s": 7819, "text": "static int VK_CONVERT − Constant for the Convert function key." }, { "code": null, "e": 7945, "s": 7882, "text": "static int VK_CONVERT − Constant for the Convert function key." }, { "code": null, "e": 7964, "s": 7945, "text": "static int VK_COPY" }, { "code": null, "e": 7983, "s": 7964, "text": "static int VK_COPY" }, { "code": null, "e": 8001, "s": 7983, "text": "static int VK_CUT" }, { "code": null, "e": 8019, "s": 8001, "text": "static int VK_CUT" }, { "code": null, "e": 8035, "s": 8019, "text": "static int VK_D" }, { "code": null, "e": 8051, "s": 8035, "text": "static int VK_D" }, { "code": null, "e": 8079, "s": 8051, "text": "static int VK_DEAD_ABOVEDOT" }, { "code": null, "e": 8107, "s": 8079, "text": "static int VK_DEAD_ABOVEDOT" }, { "code": null, "e": 8136, "s": 8107, "text": "static int VK_DEAD_ABOVERING" }, { "code": null, "e": 8165, "s": 8136, "text": "static int VK_DEAD_ABOVERING" }, { "code": null, "e": 8190, "s": 8165, "text": "static int VK_DEAD_ACUTE" }, { "code": null, "e": 8215, "s": 8190, "text": "static int VK_DEAD_ACUTE" }, { "code": null, "e": 8240, "s": 8215, "text": "static int VK_DEAD_BREVE" }, { "code": null, "e": 8265, "s": 8240, "text": "static int VK_DEAD_BREVE" }, { "code": null, "e": 8290, "s": 8265, "text": "static int VK_DEAD_CARON" }, { "code": null, "e": 8315, "s": 8290, "text": "static int VK_DEAD_CARON" }, { "code": null, "e": 8342, "s": 8315, "text": "static int VK_DEAD_CEDILLA" }, { "code": null, "e": 8369, "s": 8342, "text": "static int VK_DEAD_CEDILLA" }, { "code": null, "e": 8399, "s": 8369, "text": "static int VK_DEAD_CIRCUMFLEX" }, { "code": null, "e": 8429, "s": 8399, "text": "static int VK_DEAD_CIRCUMFLEX" }, { "code": null, "e": 8458, "s": 8429, "text": "static int VK_DEAD_DIAERESIS" }, { "code": null, "e": 8487, "s": 8458, "text": "static int VK_DEAD_DIAERESIS" }, { "code": null, "e": 8518, "s": 8487, "text": "static int VK_DEAD_DOUBLEACUTE" }, { "code": null, "e": 8549, "s": 8518, "text": "static int VK_DEAD_DOUBLEACUTE" }, { "code": null, "e": 8574, "s": 8549, "text": "static int VK_DEAD_GRAVE" }, { "code": null, "e": 8599, "s": 8574, "text": "static int VK_DEAD_GRAVE" }, { "code": null, "e": 8623, "s": 8599, "text": "static int VK_DEAD_IOTA" }, { "code": null, "e": 8647, "s": 8623, "text": "static int VK_DEAD_IOTA" }, { "code": null, "e": 8673, "s": 8647, "text": "static int VK_DEAD_MACRON" }, { "code": null, "e": 8699, "s": 8673, "text": "static int VK_DEAD_MACRON" }, { "code": null, "e": 8725, "s": 8699, "text": "static int VK_DEAD_OGONEK" }, { "code": null, "e": 8751, "s": 8725, "text": "static int VK_DEAD_OGONEK" }, { "code": null, "e": 8787, "s": 8751, "text": "static int VK_DEAD_SEMIVOICED_SOUND" }, { "code": null, "e": 8823, "s": 8787, "text": "static int VK_DEAD_SEMIVOICED_SOUND" }, { "code": null, "e": 8848, "s": 8823, "text": "static int VK_DEAD_TILDE" }, { "code": null, "e": 8873, "s": 8848, "text": "static int VK_DEAD_TILDE" }, { "code": null, "e": 8905, "s": 8873, "text": "static int VK_DEAD_VOICED_SOUND" }, { "code": null, "e": 8937, "s": 8905, "text": "static int VK_DEAD_VOICED_SOUND" }, { "code": null, "e": 8959, "s": 8937, "text": "static int VK_DECIMAL" }, { "code": null, "e": 8981, "s": 8959, "text": "static int VK_DECIMAL" }, { "code": null, "e": 9002, "s": 8981, "text": "static int VK_DELETE" }, { "code": null, "e": 9023, "s": 9002, "text": "static int VK_DELETE" }, { "code": null, "e": 9044, "s": 9023, "text": "static int VK_DIVIDE" }, { "code": null, "e": 9065, "s": 9044, "text": "static int VK_DIVIDE" }, { "code": null, "e": 9114, "s": 9065, "text": "static int VK_DOLLAR − Constant for the \"$\" key." }, { "code": null, "e": 9163, "s": 9114, "text": "static int VK_DOLLAR − Constant for the \"$\" key." }, { "code": null, "e": 9228, "s": 9163, "text": "static int VK_DOWN − Constant for the non-numpad down arrow key." }, { "code": null, "e": 9293, "s": 9228, "text": "static int VK_DOWN − Constant for the non-numpad down arrow key." }, { "code": null, "e": 9309, "s": 9293, "text": "static int VK_E" }, { "code": null, "e": 9325, "s": 9309, "text": "static int VK_E" }, { "code": null, "e": 9343, "s": 9325, "text": "static int VK_END" }, { "code": null, "e": 9361, "s": 9343, "text": "static int VK_END" }, { "code": null, "e": 9381, "s": 9361, "text": "static int VK_ENTER" }, { "code": null, "e": 9401, "s": 9381, "text": "static int VK_ENTER" }, { "code": null, "e": 9457, "s": 9401, "text": "static int VK_EQUALS − Constant for the equals key, \"=\"" }, { "code": null, "e": 9513, "s": 9457, "text": "static int VK_EQUALS − Constant for the equals key, \"=\"" }, { "code": null, "e": 9534, "s": 9513, "text": "static int VK_ESCAPE" }, { "code": null, "e": 9555, "s": 9534, "text": "static int VK_ESCAPE" }, { "code": null, "e": 9622, "s": 9555, "text": "static int VK_EURO_SIGN − Constant for the Euro currency sign key." }, { "code": null, "e": 9689, "s": 9622, "text": "static int VK_EURO_SIGN − Constant for the Euro currency sign key." }, { "code": null, "e": 9748, "s": 9689, "text": "static int VK_EXCLAMATION_MARK − Constant for the \"!\" key." }, { "code": null, "e": 9807, "s": 9748, "text": "static int VK_EXCLAMATION_MARK − Constant for the \"!\" key." }, { "code": null, "e": 9823, "s": 9807, "text": "static int VK_F" }, { "code": null, "e": 9839, "s": 9823, "text": "static int VK_F" }, { "code": null, "e": 9892, "s": 9839, "text": "static int VK_F1 − Constant for the F1 function key." }, { "code": null, "e": 9945, "s": 9892, "text": "static int VK_F1 − Constant for the F1 function key." }, { "code": null, "e": 10000, "s": 9945, "text": "static int VK_F10 − Constant for the F10 function key." }, { "code": null, "e": 10055, "s": 10000, "text": "static int VK_F10 − Constant for the F10 function key." }, { "code": null, "e": 10110, "s": 10055, "text": "static int VK_F11 − Constant for the F11 function key." }, { "code": null, "e": 10165, "s": 10110, "text": "static int VK_F11 − Constant for the F11 function key." }, { "code": null, "e": 10220, "s": 10165, "text": "static int VK_F12 − Constant for the F12 function key." }, { "code": null, "e": 10275, "s": 10220, "text": "static int VK_F12 − Constant for the F12 function key." }, { "code": null, "e": 10330, "s": 10275, "text": "static int VK_F13 − Constant for the F13 function key." }, { "code": null, "e": 10385, "s": 10330, "text": "static int VK_F13 − Constant for the F13 function key." }, { "code": null, "e": 10440, "s": 10385, "text": "static int VK_F14 − Constant for the F14 function key." }, { "code": null, "e": 10495, "s": 10440, "text": "static int VK_F14 − Constant for the F14 function key." }, { "code": null, "e": 10550, "s": 10495, "text": "static int VK_F15 − Constant for the F15 function key." }, { "code": null, "e": 10605, "s": 10550, "text": "static int VK_F15 − Constant for the F15 function key." }, { "code": null, "e": 10660, "s": 10605, "text": "static int VK_F16 − Constant for the F16 function key." }, { "code": null, "e": 10715, "s": 10660, "text": "static int VK_F16 − Constant for the F16 function key." }, { "code": null, "e": 10770, "s": 10715, "text": "static int VK_F17 − Constant for the F17 function key." }, { "code": null, "e": 10825, "s": 10770, "text": "static int VK_F17 − Constant for the F17 function key." }, { "code": null, "e": 10880, "s": 10825, "text": "static int VK_F18 − Constant for the F18 function key." }, { "code": null, "e": 10935, "s": 10880, "text": "static int VK_F18 − Constant for the F18 function key." }, { "code": null, "e": 10990, "s": 10935, "text": "static int VK_F19 − Constant for the F19 function key." }, { "code": null, "e": 11045, "s": 10990, "text": "static int VK_F19 − Constant for the F19 function key." }, { "code": null, "e": 11098, "s": 11045, "text": "static int VK_F2 − Constant for the F2 function key." }, { "code": null, "e": 11151, "s": 11098, "text": "static int VK_F2 − Constant for the F2 function key." }, { "code": null, "e": 11206, "s": 11151, "text": "static int VK_F20 − Constant for the F20 function key." }, { "code": null, "e": 11261, "s": 11206, "text": "static int VK_F20 − Constant for the F20 function key." }, { "code": null, "e": 11316, "s": 11261, "text": "static int VK_F21 − Constant for the F21 function key." }, { "code": null, "e": 11371, "s": 11316, "text": "static int VK_F21 − Constant for the F21 function key." }, { "code": null, "e": 11426, "s": 11371, "text": "static int VK_F22 − Constant for the F22 function key." }, { "code": null, "e": 11481, "s": 11426, "text": "static int VK_F22 − Constant for the F22 function key." }, { "code": null, "e": 11536, "s": 11481, "text": "static int VK_F23 − Constant for the F23 function key." }, { "code": null, "e": 11591, "s": 11536, "text": "static int VK_F23 − Constant for the F23 function key." }, { "code": null, "e": 11646, "s": 11591, "text": "static int VK_F24 − Constant for the F24 function key." }, { "code": null, "e": 11701, "s": 11646, "text": "static int VK_F24 − Constant for the F24 function key." }, { "code": null, "e": 11754, "s": 11701, "text": "static int VK_F3 − Constant for the F3 function key." }, { "code": null, "e": 11807, "s": 11754, "text": "static int VK_F3 − Constant for the F3 function key." }, { "code": null, "e": 11860, "s": 11807, "text": "static int VK_F4 − Constant for the F4 function key." }, { "code": null, "e": 11913, "s": 11860, "text": "static int VK_F4 − Constant for the F4 function key." }, { "code": null, "e": 11966, "s": 11913, "text": "static int VK_F5 − Constant for the F5 function key." }, { "code": null, "e": 12019, "s": 11966, "text": "static int VK_F5 − Constant for the F5 function key." }, { "code": null, "e": 12072, "s": 12019, "text": "static int VK_F6 − Constant for the F6 function key." }, { "code": null, "e": 12125, "s": 12072, "text": "static int VK_F6 − Constant for the F6 function key." }, { "code": null, "e": 12178, "s": 12125, "text": "static int VK_F7 − Constant for the F7 function key." }, { "code": null, "e": 12231, "s": 12178, "text": "static int VK_F7 − Constant for the F7 function key." }, { "code": null, "e": 12284, "s": 12231, "text": "static int VK_F8 − Constant for the F8 function key." }, { "code": null, "e": 12337, "s": 12284, "text": "static int VK_F8 − Constant for the F8 function key." }, { "code": null, "e": 12390, "s": 12337, "text": "static int VK_F9 − Constant for the F9 function key." }, { "code": null, "e": 12443, "s": 12390, "text": "static int VK_F9 − Constant for the F9 function key." }, { "code": null, "e": 12463, "s": 12443, "text": "static int VK_FINAL" }, { "code": null, "e": 12483, "s": 12463, "text": "static int VK_FINAL" }, { "code": null, "e": 12502, "s": 12483, "text": "static int VK_FIND" }, { "code": null, "e": 12521, "s": 12502, "text": "static int VK_FIND" }, { "code": null, "e": 12601, "s": 12521, "text": "static int VK_FULL_WIDTH − Constant for the Full-Width Characters function key." }, { "code": null, "e": 12681, "s": 12601, "text": "static int VK_FULL_WIDTH − Constant for the Full-Width Characters function key." }, { "code": null, "e": 12697, "s": 12681, "text": "static int VK_G" }, { "code": null, "e": 12713, "s": 12697, "text": "static int VK_G" }, { "code": null, "e": 12735, "s": 12713, "text": "static int VK_GREATER" }, { "code": null, "e": 12757, "s": 12735, "text": "static int VK_GREATER" }, { "code": null, "e": 12773, "s": 12757, "text": "static int VK_H" }, { "code": null, "e": 12789, "s": 12773, "text": "static int VK_H" }, { "code": null, "e": 12869, "s": 12789, "text": "static int VK_HALF_WIDTH − Constant for the Half-Width Characters function key." }, { "code": null, "e": 12949, "s": 12869, "text": "static int VK_HALF_WIDTH − Constant for the Half-Width Characters function key." }, { "code": null, "e": 12968, "s": 12949, "text": "static int VK_HELP" }, { "code": null, "e": 12987, "s": 12968, "text": "static int VK_HELP" }, { "code": null, "e": 13052, "s": 12987, "text": "static int VK_HIRAGANA − Constant for the Hiragana function key." }, { "code": null, "e": 13117, "s": 13052, "text": "static int VK_HIRAGANA − Constant for the Hiragana function key." }, { "code": null, "e": 13136, "s": 13117, "text": "static int VK_HOME" }, { "code": null, "e": 13155, "s": 13136, "text": "static int VK_HOME" }, { "code": null, "e": 13171, "s": 13155, "text": "static int VK_I" }, { "code": null, "e": 13187, "s": 13171, "text": "static int VK_I" }, { "code": null, "e": 13265, "s": 13187, "text": "static int VK_INPUT_METHOD_ON_OFF − Constant for the input method on/off key." }, { "code": null, "e": 13343, "s": 13265, "text": "static int VK_INPUT_METHOD_ON_OFF − Constant for the input method on/off key." }, { "code": null, "e": 13364, "s": 13343, "text": "static int VK_INSERT" }, { "code": null, "e": 13385, "s": 13364, "text": "static int VK_INSERT" }, { "code": null, "e": 13475, "s": 13385, "text": "static int VK_INVERTED_EXCLAMATION_MARK − Constant for the inverted exclamation mark key." }, { "code": null, "e": 13565, "s": 13475, "text": "static int VK_INVERTED_EXCLAMATION_MARK − Constant for the inverted exclamation mark key." }, { "code": null, "e": 13581, "s": 13565, "text": "static int VK_J" }, { "code": null, "e": 13597, "s": 13581, "text": "static int VK_J" }, { "code": null, "e": 13680, "s": 13597, "text": "static int VK_JAPANESE_HIRAGANA − Constant for the Japanese-Hiragana function key." }, { "code": null, "e": 13763, "s": 13680, "text": "static int VK_JAPANESE_HIRAGANA − Constant for the Japanese-Hiragana function key." }, { "code": null, "e": 13846, "s": 13763, "text": "static int VK_JAPANESE_KATAKANA − Constant for the Japanese-Katakana function key." }, { "code": null, "e": 13929, "s": 13846, "text": "static int VK_JAPANESE_KATAKANA − Constant for the Japanese-Katakana function key." }, { "code": null, "e": 14006, "s": 13929, "text": "static int VK_JAPANESE_ROMAN − Constant for the Japanese-Roman function key." }, { "code": null, "e": 14083, "s": 14006, "text": "static int VK_JAPANESE_ROMAN − Constant for the Japanese-Roman function key." }, { "code": null, "e": 14099, "s": 14083, "text": "static int VK_K" }, { "code": null, "e": 14115, "s": 14099, "text": "static int VK_K" }, { "code": null, "e": 14134, "s": 14115, "text": "static int VK_KANA" }, { "code": null, "e": 14153, "s": 14134, "text": "static int VK_KANA" }, { "code": null, "e": 14223, "s": 14153, "text": "static int VK_KANA_LOCK − Constant for the locking Kana function key." }, { "code": null, "e": 14293, "s": 14223, "text": "static int VK_KANA_LOCK − Constant for the locking Kana function key." }, { "code": null, "e": 14313, "s": 14293, "text": "static int VK_KANJI" }, { "code": null, "e": 14333, "s": 14313, "text": "static int VK_KANJI" }, { "code": null, "e": 14398, "s": 14333, "text": "static int VK_KATAKANA − Constant for the Katakana function key." }, { "code": null, "e": 14463, "s": 14398, "text": "static int VK_KATAKANA − Constant for the Katakana function key." }, { "code": null, "e": 14535, "s": 14463, "text": "static int VK_KP_DOWN − Constant for the numeric keypad down arrow key." }, { "code": null, "e": 14607, "s": 14535, "text": "static int VK_KP_DOWN − Constant for the numeric keypad down arrow key." }, { "code": null, "e": 14679, "s": 14607, "text": "static int VK_KP_LEFT − Constant for the numeric keypad left arrow key." }, { "code": null, "e": 14751, "s": 14679, "text": "static int VK_KP_LEFT − Constant for the numeric keypad left arrow key." }, { "code": null, "e": 14825, "s": 14751, "text": "static int VK_KP_RIGHT − Constant for the numeric keypad right arrow key." }, { "code": null, "e": 14899, "s": 14825, "text": "static int VK_KP_RIGHT − Constant for the numeric keypad right arrow key." }, { "code": null, "e": 14967, "s": 14899, "text": "static int VK_KP_UP − Constant for the numeric keypad up arrow key." }, { "code": null, "e": 15035, "s": 14967, "text": "static int VK_KP_UP − Constant for the numeric keypad up arrow key." }, { "code": null, "e": 15051, "s": 15035, "text": "static int VK_L" }, { "code": null, "e": 15067, "s": 15051, "text": "static int VK_L" }, { "code": null, "e": 15132, "s": 15067, "text": "static int VK_LEFT − Constant for the non-numpad left arrow key." }, { "code": null, "e": 15197, "s": 15132, "text": "static int VK_LEFT − Constant for the non-numpad left arrow key." }, { "code": null, "e": 15256, "s": 15197, "text": "static int VK_LEFT_PARENTHESIS − Constant for the \"(\" key." }, { "code": null, "e": 15315, "s": 15256, "text": "static int VK_LEFT_PARENTHESIS − Constant for the \"(\" key." }, { "code": null, "e": 15334, "s": 15315, "text": "static int VK_LESS" }, { "code": null, "e": 15353, "s": 15334, "text": "static int VK_LESS" }, { "code": null, "e": 15369, "s": 15353, "text": "static int VK_M" }, { "code": null, "e": 15385, "s": 15369, "text": "static int VK_M" }, { "code": null, "e": 15404, "s": 15385, "text": "static int VK_META" }, { "code": null, "e": 15423, "s": 15404, "text": "static int VK_META" }, { "code": null, "e": 15477, "s": 15423, "text": "static int VK_MINUS − Constant for the minus key, \"-\"" }, { "code": null, "e": 15531, "s": 15477, "text": "static int VK_MINUS − Constant for the minus key, \"-\"" }, { "code": null, "e": 15556, "s": 15531, "text": "static int VK_MODECHANGE" }, { "code": null, "e": 15581, "s": 15556, "text": "static int VK_MODECHANGE" }, { "code": null, "e": 15604, "s": 15581, "text": "static int VK_MULTIPLY" }, { "code": null, "e": 15627, "s": 15604, "text": "static int VK_MULTIPLY" }, { "code": null, "e": 15643, "s": 15627, "text": "static int VK_N" }, { "code": null, "e": 15659, "s": 15643, "text": "static int VK_N" }, { "code": null, "e": 15731, "s": 15659, "text": "static int VK_NONCONVERT − Constant for the Don't Convert function key." }, { "code": null, "e": 15803, "s": 15731, "text": "static int VK_NONCONVERT − Constant for the Don't Convert function key." }, { "code": null, "e": 15826, "s": 15803, "text": "static int VK_NUM_LOCK" }, { "code": null, "e": 15849, "s": 15826, "text": "static int VK_NUM_LOCK" }, { "code": null, "e": 15903, "s": 15849, "text": "static int VK_NUMBER_SIGN − Constant for the \"#\" key." }, { "code": null, "e": 15957, "s": 15903, "text": "static int VK_NUMBER_SIGN − Constant for the \"#\" key." }, { "code": null, "e": 15979, "s": 15957, "text": "static int VK_NUMPAD0" }, { "code": null, "e": 16001, "s": 15979, "text": "static int VK_NUMPAD0" }, { "code": null, "e": 16023, "s": 16001, "text": "static int VK_NUMPAD1" }, { "code": null, "e": 16045, "s": 16023, "text": "static int VK_NUMPAD1" }, { "code": null, "e": 16067, "s": 16045, "text": "static int VK_NUMPAD2" }, { "code": null, "e": 16089, "s": 16067, "text": "static int VK_NUMPAD2" }, { "code": null, "e": 16111, "s": 16089, "text": "static int VK_NUMPAD3" }, { "code": null, "e": 16133, "s": 16111, "text": "static int VK_NUMPAD3" }, { "code": null, "e": 16155, "s": 16133, "text": "static int VK_NUMPAD4" }, { "code": null, "e": 16177, "s": 16155, "text": "static int VK_NUMPAD4" }, { "code": null, "e": 16199, "s": 16177, "text": "static int VK_NUMPAD5" }, { "code": null, "e": 16221, "s": 16199, "text": "static int VK_NUMPAD5" }, { "code": null, "e": 16243, "s": 16221, "text": "static int VK_NUMPAD6" }, { "code": null, "e": 16265, "s": 16243, "text": "static int VK_NUMPAD6" }, { "code": null, "e": 16287, "s": 16265, "text": "static int VK_NUMPAD7" }, { "code": null, "e": 16309, "s": 16287, "text": "static int VK_NUMPAD7" }, { "code": null, "e": 16331, "s": 16309, "text": "static int VK_NUMPAD8" }, { "code": null, "e": 16353, "s": 16331, "text": "static int VK_NUMPAD8" }, { "code": null, "e": 16375, "s": 16353, "text": "static int VK_NUMPAD9" }, { "code": null, "e": 16397, "s": 16375, "text": "static int VK_NUMPAD9" }, { "code": null, "e": 16413, "s": 16397, "text": "static int VK_O" }, { "code": null, "e": 16429, "s": 16413, "text": "static int VK_O" }, { "code": null, "e": 16497, "s": 16429, "text": "static int VK_OPEN_BRACKET − Constant for the open bracket key, \"[\"" }, { "code": null, "e": 16565, "s": 16497, "text": "static int VK_OPEN_BRACKET − Constant for the open bracket key, \"[\"" }, { "code": null, "e": 16581, "s": 16565, "text": "static int VK_P" }, { "code": null, "e": 16597, "s": 16581, "text": "static int VK_P" }, { "code": null, "e": 16621, "s": 16597, "text": "static int VK_PAGE_DOWN" }, { "code": null, "e": 16645, "s": 16621, "text": "static int VK_PAGE_DOWN" }, { "code": null, "e": 16667, "s": 16645, "text": "static int VK_PAGE_UP" }, { "code": null, "e": 16689, "s": 16667, "text": "static int VK_PAGE_UP" }, { "code": null, "e": 16709, "s": 16689, "text": "static int VK_PASTE" }, { "code": null, "e": 16729, "s": 16709, "text": "static int VK_PASTE" }, { "code": null, "e": 16749, "s": 16729, "text": "static int VK_PAUSE" }, { "code": null, "e": 16769, "s": 16749, "text": "static int VK_PAUSE" }, { "code": null, "e": 16825, "s": 16769, "text": "static int VK_PERIOD − Constant for the period key, \".\"" }, { "code": null, "e": 16881, "s": 16825, "text": "static int VK_PERIOD − Constant for the period key, \".\"" }, { "code": null, "e": 16928, "s": 16881, "text": "static int VK_PLUS − Constant for the \"+\" key." }, { "code": null, "e": 16975, "s": 16928, "text": "static int VK_PLUS − Constant for the \"+\" key." }, { "code": null, "e": 17060, "s": 16975, "text": "static int VK_PREVIOUS_CANDIDATE − Constant for the Previous Candidate function key." }, { "code": null, "e": 17145, "s": 17060, "text": "static int VK_PREVIOUS_CANDIDATE − Constant for the Previous Candidate function key." }, { "code": null, "e": 17171, "s": 17145, "text": "static int VK_PRINTSCREEN" }, { "code": null, "e": 17197, "s": 17171, "text": "static int VK_PRINTSCREEN" }, { "code": null, "e": 17217, "s": 17197, "text": "static int VK_PROPS" }, { "code": null, "e": 17237, "s": 17217, "text": "static int VK_PROPS" }, { "code": null, "e": 17253, "s": 17237, "text": "static int VK_Q" }, { "code": null, "e": 17269, "s": 17253, "text": "static int VK_Q" }, { "code": null, "e": 17289, "s": 17269, "text": "static int VK_QUOTE" }, { "code": null, "e": 17309, "s": 17289, "text": "static int VK_QUOTE" }, { "code": null, "e": 17332, "s": 17309, "text": "static int VK_QUOTEDBL" }, { "code": null, "e": 17355, "s": 17332, "text": "static int VK_QUOTEDBL" }, { "code": null, "e": 17371, "s": 17355, "text": "static int VK_R" }, { "code": null, "e": 17387, "s": 17371, "text": "static int VK_R" }, { "code": null, "e": 17454, "s": 17387, "text": "static int VK_RIGHT − Constant for the non-numpad right arrow key." }, { "code": null, "e": 17521, "s": 17454, "text": "static int VK_RIGHT − Constant for the non-numpad right arrow key." }, { "code": null, "e": 17581, "s": 17521, "text": "static int VK_RIGHT_PARENTHESIS − Constant for the \")\" key." }, { "code": null, "e": 17641, "s": 17581, "text": "static int VK_RIGHT_PARENTHESIS − Constant for the \")\" key." }, { "code": null, "e": 17722, "s": 17641, "text": "static int VK_ROMAN_CHARACTERS − Constant for the Roman Characters function key." }, { "code": null, "e": 17803, "s": 17722, "text": "static int VK_ROMAN_CHARACTERS − Constant for the Roman Characters function key." }, { "code": null, "e": 17819, "s": 17803, "text": "static int VK_S" }, { "code": null, "e": 17835, "s": 17819, "text": "static int VK_S" }, { "code": null, "e": 17861, "s": 17835, "text": "static int VK_SCROLL_LOCK" }, { "code": null, "e": 17887, "s": 17861, "text": "static int VK_SCROLL_LOCK" }, { "code": null, "e": 17949, "s": 17887, "text": "static int VK_SEMICOLON − Constant for the semicolon key, \";\"" }, { "code": null, "e": 18011, "s": 17949, "text": "static int VK_SEMICOLON − Constant for the semicolon key, \";\"" }, { "code": null, "e": 18114, "s": 18011, "text": "static int VK_SEPARATER − This constant is obsolete, and is included only for backwards compatibility." }, { "code": null, "e": 18217, "s": 18114, "text": "static int VK_SEPARATER − This constant is obsolete, and is included only for backwards compatibility." }, { "code": null, "e": 18282, "s": 18217, "text": "static int VK_SEPARATOR − Constant for the Numpad Separator key." }, { "code": null, "e": 18347, "s": 18282, "text": "static int VK_SEPARATOR − Constant for the Numpad Separator key." }, { "code": null, "e": 18367, "s": 18347, "text": "static int VK_SHIFT" }, { "code": null, "e": 18387, "s": 18367, "text": "static int VK_SHIFT" }, { "code": null, "e": 18449, "s": 18387, "text": "static int VK_SLASH − Constant for the forward slash key, \"/\"" }, { "code": null, "e": 18511, "s": 18449, "text": "static int VK_SLASH − Constant for the forward slash key, \"/\"" }, { "code": null, "e": 18531, "s": 18511, "text": "static int VK_SPACE" }, { "code": null, "e": 18551, "s": 18531, "text": "static int VK_SPACE" }, { "code": null, "e": 18570, "s": 18551, "text": "static int VK_STOP" }, { "code": null, "e": 18589, "s": 18570, "text": "static int VK_STOP" }, { "code": null, "e": 18612, "s": 18589, "text": "static int VK_SUBTRACT" }, { "code": null, "e": 18635, "s": 18612, "text": "static int VK_SUBTRACT" }, { "code": null, "e": 18651, "s": 18635, "text": "static int VK_T" }, { "code": null, "e": 18667, "s": 18651, "text": "static int VK_T" }, { "code": null, "e": 18685, "s": 18667, "text": "static int VK_TAB" }, { "code": null, "e": 18703, "s": 18685, "text": "static int VK_TAB" }, { "code": null, "e": 18719, "s": 18703, "text": "static int VK_U" }, { "code": null, "e": 18735, "s": 18719, "text": "static int VK_U" }, { "code": null, "e": 18821, "s": 18735, "text": "static int VK_UNDEFINED − This value is used to indicate that the keyCode is unknown." }, { "code": null, "e": 18907, "s": 18821, "text": "static int VK_UNDEFINED − This value is used to indicate that the keyCode is unknown." }, { "code": null, "e": 18960, "s": 18907, "text": "static int VK_UNDERSCORE − Constant for the \"_\" key." }, { "code": null, "e": 19013, "s": 18960, "text": "static int VK_UNDERSCORE − Constant for the \"_\" key." }, { "code": null, "e": 19032, "s": 19013, "text": "static int VK_UNDO" }, { "code": null, "e": 19051, "s": 19032, "text": "static int VK_UNDO" }, { "code": null, "e": 19112, "s": 19051, "text": "static int VK_UP − Constant for the non-numpad up arrow key." }, { "code": null, "e": 19173, "s": 19112, "text": "static int VK_UP − Constant for the non-numpad up arrow key." }, { "code": null, "e": 19189, "s": 19173, "text": "static int VK_V" }, { "code": null, "e": 19205, "s": 19189, "text": "static int VK_V" }, { "code": null, "e": 19221, "s": 19205, "text": "static int VK_W" }, { "code": null, "e": 19237, "s": 19221, "text": "static int VK_W" }, { "code": null, "e": 19311, "s": 19237, "text": "static int VK_WINDOWS − Constant for the Microsoft Windows \"Windows\" key." }, { "code": null, "e": 19385, "s": 19311, "text": "static int VK_WINDOWS − Constant for the Microsoft Windows \"Windows\" key." }, { "code": null, "e": 19401, "s": 19385, "text": "static int VK_X" }, { "code": null, "e": 19417, "s": 19401, "text": "static int VK_X" }, { "code": null, "e": 19433, "s": 19417, "text": "static int VK_Y" }, { "code": null, "e": 19449, "s": 19433, "text": "static int VK_Y" }, { "code": null, "e": 19465, "s": 19449, "text": "static int VK_Z" }, { "code": null, "e": 19481, "s": 19465, "text": "static int VK_Z" }, { "code": null, "e": 19555, "s": 19481, "text": "KeyEvent(Component source, int id, long when, int modifiers, int keyCode)" }, { "code": null, "e": 19580, "s": 19555, "text": "Deprecated. as of JDK1.1" }, { "code": null, "e": 19668, "s": 19580, "text": "KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)" }, { "code": null, "e": 19698, "s": 19668, "text": "Constructs a KeyEvent object." }, { "code": null, "e": 19803, "s": 19698, "text": "KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation)" }, { "code": null, "e": 19821, "s": 19803, "text": "char getKeyChar()" }, { "code": null, "e": 19882, "s": 19821, "text": "Returns the character associated with the key in this event." }, { "code": null, "e": 19899, "s": 19882, "text": "int getKeyCode()" }, { "code": null, "e": 19966, "s": 19899, "text": "Returns the integer keyCode associated with the key in this event." }, { "code": null, "e": 19987, "s": 19966, "text": "int getKeyLocation()" }, { "code": null, "e": 20051, "s": 19987, "text": "Returns the location of the key that originated this key event." }, { "code": null, "e": 20100, "s": 20051, "text": "static String getKeyModifiersText(int modifiers)" }, { "code": null, "e": 20183, "s": 20100, "text": "Returns a String describing the modifier key(s), such as \"Shift\", or \"Ctrl+Shift\"." }, { "code": null, "e": 20221, "s": 20183, "text": "static String getKeyText(int keyCode)" }, { "code": null, "e": 20291, "s": 20221, "text": "Returns a String describing the keyCode, such as \"HOME\", \"F1\" or \"A\"." }, { "code": null, "e": 20313, "s": 20291, "text": "boolean isActionKey()" }, { "code": null, "e": 20371, "s": 20313, "text": "Returns whether the key in this event is an \"action\" key." }, { "code": null, "e": 20392, "s": 20371, "text": "String paramString()" }, { "code": null, "e": 20443, "s": 20392, "text": "Returns a parameter string identifying this event." }, { "code": null, "e": 20473, "s": 20443, "text": "void setKeyChar(char keyChar)" }, { "code": null, "e": 20528, "s": 20473, "text": "Set the keyChar value to indicate a logical character." }, { "code": null, "e": 20557, "s": 20528, "text": "void setKeyCode(int keyCode)" }, { "code": null, "e": 20607, "s": 20557, "text": "Set the keyCode value to indicate a physical key." }, { "code": null, "e": 20640, "s": 20607, "text": "void setModifiers(int modifiers)" }, { "code": null, "e": 20667, "s": 20640, "text": "Deprecated. as of JDK1.1.4" }, { "code": null, "e": 20724, "s": 20667, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 20750, "s": 20724, "text": "java.awt.event.InputEvent" }, { "code": null, "e": 20780, "s": 20750, "text": "java.awt.event.ComponentEvent" }, { "code": null, "e": 20798, "s": 20780, "text": "java.awt.AWTEvent" }, { "code": null, "e": 20820, "s": 20798, "text": "java.util.EventObject" }, { "code": null, "e": 20837, "s": 20820, "text": "java.lang.Object" }, { "code": null, "e": 20872, "s": 20837, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 20892, "s": 20872, "text": " Pranjal Srivastava" }, { "code": null, "e": 20925, "s": 20892, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 20945, "s": 20925, "text": " Pranjal Srivastava" }, { "code": null, "e": 20980, "s": 20945, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 21016, "s": 20980, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 21051, "s": 21016, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 21064, "s": 21051, "text": " Travis Rose" }, { "code": null, "e": 21097, "s": 21064, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 21110, "s": 21097, "text": " Travis Rose" }, { "code": null, "e": 21117, "s": 21110, "text": " Print" }, { "code": null, "e": 21128, "s": 21117, "text": " Add Notes" } ]
dl-horizontal class in Bootstrap
In definition list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal. You can try to run the following code to implement the dl-horizontal class: Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap lists</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <h1>Lists</h1> <h2>Fruits (Ordered List)</h2> <ol> <li>Kiwi</li> <li>Apple</li> <li>Mango</li> </ol> <h2>Vegetables (UnOrdered List)</h2> <ul> <li>Tomato</li> <li>Brinjal</li> <li>Broccoli</li> </ul> <h2>Horizontal Definition List</h2> <dl class = "dl-horizontal"> <dt>Description 1</dt> <dd>Item 1</dd> <dt>Description 2</dt> <dd>Item 2</dd> </dl> </body> </html>
[ { "code": null, "e": 1403, "s": 1062, "text": "In definition list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal." }, { "code": null, "e": 1479, "s": 1403, "text": "You can try to run the following code to implement the dl-horizontal class:" }, { "code": null, "e": 1489, "s": 1479, "text": "Live Demo" }, { "code": null, "e": 2491, "s": 1489, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap lists</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h1>Lists</h1>\n <h2>Fruits (Ordered List)</h2>\n <ol>\n <li>Kiwi</li>\n <li>Apple</li>\n <li>Mango</li>\n </ol>\n <h2>Vegetables (UnOrdered List)</h2>\n <ul>\n <li>Tomato</li>\n <li>Brinjal</li>\n <li>Broccoli</li>\n </ul>\n <h2>Horizontal Definition List</h2>\n <dl class = \"dl-horizontal\">\n <dt>Description 1</dt>\n <dd>Item 1</dd>\n <dt>Description 2</dt>\n <dd>Item 2</dd>\n </dl>\n </body>\n</html>" } ]
Interactive Dashboards for Data Science | by Pier Paolo Ippolito | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Create Audio Narrations with Play.ht Creating an online Data Science Dashboard can be a really powerful way of communicating the results of a Data Science project. A good Dashboard can: Summarise the main results of a data analysis. Enable the customers/company managers to test how varying some parameters can affect a certain outcome. Fetch continuously new data to update its graphs and summaries. Allow us to make predictions online using either pre-trained Machine Learning models or training them online. Nowadays, there are many different services which can be used to create Dashboards. Some examples are: Dash by Plotly Bokeh Dashboards Google Data Studio Tableau The first two examples require a good Python programming knowledge in order to create Dashboards, instead, the last two don’t necessarily require any programming knowledge (they provide although fewer customisation options). In this article, I will walk you through how to create and deploy online a Dashboard using Plotly Dash. All the code used in this article (and more!) is available in on my GitHub account. My final version of the Dashboard is available to be tested online at this link. Dash is an Open Source Python library designed by Plotly for creating reactive, Web-based applications. This library is built on top of other packages such as: Flask, Plotly.js, React and React Js. Every Dash App is composed of two main parts: Layout = is used to define how all the content should be laid out on the application. Callbacks = are used to make each of the desired components of the Dashboard interactive. Additionally, Dash provides a collection of HTML classes to generate HTML code in Python (dash-html-components), Markdown and App Authentication support. All the necessary libraries needed to get started with Dash are listed below. pip install dash pip install dash-renderer pip install dash-html-components pip install dash-core-components pip install plotly In order to create the following dashboard, I made use of two different datasets. The first one is the Huge Stock Market Dataset by Boris Marjanovic and the second one is the Facebook metrics Data Set by Moro, S., Rita, P., & Vala, B. Before loading the first dataset on the dashboard application, I performed some pre-processing analysis, the resulting dataset is available here. In this demonstration, we will create together a Dashboard composed of two tabs. The first tab will show the High, Low and Volume Stock market indicators of companies such as Facebook, Apple, Microsoft and Tesla. The second tab will instead show the distributions of each of the features available in the Facebook Performance Metrics dataset (Figure 3). If you are interested in adding more features to this App, on my GitHub repository is available a more advanced version. First of all, we need to create a Python file called app.py and import all the required dependencies. In this file, we will write all the code necessary to launch our Dashboard. The datasets we are going to work with will have a structure like shown in Figure 4 and 5. We can then set-up our App and its layout using the code shown below. The layout is stored in app.layout, and all the desired HTML components such as Div, H1, H2, P, etc have been added using the dash_html_components (html) library. Finally, we can add interactive components to our dashboard (eg. tabs, dropdowns, radio buttons) using the dash_core_components (dcc) library. In this case, I decided to divide this Dashboard into two tabs. In the first one, will be analysed the Stock Prices dataset and in the second one the Performance Metrics dataset. The layout of the first tab is subsequently divided into other two parts each of them formed by an H1 title, a dropdown menu with four different options and a time-series graph. The second tab is instead formed by just an H1 title, a dropdown menu with 18 different options and a histogram. Once defined the layout of our Dashboard, we can then go on and design the graphs and their interaction with the dropdown menus. The graphs can be designed creating functions and instead the interactions between the graphs and the dropdown menus can be designed using callbacks. The code below can be divided in 3 main sections: a High-Low Stock Prices Time Series graph, a Market Volume Time Series graph and a Performance Metrics Feature Distributions graph. The first two sections are really similar, in fact, they are designed to create the same type of graph. The only difference is that in the second graph just one feature is considered instead of two. In each of the 3 sections, the callbacks (@app.callback) are used to take the selected values from the dropdowns, send them as input to the graph function and then take the variable returned by the function to pass it to the graph declared in the layout. These callbacks will automatically get called every-time the values in the dropdowns changes. The callbacks can automatically identify which of the different dropdowns available on the Dashboard changed value and which graph to subsequently update thanks to the unique id values set before in the Dashboard Layout. Each of the three functions shown below use Plotly syntax to create the graphs. If you have never used Plotly before, in one of my previous articles I have already talked about Interactive Data Visualization. The fist function will generate the graph shown below. The second one will instead create the graph shown in Figure 7. Lastly, the third function will generate the feature distribution histogram on the second tab of the Dashboard (Figure 8). Finally, we can start a local server and make our application run by using the following two lines of code. Now that our app is ready, we can simply lunch it by opening our computer terminal in our current working directory and typing python app.py. This will start a web server at http://127.0.0.1:8050/, going at this link we will see our final Python App running. It is possible to easily deploy online Dash Apps for free hosting our application on Heroku. If you are interested in doing so, I wrote another article about Flask and Heroku for online Machine Learning deployment. Additionally, also the Dash documentation provides guidance on how to deploy Dash Apps on Heroku. This Dashboard can be further developed by adding additional features such as: Use a web-scraping mechanism to fetch new Stock Market data in real-time to update all the related graphs. Add more Data Visualisation charts. Create Machine Learning models to make predictions (eg. ARIMA, LSTM). Improve the Dashboard overall design. A more advanced version of this dashboard is available to be tested online at this link. If you need any help to add any of these additional features, the Dash documentation is a great place where to start. I hope you enjoyed this article, thank you for reading! If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details: Linkedin Personal Blog Personal Website Medium Profile GitHub Kaggle [1] Dash operationalizes Python & R models at scale, Plotly. Accessed at: https://plot.ly/dash
[ { "code": null, "e": 174, "s": 172, "text": "1" }, { "code": null, "e": 176, "s": 174, "text": "2" }, { "code": null, "e": 178, "s": 176, "text": "3" }, { "code": null, "e": 180, "s": 178, "text": "4" }, { "code": null, "e": 182, "s": 180, "text": "5" }, { "code": null, "e": 184, "s": 182, "text": "6" }, { "code": null, "e": 186, "s": 184, "text": "7" }, { "code": null, "e": 188, "s": 186, "text": "8" }, { "code": null, "e": 190, "s": 188, "text": "9" }, { "code": null, "e": 193, "s": 190, "text": "10" }, { "code": null, "e": 212, "s": 193, "text": "Powered by Play.ht" }, { "code": null, "e": 238, "s": 212, "text": "Create audio with Play.ht" }, { "code": null, "e": 275, "s": 238, "text": "Create Audio Narrations with Play.ht" }, { "code": null, "e": 424, "s": 275, "text": "Creating an online Data Science Dashboard can be a really powerful way of communicating the results of a Data Science project. A good Dashboard can:" }, { "code": null, "e": 471, "s": 424, "text": "Summarise the main results of a data analysis." }, { "code": null, "e": 575, "s": 471, "text": "Enable the customers/company managers to test how varying some parameters can affect a certain outcome." }, { "code": null, "e": 639, "s": 575, "text": "Fetch continuously new data to update its graphs and summaries." }, { "code": null, "e": 749, "s": 639, "text": "Allow us to make predictions online using either pre-trained Machine Learning models or training them online." }, { "code": null, "e": 852, "s": 749, "text": "Nowadays, there are many different services which can be used to create Dashboards. Some examples are:" }, { "code": null, "e": 867, "s": 852, "text": "Dash by Plotly" }, { "code": null, "e": 884, "s": 867, "text": "Bokeh Dashboards" }, { "code": null, "e": 903, "s": 884, "text": "Google Data Studio" }, { "code": null, "e": 911, "s": 903, "text": "Tableau" }, { "code": null, "e": 1136, "s": 911, "text": "The first two examples require a good Python programming knowledge in order to create Dashboards, instead, the last two don’t necessarily require any programming knowledge (they provide although fewer customisation options)." }, { "code": null, "e": 1324, "s": 1136, "text": "In this article, I will walk you through how to create and deploy online a Dashboard using Plotly Dash. All the code used in this article (and more!) is available in on my GitHub account." }, { "code": null, "e": 1405, "s": 1324, "text": "My final version of the Dashboard is available to be tested online at this link." }, { "code": null, "e": 1603, "s": 1405, "text": "Dash is an Open Source Python library designed by Plotly for creating reactive, Web-based applications. This library is built on top of other packages such as: Flask, Plotly.js, React and React Js." }, { "code": null, "e": 1649, "s": 1603, "text": "Every Dash App is composed of two main parts:" }, { "code": null, "e": 1735, "s": 1649, "text": "Layout = is used to define how all the content should be laid out on the application." }, { "code": null, "e": 1825, "s": 1735, "text": "Callbacks = are used to make each of the desired components of the Dashboard interactive." }, { "code": null, "e": 1979, "s": 1825, "text": "Additionally, Dash provides a collection of HTML classes to generate HTML code in Python (dash-html-components), Markdown and App Authentication support." }, { "code": null, "e": 2057, "s": 1979, "text": "All the necessary libraries needed to get started with Dash are listed below." }, { "code": null, "e": 2191, "s": 2057, "text": "pip install dash pip install dash-renderer pip install dash-html-components pip install dash-core-components pip install plotly" }, { "code": null, "e": 2426, "s": 2191, "text": "In order to create the following dashboard, I made use of two different datasets. The first one is the Huge Stock Market Dataset by Boris Marjanovic and the second one is the Facebook metrics Data Set by Moro, S., Rita, P., & Vala, B." }, { "code": null, "e": 2572, "s": 2426, "text": "Before loading the first dataset on the dashboard application, I performed some pre-processing analysis, the resulting dataset is available here." }, { "code": null, "e": 2926, "s": 2572, "text": "In this demonstration, we will create together a Dashboard composed of two tabs. The first tab will show the High, Low and Volume Stock market indicators of companies such as Facebook, Apple, Microsoft and Tesla. The second tab will instead show the distributions of each of the features available in the Facebook Performance Metrics dataset (Figure 3)." }, { "code": null, "e": 3047, "s": 2926, "text": "If you are interested in adding more features to this App, on my GitHub repository is available a more advanced version." }, { "code": null, "e": 3225, "s": 3047, "text": "First of all, we need to create a Python file called app.py and import all the required dependencies. In this file, we will write all the code necessary to launch our Dashboard." }, { "code": null, "e": 3316, "s": 3225, "text": "The datasets we are going to work with will have a structure like shown in Figure 4 and 5." }, { "code": null, "e": 3692, "s": 3316, "text": "We can then set-up our App and its layout using the code shown below. The layout is stored in app.layout, and all the desired HTML components such as Div, H1, H2, P, etc have been added using the dash_html_components (html) library. Finally, we can add interactive components to our dashboard (eg. tabs, dropdowns, radio buttons) using the dash_core_components (dcc) library." }, { "code": null, "e": 4162, "s": 3692, "text": "In this case, I decided to divide this Dashboard into two tabs. In the first one, will be analysed the Stock Prices dataset and in the second one the Performance Metrics dataset. The layout of the first tab is subsequently divided into other two parts each of them formed by an H1 title, a dropdown menu with four different options and a time-series graph. The second tab is instead formed by just an H1 title, a dropdown menu with 18 different options and a histogram." }, { "code": null, "e": 4441, "s": 4162, "text": "Once defined the layout of our Dashboard, we can then go on and design the graphs and their interaction with the dropdown menus. The graphs can be designed creating functions and instead the interactions between the graphs and the dropdown menus can be designed using callbacks." }, { "code": null, "e": 4623, "s": 4441, "text": "The code below can be divided in 3 main sections: a High-Low Stock Prices Time Series graph, a Market Volume Time Series graph and a Performance Metrics Feature Distributions graph." }, { "code": null, "e": 4822, "s": 4623, "text": "The first two sections are really similar, in fact, they are designed to create the same type of graph. The only difference is that in the second graph just one feature is considered instead of two." }, { "code": null, "e": 5392, "s": 4822, "text": "In each of the 3 sections, the callbacks (@app.callback) are used to take the selected values from the dropdowns, send them as input to the graph function and then take the variable returned by the function to pass it to the graph declared in the layout. These callbacks will automatically get called every-time the values in the dropdowns changes. The callbacks can automatically identify which of the different dropdowns available on the Dashboard changed value and which graph to subsequently update thanks to the unique id values set before in the Dashboard Layout." }, { "code": null, "e": 5601, "s": 5392, "text": "Each of the three functions shown below use Plotly syntax to create the graphs. If you have never used Plotly before, in one of my previous articles I have already talked about Interactive Data Visualization." }, { "code": null, "e": 5656, "s": 5601, "text": "The fist function will generate the graph shown below." }, { "code": null, "e": 5720, "s": 5656, "text": "The second one will instead create the graph shown in Figure 7." }, { "code": null, "e": 5843, "s": 5720, "text": "Lastly, the third function will generate the feature distribution histogram on the second tab of the Dashboard (Figure 8)." }, { "code": null, "e": 5951, "s": 5843, "text": "Finally, we can start a local server and make our application run by using the following two lines of code." }, { "code": null, "e": 6210, "s": 5951, "text": "Now that our app is ready, we can simply lunch it by opening our computer terminal in our current working directory and typing python app.py. This will start a web server at http://127.0.0.1:8050/, going at this link we will see our final Python App running." }, { "code": null, "e": 6523, "s": 6210, "text": "It is possible to easily deploy online Dash Apps for free hosting our application on Heroku. If you are interested in doing so, I wrote another article about Flask and Heroku for online Machine Learning deployment. Additionally, also the Dash documentation provides guidance on how to deploy Dash Apps on Heroku." }, { "code": null, "e": 6602, "s": 6523, "text": "This Dashboard can be further developed by adding additional features such as:" }, { "code": null, "e": 6709, "s": 6602, "text": "Use a web-scraping mechanism to fetch new Stock Market data in real-time to update all the related graphs." }, { "code": null, "e": 6745, "s": 6709, "text": "Add more Data Visualisation charts." }, { "code": null, "e": 6815, "s": 6745, "text": "Create Machine Learning models to make predictions (eg. ARIMA, LSTM)." }, { "code": null, "e": 6853, "s": 6815, "text": "Improve the Dashboard overall design." }, { "code": null, "e": 6942, "s": 6853, "text": "A more advanced version of this dashboard is available to be tested online at this link." }, { "code": null, "e": 7060, "s": 6942, "text": "If you need any help to add any of these additional features, the Dash documentation is a great place where to start." }, { "code": null, "e": 7116, "s": 7060, "text": "I hope you enjoyed this article, thank you for reading!" }, { "code": null, "e": 7274, "s": 7116, "text": "If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:" }, { "code": null, "e": 7283, "s": 7274, "text": "Linkedin" }, { "code": null, "e": 7297, "s": 7283, "text": "Personal Blog" }, { "code": null, "e": 7314, "s": 7297, "text": "Personal Website" }, { "code": null, "e": 7329, "s": 7314, "text": "Medium Profile" }, { "code": null, "e": 7336, "s": 7329, "text": "GitHub" }, { "code": null, "e": 7343, "s": 7336, "text": "Kaggle" } ]
JavaScript Number - toFixed()
This method formats a number with a specific number of digits to the right of the decimal. Its syntax is as follows − number.toFixed( [digits] ) digits − The number of digits to appear after the decimal point. A string representation of number that does not use exponential notation and has the exact number of digits after the decimal place. Try the following example. <html> <head> <title>JavaScript toFixed() Method</title> </head> <body> <script type = "text/javascript"> var num = 177.1234; document.write("num.toFixed() is : " + num.toFixed()); document.write("<br />"); document.write("num.toFixed(6) is : " + num.toFixed(6)); document.write("<br />"); document.write("num.toFixed(1) is : " + num.toFixed(1)); document.write("<br />"); document.write("(1.23e+20).toFixed(2) is:" + (1.23e+20).toFixed(2)); document.write("<br />"); document.write("(1.23e-10).toFixed(2) is : " + (1.23e-10).toFixed(2)); </script> </body> </html> num.toFixed() is : 177 num.toFixed(6) is : 177.123400 num.toFixed(1) is : 177.1 (1.23e+20).toFixed(2) is:123000000000000000000.00 (1.23e-10).toFixed(2) is : 0.00 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2557, "s": 2466, "text": "This method formats a number with a specific number of digits to the right of the decimal." }, { "code": null, "e": 2584, "s": 2557, "text": "Its syntax is as follows −" }, { "code": null, "e": 2612, "s": 2584, "text": "number.toFixed( [digits] )\n" }, { "code": null, "e": 2677, "s": 2612, "text": "digits − The number of digits to appear after the decimal point." }, { "code": null, "e": 2810, "s": 2677, "text": "A string representation of number that does not use exponential notation and has the exact number of digits after the decimal place." }, { "code": null, "e": 2837, "s": 2810, "text": "Try the following example." }, { "code": null, "e": 3572, "s": 2837, "text": "<html>\n <head>\n <title>JavaScript toFixed() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var num = 177.1234;\n document.write(\"num.toFixed() is : \" + num.toFixed()); \n document.write(\"<br />\"); \n \n document.write(\"num.toFixed(6) is : \" + num.toFixed(6)); \n document.write(\"<br />\"); \n \n document.write(\"num.toFixed(1) is : \" + num.toFixed(1)); \n document.write(\"<br />\"); \n \n document.write(\"(1.23e+20).toFixed(2) is:\" + (1.23e+20).toFixed(2)); \n document.write(\"<br />\"); \n \n document.write(\"(1.23e-10).toFixed(2) is : \" + (1.23e-10).toFixed(2)); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3736, "s": 3572, "text": "num.toFixed() is : 177\nnum.toFixed(6) is : 177.123400\nnum.toFixed(1) is : 177.1\n(1.23e+20).toFixed(2) is:123000000000000000000.00\n(1.23e-10).toFixed(2) is : 0.00 \n" }, { "code": null, "e": 3771, "s": 3736, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3785, "s": 3771, "text": " Anadi Sharma" }, { "code": null, "e": 3819, "s": 3785, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3833, "s": 3819, "text": " Lets Kode It" }, { "code": null, "e": 3868, "s": 3833, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3885, "s": 3868, "text": " Frahaan Hussain" }, { "code": null, "e": 3920, "s": 3885, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3937, "s": 3920, "text": " Frahaan Hussain" }, { "code": null, "e": 3970, "s": 3937, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3998, "s": 3970, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4032, "s": 3998, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4060, "s": 4032, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4067, "s": 4060, "text": " Print" }, { "code": null, "e": 4078, "s": 4067, "text": " Add Notes" } ]
Check if a key is present in a C++ map or unordered_map
In C++ the Maps and unordered maps are hash tables. They use some keys and their respective key values. Here we will see how to check whether a given key is present in the hash table or not. The code will be like below − Live Demo #include<iostream> #include<map> using namespace std; string isPresent(map<string, int> m, string key) { if (m.find(key) == m.end()) return "Not Present"; return "Present"; } int main() { map<string, int> my_map; my_map["first"] = 4; my_map["second"] = 6; my_map["third"] = 6; string check1 = "fifth", check2 = "third"; cout << check1 << ": " << isPresent(my_map, check1) << endl; cout << check2 << ": " << isPresent(my_map, check2); } fifth: Not Present third: Present
[ { "code": null, "e": 1283, "s": 1062, "text": "In C++ the Maps and unordered maps are hash tables. They use some keys and their respective key values. Here we will see how to check whether a given key is present in the hash table or not. The code will be like below −" }, { "code": null, "e": 1294, "s": 1283, "text": " Live Demo" }, { "code": null, "e": 1760, "s": 1294, "text": "#include<iostream>\n#include<map>\nusing namespace std;\nstring isPresent(map<string, int> m, string key) {\n if (m.find(key) == m.end())\n return \"Not Present\";\n return \"Present\";\n}\nint main() {\n map<string, int> my_map;\n my_map[\"first\"] = 4;\n my_map[\"second\"] = 6;\n my_map[\"third\"] = 6;\n string check1 = \"fifth\", check2 = \"third\";\n cout << check1 << \": \" << isPresent(my_map, check1) << endl;\n cout << check2 << \": \" << isPresent(my_map, check2);\n}" }, { "code": null, "e": 1794, "s": 1760, "text": "fifth: Not Present\nthird: Present" } ]
Financial Signal Processing — Part 1 | by Yao Lei Xu | Towards Data Science
Algorithmic trading is hard. You can’t just stick a dozen technical analysis signals into a neural network and expect to become a millionaire next month. This is because processing financial data is all about the details. Setting aside all the potential biases and mistakes that beginners can make, most financial machine learning and algo trading projects fail because they ignore the subtle assumptions within a financial context. To that end, today I will go back and discuss the fundamentals of financial signal processing. I will examine various properties of financial data, when and how to process them in a particular way, and how to analyze them through machine learning techniques. (You can find the full code and additional resources here) Most machine learning techniques assume stationarity in the data. However, stationarity is rarely found in finance, which can cause several issues. Before diving into financial signals, it’s important to mention the concept of stationarity, as it is the fundamental assumption behind most modern machine learning techniques. Setting aside the rigorous mathematical definition, what stationarity implies is that the statistics (e.g. mean and variance) of the underlying signals are constant over time. For instance, consider ML problems involving the classification of cats and dogs, where the underlying biology of the animals doesn’t change everyday with drastic differences. The stationarity of the biological features allows the ML models to pick up patterns that will remain true over time, which allows the models to generalize well out-of-sample. In finance however, stationarity is a huge issue. Consider for instance the price signal of Apple in the figure below. It doesn’t take rigorous statistical tests to see that the average price does not remain constant over time. Consider a train-test split framework with the above data, where the price signal before 2019 is used for training and the remaining for testing. If one were to naively scale the price range from [100, 400] to [0, 1], it would result in look-ahead bias (leakage of test set information to the training set). This would result in an unrealistically better performance, since the ML model implicitely knows what the max price will be in the future from the scaling. Intuitively, if you were implementing this ML model back in 2019, there is no way you could have known that the price of AAPL would end up around 400 in 2020 (and if you knew, you wouldn’t need ML in the first place). What if we scaled the price range using the training set? Scaling the price range from [100, 250] to [0,1] would result in no look-ahead bias, but all the prices greater than 250 in the test set would be scaled to be greater than 1. This is particularly problematic for ML models that need the features to be within a certain scaled range, such as neural networks. A much better solution is to process the above signal through log-differencing, as discussed below. Log-differencing the price data can generate stationary signals suitable for machine learning techniques, which is often better than raw price signals. Log-differencing computes the difference between log-values at time t-1 and t which is also often referred to as log-returns, as shown below. A price signal processed through log-returns have a number of advantages: (1) It renders the original signal stationary, as shown in the figure below. By a simple inspection, we can see that the new signal has a constant mean of around 0, as well as a more constant variance. (2) Log-returns tend to be more normally distributed than the price data, which is great for classical statistical models that rely on the normality assumption. (3) Log-returns are time-additive, which allows us to compute backtests through simple additions (see the article here for a more detailed explanation). The major draw back of log-returns is that it removes the memory component, which destroys the pricing information. In most applications, this is usually not an issue. For instance, a lot of quantitative finance literature in portfolio optimization, momentum strategies, mean-reversion strategies, etc. rely on how much do asset prices change together. Hence the comparison of log-returns is more meaningful than the comparison of prices. However, for other financial instruments, such as commodity futures, the exact price value might have real-life impact on industries that rely on those commodities. So in that case, the pricing information can be more meaningful than log-returns. Finally, there can be some additional subtleties in the computation of log-returns, which can be adjusted through volume based sampling and fractional differencing. Those techniques will be discussed in a future post. Rolling statistics of log-returns can be processed through machine learning methods, offering market insights. As discussed previously, log-returns tend to follow a nicer distribution. For a short-term window, it is often desirable to analyze different statistics associated with that distribution, such as mean, standard deviation, skew, and kurtosis, which tend to be stationary as well. In Python, these can be computed easily through the rolling function in pandas: w = 22 # number of trading days in a months1 = rs.rolling(w).mean() # moving averages2 = rs.rolling(w).std() # moving standard deviations3 = rs.rolling(w).skew() # moving skewnesss4 = rs.rolling(w).kurt() # moving kurtosissignals = pd.concat([s1, s2, s3, s4], axis=1)signals.columns = ['mean', 'std dev', 'skew', 'kurtosis']signals.plot(subplots=True, figsize=(10,7), legend=True); In particular, the rolling computation of the standard deviation can be extremely useful in analysing market volatility. Volatility has a special role in financial machine learning. Intuitively, volatility measures how much uncertainty/movement/chaos is present in the market. In addition, it can be used to measure the amount of “risk” present in the market (although alternative/better definitions of risk exist, such as “exposure”). The concept of volatility is also tightly linked to the idea of market regimes, which can be used to identify different market conditions. For instance, we could run a clustering algorithm on the volatility levels of the SP500 at different times: from sklearn.mixture import GaussianMixturew = 22vol = rs.rolling(w).std()vol = vol.dropna()labels = GaussianMixture(2).fit_predict(vol.values.reshape(-1,1))prices = prices.reindex(vol.index)prices[labels==0].plot(style='bo', alpha=0.2)prices[labels==1].plot(style='ro', alpha=0.2)plt.title('Volatility Regimes SPY') By fitting a Gaussian Mixture on the observed volatility levels, the ML model automatically inferred bullish and bearish markets regimes. This is intuitive since market sell-offs are often driven by panic selling decisions, which can lead to sharp declines that increases the chaos in the market, resulting in higher volatility. In contrast, bullish markets are characterized by a steadier increase in value, which leads to lower volatility. The identification of market regimes is especially important for financial machine learning, since a model trained during a bullish market is unlikely to do well in a bearish one and vice-versa. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. I hope you enjoyed the article! Follow me if you would like to see more content like this. Also, check out my website for the full code and additional resources.
[ { "code": null, "e": 605, "s": 172, "text": "Algorithmic trading is hard. You can’t just stick a dozen technical analysis signals into a neural network and expect to become a millionaire next month. This is because processing financial data is all about the details. Setting aside all the potential biases and mistakes that beginners can make, most financial machine learning and algo trading projects fail because they ignore the subtle assumptions within a financial context." }, { "code": null, "e": 864, "s": 605, "text": "To that end, today I will go back and discuss the fundamentals of financial signal processing. I will examine various properties of financial data, when and how to process them in a particular way, and how to analyze them through machine learning techniques." }, { "code": null, "e": 923, "s": 864, "text": "(You can find the full code and additional resources here)" }, { "code": null, "e": 1071, "s": 923, "text": "Most machine learning techniques assume stationarity in the data. However, stationarity is rarely found in finance, which can cause several issues." }, { "code": null, "e": 1248, "s": 1071, "text": "Before diving into financial signals, it’s important to mention the concept of stationarity, as it is the fundamental assumption behind most modern machine learning techniques." }, { "code": null, "e": 1424, "s": 1248, "text": "Setting aside the rigorous mathematical definition, what stationarity implies is that the statistics (e.g. mean and variance) of the underlying signals are constant over time." }, { "code": null, "e": 1776, "s": 1424, "text": "For instance, consider ML problems involving the classification of cats and dogs, where the underlying biology of the animals doesn’t change everyday with drastic differences. The stationarity of the biological features allows the ML models to pick up patterns that will remain true over time, which allows the models to generalize well out-of-sample." }, { "code": null, "e": 2004, "s": 1776, "text": "In finance however, stationarity is a huge issue. Consider for instance the price signal of Apple in the figure below. It doesn’t take rigorous statistical tests to see that the average price does not remain constant over time." }, { "code": null, "e": 2468, "s": 2004, "text": "Consider a train-test split framework with the above data, where the price signal before 2019 is used for training and the remaining for testing. If one were to naively scale the price range from [100, 400] to [0, 1], it would result in look-ahead bias (leakage of test set information to the training set). This would result in an unrealistically better performance, since the ML model implicitely knows what the max price will be in the future from the scaling." }, { "code": null, "e": 2686, "s": 2468, "text": "Intuitively, if you were implementing this ML model back in 2019, there is no way you could have known that the price of AAPL would end up around 400 in 2020 (and if you knew, you wouldn’t need ML in the first place)." }, { "code": null, "e": 3051, "s": 2686, "text": "What if we scaled the price range using the training set? Scaling the price range from [100, 250] to [0,1] would result in no look-ahead bias, but all the prices greater than 250 in the test set would be scaled to be greater than 1. This is particularly problematic for ML models that need the features to be within a certain scaled range, such as neural networks." }, { "code": null, "e": 3151, "s": 3051, "text": "A much better solution is to process the above signal through log-differencing, as discussed below." }, { "code": null, "e": 3303, "s": 3151, "text": "Log-differencing the price data can generate stationary signals suitable for machine learning techniques, which is often better than raw price signals." }, { "code": null, "e": 3445, "s": 3303, "text": "Log-differencing computes the difference between log-values at time t-1 and t which is also often referred to as log-returns, as shown below." }, { "code": null, "e": 4035, "s": 3445, "text": "A price signal processed through log-returns have a number of advantages: (1) It renders the original signal stationary, as shown in the figure below. By a simple inspection, we can see that the new signal has a constant mean of around 0, as well as a more constant variance. (2) Log-returns tend to be more normally distributed than the price data, which is great for classical statistical models that rely on the normality assumption. (3) Log-returns are time-additive, which allows us to compute backtests through simple additions (see the article here for a more detailed explanation)." }, { "code": null, "e": 4474, "s": 4035, "text": "The major draw back of log-returns is that it removes the memory component, which destroys the pricing information. In most applications, this is usually not an issue. For instance, a lot of quantitative finance literature in portfolio optimization, momentum strategies, mean-reversion strategies, etc. rely on how much do asset prices change together. Hence the comparison of log-returns is more meaningful than the comparison of prices." }, { "code": null, "e": 4721, "s": 4474, "text": "However, for other financial instruments, such as commodity futures, the exact price value might have real-life impact on industries that rely on those commodities. So in that case, the pricing information can be more meaningful than log-returns." }, { "code": null, "e": 4939, "s": 4721, "text": "Finally, there can be some additional subtleties in the computation of log-returns, which can be adjusted through volume based sampling and fractional differencing. Those techniques will be discussed in a future post." }, { "code": null, "e": 5050, "s": 4939, "text": "Rolling statistics of log-returns can be processed through machine learning methods, offering market insights." }, { "code": null, "e": 5329, "s": 5050, "text": "As discussed previously, log-returns tend to follow a nicer distribution. For a short-term window, it is often desirable to analyze different statistics associated with that distribution, such as mean, standard deviation, skew, and kurtosis, which tend to be stationary as well." }, { "code": null, "e": 5409, "s": 5329, "text": "In Python, these can be computed easily through the rolling function in pandas:" }, { "code": null, "e": 5791, "s": 5409, "text": "w = 22 # number of trading days in a months1 = rs.rolling(w).mean() # moving averages2 = rs.rolling(w).std() # moving standard deviations3 = rs.rolling(w).skew() # moving skewnesss4 = rs.rolling(w).kurt() # moving kurtosissignals = pd.concat([s1, s2, s3, s4], axis=1)signals.columns = ['mean', 'std dev', 'skew', 'kurtosis']signals.plot(subplots=True, figsize=(10,7), legend=True);" }, { "code": null, "e": 5912, "s": 5791, "text": "In particular, the rolling computation of the standard deviation can be extremely useful in analysing market volatility." }, { "code": null, "e": 6227, "s": 5912, "text": "Volatility has a special role in financial machine learning. Intuitively, volatility measures how much uncertainty/movement/chaos is present in the market. In addition, it can be used to measure the amount of “risk” present in the market (although alternative/better definitions of risk exist, such as “exposure”)." }, { "code": null, "e": 6474, "s": 6227, "text": "The concept of volatility is also tightly linked to the idea of market regimes, which can be used to identify different market conditions. For instance, we could run a clustering algorithm on the volatility levels of the SP500 at different times:" }, { "code": null, "e": 6791, "s": 6474, "text": "from sklearn.mixture import GaussianMixturew = 22vol = rs.rolling(w).std()vol = vol.dropna()labels = GaussianMixture(2).fit_predict(vol.values.reshape(-1,1))prices = prices.reindex(vol.index)prices[labels==0].plot(style='bo', alpha=0.2)prices[labels==1].plot(style='ro', alpha=0.2)plt.title('Volatility Regimes SPY')" }, { "code": null, "e": 7233, "s": 6791, "text": "By fitting a Gaussian Mixture on the observed volatility levels, the ML model automatically inferred bullish and bearish markets regimes. This is intuitive since market sell-offs are often driven by panic selling decisions, which can lead to sharp declines that increases the chaos in the market, resulting in higher volatility. In contrast, bullish markets are characterized by a steadier increase in value, which leads to lower volatility." }, { "code": null, "e": 7428, "s": 7233, "text": "The identification of market regimes is especially important for financial machine learning, since a model trained during a bullish market is unlikely to do well in a bearish one and vice-versa." }, { "code": null, "e": 7728, "s": 7428, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 7819, "s": 7728, "text": "I hope you enjoyed the article! Follow me if you would like to see more content like this." } ]
Telecom Billing - Quick Guide
Sending voice, data, picture, fax, etc., from one point to another using electronic media is termed as telecommunication and in short 'telecom'. Examples include Phone, Radio, Television and Internet. The medium of transmission includes Wire (Copper), Fiber Optics, Ether (wireless), Radio towers, Microwave, Satellite, etc. Now, let us list down a few international telecom operators, who are providing satisfactory telecom services to their customers − Verizon Vodafone Airtel TATA Etisalat Qtel Let us also list down a few basic telecom services being provided by various well known telecom operators − Voice Call Fax Service SMS & MMS Internet Connection Data Download and Upload Video Conferencing IP based services, i.e., voice over IP or VPN Telecom operators are charging their customers in various ways, but there are two mainly used parameters to charge a customer − Rental Charges − These are the charges taken from the customers on monthly basis against the service provided. For example, your telephone monthly charges would be $5.00 regardless you use it or not. Rental Charges − These are the charges taken from the customers on monthly basis against the service provided. For example, your telephone monthly charges would be $5.00 regardless you use it or not. Usage Charges − These are the charges taken from the customers based on the service utilization. For example, you would be charged for all the calls you made or data downloaded using your phone. Usage Charges − These are the charges taken from the customers based on the service utilization. For example, you would be charged for all the calls you made or data downloaded using your phone. Apart from monthly rental and usage charges, operators may charge you for service initiation, installation, service suspension or termination as well. Telecom Billing is a process of collecting usage, aggregating it, applying required usage and rental charges, and finally generating invoices for the customers. Telecom Billing process also includes receiving and recording payments from the customers. There could be very complex charging scenarios, which would be difficult to handle manually. There are state-of-the-art Billing Systems available in the software market that can handle billing tasks very efficiently and provide lots of flexibilities to service providers to offer their services with different price structures. Billing systems are often viewed as accounts receivable, as the billing system assists in the collection (receipt) of money from customers. Billing systems are also part of accounts payable (for inter-carrier settlements), as customers often use services from other companies such as wireless roaming, long distance, and call completion through other networks. Billing systems are high end, reliable, and expensive softwares, which provide various functionalities. Here is a list of most important features but not limited to the following − Rating & billing − It involves rating the products or services usage and producing monthly bills. Rating & billing − It involves rating the products or services usage and producing monthly bills. Payment processing − It involves posting of the customer's payments into his/her account. Payment processing − It involves posting of the customer's payments into his/her account. Credit control and collections − It involves chasing the outstanding payments and taking appropriate actions to collect the payments. Credit control and collections − It involves chasing the outstanding payments and taking appropriate actions to collect the payments. Disputes and adjustments − It involves recording customer's disputes against their bills and creating adjustment to refund the disputed amount in order to settle the disputes. Disputes and adjustments − It involves recording customer's disputes against their bills and creating adjustment to refund the disputed amount in order to settle the disputes. Pre-pay and post-pay services − It involves supporting both the pre-paid and the post-paid customer bases. Pre-pay and post-pay services − It involves supporting both the pre-paid and the post-paid customer bases. Multilingual & multiple currencies − Multilingual and multiple currencies support is required if the business is spread across the globe and have multinational customers or else if the government regulations demand for it. Multilingual & multiple currencies − Multilingual and multiple currencies support is required if the business is spread across the globe and have multinational customers or else if the government regulations demand for it. Inter-carrier settlements − It involve sharing of revenue between carriers that provide services to each other's customers. Inter-carrier settlements − It involve sharing of revenue between carriers that provide services to each other's customers. Products & services − This involves providing flexible way to maintain various products and services and sell them individually or in packages. Products & services − This involves providing flexible way to maintain various products and services and sell them individually or in packages. Discount applications − This involves defining various discount schemes in order to reduce customer churn and attract and increase customer base. Discount applications − This involves defining various discount schemes in order to reduce customer churn and attract and increase customer base. When you drill down billing subject, it becomes more complicated. I would try to cover most of the concepts later in this tutorial, but first, let us have a broad view of the widely used billing types − Pre-pay Billing − A billing mechanism where customer pays in advance and after that starts using a service. Usually, prepaid customers do not receive any invoice and they are charged in real time by the highly available billing systems called 'IN'(Intelligent Network). Pre-pay Billing − A billing mechanism where customer pays in advance and after that starts using a service. Usually, prepaid customers do not receive any invoice and they are charged in real time by the highly available billing systems called 'IN'(Intelligent Network). Post-pay Billing − This is the conventional billing, which is coming for many years. Here, customers buy products and services and use them throughout the month, and by end of the month, invoices are generated by the service provider and sent those invoices to the customers to make their due payment. Post-pay Billing − This is the conventional billing, which is coming for many years. Here, customers buy products and services and use them throughout the month, and by end of the month, invoices are generated by the service provider and sent those invoices to the customers to make their due payment. Interconnect Billing: The network operator is usually financially responsible for services provided to its customers by other networks regardless of whether or not the customer pays for the service. Interconnect billing is related to inter-carrier or sometime called partner settlements. Interconnect Billing: The network operator is usually financially responsible for services provided to its customers by other networks regardless of whether or not the customer pays for the service. Interconnect billing is related to inter-carrier or sometime called partner settlements. Roaming Charges − When a customer goes from one network operator's coverage area to another operator's coverage area, the first operator would pay marginal charges to the second operator to provide services to their customers. Such type of charges are settled through roaming billing. This settlement is done as per TAP3 protocol, which we will discuss in the upcoming chapters. Roaming Charges − When a customer goes from one network operator's coverage area to another operator's coverage area, the first operator would pay marginal charges to the second operator to provide services to their customers. Such type of charges are settled through roaming billing. This settlement is done as per TAP3 protocol, which we will discuss in the upcoming chapters. Convergent Billing − Convergent billing is the integration of all service charges onto a single customer invoice. Convergent billing means creating a unified view of the customer and all services (Mobile, Fixed, IP, etc.,) provided to that customer. Convergent Billing − Convergent billing is the integration of all service charges onto a single customer invoice. Convergent billing means creating a unified view of the customer and all services (Mobile, Fixed, IP, etc.,) provided to that customer. Billing Systems are the backbone of any telecom operator. If operators do not have a strong billing system, then it would not be possible for them to offer their products and services with attractive promotions and deals and ultimately they can not stand in today's competitive and dynamic market. You can find thousands of vendors, who are selling their billing products with a claim of lot of features, but there are a few in the market which are really good and most commonly used. Some of the good billing systems are listed below − www.convergys.com www.amdocs.com www.amsinc.com/telecom www.kenan.com www.intecbilling.com www.intecbilling.com www.ericsson.com The following diagram shows the typical architecture of a Billing System − Here, we have two possibilities − CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. Second possibility could be that the CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. Second possibility could be that the CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. Considering the above system architecture: → After a call is made or you can say a usage is generated by the end customer, the mediation system gathers usage data from the network switch and builds a call-detail record (CDR). This CDR must contain 'A' party number and 'B' party number, the start and the end date & times. The CDR is then stored until it can be rated. To rate the call, the CDR is examined to see if the call is, for example, an 800 number, a local call that is covered by a local-area calling plan, international call or a toll call. Information such as the time of the call was placed and city code or country codes are used to calculate the rate for the call. Once each call is rated, this information is stored until the invoice is run, usually once a month. When the invoice is run, other nonusage charges, such as discounts or monthly fees, can be applied to the bill or sometime called invoice. There could be a rating time discount or billing time discount, different payments done by the customers, different adjustments given, all these information contribute in the final invoice generation. This information is then converted in a format, which can be printed in a readable form. Finally, the envelope is printed, stuffed with enclosures, and mailed to the end customer. A billing system should be composed of a series of independent applications that, when run together, are referred to as the billing system. A good billing system should provide the following major functionalities with a depth of flexibility − Customer-interface Management − The billing system must be able to handle customer-initiated contact, oversee outbound customer contact, and manage the contact life cycle. Customer-interface Management − The billing system must be able to handle customer-initiated contact, oversee outbound customer contact, and manage the contact life cycle. Order Management − It is a basic functionality, which should be available in a typical billing system. Billing system should be capable enough to capture product & service order and manage the order-entry life cycle, and oversee the order-completion life cycle. Order Management − It is a basic functionality, which should be available in a typical billing system. Billing system should be capable enough to capture product & service order and manage the order-entry life cycle, and oversee the order-completion life cycle. Sales and Marketing − A satisfactory billing system should answer customer's query, handle commissions, provide sales support, track prospects, manage campaigns, analyze product performance, and acquire multiple dwelling units. Sales and Marketing − A satisfactory billing system should answer customer's query, handle commissions, provide sales support, track prospects, manage campaigns, analyze product performance, and acquire multiple dwelling units. Rate Plans and Rating − A billing systems must manage a variety of products and services, different rate plans associated with those products and services and should provide flexible ways to rate usage generated by those products and services. Rate Plans and Rating − A billing systems must manage a variety of products and services, different rate plans associated with those products and services and should provide flexible ways to rate usage generated by those products and services. Discounting − A billing system should be capable of giving various types of discounts on different usages and rentals. Discounting − A billing system should be capable of giving various types of discounts on different usages and rentals. Invoicing − It is important that the system performs billing inquiry, generates bills, processes deposits, performs account administration, maintains tax and fee information, and processes financial information. Invoicing − It is important that the system performs billing inquiry, generates bills, processes deposits, performs account administration, maintains tax and fee information, and processes financial information. Credit Control & Collection − A billing system should control usage and revenue by assigning different credit classes to different customers. System should support payment collection and applying them on different invoices. Credit Control & Collection − A billing system should control usage and revenue by assigning different credit classes to different customers. System should support payment collection and applying them on different invoices. Multilingual Support − Multilingual support involves providing invoices and customer care services in multiple languages. Multilingual Support − Multilingual support involves providing invoices and customer care services in multiple languages. Multiple Currencies − Multiple currencies used in different countries can complicate the billing system as the billing and customer care system must be capable of recording and processing in units of multiple currencies. Multiple Currencies − Multiple currencies used in different countries can complicate the billing system as the billing and customer care system must be capable of recording and processing in units of multiple currencies. Partner revenue management − Partner revenue management are the sharing of revenue between carriers that provide services to each other's customers. Partner revenue management − Partner revenue management are the sharing of revenue between carriers that provide services to each other's customers. Problem Handling − A billing system should also be able to manage trouble-ticket entry, coordinate trouble-ticket closure, and track the resolution progress of a trouble ticket. Problem Handling − A billing system should also be able to manage trouble-ticket entry, coordinate trouble-ticket closure, and track the resolution progress of a trouble ticket. Performance Reporting − A satisfactory system will provide performance reporting, ensure quality-of-service (QoS) reporting, create management reports, and generate regulatory reports. Performance Reporting − A satisfactory system will provide performance reporting, ensure quality-of-service (QoS) reporting, create management reports, and generate regulatory reports. Installation and Maintenance − The system should also provide workforce scheduling and manage activities performed at the customer premises. Installation and Maintenance − The system should also provide workforce scheduling and manage activities performed at the customer premises. Auditing & Security − A billing system should perform data audits and integrity checks. A secure system is always desirable for an operator. Auditing & Security − A billing system should perform data audits and integrity checks. A secure system is always desirable for an operator. Apart from the above functionalities, a good billing system should be − Accelerating time-to-market for new service launches. Accelerating time-to-market for new service launches. Enabling convergent view of customers and products. Enabling convergent view of customers and products. Supporting cost-efficient architectural scalability. Supporting cost-efficient architectural scalability. Enabling partner relationship management and settlement. Enabling partner relationship management and settlement. Reducing total cost of ownership. Reducing total cost of ownership. Starting from the next chapter, we would try to cover complete process starting from defining products and services, associating plan and tariffs with those products, acquiring customers (selling products to the end customers), capturing usage generated by those customers, and finally, rating and billing that usage to send a final bill to those customers. Let us suppose a telecom operator like Airtel wants to set up a billing system of its own. Then, Airtel would have to first define its products and services by its sales and marketing department before moving on to set up a billing system. A product is a logical or physical entity, which can be sold out to an end customer by the operators. This could be a mobile phone, internet connection, Voice call connection, VPN, Video on demand, Digital TV connection, etc. A product can have its monthly rental, which we call periodic charges also. A product can be usage generating product or non-usage generating product. A usage generating product is sometime called event generating product and non-usage generating product is called non-event generating product. For example, voice call connection, which comes along with a phone number, is a usage generating product because it generates usage whenever end customer uses this product to make a voice call. A simple phone set without a connection is a non-usage generating product and it could be given to a customer based on monthly rent only. So even if, a customer is not using it, he has to pay monthly rental. When we talk about them from marketing point of view, as such there is no difference between products and services because most of the times, both are used interchangeably by different billing and marketing experts. Simply put, an operator uses its products to provide voice services to its customers. An international call can be called a service provided using a voice call connection. Another example could be 800 number call may or may not be available through a particular operator, call waiting, call forward could be said a service provided by a model of a phone set or by an operator. This tutorial will use Product and Service terms interchangeably. Keeping it simple, Products are the items that customers can either buy outright or lease. products may be − Real objects (a mobile phone, for example) Services (a call waiting service on a telephone system, for example) More abstract concepts (a service level agreement, for example) Related products can be grouped together into a product family. Multiple levels of products are possible, so a product can be both a parent and a child at the same time. In addition, each product family can have more than one parent product if required. Examples of product families are − Telephony services Cable TV Internet Leased Line Many a times, operators bundle more than one product into a single group and sell them as complete package. There are billing systems, which support bundling of various types of products together as a package. It can be offered at discounted price. Packages allow a product to be offered to a customer at a reduced price if it is taken as part of a package. Each package can consist of any number of products and these products can be taken from more than one product family. This package price plan for a product is usually different to its comparison (that is, non-package) price plan, as this is how the company offers a discount to the customer for buying the complete package. However, this is not mandatory, as a product can have one of its normal price plans assigned to it within a package. A product can have a number of attributes associated with them. Product attributes allow information about individual product instances to be held where the relevant information differs between types of product. For example, a pay TV product may have an attribute recording its set-top box number. Further, a mobile phone product may need attributes to record the International Mobile Subscriber Identity (IMSI) and Mobile Station International ISDN Number (MSISDN). A product can have a number of event types associated with it. These event types govern the events that can be generated by the product. For example, a mobile phone product could have event types such as voice calls and messaging services. There could be many more event types associated with a single phone device and operator can charge end customer for each of the event generated by the customer. Once your marketing department finalized all the products, services, packages and associated prices, they are configured in the billing system. Different billing systems provide different levels of flexibilities of defining products and their hierarchies in terms of parent, child, and grandchild products. Some systems are flexible enough to support packages and bundles and a few provide limited functionalities related to packages and discounted prices. Some systems keep product catalogues separately from the price catalogues to provide better modular approach and some billing systems combine products descriptions, their features, and associated prices altogether. Once all the products, services, packages and their events are configured in the billing system, next step is to define their rental and usage prices, which we will cover in next chapter. If you understood what is a product or service and package, then you can proceed to the next chapter to understand how their prices are defined by the marketing department available with any operator. Marketing department in a telecom operator company works hard to define rental & usage charges for different products and services. These charges are defined keeping other competitors and regulations in mind. Broadly speaking, there are two type of tariffs, also called rate or price plans, depending terminology used in different billing system. There could be different types of charges to be applied for a product and associated services. For a given product, an operator can define one or more of the following charges, but they are not limited to only these charges, there could be some other type of charges depending on country, location, and business situation − Product Initiation Charges − These are one-time charges, which can be taken from the customer as a part of installation, activation, service or initiating a connection. Product Initiation Charges − These are one-time charges, which can be taken from the customer as a part of installation, activation, service or initiating a connection. Product Periodic Charges − These are the charges, which can be applied on monthly or bi-monthly or yearly basis as a rental of the product and service provided. Product Periodic Charges − These are the charges, which can be applied on monthly or bi-monthly or yearly basis as a rental of the product and service provided. Product Termination Charges − These are the charges, which can be applied on termination of the product and service. Product Termination Charges − These are the charges, which can be applied on termination of the product and service. Product Suspension Charges − These are the charges, which can be applied if a product is suspended because of some reason; for example, non-payment. Product Suspension Charges − These are the charges, which can be applied if a product is suspended because of some reason; for example, non-payment. Product Suspension Periodic Charges − There could be a requirement to charge a customer periodically even if a customer is suspended because of some reason. Product Suspension Periodic Charges − There could be a requirement to charge a customer periodically even if a customer is suspended because of some reason. Product Re-activation Charges − Assuming a product was suspended due to some reason and now it needs its activation, an operator can apply re-activation charges for this service. Product Re-activation Charges − Assuming a product was suspended due to some reason and now it needs its activation, an operator can apply re-activation charges for this service. Product Usage Charges − This is most important type of charge, which would be applied based on the usage of the service. For example, call per minute or per second, data download per MB, etc. Product Usage Charges − This is most important type of charge, which would be applied based on the usage of the service. For example, call per minute or per second, data download per MB, etc. All the above charges are defined (i.e., configured) in different tariff catalogues inclusive or exclusive of applicable tax depending on regulatory. These catalogues vary from a billing system to billing system. Some billing systems keep all the prices in a single catalogue and some billing systems keep usage charges separate from other charges. These catalogues are maintained in the billing system, but they are also made available to front end system so that different tariffs can be applied to the customer while creating customer account. All the prices are defined based on products and their packages as well. There could be different combinations of products giving different prices in different packages. Following section would give you an idea on different concepts, which are closely related to tariff definition − There may be situation, when an operator would like to charge their customers in advance for some services and at the end of every month for some other services. Charges taken in advance before providing the services are called in-advance charging and charges taken after providing the services are called in-arrear charges. For in-arrears charging, the product charges are applied for a period up to at least the day before the current nominal bill date (or bill request date for non-periodic bills). So while configuring different charges, billing system should give a provision to configure charges in advance and it is always optional for the operators if they want to configure a particular price in-advance or in-arrears. NOTE − Usage charges can not be taken in advance until they are lump-sum because you never know how much usage a customer is going to generate in the coming month. If they are lump-sum amount, then you can take that amount in advance and let the customers use unlimited services based on their requirements. Consider a situation, when a customer takes phone connection in the middle of the month and his invoice needs to be generated on the first day of every month. If prices are non-proratable, billing system would charge the customer for the whole, month which would not be fair with the customer. Same apply at the termination, if customer terminates a service in the middle of the month, then operator may not be willing to charge the customer for rest of the month. Pro-ratable pricing means that they would apply only for the number of days customer is going to use the service. For example, if monthly product rental is $30 and customer used this product for 10 days only, then billing system should charge the customer only $10 for those 10 days. So billing system should provide an option to configure the particular prices to be pro-ratable as well as non-proratable and let the operators choose what suites them best. Now, let us consider a situation where an operator is charging a customer in advance for the whole month, but customer leaves in the middle of the month after using a service for 10 days. If prices were configured as non-refundable, then they would not be refunded to the customer, but if they were configured as refundable, then they would be refunded to the customer. Second rule, if prices were configured as pro-ratable, then they would be refunded based on pro-ration, otherwise they would be refunded as a whole. A good billing system provides an option to override base prices at the time they are given to the customer. For example, for a particular product base prices in the catalogue are defined $30 per month but customer is not ready to pay $30 per month, and based on some bargaining, he is ready to pay $25 per month. In such a situation, customer service representative (CSR) should be able to override defined base price $30 and add them as $25 at the time of customer creation in the system. Billing system should give an optional provision to the operators if a particular price can be overridden or not and let the operators decide if they want to override some charges at the time of sale or they are fixed in all the situation. All the operators would like to know how much they have earned using a particular product, its rental, suspension or usage, etc. While defining different prices in the catalogue, billing system should give a provision to associate some kind of revenue codes or keywords with different types of charges. This helps in generating different reports based on the codes associated with the revenue. An operator may define different tariffs, which can be offered to different people having different credit classes. For example, a 5mbps data line at a cost of $100 per month can be offered to a customer having monthly income more than $1000/month and a 1mbps data line can be offered to a customer having minimum monthly income $500/month. All the billing systems give options to define different credit classes, which can be assigned to customers based on their credit history and income and may be based on some other parameters defined by the operator. All the products and services can have different tariff plans, which can be offered to different classes of people ranging from general class to VIP class. There are number of parameters, which can be used while defining usage charges. For example − Calls in daytime, usually called peak time, will be charged on higher rate and in night time, i.e., off peak time rate will be relatively low. Calls in daytime, usually called peak time, will be charged on higher rate and in night time, i.e., off peak time rate will be relatively low. If calls are terminating within the same network, usually called on-net calls, would be charged at relatively low prices. If calls are terminating within the same network, usually called on-net calls, would be charged at relatively low prices. Calls during weekend, i.e., Sat and Sun would be charged at low prices. Calls during weekend, i.e., Sat and Sun would be charged at low prices. Calls to a particular destination would be charged at high prices. Calls to a particular destination would be charged at high prices. Calls during some festival would be charged at special prices. Calls during some festival would be charged at special prices. Data download from a particular site would be free of cost. Data download from a particular site would be free of cost. Sending SMS to a particular code would be charged at high rate. Sending SMS to a particular code would be charged at high rate. Calls within a particular group of numbers, usually called closed user group (CUG), would be charged at zero price. Calls within a particular group of numbers, usually called closed user group (CUG), would be charged at zero price. Sending international or national MMS would be charged at the same prices. Sending international or national MMS would be charged at the same prices. Billing systems provide lots of flexibility to define various such rules to charge voice, data, SMS, or MMS usage generated by the customer. Now, we have all the products, services, and associated tariffs available in the billing system. In the next chapter, we will see how to sell these products to the end-users and create their records in the system. A customer is a "legal entity" (that can be either an individual or a company) that takes the products and services offered by the service provider and responsible for paying the bills. In a residential billing scenario, a customer might be a single householder. In a business billing scenario, a customer might be a corporation. Individual customer − An individual customer is a single person (or household), who buys one or more products and pay the bills. There would not be any hierarchy required to maintain customer or account. Individual customer − An individual customer is a single person (or household), who buys one or more products and pay the bills. There would not be any hierarchy required to maintain customer or account. Company customers − A company customer is a single company or branch of a company. There could be a typical parent and child type of customer hierarchy representing different branches or departments of the company. Company customers − A company customer is a single company or branch of a company. There could be a typical parent and child type of customer hierarchy representing different branches or departments of the company. Customer Acquisition is the process of identifying, attracting and retaining the potentially profitable customers. This is a handled using system called Customer Relationship Management (CRM), which is one of the important business support systems (BSS). A CRM system would always be connected with various systems including billing system and feeds customer personal data and product and service information to the billing system. A customer, who is purchasing the products & services, needs to be activated in the system and for this, various details about the customer are required − The customer may have to fill up an application form providing personal details. The customer may have to fill up an application form providing personal details. Validate the identity of the customer in order to prevent fraud. Validate the identity of the customer in order to prevent fraud. Service Provider needs to carry out a credit check on the customer and assign appropriate credit class based on credit history and monthly income, etc. Service Provider needs to carry out a credit check on the customer and assign appropriate credit class based on credit history and monthly income, etc. Offer appropriate products, which are provisioned at the network to provide the service. Offer appropriate products, which are provisioned at the network to provide the service. Once the customer is acquired, it is required to manage and retain the customer, which involves − Interacting & communicating with the customer for sales and collection activities. Interacting & communicating with the customer for sales and collection activities. These interactions can be recorded in different formats like Notes, voice recordings, etc. This data can be used to analyze the behavior of the customer and helps the service provider to provide better services in order to retain the customer These interactions can be recorded in different formats like Notes, voice recordings, etc. This data can be used to analyze the behavior of the customer and helps the service provider to provide better services in order to retain the customer Handling trouble tickets raised by the customers against any problem they face with the network or invoice, etc. This data can also be used to analyze the behavior of the customer and helps the service provider for the betterment of the services in order to retain the customer. Handling trouble tickets raised by the customers against any problem they face with the network or invoice, etc. This data can also be used to analyze the behavior of the customer and helps the service provider for the betterment of the services in order to retain the customer. Handling any bill disputes and adjustments raised in between the customer and service provider. Handling any bill disputes and adjustments raised in between the customer and service provider. A typical customer life cycle is shown below in the following diagram − All the phases comprising a customer life cycle are briefed here − Customer Engagement − The customer contacts the CSR (Customer Service Representative) and the CSR engages the customer with the various products and services offered by selling them to the customer. Customer Engagement − The customer contacts the CSR (Customer Service Representative) and the CSR engages the customer with the various products and services offered by selling them to the customer. Order Creation and Fulfilment − The customer takes the product(s) and services(s) and the CSR creates and completes the order into the system, which is then fulfilled by supplying required product and services to the customer. Order Creation and Fulfilment − The customer takes the product(s) and services(s) and the CSR creates and completes the order into the system, which is then fulfilled by supplying required product and services to the customer. Service Provisioning − The products and services are provisioned at the network using a system called Provisioning System. The Provisioning System informs the network about the customer's information and the services they are authorized to use. In fact, this activates the customer on the network. Service Provisioning − The products and services are provisioned at the network using a system called Provisioning System. The Provisioning System informs the network about the customer's information and the services they are authorized to use. In fact, this activates the customer on the network. Products Utilization − Once the customer is activated on the network, the customer starts using the products & services including, making a call, data download, etc. Products Utilization − Once the customer is activated on the network, the customer starts using the products & services including, making a call, data download, etc. Products and services usage is Rated & Billed − Customer usage is collected from the network and then it is rated based on the defined rate plans and billed to apply product rentals and required discounts, adjustments, etc. Products and services usage is Rated & Billed − Customer usage is collected from the network and then it is rated based on the defined rate plans and billed to apply product rentals and required discounts, adjustments, etc. Bill Delivery − Once a bill is generated, it is delivered to the end customer demanding for the revenue against the services provided. Bill Delivery − Once a bill is generated, it is delivered to the end customer demanding for the revenue against the services provided. Bill Payments − Customer makes the payments against the received invoices. Bill Payments − Customer makes the payments against the received invoices. Dunning & Collection − There may be many customers, who will not pay their bills on time. For such type of customers, different dunning letters are sent to remind them about their payments. If a customer does not pay on time, then different collections are taken starting from stopping the customer services one by one. Dunning & Collection − There may be many customers, who will not pay their bills on time. For such type of customers, different dunning letters are sent to remind them about their payments. If a customer does not pay on time, then different collections are taken starting from stopping the customer services one by one. Customer Termination − There may be various reasons when it is required to terminate a customer in the system. For example, customer may be migrating to different location, or customer may not be happy with the services provided, etc. Customer Termination − There may be various reasons when it is required to terminate a customer in the system. For example, customer may be migrating to different location, or customer may not be happy with the services provided, etc. On a given date, total number of active customers in the system are called the customer base. Adding a customer into the system, and terminating a customer from the system, is known as customer churn. Typically, there are following types of customers in today's telecom market − Mobile Pre-Paid Customers − These are the customers, who use Mobile services by paying their charges in advance. For example, GSM, GPRS phone users. These customers recharge their phone based on their requirements. Mobile Pre-Paid Customers − These are the customers, who use Mobile services by paying their charges in advance. For example, GSM, GPRS phone users. These customers recharge their phone based on their requirements. Mobile Post-Paid Customers − These are the customers, who use Mobile services by paying their charges after every invoice they receive. For example, GSM, GPRS phone users. These customers pay their bills on monthly or bi-monthly basis. Mobile Post-Paid Customers − These are the customers, who use Mobile services by paying their charges after every invoice they receive. For example, GSM, GPRS phone users. These customers pay their bills on monthly or bi-monthly basis. Fixed Pre-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges in advance. For example, PSTN, WiMax phone users. These customers recharge their phones based on their requirements. Fixed Pre-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges in advance. For example, PSTN, WiMax phone users. These customers recharge their phones based on their requirements. Fixed Post-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges after every invoice they receive. For example, PSTN, WiMax phone users. These customers pay their bills on monthly or bi-monthly basis. Fixed Post-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges after every invoice they receive. For example, PSTN, WiMax phone users. These customers pay their bills on monthly or bi-monthly basis. Now, we have customers in our billing system along with products and services. Customer starts utilizing all the products and services bought and start generating national and international, data and voice calls, which will be rated and billed by the billing system and we will discuss those processes in subsequent chapters. A customer starts generating usage at Network as soon as he/she starts using the products and services sold by the operator. A network element is a combination of software plus hardware and responsible for overall service control and metering events for any type of service. An event is a single billable occurrence of product usage, typically captured electronically by a network. For example, when a mobile phone user makes a telephone call, an event is generated, which contains information about that phone call, such as the call duration, the time of day the call was made, and the number that was called. An event along with all its attributes is called Call Detail Record (CDR). A data collector in the network switch captures the usage in the form of Call Detail Record (CDR)/Usage Detail Record (UDR). These raw CDRs/UDRs are in turn converted by the mediation system into a format understandable by the Billing System. There could be different network elements controlling the services and producing different types of CDRs; for example, for GSM telephony − Voice calls are captured by the MSC (Mobile Switching Centre). SMS traffic is captured by the SMSC. Data traffic is captured by the GGSN. MMS traffic is captured by the MMSC. Roaming CDRs are captured by roaming partner's switching element. For more information on GSM, MSC, SMS, SMSC, GGSN, MMS, MMSC, please refer to our GSM tutorials. The following diagram shows the Network elements capturing Usage data and sending Raw UDRs to the Mediation System and finally to the Billing System for rating and billing. As mentioned above, a CDR keeps usage details along with various other useful information. Below are the most important attributes of a CDR − Calling Party (A number). Calling Party (A number). Called Party (B number). Called Party (B number). Call Start (date and time). Call Start (date and time). How long the call was (duration). How long the call was (duration). Call Type (Voice, SMS, Data etc). Call Type (Voice, SMS, Data etc). A unique sequence number identifying the record. A unique sequence number identifying the record. Additionally, a CDR may also record other information such as − The identifier of the telephone exchange. The identifier of the telephone exchange. The result of the call (whether it was answered, busy, etc.). The result of the call (whether it was answered, busy, etc.). Trunk or route used to connect the call. Trunk or route used to connect the call. Any fault condition encountered. Any fault condition encountered. Indicators that note the use of features such as call forwarding, three-way calling, etc. Indicators that note the use of features such as call forwarding, three-way calling, etc. Any facilities used during the call, such as call waiting or call diversion. Any facilities used during the call, such as call waiting or call diversion. Various other attributes depending on requirement. Various other attributes depending on requirement. The accurate recording of all required information in a UDR depends on the logic of the switch vendor plus the switch specific table entries. If either of these cannot record the data accurately, the mediation system will not be able to recognize the completed calls and pass them to the billing system. The Mediation System collects CDRs from different network elements in different formats. Various network elements generate CDRs in ASN.1 format and some network elements have their own proprietary format of CDRs. The Mediation System processes all the CDRs and converts them into a format compatible to the down stream system, which is usually a Billing System. The Mediation System applies various rules on CDRs to process them; for example, mediation system marks the international calls based on the dialed number (B-Number), same way mediation system marks the on-net calls based on A-Number and B-Number. There may be a requirement to filter out all the calls, which are having call duration less than 5 seconds, the best place to filter out such types of calls will be at Mediation System level. Same way, if some extra information is required in the CDRs, which is critical to billing, then Mediation System will help in providing such information based on some other attributes available within the CDRs. Once the collected CDRs are processed, Mediation System pushes all the CDRs to the Billing System using FTP because usually Mediation and Billing systems run on different machines. Well, now you have captured customer generated usage. The next chapter will cover how we can rate this captured usage so that due revenue can be collected from the end-user. Rate is the charge/price for the occurrence of an event. Examples of rate include charge for the duration of the telephone call: For example: "0.40 INR per 1 minute" or a specific quantity. For example: 10.00 INR for 1MB download or it can be charged for the quality of service. We already explained that Event is a single occurrence of product/service usage. The events are captured by the network elements in the form of CDRS/UDRs and passed to the Billing system for rating & billing. Rating is the process of determining the charge/price of individual events. For example, the price for 2 minutes call is 0.80 INR with the rate of 0.40 INR per minute. Rating Engine, which is part of the Billing system, carries out this rating function. Rating Engine receives the events in the form of data records called as Call Detail Records (CDRs) or Usage Detail Records (UDRs), which describe the use of a product/service. A CDR is a string of data that contains call information such as call date and time, call length, calling party, called party, etc., which are used to rate the events. There is a list of basic functions of Rating/Rating Engine − Accepting CDRs from the Mediation System or other service providers or roaming partners in case of roaming usage. Accepting CDRs from the Mediation System or other service providers or roaming partners in case of roaming usage. Validating the CDRs and eliminating any duplicate records. These duplicate events are stored in a database table for later verification. Validating the CDRs and eliminating any duplicate records. These duplicate events are stored in a database table for later verification. To determine the customer account that has to be charged for the event. Here, Rate process picks up the event source ( Mobile Number or IP Address, etc.) and checks the database to verify if this event source is associated with any account. This step is called Event Guiding. To determine the customer account that has to be charged for the event. Here, Rate process picks up the event source ( Mobile Number or IP Address, etc.) and checks the database to verify if this event source is associated with any account. This step is called Event Guiding. If the event can not be guided, then this event will be rejected and can be put in suspense category. These rejected events are stored in a database table for later verification. If the event can not be guided, then this event will be rejected and can be put in suspense category. These rejected events are stored in a database table for later verification. To calculate the cost/price of the event as per the rating tariff (also referred as rate plan). To calculate the cost/price of the event as per the rating tariff (also referred as rate plan). To apply any applicable rating time discounts. This could be first five minutes free and after that call will be charged at normal rate. Such type of discounts are called rating time discounts. To apply any applicable rating time discounts. This could be first five minutes free and after that call will be charged at normal rate. Such type of discounts are called rating time discounts. To store the rated event in the database for a billing purpose or send it to the external system for billing. To store the rated event in the database for a billing purpose or send it to the external system for billing. The following image shows an overview of the Rating Engine and its associated functions − The customer's information determines the rate plan (rating tariff) to use in charge/price calculation. The rating engine uses the rating tables, and the event information from the CDRs (e.g. distance, time of day, location of the call, duration or volume of the event, etc.) to calculate the actual charge for each call. A duplicate event is defined as any unbilled event that relates to another unbilled event in all of the following ways − The account numbers are identical. The event sources are identical. The event type IDs are identical. The event dates and times are identical. Any other criteria can be defined in the billing system to identify duplicate events. There are a number of situations that may cause duplicate events to be submitted to the Billing system − A failure of the mediation system's filtering mechanism. Coding errors in the mediation system software. A repetition of all or part of an event file being passed to the Rating Engine. When Billing System encounters a problem with a particular event, the offending event is rejected. Rejection may be due to problems with any of the following − The event itself. The rate plan. Customer and account data. Configuration data. There are three main reasons for rejecting an event − Parsing errors prevent the Billing System from reading the information in the event detail record. A parsing error may occur because the data in the event record is corrupt or in the wrong format. Parsing errors prevent the Billing System from reading the information in the event detail record. A parsing error may occur because the data in the event record is corrupt or in the wrong format. Unguideable errors prevent Geneva from identifying the event source or account associated with the event. An unguideable error may occur because the event source does not yet exist in the Billing System database. Unguideable errors prevent Geneva from identifying the event source or account associated with the event. An unguideable error may occur because the event source does not yet exist in the Billing System database. Unrateable errors prevent Billing System from calculating a cost for the event. An unrateable error may occur because of problems with a rate plan. Unrateable errors prevent Billing System from calculating a cost for the event. An unrateable error may occur because of problems with a rate plan. All the rejected events are posted to a special account, which is called internal account or suspense account and these rejected events are called suspense events. Finance department keeps track of all the rejected events and count them as a part of revenue loss. IT department always gives alot of attention to resolve rejected events and rate them properly to save revenue. If a rejected event cannot be fixed and the Operator does not want to post it to an internal account, the event can be discarded. When an event is discarded, it will not be submitted to the Rating Engine and no further attempts to rate it will take place. Real-time rating is the process of taking events as they occur and rating them immediately, with as little delay as possible between event generation and costing. Real-time rating can be contrasted with file-based rating, where event details are stored in a file buffer for hours, days, or weeks before the whole file is finally rated. Real-time system process includes e-commerce transactions and data download. Any application where events must be rated and applied quickly to a customer's account is a suitable candidate for real-time rating. There are several situations in which it may be necessary to rerate events. For example, when − An error in the rate plan used resulted in incorrectly priced events. An error in the rate plan used resulted in incorrectly priced events. The events were loaded against the wrong account (due to incorrect event source registration). The events were loaded against the wrong account (due to incorrect event source registration). An existing rate plan was replaced at some point between the last and the next billing dates. An existing rate plan was replaced at some point between the last and the next billing dates. The rate plan, price plan, or event source for a product has been retrospectively changed. The rate plan, price plan, or event source for a product has been retrospectively changed. The process for rerating events is very simple and it is as follows − Unload/Unrate all the events from the database using provided utility. Most of the billing system provides a utility to unload or unrate all the rated events. Unload/Unrate all the events from the database using provided utility. Most of the billing system provides a utility to unload or unrate all the rated events. Fix the problem wherever it lies. Fix the problem wherever it lies. Resubmit the events for rating by the Rating Engine. Resubmit the events for rating by the Rating Engine. Partial events allow a customer's balance to be maintained while an event is in progress. For example, in case of a long data download, mediation system will keep sending partial events to the billing system so that billing system keep rating them instead of waiting for event completion, and as soon as customer's credit limit breach, account will be barred and Network element will be informed to terminate the call. The Rating Engine can automatically check to see if any rating time thresholds, including rating time discount thresholds, have been reached. Rating time thresholds help in protecting operators from lots of revenue loss. For example, a customer may not be willing to pay more than his credit limit, in such a case, it becomes necessary to terminate customer's call as soon as it reaches to credit limit threshold. If it is required to take rating time action, then it is important to have as much as real time rating as possible. So far, we have seen how a customer generates usage and how mediation system pushes that usage (CDRs) to the Billing System and how a Billing System rate those CDRs. In the next chapter, we will discuss how to collect all the rated CDRs for the whole month and generate final invoice/bill, which is sent to the end customer to collect revenue for the provided services. Billing is the aggregation of all non-recurring, periodic, and chargeable events on an account-by-account basis. It is also the calculation of all outstanding charges and available discounts and bonuses. The output from billing process is a stream of tagged bill data that can be used to create a bill on paper, disk, or any other media. Billing Engine, which is part of the Billing System, creates invoices. The following diagram shows the basic diagram of the Billing Engine and associated functions − The Billing Engine picks up an account to generate a bill and the following associated information to generate invoice data − All the rated CDRs for the customer within the month of invoice. All the rated CDRs for the customer within the month of invoice. All types of charges (initiation, installation, periodic, suspension, termination, etc.,) applicable for the customer's products and services. All types of charges (initiation, installation, periodic, suspension, termination, etc.,) applicable for the customer's products and services. If there is any refund or any other charges applicable. If there is any refund or any other charges applicable. Total outstanding from previous bills. Total outstanding from previous bills. Total payments made by the customer in the given month. Total payments made by the customer in the given month. Total adjustment passed in favor of the customer or against the customer. Total adjustment passed in favor of the customer or against the customer. Total discount given to the customer. Total discount given to the customer. Total taxes applicable on customer's usage and rental charges. Total taxes applicable on customer's usage and rental charges. Billing configuration parameter required to run the Billing Engine; for example, payment due date, etc. Billing configuration parameter required to run the Billing Engine; for example, payment due date, etc. The above-mentioned information is just an indicative and may vary from billing system to billing system and operator to operator. Billing Engine produces raw data having all the information required to generate a final bill and this raw data can be used to generate a final invoice to be sent to the end customer. When a customer is added into the Billing System, system assigns the customer a predefined Bill Cycle. A bill cycle is a date on which Billing Engine runs and produces bills for a set of customers. If there are many customers, then they are divided into different billing cycles. For example, a group of customers can have billing data as 1st of every month; another can have the billing date on 15th of every month. If a customer is assigned to run a bill on 1st of the month, this would be called customer's nominal bill date. But because of various reasons, many times bill run becomes delayed and actual bill gets generated on a later date, this would be called actual bill date. There could be various types of bills available for a user. Few of them may not be supported by some Billing Systems. Initiation bill Normally, only requested as the first bill on an account. Includes product charges and adjustments, but no events. Periodic bill Produced at regular intervals. Includes all periodic charges, events, and adjustments. Interim bill An extra bill that contains charges due to events processed for the account since the last bill. Includes all events and adjustments, but no periodic charges. Suspension bill Sent when an account has been suspended. Includes all periodic charges, events, and adjustments. Final bill Sent when an account has been terminated to bill all outstanding charges that are due. Includes all periodic charges, events, and adjustments, along with any refunds; for example, the return of a deposit. Post-final bill Sent when a terminated account has receivables outstanding after the production of a final bill. Includes any post-termination events and adjustments, but no periodic charges. Credit note An extra bill that contains all adjustments in the customer's favor generated since the last bill. Summary Statements A summary statement can be produced for a customer-driven billing hierarchy. It can summarize all the bills produced by all accounts associated with the respective customer. Optionally, they can also concatenate all the bills into a single statement. Bills are produced either automatically or on request from a customer. A Billing System can generate bills in two modes, for example − Test (what if?) billing mode − This mode if used to produce formatted test bills whilst leaving the database unchanged. These bills are useful to make sure that system is working fine and test after making changes to bill templates or tariffs. Test (what if?) billing mode − This mode if used to produce formatted test bills whilst leaving the database unchanged. These bills are useful to make sure that system is working fine and test after making changes to bill templates or tariffs. When running the Billing Engine in test mode, commits are not made to the database. So there would not be any impact on customer's profile even after running test billing many number of times. When running the Billing Engine in test mode, commits are not made to the database. So there would not be any impact on customer's profile even after running test billing many number of times. Test bills are usually run for a sample set of customers. If you are satisfied with the test bills, then you can proceed for production bills. Test bills are usually run for a sample set of customers. If you are satisfied with the test bills, then you can proceed for production bills. Production (live) billing mode − This mode is used to produce normal production bills. Most of the time, this is the default mode for the Billing Engine. Production (live) billing mode − This mode is used to produce normal production bills. Most of the time, this is the default mode for the Billing Engine. Once a production bill is generated, Billing Engine updates customer's profile in the database with the total outstanding balance to be paid by the customer, and next bill date, etc. Once a production bill is generated, Billing Engine updates customer's profile in the database with the total outstanding balance to be paid by the customer, and next bill date, etc. Billing Engine assigns different invoice numbers to all the production bills which help in keeping track of different payments made against the invoice. There may be a situation when it is not worth to generate a bill and better to suppress the bill. Following are such type of situations − Suppressing bills for accounts with zero (zero activity bills) or very little value (small bills). Suppressing bills for accounts with zero (zero activity bills) or very little value (small bills). A particular type of bill can also be suppressed if multiple bill types are requested/scheduled at the same time and therefore preventing unnecessary bills from being sent to the customer. A particular type of bill can also be suppressed if multiple bill types are requested/scheduled at the same time and therefore preventing unnecessary bills from being sent to the customer. A small bill is a bill that falls between the ranges defined by the minimum positive bill amount and the maximum negative bill amount, exceptional bill conditions. Small valued bills are produced and then removed from the billing process, so that they are not sent out to customers. Examples of possible exceptional bills are unusually high bills or bills, which exceed the account's credit limit by a set multiplier. The Billing Engine performs some basic checks on the bill data that it produces. These involve testing the total being billed to ensure that the following conditions are met − The bill total is greater than the minimum negative bill amount. The bill total is greater than the minimum negative bill amount. The bill total is less than the maximum positive bill amount. The bill total is less than the maximum positive bill amount. The bill total is less than account's credit limit multiplied by the credit limit multiplier. The bill total is less than account's credit limit multiplied by the credit limit multiplier. All the above conditions vary from billing system to billing system and operator to operator and they are called exceptional bills conditions. By default, all the invoices provide a detailed summary of product and service charges along with usage charges. But it does not provide the details on all the calls made by the customer. An itemized bill means giving complete details of all the calls made by the customer. This needs more number of papers to be printed. Recent trend is to send itemized bill through electronic e-mail and summary statement is sent using a physical copy of the bill. There are Billing Systems, which provide Billing Formatting utilities, which can be used to generate final formatted bills. Bill formatters take the output data produced by the Billing Engine and usually generate either Post Script file or a PDF file, which can be used by the Bill Printing Company. If Billing System is not capable enough to generate formatted bills, then system generates a set of tagged files along with billing information and any external Bill Formatter can use that tagged information to generate a well-formatted invoice. No matter, if Billing System generates formatted invoice or we use an external tool to generate these formatted invoice using raw data generated by the billing engine, finally these invoices are sent to the bill printing company, who takes care of generating final copy of generating invoice. We will discuss it in detail in the subsequent chapter "Invoice Generation." Next chapter would explain discount process, which is actually a part of rating and billing process, but we kept it as a separate section because of the various that items need more explanation. We will discuss different types of discount hierarchies and which can be given at the time of rating and billing. All discounts alter (most commonly to reduce) the price to be paid for a set of events and/or products. Discount is a way of giving customer money off. Discount defines a set amount of money (percentage or monetary) to be applied to products or usage that meet certain criteria. For example, all the local calls made on a particular day say 01-01-2010 are charged at $0.20. Discounts can be calculated either during the rating process or during the billing process − Rating Time Discount − All the discounts given at the time of rating process. These discounts can be given at usage only. An example of rating time discount is "5% off the first hour of all international calls". Rating Time Discount − All the discounts given at the time of rating process. These discounts can be given at usage only. An example of rating time discount is "5% off the first hour of all international calls". Billing Time Discount − All the discounts given at the time of billing process. These discounts can be given on rated usage as well as on product & service charges. An example of billing time discount is "5% off if you spend over $15 within a month". Billing Time Discount − All the discounts given at the time of billing process. These discounts can be given on rated usage as well as on product & service charges. An example of billing time discount is "5% off if you spend over $15 within a month". A pre-itemization discount is one that modifies the price of each event to which it applies to determine a rerated price. This discount also comes in billing time discount category, but this is related to rating of the calls. Other billing time discounts leave the price of the event unmodified. A pre-itemization discount cannot incorporate product charges, only event charges. The size of a discount is determined using a series of discount steps and thresholds. Discount steps allow the size of the discount to be changed when particular thresholds are reached. For example, a discount for telephony events could depend upon the number of minutes spent calling with 10 percent off after 100 minutes and 20 percent off after 200 minutes. Each discount should have at least one step. Further steps can be added if the discount is required to become more or less favorable with greater volumes. Each discount step can have its discount expressed as either an amount of money or a percentage (but not both). There could be infinite types of discounts given to the end customer, but it depends on what your billing supports. Following are the simple, but very good types of discounts, which can be offered − These are the discounts where a set of products & events determine the discounts for another set of products & events. For example, "10 SMS free if more than $30 is spent on mobile calls". Here mobile calls determine the discount and SMS product gets the discounts, such type of discounts are called cross product discounts. These are only applicable to the portion of the set of events or money spent that falls between the assigned discount thresholds. For example, in the following diagram, 0% off for a spend of $0-$100 threshold or 0-100 events threshold, 5% off for a spend of $100-$200 threshold or 100-200 events threshold, etc. These are the discounts based on the number of events or product charges that a certain product generates. For example, in the following diagram, 5% off for a spend of $100 or 100 events, etc. As seen, the greater the spend, the more the discount. Tax discounts provide an alternative method for dealing with some tax exemptions. They are calculated and applied when the account is billed. Most discounts have a discount period associated with them, which can be any number of days, weeks, or months. This period can be used in three ways − To specify the time over which a threshold value is meant to be reached. To specify the time over which a threshold value is meant to be reached. To specify the frequency with which an absolute discount is meant to be applied. To specify the frequency with which an absolute discount is meant to be applied. To specify how often the highest usage is determined for discounts with highest usage filters attached. To specify how often the highest usage is determined for discounts with highest usage filters attached. Discounts could be pro-rated and non-prorated based on the requirement. If discount is pro-rated, then discount will be calculated based on the number of days service has been under use, and in case of non-proration discount, it will be calculated for the whole period for which discount has been configured. Bonus schemes are methods of giving the customer free events, where the number of free events is determined by the prior usage of or charge for one or more products over a period of time (for example, the previous year). For example, "Take the Super deal telephony package and get $10 of free calls for every three hours of international calls made in the previous quarter." There are other ways of giving customers money off, for example, giving a more favorable price plan via a package, reducing the unit rate of a product as the quantity taken increases. Calling circle Groups define a relationship between users, who are modelled as members and (by default) non-members. Within this model, a call made by a member of the circle to another member of the circle would be priced using a different rate to that applied to a non-member (or associate) making the same call. The relationship between the calling parties is determined by the combination of caller identities. Calling circles can span networks if the networks belong to the same operator and a single calling circle can include both mobile and fixed-line users. We already have covered Billing Processes in the previous chapter. In the next chapter, we will discuss the last part of Invoice Generation starting from raw invoice data to structured bill formation. Most of the billing systems generate structured ASCII text containing the information content of the bill. The bill data for each bill is written initially to either database or flat text files. The format of the data at this stage is the same, regardless of how the data is to be processed. This bill data can then be processed by one of a number of formatting engines to produce output in the desired form. For example, paper, CD-ROM, etc. There are Billing Systems available, which provide internal Bill Formatting tools. If a billing system does not provide capable tool to generate formatted bills, then there are third party tools available like DOC1, which is one of the most commonly used tools. Here is a typical diagram showing the flow of bill formatting − Following is the snapshot of a bill data taken from Convergy's Infinys Billing System − DOCSTART_85 DOCTYPE BILL GENEVAVERSION 5.0 BILLSTYLE 1 BILLTYPE 1 BILLTEMPLATE 85 BILLSEQ 1 BILLVERSION 1 ACCCURRENCYCODE BEF BILLLANGID 2 BILLLANGNAME English (US) BILLLANGLOCALE us PAYMETHODID 1 FORMATREQ A30001001/0001 COPYBILLNUM 0 BILLPURPOSE 1 ADDRESSNAME Dr D Jackson POSITION Project Manager DEPARTMENT Recruitment ADDRESS1 12 South Street ADDRESS2 Detroit ADDRESS3 Michigan ZIPCODE 12345 COUNTRY United States BSTARTACCFADDR ACCFADDR_1 United States ACCFADDR_2 Michigan ACCFADDR_3 12345 ACCFADDR_4 12 South Street ACCFADDR_5 Detroit ACCFADDR_6 Dr D Jackson BENDACCFADDR CUSTOMERREF C30001 CUSTOMERTYPE Standard ACCTAXSTATUS Exclusive INVOICINGCONAME Invoicing company for English (US) INVOICINGCOADDRESS1 Company House INVOICINGCOADDRESS2 Atlanta INVOICINGCOVATREG taxref000576 ACCOUNTNO A30001001 BENDBFPAYSUMMARY BALOUT 0.00 CHARGES 142.00 NEWBAL 142.00 BSTARTBFPAYDETAILS ACCDEPPREVTOT 0.00 ACCDEPCHANGE 0.00 ACCDEPCURRTOT 0.00 BENDBFPAYDETAILS BENDBFSTATEMENT BILLREF A30001001@0001 BILLDATE 02/20/99 NEXTBILLDATE 03/20/99 BSTARTPAYMENTDUEINFO PAYMENTDUEDATE 03/04/99 DEBTSTARTDATE 02/25/99 PAYMENTTERMDESC Payment due 7 days after the bill date PAYMENTDUEDAYS 7 BENDPAYMENTDUEINFO GIROREF 34 GIROACCOUNT 404 7800 OCRREF 1300010019 OCRSORTCODE V6344047800 GIROAMOUNT 142.00 OCRAMOUNT 000142000 INVOICEACTUALDATE 02/25/99 INVOICETAXDATE 02/25/99 INVOICESTART 01/03/99 INVOICEEND 02/19/99 TAXTYPE 1,2.00, TENDTAXTYPE INVTOTALTAX 2.00 BENDTAXDETAILS INVTOTAL 142.00 INVTOTALROUNDED 142.00 TOTALSAVE -11.00 PERIODEND 02/25/99 POINTSBALANCE 0 POINTSEARNED 0 POINTSREDEEMED 0 POINTSADJUST 0 NEWPOINTSBALANCE 0 DOCEND Bill data consists of succession of lines of ASCII text. Each line takes the form − TAGNAME tagvalue TAGNAME and tag value are separated by a tag separator (tagsep) of a space. The tagvalue can be either a single value or a list of values separated by delimiters (sep). The delimiter used is a comma unless specified. A Billing Engine may not be able to generate all the information required in the bill or there may be a requirement to perform some special calculation on the data provided in the invoice. This is called Bill Post Processing and usually done by a custom component called Bill Post Processor (BPP). A BPP can be written in your preferred programming language, which reads a raw invoice file and performs required modification into this file before passing it for the final formatting. There is none billing systems available which provide out-of-the-box BPP functionality because requirements vary operator to operator and this process can not be standardized. At most, billing system can provide a plug-in point to plug your custom BPP along with Billing Engine. DOC1 is very famous Bill Formatter tool available from PitneyBowes Company, which helps in bill formatting into PDF or Post Script files. As mentioned above, the output of the Billing Engine is structured ASCII text containing the information content of the bill. A mapping is established between source invoice file tags generated by the billing system and tags required by DOC1. DOC1 requires fixed length tags as shown below. The following is a hypothetical sample from the invoice file provided − ACCOUNTNO ACC0010000 ACCUMBONUSPOINTS_1 BON0050100 ACCUMBONUSPOINTS_2 BON0050100 ACCUMBONUSPOINTS_3 BON0050100 ACCUMBONUSPOINTS_4 BON0050100 ACCUMBONUSPOINTS_5 BON0050100 ADDRESS1 ACC0030000 ADDRESS2 ACC0040000 ADDRESS3 ACC0050000 ADDRESS4 ACC0060000 ADDRESS5 ACC0070000 ADDRESSNAME ACC0020000 BUSINESSNAME ACC0120000 TSTARTADJ ADJ0000000 .......... Now using the above translations, a final file would be generated for DOC1 and DOC1 will take care of generating final invoice using the information provided. Some modifications can also be performed at DOC1 level, but it does not provide much flexibility to modify the invoice. You can try latest version, which can help you much more the expectations. Once all the accounts are billed and invoices are formatted using either internal or external bill formatter, these invoices are sent to the Bill Print Company for final printing. If an operator is using Electronic e-mail facility to send a bill to their customer, then a copy of the same bill can be sent to e-mail system to send it to the end customer. Tier 1 operators (having 20-30 million or more customer base) usually outsource this task including bill distribution. After generating invoices, they are sent to the end customers. Now, it is time to collect revenue from the customer. We would discuss revenue collection process after one chapter. Before we proceed further, let us cover Credit Control Part, which is very important and should be covered before revenue collection. All the operators provide their services and collect revenue from the end customers to survive in the business. There may be two possible ways to charge an end customer − In-Advance − An operator charges the customers in advance before providing the service. This leads to less customer satisfaction, but operator is more secure from revenue point of view. In-Advance − An operator charges the customers in advance before providing the service. This leads to less customer satisfaction, but operator is more secure from revenue point of view. In-Arrears − An operator pushes himself on risk and charges the customer at the end of every month after providing required services. This leads to more customer satisfaction, but operator is on a risk of collecting less revenue. In-Arrears − An operator pushes himself on risk and charges the customer at the end of every month after providing required services. This leads to more customer satisfaction, but operator is on a risk of collecting less revenue. There is always a threshold up to what an operator can tolerate revenue loss associated with a particular customer; same time, there is a threshold of risk an operator can take with a particular customer. For example, if a customer's income is $10,000/month, then operator can provide him their services very easily up to $1000 - $2000 but for the same operator it would be difficult to provide him a service, which would cost almost $10,000/month because in such a situation, it would be difficult for the customer to make monthly payment. Keeping the same concept, operators define different credit classes, which they use to classify their customers and associate different credit and collection actions. The credit class defines a category of the customer and associated risk of revenue can be taken with that customer. A credit class also defines which collections schedule is to be applied to the customer, should its owner fail to make the (undisputed) payments that are due. All the Billing Systems provide facility to define various credit classes, which can be assigned to different customers at the time of adding them into the system. Some examples of credit classes are as follows − VIP Credit Class − This can be assigned to VIP customers and would have very high value of credit limit. VIP Credit Class − This can be assigned to VIP customers and would have very high value of credit limit. General Public Class − This is the most common credit class and would have almost $100 or $200 credit limit. General Public Class − This is the most common credit class and would have almost $100 or $200 credit limit. Segment Specific Class − These classes can be defined based on different segments such as police, military, or bank officers, etc. Operator can define credit limit based on their comfort. Segment Specific Class − These classes can be defined based on different segments such as police, military, or bank officers, etc. Operator can define credit limit based on their comfort. There could be infinite number of credit classes defined based on the requirements and category of the customers. There are mainly two stages where credit can be controlled for a particular type of customer category − This is rating time control, which is done by the Rating Processes. Here, customer's usage and total charges are checked against the assigned credit limit, and if customer starts approaching towards the assigned credit limit, customer is informed about the same and after breaching the credit limit an appropriate action can be taken. There are operators, who would like to bar (i.e., temporarily stop) the services if customer is breaching the credit limit and they would be unbarred once the payment is done. For example, a customer having a credit limit of $200 will be informed on 80% of usage by a means of SMS, on reaching a threshold of 90% might be informed by means of a reminder call, etc., and when 100% credit limit has been reached, then outgoing might be barred. To control the credit, operators like to bar only outgoing calls in case of Voice and SMS usage, but in case of data download, customer would not be able to perform any data download. This is usually done after sending the invoices and more related to revenue collection process, which we would discuss in next chapter. To control the credit at rating time, it is important to keep rating as real time as possible. If usage is not being captured in real time and it is being rated after a long gap, then there is a possibility that customers would have crossed their credit limit and legally customer may not be able to pay the amount beyond their assigned credit limits, but this varies from country to country and operator to operator. There are billing systems, which support deposits to be held against accounts. Deposits are held alongside the account balance and cash can be transferred between the two. There could be different level of deposits to provide different kinds of services, which can be maintained against an account. Deposits help operators to cover their revenue in case customer is not able to make their payments. Hope you have some idea on how to control credit given to the different classes of customers. Still there would be various customers, who would not pay on time even after giving them a credit within their capacity. There are various customers, who do not pay at all after using the services. In the next chapter, we will explain how we define different revenue collection processes and schedules to collect the revenue for the services provided. After an invoice is generated and dispatched to the customer, ideally, all customers will receive their bills and pay promptly. However, there may be some customers, who do not pay their bills and there may be an unacceptable delay in paying the bill and hence the service providers must take some action needed to remedy the situation and collect the outstanding balance due (called account receivable, abbreviated as A/R). Collection is the process of chasing past due receivables on customer account. This usually involves sending notifications to the customer and taking appropriate actions in absence of due payments after the due date. Billing Systems support dunning (receivables chasing) both at the invoice level where receivables are chased on an invoice by invoice basis and at the account level whereby all overdue amounts for an account, across several invoices, can be handled by a single dunning action. The dunning model to be used for an account will be assigned on the basis of its credit class. A core collection process includes the following two items − Collections Aging Tracking − This is the process of tracking the customer invoices that have not been paid within the specified payment period due date. It deals with the "age of account receivables"; for example, invoices that are 0-30 days overdue, 30-60 days overdue, etc. Collections Aging Tracking − This is the process of tracking the customer invoices that have not been paid within the specified payment period due date. It deals with the "age of account receivables"; for example, invoices that are 0-30 days overdue, 30-60 days overdue, etc. Collections Actions − Collection action is the action that is performed when the account receivable reaches a particular age. For example, reminder messages to the customer to be mailed or recorded audio message should be played. Collections Actions − Collection action is the action that is performed when the account receivable reaches a particular age. For example, reminder messages to the customer to be mailed or recorded audio message should be played. Normally, collections actions are taken in the following steps − Send reminder mail and/or call: The customer service department contacts the customer reminding the payment. Still if there is no payment received, then proceed for the next action. Send reminder mail and/or call: The customer service department contacts the customer reminding the payment. Still if there is no payment received, then proceed for the next action. Send red letter − For example, a "Pay in seven days" letter is issued. Still if the payment is not received, then proceed for the next action. Send red letter − For example, a "Pay in seven days" letter is issued. Still if the payment is not received, then proceed for the next action. Disconnect the service − The network management department suspends the service. Disconnect the service − The network management department suspends the service. Collections schedules define collections actions, which should be carried out and the times at which they should be carried out when a customer does not pay. The collections schedule specifies the series of stages that make up the collections process. For each stage, it covers − The effective age that the receivables have to be for an action to take place. The effective age of receivable is calculated by taking the actual age of receivable. The effective age that the receivables have to be for an action to take place. The effective age of receivable is calculated by taking the actual age of receivable. The action to be taken. This might be an action that Billing System is to perform, for example, sending out a dunning notice on a particular date. The action to be taken. This might be an action that Billing System is to perform, for example, sending out a dunning notice on a particular date. Whether or not the action is mandatory. If an action is mandatory, subsequent actions cannot take place until this one has been performed. Whether or not the action is mandatory. If an action is mandatory, subsequent actions cannot take place until this one has been performed. The minimum receivables amount below which the action will not take place. The minimum receivables amount below which the action will not take place. In the early stages of the collections process, the soft collection action will typically be to send a number of dunning notices, which are simple reminder letters and requests for the payment. After a number of dunning notices have been sent at various stages, other actions are typically scheduled. For example, you can specify that a customer services representative (CSR) should telephone the customer to ask why they have not paid. If the initial attempts fail, then more aggressive actions can be taken like barring the services, or disconnecting the services or hot-lining (hot-lining is the process of re-directing all calls of delinquent customers to collections operator). If all the attempts to collect the dues fail, then the service provider may write-off the account and marks the due amount as bad debt or may hand over (sell off) the account to a collection agency. Collection agencies work on a percentage of collected revenue. However, once the uncollected account invoices are sold off to a collection agency, the service provider is not allowed to work with the customer regarding the payments. Here, write-off means service provider (operator) clears the dues on behalf of the customer and closes the account forever. This is done for accounting purpose, otherwise it is a loss for the operator. The service provider maintains the history of the write-off accounts, also called blacklist customers so that they are not re-activated again and informs the credit checking/reporting agencies about such accounts. Most of the customers make their payment before the due date. There can be different channels, which are used to make payments. In the next chapter, we will discuss different types of payments and their end-to-end processing to settle down the invoices. Once the invoices are sent to the customers, the customers start making payments of their bills. The processing of bill payments into the billing system is called payment processing. The payments made by the customers are posted to the customers' account. If there are any outstanding invoices, then which invoice is paid depends on the account's accounting method. There are two types of accounting methods − Balance forward accounting − Using this method, if a number of invoices are outstanding, payments received are allocated to invoices according to the age of the receivable, with the oldest invoice being created first. Balance forward accounting − Using this method, if a number of invoices are outstanding, payments received are allocated to invoices according to the age of the receivable, with the oldest invoice being created first. Open item accounting − This method allows payments to be allocated to specific invoices. Open item accounting is particularly useful when dealing with payments from the business customers. Open item accounting − This method allows payments to be allocated to specific invoices. Open item accounting is particularly useful when dealing with payments from the business customers. A customer can make payment using different payment methods that are supported by the service provider; for example, the customer can make payments using the payment methods such as cheque, credit card, debit card or wire transfers, or direct cash deposit. An operator may have multiple bank accounts into which it will receive payment done through bank accounts directly. These bank accounts are referred to as holding accounts and sends payment details to the billing system in text files. If payments are received outside the billing system either manually or electronically, then those payments are uploaded into the system using automated process to settle down the invoices. Billing Systems provide facility to capture credit card or debit card information and automatic payment methods on monthly basis. If payment method is set automatic using either credit card or debit card, payment requests are generated automatically after every invoice or on a given date and these requests are sent to the payment gateways (or banks) for payment authorization. Once all the payments are authorized, they are uploaded into the billing system to settle down the due invoices. If the payments are made using cash or cheque, then either it can be entered into the system upfront the customer or if this is collected by some agencies, then all such payments are collected and posted to the billing system using automated methods provided by the billing system. For all the payments received, payment files are prepared with a predefined format and then they are pushed automatically to a predefined location from where Billing System picks them up and uploads into the billing database. There may be a situation, when a payment made by credit card or cheque does not go through. If this payment is already posted into the system, then it needs a cancellation to adjust the amount. Billing System provides utilities to handle failed or cancelled payments. An interface is a bound between the billing system and any other external system to receive the payment. Interface allows two systems to communicate with other based on predefined rules. For example, a simple text file could be a payment interface between a bank and the billing system. If interface is file based, banks keep sending payment details using payment files in predefined format. There could be an online API-based interface between a bank and the billing system. If an online interface is in place, then bank will call the provided API to post the payment directly into the billing system. Similar way, there could be file-based or online interfaces provided for third party involved in collecting payments. So far, we have almost gone through the complete life cycle of a telecom customer. The next chapter is important to understand the dispute situation that arises between operators and customers. A dispute is a record of a query about an amount of money on an account. Normally, a dispute will be recorded when a customer queries some aspect of their bill. Disputes can be raised − Against an invoice on an account. Against an invoice on an account. Against a particular rated event on the account. For example, if a customer disputes a particular pay-per-view TV event due to a power cut. Against a particular rated event on the account. For example, if a customer disputes a particular pay-per-view TV event due to a power cut. After a dispute is recorded, it would be investigated, verified in order to either − Accept − If the raised dispute is valid from customer side, then the dispute would be accepted, and would be refunded to the customer. Accept − If the raised dispute is valid from customer side, then the dispute would be accepted, and would be refunded to the customer. Reject − If the dispute found to be not acceptable, then the dispute would be rejected. Reject − If the dispute found to be not acceptable, then the dispute would be rejected. Cancel − If the dispute is entered in error, then the dispute would be canceled. Cancel − If the dispute is entered in error, then the dispute would be canceled. The following points should be noted for the dispute and a billing system should support these points − Collections actions are not escalated while amounts have a dispute status of pending, but the collections are aged during this period. Collections actions are not escalated while amounts have a dispute status of pending, but the collections are aged during this period. Disputed events are not included in collections calculation until they are billed. After this, the collections are aged as normal. Disputed events are not included in collections calculation until they are billed. After this, the collections are aged as normal. An adjustment is a method of crediting or debiting an account with an arbitrary amount of money. Adjustments can be lodged against either an account as a whole or against a particular rated event on that account. A Billing System allows to create different types of adjustments, which can be used in different situations and each adjustment flows through different stages of approval. If a dispute is accepted, an adjustment is created to credit the account with the disputed amount. Adjustments should not affect the balance of an account until they are approved. Adjustments with a status of pending approval do not affect billing or collections. Disputes and adjustments that are made for tax inclusive accounts are assumed to be inclusive of tax. The gross amount is entered and will be available for output on the bill. In the next chapter, we will discuss different types of reports required for the management. There could be a list of reports available out-of-the-box and there may be some reports, which would need custom development. Various reports are generated to provide valuable information to management on finance, sales and performance of the system. Different kinds of reports like financial reports, management reports, reconciliation reports, network activity reports, etc., can be generated. Reports contain information that drives business success and help to monitor the health of business, identify any problem areas so that appropriate corrective actions can be taken. Reporting is one of the areas where none of the Billing Systems can meet 100% requirements out-of-the-box. Definitely marketing or finance departments will come up with such reporting requirements, which would need lots of custom development. If your Billing System is pushing data on Data Warehouse (DWH), then you can transfer reporting activities towards DWH system, but still many departments would like to have important reports from the source system, which is the Billing System. We can categorize reports into two categories − Core/Canned Reports − These reports are provided by the Billing System as core functionality of the system. Sometimes, they are called canned or standard reports. Core/Canned Reports − These reports are provided by the Billing System as core functionality of the system. Sometimes, they are called canned or standard reports. Custom Reports − These reports would not be available directly from the system and it would need some development using PL/SQL, PERL, or Shell script, etc. Custom Reports − These reports would not be available directly from the system and it would need some development using PL/SQL, PERL, or Shell script, etc. Different billing systems provide different types of reports in different areas. Interconnect Billing Systems are required to provide more functionalities related to reporting because they deal with wholesale billing. Following is the list of reports required by different departments − Payment reports provide information on the customer's account payments during a period of time. Account Receivables aging reports provide information on the account receivables, outstanding dues, etc. Disputes & adjustment reports help in identifying the pattern of reasons for disputes & adjustments and help to understand the reason for such disputes & adjustments and take appropriate corrective action. Management reports provide information on customers, their products & services usage, call patterns, customer feedback, etc. These reports help to take appropriate steps to reduce customer churn to introduce new services. Churn is the process of customers disconnecting from one service provider and moving to another service provider and this can be due to many reasons like inadequate customer service or lack of competitive products or lack of competitive charges or it can be due to a natural reason of geographic relocation of the customer. These reports provide Revenue Assurance (RA) information ensuring that all the sources of revenue and expenses are under observation and there is no leakage of any sort of revenues. For example, revenue can be lost due to many reasons like leakage in network system or mediation or billing mistakes, demand for introducing new services quickly, etc. Revenue assurance reports help to identify where the leakage is so that appropriate actions can be taken. These reports provide information to identify the areas of network congestion so that corrective measures (rerouting or adding more resources) can be accomplished to overcome these problems. The following is further an imaginary list of a few other reports, which can be required out of a Billing System − There could be a list of reports, which is required on monthly, weekly, or daily basis. So, such type of reports are developed if they are not available and scheduled within the system, so that they can be sent in end user's e-mail box without any manual intervention. There will a demand of different reports time to time based on some requirements, such type of reports cannot be imagined and developed in advance. So these reports are developed and sent based on demand from different users. Starting from the next chapter, we will cover different types of billing; for example, retail, wholesale, MVNO, roaming, etc. Most of the operators provide two options to their customers, to go for a postpaid or a prepaid connection. A Postpaid as well as prepaid connections have their own advantages and disadvantages. Usually, an operator will have 70%-80% customer base comprising of pre-paid customers and rest of the customer base will come from post-paid side. For an operator, it is always good to have more post-paid customers. You might be willing to know about the differences between the two types of customers, services and systems. Let us list down a few major differences between the two − Service Payments − This is the most important factor, which differentiates between two customer bases. Pre-paid customers make payment in advance before using the service, whereas post-paid customers use offered services throughout of the month, and at the end of the month, customer receives the bill to pay within the given time frame. Service Payments − This is the most important factor, which differentiates between two customer bases. Pre-paid customers make payment in advance before using the service, whereas post-paid customers use offered services throughout of the month, and at the end of the month, customer receives the bill to pay within the given time frame. Charging & Billing − For pre-paid customer, it is required to charge the customer in real time for all the usage whereas post-paid customers can be charged at the end of the month. Charging & Billing − For pre-paid customer, it is required to charge the customer in real time for all the usage whereas post-paid customers can be charged at the end of the month. Service Offerings − Post-paid billing systems provide more flexibilities in comparison of real time charging systems. For example, real time charging system is not flexible to maintain a complex business customers' hierarchy, where as a post-paid billing system can handle a customer hierarchy up to N level. Service Offerings − Post-paid billing systems provide more flexibilities in comparison of real time charging systems. For example, real time charging system is not flexible to maintain a complex business customers' hierarchy, where as a post-paid billing system can handle a customer hierarchy up to N level. Support & Maintenance − An operator needs to give same at tention to both the businesses. If, for a pre-paid business, operator needs to have skilled manpower to control the operation, same time operator needs a great staff to handle post-paid customer's queries related to their charging, bills, and fixing operational issues. Support & Maintenance − An operator needs to give same at tention to both the businesses. If, for a pre-paid business, operator needs to have skilled manpower to control the operation, same time operator needs a great staff to handle post-paid customer's queries related to their charging, bills, and fixing operational issues. Supported Network − A long time ago, the network of the prepaid and the postpaid connections were different. This used to invoke complaints that the prepaid connection would offer better connectivity than the postpaid or vice versa. This is the age of convergent billing and operators are running their business with the same network without compromising communication quality. Supported Network − A long time ago, the network of the prepaid and the postpaid connections were different. This used to invoke complaints that the prepaid connection would offer better connectivity than the postpaid or vice versa. This is the age of convergent billing and operators are running their business with the same network without compromising communication quality. Network elements (like switches, SMSC) produce raw usage called Usage Detail Records (UDRs) or Call Detail Records (CDRs), which contain information required by the billing system − Calling number (A number) Calling number (A number) Called number (the number receiving the call) (B number) Called number (the number receiving the call) (B number) when the call started (date and time) when the call started (date and time) Call duration Call duration Call Type (MOC, MTC, etc., MOC stands for Mobile Originated Call and MTC stands for Mobile Terminated Call) Call Type (MOC, MTC, etc., MOC stands for Mobile Originated Call and MTC stands for Mobile Terminated Call) The above raw UDRs from network elements and also from other service providers are received by the billing system and the billing system converts these into a format understandable by the system. The above formatted/converted UDR is then guided to find the customer/account to which the call should be charged and then rate the event accordingly. The above rated UDRs are then stored in the billing data store, and on the billing cycle date, the billing process picks up these rated UDRs and processes these and renders bill/invoice, taking into account, the payments, taxes, discounts, etc. The customer then pays the bill and the billing system is updated with the payment details. Following is the diagram showing the above standard billing process − Steps involved in prepaid billing in brief are as follows − When customer makes a call, prepaid switching gateway captures the calling number and sends the account information to the real time billing system. When customer makes a call, prepaid switching gateway captures the calling number and sends the account information to the real time billing system. Real time billing systems using the above information, authenticates the identity of the user, calculates the customer account's remaining balance using the rating tariff table and maximum allowable duration of the call, and sends this information to the prepaid gateway. Real time billing systems using the above information, authenticates the identity of the user, calculates the customer account's remaining balance using the rating tariff table and maximum allowable duration of the call, and sends this information to the prepaid gateway. The gateway establishes the call. The gateway establishes the call. During the call, gateway monitors the call so that the user do not exceed the maximum allowable call duration. During the call, gateway monitors the call so that the user do not exceed the maximum allowable call duration. When the call is over, the gateway sends the actual call duration to the prepaid billing system, which then calculates the actual call cost and updates the account balance, decreasing the remaining balance. When the call is over, the gateway sends the actual call duration to the prepaid billing system, which then calculates the actual call cost and updates the account balance, decreasing the remaining balance. The following figure shows the general prepaid billing scenario − Prepaid billing process involves the following important steps along with account information gathering and updating account after the call is completed − Authenticating − Authentication is the process of verifying that a user is who he or she claims to be. The user supplies a user ID and an authentication credential, such as a password. The system accepts these as inputs and verifies that the user is valid and has access to the system. Authenticating − Authentication is the process of verifying that a user is who he or she claims to be. The user supplies a user ID and an authentication credential, such as a password. The system accepts these as inputs and verifies that the user is valid and has access to the system. Authorizing − Authorization is the process of verifying what an authenticated user is allowed to do. Generally, Remote Access Dial In User Server (RADIUS) protocol is used to limit access to the system to registered and authorized customers. Authorizing − Authorization is the process of verifying what an authenticated user is allowed to do. Generally, Remote Access Dial In User Server (RADIUS) protocol is used to limit access to the system to registered and authorized customers. Providing advice of charge (AOC) − This gives information about the actual cost of the call either prior to or after the event. AOC provides the ability of a telecommunications system to advice of the actual costs of the event either prior to or after the occurrence of the event. Providing advice of charge (AOC) − This gives information about the actual cost of the call either prior to or after the event. AOC provides the ability of a telecommunications system to advice of the actual costs of the event either prior to or after the occurrence of the event. When we talk about telecom billing then by default it is about retail billing. As discussed earlier, telecom retail billing is defined as follows − "Telecom Billing is a process of collecting usage, aggregating it, applying required usage and rental charges, and finally generating invoices for the customers. Telecom Billing process also includes receiving and recording payments from the customers." Retail billing deals directly with the end customer and comes with lots of challenges to meet the end customer expectations and regulatory obligations. A billing is assumed to be successful as long as it is fulfilling the following criteria − Timely Billing − End customer's invoice is being generated on time, i.e., nominal date. There may be some circumstances when the end customer does not get his/her invoices on time because of some logistic issues, but it is IT's responsibility to generate all the due bills on due date. Timely Billing − End customer's invoice is being generated on time, i.e., nominal date. There may be some circumstances when the end customer does not get his/her invoices on time because of some logistic issues, but it is IT's responsibility to generate all the due bills on due date. Billing Accuracy − This is the most important factor for the customer satisfaction and from regulatory obligation point of view. If billing system is not generating accurate bills, then it can lead to serious business issues from legality point of view as well as leaving a customer in unhappy state. Billing Accuracy − This is the most important factor for the customer satisfaction and from regulatory obligation point of view. If billing system is not generating accurate bills, then it can lead to serious business issues from legality point of view as well as leaving a customer in unhappy state. Retail billing deals with the end customer and billing an individual customer, whereas wholesale billing deals with billing to the following entities depending on situation and nature of business − Billing resellers associated with a telecom operator. Billing resellers associated with a telecom operator. Billing interconnect partners for providing interconnection to make calls to another operator's customers. Billing interconnect partners for providing interconnection to make calls to another operator's customers. Billing roaming partners for providing services to their customers when they roamed in an operator's coverage area. Billing roaming partners for providing services to their customers when they roamed in an operator's coverage area. Wholesale billing is easy in comparison to retail billing and allows a big level of threshold of tolerance, whereas retail billing always needs to be 100% accurate. Wholesale billing can never be 100% accurate because of various reasons like difference in prices configured in two operators' systems or difference in number of calls rated because some of the calls may get missed at any network element. There are specialized billing systems, which are being used to handle retail billing like Convergys and Amdocs Billing systems are famous for retail billing, whereas ASCADE and INTEC billing systems are famous for wholesale billing. Wholesale billing can also be settled using retail billing systems by using simple reports because they do not deal with too many discounts and promotion types, whereas retail billing needs all these complications and can not be handled using wholesale billing systems. All the concepts discussed so far in this tutorial were related to retail billing and subsequent chapters will discuss about interconnect billing, roaming billing, and other billing types. Interconnect is the process of handling calls for other service providers. This allows the customers of one service provider to communicate with the customers of another service provider. If two operators A and B are not interconnect partners, then it would not be possible for a customer of Operator A to communicate with a customer of operator B. Usually, operators keep their agreements with each other to allow their customers to communicate with each other. This gives good business opportunity to all the operators engaged in interconnection. Any interconnection point at which the parties agree to connect their respective Networks is called "Interconnection Point". Examples of interconnection include − Two adjacent, non-competing telephone networks interconnect so that subscribers on one network can call those on the other. Two adjacent, non-competing telephone networks interconnect so that subscribers on one network can call those on the other. Long-distance carriers obtain access to the facilities of a local service provider and compete against that provider in providing long-distance services to a common customer base. Long-distance carriers obtain access to the facilities of a local service provider and compete against that provider in providing long-distance services to a common customer base. Traditional wireline telephone and new wireless mobile carriers interconnect so that subscribers of the traditional phone service can call wireless subscribers, and vice versa. Traditional wireline telephone and new wireless mobile carriers interconnect so that subscribers of the traditional phone service can call wireless subscribers, and vice versa. New competitive local telephone carriers interconnect with the incumbent carrier so that they can attract subscribers in the common service territory and enable those subscribers to call subscribers on the incumbent's network. New competitive local telephone carriers interconnect with the incumbent carrier so that they can attract subscribers in the common service territory and enable those subscribers to call subscribers on the incumbent's network. Customers of the incumbent telephone carrier make calls to their dial-up Internet Service Provider, which in turn is a customer of a competing local carrier. Customers of the incumbent telephone carrier make calls to their dial-up Internet Service Provider, which in turn is a customer of a competing local carrier. This is process of the production of invoices to send to an interconnect partner relating to incoming interconnect call detail records (CDR). Interconnect Billing concerned with calculating the amounts to be paid to and received from each of the network operators that our infrastructure connects in order for the successful call origination and termination. The CDR for interconnecting calls keep the call routing information as a group of valid values to identify the carrier and the country details. Note that the set of Interconnect CDRs includes the following details − CDRs are those billable to retail and wholesale customers. It is revenue for the telecom provider. It is also referred as local billing. CDRs are those billable to retail and wholesale customers. It is revenue for the telecom provider. It is also referred as local billing. CDRs that are only billable for Interconnect providers. Eg: Outgoing calls, Outgoing Transit calls, Incoming calls, etc. The Outgoing calls are the expense and Incoming calls are the revenue for the Telecom Provider. CDRs that are only billable for Interconnect providers. Eg: Outgoing calls, Outgoing Transit calls, Incoming calls, etc. The Outgoing calls are the expense and Incoming calls are the revenue for the Telecom Provider. Interconnect Billing systems do pricing of all incoming and outgoing interconnect CDRs. Usually, an interconnect price is determined for both incoming and outgoing interconnect CDRs on the basis of the incoming or outgoing trunk interconnect route that carries the call. Most commonly, a trunk ID represents a unique interconnect partner in the interconnect Billing System. The Settlement Process will be used to settle the Network Operator/Carrier involved in carrying calls from Interconnect Owner to Other Network Operator destination or vice versa. The Process will bring the Outgoing (Expense to Interconnect Owner) and Incoming (Revenue to Interconnect Owner) traffic for the settlement. Settlement can be done on monthly or bi-weekly basis using manual or automated process. It depends on billing system to billing system how it supports partner's settlement. Netting used to perform after the settlement is completed for the agreed Provider/Carrier. The netting is done by multiple settlement period for the multiple services, which it supports the same currency in Operator level. There are two types of netting methods − AFTER − After for Netting of Operator's Interconnecting cost after subtracting the amount between operator and Provider/Carrier AFTER − After for Netting of Operator's Interconnecting cost after subtracting the amount between operator and Provider/Carrier BEFORE − Before for Netting of Operator's Interconnecting cost without any subtracting of the amount between operator and Provider/Carrier. BEFORE − Before for Netting of Operator's Interconnecting cost without any subtracting of the amount between operator and Provider/Carrier. This is the process of the reconciliation of invoices coming from an interconnect partner which relate to outgoing CDRs. Every month interconnect partners exchange their CDRs for reconciliation purpose. It is very common to have discrepancies in the CDRs provided by the two partners. Billing Systems provide reports facilitating reconciliation of incoming and outgoing interconnect CDRs. These reports keep parameters such as call type, destination, cost band, and duration so that these CDRs can be used by both operators to match those parameters and identify missing CDRs. There may be a situation, when some CDRs are found missing at either of the operators' side. After doing required reconciliation if matter does not settle, then various negotiations happen between the partners, and finally, matter is settled by paying some nominal amount to the impacted interconnect partner. There could be various interconnect call scenarios depending on type of agreement between different operators. Let us try to cover a few most commonly used − Operator A's customer makes national call to Operator B's customer. In this case operator A will pay some amount to operator B. Operator A's customer makes national call to Operator B's customer. In this case operator A will pay some amount to operator B. Operator A's customer makes international call through Operator B, because operator A does not have direct agreement with any international operator. In this case, operator A will pay some amount to operator B and operator B will take care of settling down international operator. Operator A's customer makes international call through Operator B, because operator A does not have direct agreement with any international operator. In this case, operator A will pay some amount to operator B and operator B will take care of settling down international operator. Operator A's customer makes international call directly using an international operator. In this case, operator A will pay some amount to international operator directly. Operator A's customer makes international call directly using an international operator. In this case, operator A will pay some amount to international operator directly. All the above calls could be voice, SMS, MMS, and data, etc. To have a successful interconnection, the following issues should be dealt with in the interconnection agreement or by rule or order from the regulatory authority − Prices and adjustments − This includes the initial level of interconnection charges, a definition of the currency in which interconnection charges are to be paid and how prices will adjust over the term of the agreement to account for exchange rate changes and inflation. Prices and adjustments − This includes the initial level of interconnection charges, a definition of the currency in which interconnection charges are to be paid and how prices will adjust over the term of the agreement to account for exchange rate changes and inflation. Points of interconnection − The physical locations, where interconnection will take place and the technical standards to be employed in the interconnection are defined. Points of interconnection − The physical locations, where interconnection will take place and the technical standards to be employed in the interconnection are defined. Transport and traffic routing − Some definition must be made for how calls will be routed and what will be transported to deliver the calls. Transport and traffic routing − Some definition must be made for how calls will be routed and what will be transported to deliver the calls. Quality of service − Quality standards are defined, particularly for time to provision circuits and for call blocking levels, and remedies are defined for when those standards are not met. Quality of service − Quality standards are defined, particularly for time to provision circuits and for call blocking levels, and remedies are defined for when those standards are not met. Billing and collection − When and how to collect traffic data, when and how to exchange bills, and when and how to make payment should be specified. Billing and collection − When and how to collect traffic data, when and how to exchange bills, and when and how to make payment should be specified. Reconciliation − A process for reconciling traffic data and for making inquiries to the other party and for handling claims also should be incorporated. A procedure for resolving discrepancies is useful which often involves seeking recourse to arbitration, the regulator, or to the courts. Reconciliation − A process for reconciling traffic data and for making inquiries to the other party and for handling claims also should be incorporated. A procedure for resolving discrepancies is useful which often involves seeking recourse to arbitration, the regulator, or to the courts. Numbering Plan − Access of each operator to the country's numbering plan and numbering resources must be defined. Numbering Plan − Access of each operator to the country's numbering plan and numbering resources must be defined. Traffic Load − Capacity to deliver and receive the traffic that flows between the interconnecting networks should be discussed and documented. Traffic Load − Capacity to deliver and receive the traffic that flows between the interconnecting networks should be discussed and documented. Operators can have different types of agreements to exchange their traffic. Most commonly used agreements are listed below − Bi-Lateral Agreement − Under this agreement, each party agrees to exchange digital communications traffic with the other party over its Network at the Interconnection Points and/or in one or more direct interconnections. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement. As per this agreement, both the operators can originate and terminate their calls in each other's network. Bi-Lateral Agreement − Under this agreement, each party agrees to exchange digital communications traffic with the other party over its Network at the Interconnection Points and/or in one or more direct interconnections. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement. As per this agreement, both the operators can originate and terminate their calls in each other's network. Uni-Lateral Agreement − Under this agreement, one party sends his traffic to other party's Network at the Interconnection and does not take traffic back from other party. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement. Uni-Lateral Agreement − Under this agreement, one party sends his traffic to other party's Network at the Interconnection and does not take traffic back from other party. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement. Roaming is the ability for a customer of mobile communications to automatically make and receive telephone calls, send and receive data, or access other services while travelling outside the geographical coverage area of the home network, by means of using a network of another operator. Roaming can be either national roaming or international roaming. National roaming means that mobile subscribers make use of another network in geographical areas, where their own operator does not have coverage. This is, for example, used by operators, who do not have complete coverage in a country. International roaming is used when mobile subscribers travel abroad and make use of the network of an operator in the foreign country. How does it actually take place? If a service provider does not have a network coverage in a particular city or country, then this service provider makes a roaming agreement with another service provider having network in that city or country. As per this agreement, another service provider provides all the available services to the roaming customer of first service provider. CDRs generated in one roaming partner's area are collected and rated by that roaming partner and finally they are sent to the actual service provider of the roaming customer. Actual service provider charges the end customer for all the roaming services provided based on their predefined service charges. Two roaming partners settle their financials on monthly basis by exchanging actual roaming CDRs and reports based on those CDRs. The Home Public Mobile Network is the network from the operator by which a mobile subscriber has a subscription. The term is used as opposed to Visited Public Mobile Network (VPMN). The Visited Public Mobile Network is the network used by a mobile subscriber while roaming. The term is used as opposed to Home Public Mobile Network (HPMN). There are well known bodies like MACH who interface between different roaming partners to help them to exchange their CDRs, setting up roaming agreements and resolving any dispute. Clearing houses receive billing records from one roaming partner for the inbound roamers and submit billing records to another roaming partner for which this roamer would be called outbound roamer. Transferred Account Procedure version 3 (TAP3) is the process that allows a visited network operator (VPMN) to send billing records of roaming subscribers to their respective home network operator (HPMN). TAP3 is the latest version of the standard and will enable billing for a host of new services that networks intend to offer their customers. Clearing house uses TAP3 protocol to exchange all the CDRs between different roaming partners. TAP3 defines how and what information on roamed usage must be passed between Network Operators. These files are exchanged using simple FTP connection. There are different versions of TAP. TAP evolved from TAP1 through TAP2 and TAP2+ to TAP3. The latest release, TAP3, includes support for inter-standard roaming in a satellite network, WLAN and UMTS and other 3G technologies. GSM TAP Standard TD.57 − GSM Transferred Account Procedure (TAP) defines the format and validation rules for transferring roaming usage information between mobile operators in different countries. TAP3 is the third specification version of the standard. The files transferred are termed TAP files. GSM TAP Standard TD.57 − GSM Transferred Account Procedure (TAP) defines the format and validation rules for transferring roaming usage information between mobile operators in different countries. TAP3 is the third specification version of the standard. The files transferred are termed TAP files. GSM RAP Standard TD.32 − GSM Returned Accounts Procedure (RAP) defines the format for returning information on errors found within transferred TAP files/events and thereby rejecting financial liability for those files/events. The files transferred are termed RAP files. GSM RAP Standard TD.32 − GSM Returned Accounts Procedure (RAP) defines the format for returning information on errors found within transferred TAP files/events and thereby rejecting financial liability for those files/events. The files transferred are termed RAP files. Mobile subscriber travels to another country and creates usage on the foreign network. In order to bill the subscriber, this information has to be passed back to the subscriber's home network. The foreign network will collect information on the usage from it's switches, etc., and then creates TAP files containing the information set out in the standard. The files are then EXPORTED (on a regular basis, generally at least one file per day) to the home operator, who will IMPORT them and then use the information to invoice the subscriber. The foreign operator will rate the calls and then charge the subscribers home network for all the calls within a file. The home operator can mark up or re-rate the calls in order to make revenue. MVNO stands for Mobile Virtual Network Operator. A mobile virtual network operator (MVNO) is a company that provides mobile phone services, but does not have its own licensed frequency allocation of radio spectrum, nor does it necessarily have all of the infrastructure required to provide mobile telephone service. MVNE stands for Mobile Virtual Network Enabler, which is a company that provides services to mobile virtual network operators such as billing, network element provisioning, administration, operations, support of base station subsystems and operations support systems, and provision of back end network elements, to enable provision of mobile network services like cellular phone connectivity. An MVNO in reality is a reseller of mobile products and services from an actual operator, but under a different brand. For example, there is an operator A having all the infrastructure including network, switches, billing systems, provisioning system and customer care systems, etc. Now, if someone wants to start a telecom business by doing some minimum investment, then MVNO is the option to proceed. An MVNO will buy services in bulk from a well-established operator and change the brand name as per their convenience and market those products and services as an operator. Actual operator would remain transparent from the end customer and customer will have feeling like to be an end customer of MVNO. Depending on the situation, an MVNO can buy one or more infrastructure components from an operator and pay them accordingly. For example, an MVNO may like to use only network from the operator or an MVNO can use network and charging system from the operator and rest of the components like customer care, provisioning, etc., can be set up by the MVNO. MVNO's have full control over the SIM card, branding, marketing, billing, and customer care operations. The first commercially successful MVNO in the UK was Virgin Mobile UK, [3] launched in the United Kingdom in 1999 and now has over 4 million customers in the UK. MVNOs typically do not have their own infrastructure, but some leading MVNO's deploy their own mobile IN infrastructure in order to facilitate the means to offer value-added services. MNVO's can treat incumbent infrastructure such as radio equipment as a commodity, while the MVNO offers its own advanced and differentiated services based on exploitation of their own intelligent network infrastructure. In this way, each MVNO and the network operator could focus on their own niche markets and form customized detailed services that would expand their customer reach and brand. Most of the MVNOs come in the market to target only pre-paid customers and provide them only pre-paid services like voice, SMS, MMS, data, broadband, etc., with some nice value-added services. Assuming an incumbent operator sells their infrastructure to an MVNO, there could be different business models and agreements between incumbent and MVNO. Following are the most commonly used − MVNO can brand their services and sell them in the market and MVNE will help in providing those services to the end customer. Here, a fixed percent of commission will go to the MVNE. MVNO can brand their services and sell them in the market and MVNE will help in providing those services to the end customer. Here, a fixed percent of commission will go to the MVNE. MVNO can buy products and services in bulk at special discounted prices and then brand them with their name and sell in the market. MVNO can buy products and services in bulk at special discounted prices and then brand them with their name and sell in the market. MVNO sells the products and services, and based on the usage generated by the end customers, MVNO pays an amount to the MVNE. MVNO sells the products and services, and based on the usage generated by the end customers, MVNO pays an amount to the MVNE. In all the cases, MVNO may be required to pay some amount of security deposit to the MVNE and then monthly settlement happens using simple reports generated by the MVNE. An MVNE can add an MVNO in its billing system as a corporate customer as long as MVNO is providing post-paid services and can add all the products and services provided to MVNO. By the end of every month or usually after every two weeks, invoice can be generated and collection can be followed up. But usually, most of the MVNOs provide pre-paid services, which are handled in Pre-Paid system. In such a case, MVNO functionality is achieved either using built-in functionality in the pre-paid system or by simply defining a separate service class. All the usage CDRs and other information is dumped into data warehouse from where reports can be generated to prepare invoice. Assume an operator is providing different services mobile voice, fixed voice, data, IPTV, broadband, pre-paid, and post-paid, etc. A customer can have one or more of these services from the same operator. A typical customer would definitely like to have single invoice and single view of his account. A convergent billing is the integration of all service charges onto a single customer invoice and a unified view of the customer. Customer should call a call center and should get complete account information for all the services opted. Customer receives a single bill and makes a single payment for all the services. A truly Convergent Billing System should be able to consolidate any number and combination of products and services onto a single bill, regardless of the type of product and market segment, i.e., prepaid and postpaid services. Another important parameter contributing in convergent billing is a single product and price catalogue for pre-paid as well as post-paid customers. Convergent billing would help operators in achieving the following major benefits − Single product and service catalogue gives better time to market and reduced cost of implementation. Single product and service catalogue gives better time to market and reduced cost of implementation. A unified bill enables cross-service discounts, so that customers who order multiple services can receive preferential pricing. A unified bill enables cross-service discounts, so that customers who order multiple services can receive preferential pricing. Convergent billing enables multi-service packaging and pricing, whereby existing customers are enticed to add new services and new customers are attracted by innovative service bundles. Convergent billing enables multi-service packaging and pricing, whereby existing customers are enticed to add new services and new customers are attracted by innovative service bundles. Centralized customer care and support for both type of customers ( pre-paid and post-paid). Centralized customer care and support for both type of customers ( pre-paid and post-paid). So far, it has been a dream of all the big telecom operators to achieve true convergence. May be tomorrow some billing system would come which will support true convergence of all the product and services, but today it has the following obstacles to achieve real convergence − Real time Charging Systems like Ericsson IN or Nokia Siemens Charging System are very popular systems to provide solution for pre-paid product and services. These systems are not flexible enough to handle various functionalities required for post-paid customers for example: complex customer hierarchies, CDR re-rating, volume discounts, flexible reporting, roaming charging, interconnect charging, etc. Real time Charging Systems like Ericsson IN or Nokia Siemens Charging System are very popular systems to provide solution for pre-paid product and services. These systems are not flexible enough to handle various functionalities required for post-paid customers for example: complex customer hierarchies, CDR re-rating, volume discounts, flexible reporting, roaming charging, interconnect charging, etc. Post paid billing systems like Convergys Infinys or Amdocs Billing Systems are great for post-paid product and services. These systems are not capable to handle pre-paid traffic and charge the calls in real time. Importantly these systems can not be made highly available because of their base architecture. Post paid billing systems like Convergys Infinys or Amdocs Billing Systems are great for post-paid product and services. These systems are not capable to handle pre-paid traffic and charge the calls in real time. Importantly these systems can not be made highly available because of their base architecture. Keeping the two above-mentioned constraints together, if we merge both the systems by doing a kind of interfacing between pre-paid and post-paid systems, then it may be possible to achieve a true convergence. Companies like Convergys and Ericsson are working in the same direction to merge the two systems and use required functionalities from both type of systems and make them single Convergent Billing System. Support and maintenance is an integral and the most important part of a telecom operation. Customer satisfaction directly depends on how efficient and how good support is being provided to them. If customer is being put in the loop and he is not getting good response for the problem/issue raised, simply customer would switch to another available operator. Support and maintenance covers the following major areas − System support and maintenance − This includes keeping the BSS (Business Support Systems) and OSS (Operation Support Systems) running in good health. If there is any issue in any of the systems ( Billing, Provisioning, Network, Mediation, Customer Care, etc.,), then it is looked by the specialists and fixed within a minimum time frame. System support and maintenance − This includes keeping the BSS (Business Support Systems) and OSS (Operation Support Systems) running in good health. If there is any issue in any of the systems ( Billing, Provisioning, Network, Mediation, Customer Care, etc.,), then it is looked by the specialists and fixed within a minimum time frame. Customer Support − This includes fixing all the issues related to customers. A customer complains through customer care or call center and then issue flows at different stages. This issue could be related to signals, call drop, voice or data download quality, wrong bill, some dispute, service activation, or termination, etc. Customer Support − This includes fixing all the issues related to customers. A customer complains through customer care or call center and then issue flows at different stages. This issue could be related to signals, call drop, voice or data download quality, wrong bill, some dispute, service activation, or termination, etc. System upgrades − This includes upgrading an existing system with the latest version to provide more stability and flexibility in the business. New version of any system comes along with new features to cater new business requirements. This also includes hardware upgrade to maintain system performance and for more storage as well. System upgrades − This includes upgrading an existing system with the latest version to provide more stability and flexibility in the business. New version of any system comes along with new features to cater new business requirements. This also includes hardware upgrade to maintain system performance and for more storage as well. There are always different levels of support kept in place by the service providers. These levels handle different types of issues depending on their nature and severity. Most commonly used support levels are as follows − Level 1 − Customer contacts the customer support, which could be a call center and customer support specialist listens to customer problem and suggests a solution on the spot. For example, there could be some problems, which can be resolved by simply restarting the phone. So, an efficient customer care specialist knows about such type of problems and can suggest a solution without escalating the issue (usually called a trouble ticket) to the next level. Level 1 − Customer contacts the customer support, which could be a call center and customer support specialist listens to customer problem and suggests a solution on the spot. For example, there could be some problems, which can be resolved by simply restarting the phone. So, an efficient customer care specialist knows about such type of problems and can suggest a solution without escalating the issue (usually called a trouble ticket) to the next level. Level 2 − If a customer care specialist is not able to resolve a problem, then issue is escalated to second level support, which is a group of technical specialists. These specialists belong to Information Technology (IT) department, and if they are able to understand the problem, then they can suggest a solution and send the issue back to level 1, otherwise they check the nature of issue to understand if issue is related to network or billing system or provisioning system or hardware, etc., and based on the nature of the issue, issue is assigned to next level, i.e., department. Level 2 − If a customer care specialist is not able to resolve a problem, then issue is escalated to second level support, which is a group of technical specialists. These specialists belong to Information Technology (IT) department, and if they are able to understand the problem, then they can suggest a solution and send the issue back to level 1, otherwise they check the nature of issue to understand if issue is related to network or billing system or provisioning system or hardware, etc., and based on the nature of the issue, issue is assigned to next level, i.e., department. Level 3 − These are different departments specialized in their areas like core engineering, radio planning, billing, provisioning, order management, etc. If issue is escalated to them, then they analyze the problem and try to find out the root cause of the problem. Most of the times, issue will be diagnosed and fixed by third level support because they are highly skilled engineers specialized in their area. There may be situation, when issue cannot be fixed at 3rd level support because it may be related to core functionality of the system, which is not modifiable by 3rd level support. In such a case, issue is further escalated to 4th level support. Level 3 − These are different departments specialized in their areas like core engineering, radio planning, billing, provisioning, order management, etc. If issue is escalated to them, then they analyze the problem and try to find out the root cause of the problem. Most of the times, issue will be diagnosed and fixed by third level support because they are highly skilled engineers specialized in their area. There may be situation, when issue cannot be fixed at 3rd level support because it may be related to core functionality of the system, which is not modifiable by 3rd level support. In such a case, issue is further escalated to 4th level support. Level 4 − These are actual vendors of the systems supporting business, for example, billing system, network switch, provisioning system, etc. So, if issue is found to be related to the core functionality of billing system, for example, billing system is not able to apply correct discount, then it would be escalated to the billing system vendor, and if issue is related to the core functionality of the provisioning system, then it would be escalated to the provisioning system vendor. Level 4 − These are actual vendors of the systems supporting business, for example, billing system, network switch, provisioning system, etc. So, if issue is found to be related to the core functionality of billing system, for example, billing system is not able to apply correct discount, then it would be escalated to the billing system vendor, and if issue is related to the core functionality of the provisioning system, then it would be escalated to the provisioning system vendor. Support departments always work with a predefined service level agreement called SLA. These SLAs are defined and kept in place keeping various parameters in mind. For example − Severity of the issue or operational task. Severity of the issue or operational task. Business impact of the issue or operational task. Business impact of the issue or operational task. Whether issue or operational task is impacting a single customer or multiple customers. Whether issue or operational task is impacting a single customer or multiple customers. Whether the issue or operational task is directly related to revenue loss or customer satisfaction. Whether the issue or operational task is directly related to revenue loss or customer satisfaction. Based on such type of parameters, different priorities are defined and assigned to different issues or operational tasks. Operational task could be report generation, invoice generation, database cleanup activities, or backup activities. Finally, each issue and operational task comes along with an assigned priority and each priority will have associated SLA. For example, if there is a problem in creating customer order, then it would be assumed a high priority issue because it is directly impacting business. Such type of issues need to be resolved as soon as possible by the assigned department. So, a very tight SLA is defined for high priority issue. SLAs are discussed and finalized with mutual agreement keeping business need on top priority. Usually, an SLA keeps the following information − Parameters to qualify the nature of the issue whether it is priority 1st issue or 2nd priority issue or 3rd or 4th priority issue. Lower the priority number, higher is the criticality of the issue. Parameters to qualify the nature of the issue whether it is priority 1st issue or 2nd priority issue or 3rd or 4th priority issue. Lower the priority number, higher is the criticality of the issue. For a given type of priority and severity, how much time it would take to resolve the issue. For a given type of priority and severity, how much time it would take to resolve the issue. In case of failure of an SLA, what penalty would be applied. In case of failure of an SLA, what penalty would be applied. Contact points of escalation for each level of support. Contact points of escalation for each level of support. Process flow and communication medium during issue resolution. Process flow and communication medium during issue resolution. Infrastructure availability and other constraints impacting the issue resolution. Infrastructure availability and other constraints impacting the issue resolution. SLAs can be defined between different departments, between vendor and operator and between different operators as well in case of interconnection. The following diagram shows a typical architecture of a Billing System. This chapter will give a brief introduction of all the interfacing systems starting from top to bottom. This is the first system from where a customer order is captured and customer is created into the system. CRM stand for Customer Relationship Management and OMOF stands for Order Management and Order Fulfilment. There are systems like Siebel, which provides modules for CRM as well as OMOF. The CRM system keeps customer-related information along with product and services. The OMOF module is responsible to track order starting from its creation till its completion. Here, we have two possibilities − CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. Second possibility could be that CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. Second possibility could be that CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc. This system takes commands either from the Billing System or CRM/OMOF System to activate, deactivate and suspend the services. Both the architectures are valid and depend on how architect designs the whole setup. After taking provisioning commands, this system contacts with core network system to activate, deactivate or suspend the services. After a successful provisioning, this system sends a response back to either the Billing System or the CRM system depending on who sent it the last command. This system maintains all the network identifiers like phone numbers, MSISDN, IP addresses, e-mail addresses, etc., and technically it is called Network Inventory System. Depending on the system architecture, either CRM/OMOF or Billing System contacts NIS to obtain a required network identifier and assigns it to the customer at the time of order creation. This system is responsible to maintain the life cycle of network identifiers, which starts with available and then flows through different stages like activation, suspend, terminate, quarantine, and again available. Generally, Billing System does not interact with network switches. Network switches are responsible to provide all the services to the end customers based on what services have been provisioned for the customer. These systems are responsible for controlling calls, data download, SMS transfer, etc., and finally generating Call Detail Records. Network Switches include MSC, SMSC, GGSN and MMSC. For more information on GSM, MSC, SMS, SMSC, GGSN, MMS, MMSC, please refer to our GSM tutorials. The Mediation System collects CDRs from different network elements in different formats. Various network elements generate CDRs in ASN.1 format and some network elements have their own proprietary format of CDRs. The Mediation System processes all the CDRs and converts them into a format compatible to the downstream system, which is usually a Billing System. The Mediation System applies various rules on CDRs to process them; for example, mediation system marks the international calls based on the dialed number (B-Number), same way mediation system marks the on-net calls based on A-Number and B-Number. There may be a requirement to filter out all the calls, which are having call duration less than 5 seconds, the best place to filter out such type of calls will be at Mediation System level. Same way, if some extra information is required in the CDRs, which is critical to billing, then Mediation System will help in providing such information based on some other attributes available within the CDRs. Once the collected CDRs are processed, Mediation System pushes all the CDRs to the Billing System using FTP because usually Mediation and Billing systems run on different machines. This is a downstream system for the Billing System and usually keeps tons of historical data related to the customers. Billing System dumps various customer information into the DWH system. This information includes service usage, invoices, payments, discounts and adjustments, etc. All this information is used to generate various types of management reports and for business intelligence and forecast. DWH system is always meant to work on bulk and huge data, and if there is a need for any small report, then it is always worth to generate it from the billing system directly instead of abusing DWH for a small task. An Enterprise Resource Planning (ERP) system provides modules to handle Financials, Human Resources and Supply Chain Management, etc. Billing System interface with this system is used to post all the financial transactions like invoices, payments, and adjustments. This system works like a general ledger for the finance department and gives complete revenue information at any point in time it is required. As such, this is not necessarily a complete system, but it could be a kind of custom component, which sits in between the Billing System and different payment channels like banks, credit card gateway, shops, and retailers, etc. All the payment channels use payment gateway to post payments to the billing system to settle down customer invoices. Usually, Payment gateway exposes a kind of API (Application Programming Interface) to the outside world to post the payments to the Billing System. The API can be used by any external resource to post the payment. Print Add Notes Bookmark this page
[ { "code": null, "e": 2717, "s": 2391, "text": "Sending voice, data, picture, fax, etc., from one point to another using electronic media is termed as telecommunication and in short 'telecom'. Examples include Phone, Radio, Television and Internet. The medium of transmission includes Wire (Copper), Fiber Optics, Ether (wireless), Radio towers, Microwave, Satellite, etc." }, { "code": null, "e": 2847, "s": 2717, "text": "Now, let us list down a few international telecom operators, who are providing satisfactory telecom services to their customers −" }, { "code": null, "e": 2855, "s": 2847, "text": "Verizon" }, { "code": null, "e": 2864, "s": 2855, "text": "Vodafone" }, { "code": null, "e": 2871, "s": 2864, "text": "Airtel" }, { "code": null, "e": 2876, "s": 2871, "text": "TATA" }, { "code": null, "e": 2885, "s": 2876, "text": "Etisalat" }, { "code": null, "e": 2890, "s": 2885, "text": "Qtel" }, { "code": null, "e": 2998, "s": 2890, "text": "Let us also list down a few basic telecom services being provided by various well known telecom operators −" }, { "code": null, "e": 3009, "s": 2998, "text": "Voice Call" }, { "code": null, "e": 3021, "s": 3009, "text": "Fax Service" }, { "code": null, "e": 3031, "s": 3021, "text": "SMS & MMS" }, { "code": null, "e": 3051, "s": 3031, "text": "Internet Connection" }, { "code": null, "e": 3076, "s": 3051, "text": "Data Download and Upload" }, { "code": null, "e": 3095, "s": 3076, "text": "Video Conferencing" }, { "code": null, "e": 3141, "s": 3095, "text": "IP based services, i.e., voice over IP or VPN" }, { "code": null, "e": 3269, "s": 3141, "text": "Telecom operators are charging their customers in various ways, but there are two mainly used parameters to charge a customer −" }, { "code": null, "e": 3469, "s": 3269, "text": "Rental Charges − These are the charges taken from the customers on monthly basis against the service provided. For example, your telephone monthly charges would be $5.00 regardless you use it or not." }, { "code": null, "e": 3669, "s": 3469, "text": "Rental Charges − These are the charges taken from the customers on monthly basis against the service provided. For example, your telephone monthly charges would be $5.00 regardless you use it or not." }, { "code": null, "e": 3864, "s": 3669, "text": "Usage Charges − These are the charges taken from the customers based on the service utilization. For example, you would be charged for all the calls you made or data downloaded using your phone." }, { "code": null, "e": 4059, "s": 3864, "text": "Usage Charges − These are the charges taken from the customers based on the service utilization. For example, you would be charged for all the calls you made or data downloaded using your phone." }, { "code": null, "e": 4210, "s": 4059, "text": "Apart from monthly rental and usage charges, operators may charge you for service initiation, installation, service suspension or termination as well." }, { "code": null, "e": 4462, "s": 4210, "text": "Telecom Billing is a process of collecting usage, aggregating it, applying required usage and rental charges, and finally generating invoices for the customers. Telecom Billing process also includes receiving and recording payments from the customers." }, { "code": null, "e": 4791, "s": 4462, "text": "There could be very complex charging scenarios, which would be difficult to handle manually. There are state-of-the-art Billing Systems available in the software market that can handle billing tasks very efficiently and provide lots of flexibilities to service providers to offer their services with different price structures." }, { "code": null, "e": 5152, "s": 4791, "text": "Billing systems are often viewed as accounts receivable, as the billing system assists in the collection (receipt) of money from customers. Billing systems are also part of accounts payable (for inter-carrier settlements), as customers often use services from other companies such as wireless roaming, long distance, and call completion through other networks." }, { "code": null, "e": 5333, "s": 5152, "text": "Billing systems are high end, reliable, and expensive softwares, which provide various functionalities. Here is a list of most important features but not limited to the following −" }, { "code": null, "e": 5431, "s": 5333, "text": "Rating & billing − It involves rating the products or services usage and producing monthly bills." }, { "code": null, "e": 5529, "s": 5431, "text": "Rating & billing − It involves rating the products or services usage and producing monthly bills." }, { "code": null, "e": 5619, "s": 5529, "text": "Payment processing − It involves posting of the customer's payments into his/her account." }, { "code": null, "e": 5709, "s": 5619, "text": "Payment processing − It involves posting of the customer's payments into his/her account." }, { "code": null, "e": 5843, "s": 5709, "text": "Credit control and collections − It involves chasing the outstanding payments and taking appropriate actions to collect the payments." }, { "code": null, "e": 5977, "s": 5843, "text": "Credit control and collections − It involves chasing the outstanding payments and taking appropriate actions to collect the payments." }, { "code": null, "e": 6153, "s": 5977, "text": "Disputes and adjustments − It involves recording customer's disputes against their bills and creating adjustment to refund the disputed amount in order to settle the disputes." }, { "code": null, "e": 6329, "s": 6153, "text": "Disputes and adjustments − It involves recording customer's disputes against their bills and creating adjustment to refund the disputed amount in order to settle the disputes." }, { "code": null, "e": 6436, "s": 6329, "text": "Pre-pay and post-pay services − It involves supporting both the pre-paid and the post-paid customer bases." }, { "code": null, "e": 6543, "s": 6436, "text": "Pre-pay and post-pay services − It involves supporting both the pre-paid and the post-paid customer bases." }, { "code": null, "e": 6766, "s": 6543, "text": "Multilingual & multiple currencies − Multilingual and multiple currencies support is required if the business is spread across the globe and have multinational customers or else if the government regulations demand for it." }, { "code": null, "e": 6989, "s": 6766, "text": "Multilingual & multiple currencies − Multilingual and multiple currencies support is required if the business is spread across the globe and have multinational customers or else if the government regulations demand for it." }, { "code": null, "e": 7113, "s": 6989, "text": "Inter-carrier settlements − It involve sharing of revenue between carriers that provide services to each other's customers." }, { "code": null, "e": 7237, "s": 7113, "text": "Inter-carrier settlements − It involve sharing of revenue between carriers that provide services to each other's customers." }, { "code": null, "e": 7381, "s": 7237, "text": "Products & services − This involves providing flexible way to maintain various products and services and sell them individually or in packages." }, { "code": null, "e": 7525, "s": 7381, "text": "Products & services − This involves providing flexible way to maintain various products and services and sell them individually or in packages." }, { "code": null, "e": 7671, "s": 7525, "text": "Discount applications − This involves defining various discount schemes in order to reduce customer churn and attract and increase customer base." }, { "code": null, "e": 7817, "s": 7671, "text": "Discount applications − This involves defining various discount schemes in order to reduce customer churn and attract and increase customer base." }, { "code": null, "e": 8020, "s": 7817, "text": "When you drill down billing subject, it becomes more complicated. I would try to cover most of the concepts later in this tutorial, but first, let us have a broad view of the widely used billing types −" }, { "code": null, "e": 8291, "s": 8020, "text": "Pre-pay Billing − A billing mechanism where customer pays in advance and after that starts using a service. Usually, prepaid customers do not receive any invoice and they are charged in real time by the highly available billing systems called 'IN'(Intelligent Network)." }, { "code": null, "e": 8562, "s": 8291, "text": "Pre-pay Billing − A billing mechanism where customer pays in advance and after that starts using a service. Usually, prepaid customers do not receive any invoice and they are charged in real time by the highly available billing systems called 'IN'(Intelligent Network)." }, { "code": null, "e": 8864, "s": 8562, "text": "Post-pay Billing − This is the conventional billing, which is coming for many years. Here, customers buy products and services and use them throughout the month, and by end of the month, invoices are generated by the service provider and sent those invoices to the customers to make their due payment." }, { "code": null, "e": 9166, "s": 8864, "text": "Post-pay Billing − This is the conventional billing, which is coming for many years. Here, customers buy products and services and use them throughout the month, and by end of the month, invoices are generated by the service provider and sent those invoices to the customers to make their due payment." }, { "code": null, "e": 9454, "s": 9166, "text": "Interconnect Billing: The network operator is usually financially responsible for services provided to its customers by other networks regardless of whether or not the customer pays for the service. Interconnect billing is related to inter-carrier or sometime called partner settlements." }, { "code": null, "e": 9742, "s": 9454, "text": "Interconnect Billing: The network operator is usually financially responsible for services provided to its customers by other networks regardless of whether or not the customer pays for the service. Interconnect billing is related to inter-carrier or sometime called partner settlements." }, { "code": null, "e": 10121, "s": 9742, "text": "Roaming Charges − When a customer goes from one network operator's coverage area to another operator's coverage area, the first operator would pay marginal charges to the second operator to provide services to their customers. Such type of charges are settled through roaming billing. This settlement is done as per TAP3 protocol, which we will discuss in the upcoming chapters." }, { "code": null, "e": 10500, "s": 10121, "text": "Roaming Charges − When a customer goes from one network operator's coverage area to another operator's coverage area, the first operator would pay marginal charges to the second operator to provide services to their customers. Such type of charges are settled through roaming billing. This settlement is done as per TAP3 protocol, which we will discuss in the upcoming chapters." }, { "code": null, "e": 10751, "s": 10500, "text": "Convergent Billing − Convergent billing is the integration of all service charges onto a single customer invoice. Convergent billing means creating a unified view of the customer and all services (Mobile, Fixed, IP, etc.,) provided to that customer." }, { "code": null, "e": 11002, "s": 10751, "text": "Convergent Billing − Convergent billing is the integration of all service charges onto a single customer invoice. Convergent billing means creating a unified view of the customer and all services (Mobile, Fixed, IP, etc.,) provided to that customer." }, { "code": null, "e": 11300, "s": 11002, "text": "Billing Systems are the backbone of any telecom operator. If operators do not have a strong billing system, then it would not be possible for them to offer their products and services with attractive promotions and deals and ultimately they can not stand in today's competitive and dynamic market." }, { "code": null, "e": 11539, "s": 11300, "text": "You can find thousands of vendors, who are selling their billing products with a claim of lot of features, but there are a few in the market which are really good and most commonly used. Some of the good billing systems are listed below −" }, { "code": null, "e": 11557, "s": 11539, "text": "www.convergys.com" }, { "code": null, "e": 11572, "s": 11557, "text": "www.amdocs.com" }, { "code": null, "e": 11595, "s": 11572, "text": "www.amsinc.com/telecom" }, { "code": null, "e": 11609, "s": 11595, "text": "www.kenan.com" }, { "code": null, "e": 11630, "s": 11609, "text": "www.intecbilling.com" }, { "code": null, "e": 11651, "s": 11630, "text": "www.intecbilling.com" }, { "code": null, "e": 11668, "s": 11651, "text": "www.ericsson.com" }, { "code": null, "e": 11743, "s": 11668, "text": "The following diagram shows the typical architecture of a Billing System −" }, { "code": null, "e": 11777, "s": 11743, "text": "Here, we have two possibilities −" }, { "code": null, "e": 12063, "s": 11777, "text": "CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 12349, "s": 12063, "text": "CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 12552, "s": 12349, "text": "Second possibility could be that the CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 12755, "s": 12552, "text": "Second possibility could be that the CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 13078, "s": 12755, "text": "Considering the above system architecture: → After a call is made or you can say a usage is generated by the end customer, the mediation system gathers usage data from the network switch and builds a call-detail record (CDR). This CDR must contain 'A' party number and 'B' party number, the start and the end date & times." }, { "code": null, "e": 13435, "s": 13078, "text": "The CDR is then stored until it can be rated. To rate the call, the CDR is examined to see if the call is, for example, an 800 number, a local call that is covered by a local-area calling plan, international call or a toll call. Information such as the time of the call was placed and city code or country codes are used to calculate the rate for the call." }, { "code": null, "e": 13674, "s": 13435, "text": "Once each call is rated, this information is stored until the invoice is run, usually once a month. When the invoice is run, other nonusage charges, such as discounts or monthly fees, can be applied to the bill or sometime called invoice." }, { "code": null, "e": 13875, "s": 13674, "text": "There could be a rating time discount or billing time discount, different payments done by the customers, different adjustments given, all these information contribute in the final invoice generation." }, { "code": null, "e": 14056, "s": 13875, "text": "This information is then converted in a format, which can be printed in a readable form. Finally, the envelope is printed, stuffed with enclosures, and mailed to the end customer." }, { "code": null, "e": 14299, "s": 14056, "text": "A billing system should be composed of a series of independent applications that, when run together, are referred to as the billing system. A good billing system should provide the following major functionalities with a depth of flexibility −" }, { "code": null, "e": 14471, "s": 14299, "text": "Customer-interface Management − The billing system must be able to handle customer-initiated contact, oversee outbound customer contact, and manage the contact life cycle." }, { "code": null, "e": 14643, "s": 14471, "text": "Customer-interface Management − The billing system must be able to handle customer-initiated contact, oversee outbound customer contact, and manage the contact life cycle." }, { "code": null, "e": 14905, "s": 14643, "text": "Order Management − It is a basic functionality, which should be available in a typical billing system. Billing system should be capable enough to capture product & service order and manage the order-entry life cycle, and oversee the order-completion life cycle." }, { "code": null, "e": 15167, "s": 14905, "text": "Order Management − It is a basic functionality, which should be available in a typical billing system. Billing system should be capable enough to capture product & service order and manage the order-entry life cycle, and oversee the order-completion life cycle." }, { "code": null, "e": 15395, "s": 15167, "text": "Sales and Marketing − A satisfactory billing system should answer customer's query, handle commissions, provide sales support, track prospects, manage campaigns, analyze product performance, and acquire multiple dwelling units." }, { "code": null, "e": 15623, "s": 15395, "text": "Sales and Marketing − A satisfactory billing system should answer customer's query, handle commissions, provide sales support, track prospects, manage campaigns, analyze product performance, and acquire multiple dwelling units." }, { "code": null, "e": 15867, "s": 15623, "text": "Rate Plans and Rating − A billing systems must manage a variety of products and services, different rate plans associated with those products and services and should provide flexible ways to rate usage generated by those products and services." }, { "code": null, "e": 16111, "s": 15867, "text": "Rate Plans and Rating − A billing systems must manage a variety of products and services, different rate plans associated with those products and services and should provide flexible ways to rate usage generated by those products and services." }, { "code": null, "e": 16230, "s": 16111, "text": "Discounting − A billing system should be capable of giving various types of discounts on different usages and rentals." }, { "code": null, "e": 16349, "s": 16230, "text": "Discounting − A billing system should be capable of giving various types of discounts on different usages and rentals." }, { "code": null, "e": 16561, "s": 16349, "text": "Invoicing − It is important that the system performs billing inquiry, generates bills, processes deposits, performs account administration, maintains tax and fee information, and processes financial information." }, { "code": null, "e": 16773, "s": 16561, "text": "Invoicing − It is important that the system performs billing inquiry, generates bills, processes deposits, performs account administration, maintains tax and fee information, and processes financial information." }, { "code": null, "e": 16997, "s": 16773, "text": "Credit Control & Collection − A billing system should control usage and revenue by assigning different credit classes to different customers. System should support payment collection and applying them on different invoices." }, { "code": null, "e": 17221, "s": 16997, "text": "Credit Control & Collection − A billing system should control usage and revenue by assigning different credit classes to different customers. System should support payment collection and applying them on different invoices." }, { "code": null, "e": 17343, "s": 17221, "text": "Multilingual Support − Multilingual support involves providing invoices and customer care services in multiple languages." }, { "code": null, "e": 17465, "s": 17343, "text": "Multilingual Support − Multilingual support involves providing invoices and customer care services in multiple languages." }, { "code": null, "e": 17686, "s": 17465, "text": "Multiple Currencies − Multiple currencies used in different countries can complicate the billing system as the billing and customer care system must be capable of recording and processing in units of multiple currencies." }, { "code": null, "e": 17907, "s": 17686, "text": "Multiple Currencies − Multiple currencies used in different countries can complicate the billing system as the billing and customer care system must be capable of recording and processing in units of multiple currencies." }, { "code": null, "e": 18056, "s": 17907, "text": "Partner revenue management − Partner revenue management are the sharing of revenue between carriers that provide services to each other's customers." }, { "code": null, "e": 18205, "s": 18056, "text": "Partner revenue management − Partner revenue management are the sharing of revenue between carriers that provide services to each other's customers." }, { "code": null, "e": 18383, "s": 18205, "text": "Problem Handling − A billing system should also be able to manage trouble-ticket entry, coordinate trouble-ticket closure, and track the resolution progress of a trouble ticket." }, { "code": null, "e": 18561, "s": 18383, "text": "Problem Handling − A billing system should also be able to manage trouble-ticket entry, coordinate trouble-ticket closure, and track the resolution progress of a trouble ticket." }, { "code": null, "e": 18747, "s": 18561, "text": "Performance Reporting − A satisfactory system will provide performance reporting, ensure quality-of-service (QoS) reporting, create management reports, and generate regulatory reports." }, { "code": null, "e": 18933, "s": 18747, "text": "Performance Reporting − A satisfactory system will provide performance reporting, ensure quality-of-service (QoS) reporting, create management reports, and generate regulatory reports." }, { "code": null, "e": 19074, "s": 18933, "text": "Installation and Maintenance − The system should also provide workforce scheduling and manage activities performed at the customer premises." }, { "code": null, "e": 19215, "s": 19074, "text": "Installation and Maintenance − The system should also provide workforce scheduling and manage activities performed at the customer premises." }, { "code": null, "e": 19356, "s": 19215, "text": "Auditing & Security − A billing system should perform data audits and integrity checks. A secure system is always desirable for an operator." }, { "code": null, "e": 19497, "s": 19356, "text": "Auditing & Security − A billing system should perform data audits and integrity checks. A secure system is always desirable for an operator." }, { "code": null, "e": 19569, "s": 19497, "text": "Apart from the above functionalities, a good billing system should be −" }, { "code": null, "e": 19623, "s": 19569, "text": "Accelerating time-to-market for new service launches." }, { "code": null, "e": 19677, "s": 19623, "text": "Accelerating time-to-market for new service launches." }, { "code": null, "e": 19729, "s": 19677, "text": "Enabling convergent view of customers and products." }, { "code": null, "e": 19781, "s": 19729, "text": "Enabling convergent view of customers and products." }, { "code": null, "e": 19834, "s": 19781, "text": "Supporting cost-efficient architectural scalability." }, { "code": null, "e": 19887, "s": 19834, "text": "Supporting cost-efficient architectural scalability." }, { "code": null, "e": 19944, "s": 19887, "text": "Enabling partner relationship management and settlement." }, { "code": null, "e": 20001, "s": 19944, "text": "Enabling partner relationship management and settlement." }, { "code": null, "e": 20035, "s": 20001, "text": "Reducing total cost of ownership." }, { "code": null, "e": 20069, "s": 20035, "text": "Reducing total cost of ownership." }, { "code": null, "e": 20427, "s": 20069, "text": "Starting from the next chapter, we would try to cover complete process starting from defining products and services, associating plan and tariffs with those products, acquiring customers (selling products to the end customers), capturing usage generated by those customers, and finally, rating and billing that usage to send a final bill to those customers." }, { "code": null, "e": 20667, "s": 20427, "text": "Let us suppose a telecom operator like Airtel wants to set up a billing system of its own. Then, Airtel would have to first define its products and services by its sales and marketing department before moving on to set up a billing system." }, { "code": null, "e": 20893, "s": 20667, "text": "A product is a logical or physical entity, which can be sold out to an end customer by the operators. This could be a mobile phone, internet connection, Voice call connection, VPN, Video on demand, Digital TV connection, etc." }, { "code": null, "e": 21188, "s": 20893, "text": "A product can have its monthly rental, which we call periodic charges also. A product can be usage generating product or non-usage generating product. A usage generating product is sometime called event generating product and non-usage generating product is called non-event generating product." }, { "code": null, "e": 21590, "s": 21188, "text": "For example, voice call connection, which comes along with a phone number, is a usage generating product because it generates usage whenever end customer uses this product to make a voice call. A simple phone set without a connection is a non-usage generating product and it could be given to a customer based on monthly rent only. So even if, a customer is not using it, he has to pay monthly rental." }, { "code": null, "e": 21807, "s": 21590, "text": "When we talk about them from marketing point of view, as such there is no difference between products and services because most of the times, both are used interchangeably by different billing and marketing experts." }, { "code": null, "e": 22184, "s": 21807, "text": "Simply put, an operator uses its products to provide voice services to its customers. An international call can be called a service provided using a voice call connection. Another example could be 800 number call may or may not be available through a particular operator, call waiting, call forward could be said a service provided by a model of a phone set or by an operator." }, { "code": null, "e": 22359, "s": 22184, "text": "This tutorial will use Product and Service terms interchangeably. Keeping it simple, Products are the items that customers can either buy outright or lease. products may be −" }, { "code": null, "e": 22402, "s": 22359, "text": "Real objects (a mobile phone, for example)" }, { "code": null, "e": 22471, "s": 22402, "text": "Services (a call waiting service on a telephone system, for example)" }, { "code": null, "e": 22535, "s": 22471, "text": "More abstract concepts (a service level agreement, for example)" }, { "code": null, "e": 22705, "s": 22535, "text": "Related products can be grouped together into a product family. Multiple levels of products are possible, so a product can be both a parent and a child at the same time." }, { "code": null, "e": 22824, "s": 22705, "text": "In addition, each product family can have more than one parent product if required. Examples of product families are −" }, { "code": null, "e": 22843, "s": 22824, "text": "Telephony services" }, { "code": null, "e": 22852, "s": 22843, "text": "Cable TV" }, { "code": null, "e": 22861, "s": 22852, "text": "Internet" }, { "code": null, "e": 22873, "s": 22861, "text": "Leased Line" }, { "code": null, "e": 23122, "s": 22873, "text": "Many a times, operators bundle more than one product into a single group and sell them as complete package. There are billing systems, which support bundling of various types of products together as a package. It can be offered at discounted price." }, { "code": null, "e": 23349, "s": 23122, "text": "Packages allow a product to be offered to a customer at a reduced price if it is taken as part of a package. Each package can consist of any number of products and these products can be taken from more than one product family." }, { "code": null, "e": 23672, "s": 23349, "text": "This package price plan for a product is usually different to its comparison (that is, non-package) price plan, as this is how the company offers a discount to the customer for buying the complete package. However, this is not mandatory, as a product can have one of its normal price plans assigned to it within a package." }, { "code": null, "e": 23970, "s": 23672, "text": "A product can have a number of attributes associated with them. Product attributes allow information about individual product instances to be held where the relevant information differs between types of product. For example, a pay TV product may have an attribute recording its set-top box number." }, { "code": null, "e": 24139, "s": 23970, "text": "Further, a mobile phone product may need attributes to record the International Mobile Subscriber Identity (IMSI) and Mobile Station International ISDN Number (MSISDN)." }, { "code": null, "e": 24276, "s": 24139, "text": "A product can have a number of event types associated with it. These event types govern the events that can be generated by the product." }, { "code": null, "e": 24540, "s": 24276, "text": "For example, a mobile phone product could have event types such as voice calls and messaging services. There could be many more event types associated with a single phone device and operator can charge end customer for each of the event generated by the customer." }, { "code": null, "e": 24684, "s": 24540, "text": "Once your marketing department finalized all the products, services, packages and associated prices, they are configured in the billing system." }, { "code": null, "e": 24847, "s": 24684, "text": "Different billing systems provide different levels of flexibilities of defining products and their hierarchies in terms of parent, child, and grandchild products." }, { "code": null, "e": 24997, "s": 24847, "text": "Some systems are flexible enough to support packages and bundles and a few provide limited functionalities related to packages and discounted prices." }, { "code": null, "e": 25212, "s": 24997, "text": "Some systems keep product catalogues separately from the price catalogues to provide better modular approach and some billing systems combine products descriptions, their features, and associated prices altogether." }, { "code": null, "e": 25400, "s": 25212, "text": "Once all the products, services, packages and their events are configured in the billing system, next step is to define their rental and usage prices, which we will cover in next chapter." }, { "code": null, "e": 25601, "s": 25400, "text": "If you understood what is a product or service and package, then you can proceed to the next chapter to understand how their prices are defined by the marketing department available with any operator." }, { "code": null, "e": 25948, "s": 25601, "text": "Marketing department in a telecom operator company works hard to define rental & usage charges for different products and services. These charges are defined keeping other competitors and regulations in mind. Broadly speaking, there are two type of tariffs, also called rate or price plans, depending terminology used in different billing system." }, { "code": null, "e": 26272, "s": 25948, "text": "There could be different types of charges to be applied for a product and associated services. For a given product, an operator can define one or more of the following charges, but they are not limited to only these charges, there could be some other type of charges depending on country, location, and business situation −" }, { "code": null, "e": 26441, "s": 26272, "text": "Product Initiation Charges − These are one-time charges, which can be taken from the customer as a part of installation, activation, service or initiating a connection." }, { "code": null, "e": 26610, "s": 26441, "text": "Product Initiation Charges − These are one-time charges, which can be taken from the customer as a part of installation, activation, service or initiating a connection." }, { "code": null, "e": 26771, "s": 26610, "text": "Product Periodic Charges − These are the charges, which can be applied on monthly or bi-monthly or yearly basis as a rental of the product and service provided." }, { "code": null, "e": 26932, "s": 26771, "text": "Product Periodic Charges − These are the charges, which can be applied on monthly or bi-monthly or yearly basis as a rental of the product and service provided." }, { "code": null, "e": 27049, "s": 26932, "text": "Product Termination Charges − These are the charges, which can be applied on termination of the product and service." }, { "code": null, "e": 27166, "s": 27049, "text": "Product Termination Charges − These are the charges, which can be applied on termination of the product and service." }, { "code": null, "e": 27315, "s": 27166, "text": "Product Suspension Charges − These are the charges, which can be applied if a product is suspended because of some reason; for example, non-payment." }, { "code": null, "e": 27464, "s": 27315, "text": "Product Suspension Charges − These are the charges, which can be applied if a product is suspended because of some reason; for example, non-payment." }, { "code": null, "e": 27622, "s": 27464, "text": "Product Suspension Periodic Charges − There could be a requirement to charge a customer periodically even if a customer is suspended because of some reason." }, { "code": null, "e": 27780, "s": 27622, "text": "Product Suspension Periodic Charges − There could be a requirement to charge a customer periodically even if a customer is suspended because of some reason." }, { "code": null, "e": 27959, "s": 27780, "text": "Product Re-activation Charges − Assuming a product was suspended due to some reason and now it needs its activation, an operator can apply re-activation charges for this service." }, { "code": null, "e": 28138, "s": 27959, "text": "Product Re-activation Charges − Assuming a product was suspended due to some reason and now it needs its activation, an operator can apply re-activation charges for this service." }, { "code": null, "e": 28330, "s": 28138, "text": "Product Usage Charges − This is most important type of charge, which would be applied based on the usage of the service. For example, call per minute or per second, data download per MB, etc." }, { "code": null, "e": 28522, "s": 28330, "text": "Product Usage Charges − This is most important type of charge, which would be applied based on the usage of the service. For example, call per minute or per second, data download per MB, etc." }, { "code": null, "e": 28871, "s": 28522, "text": "All the above charges are defined (i.e., configured) in different tariff catalogues inclusive or exclusive of applicable tax depending on regulatory. These catalogues vary from a billing system to billing system. Some billing systems keep all the prices in a single catalogue and some billing systems keep usage charges separate from other charges." }, { "code": null, "e": 29069, "s": 28871, "text": "These catalogues are maintained in the billing system, but they are also made available to front end system so that different tariffs can be applied to the customer while creating customer account." }, { "code": null, "e": 29239, "s": 29069, "text": "All the prices are defined based on products and their packages as well. There could be different combinations of products giving different prices in different packages." }, { "code": null, "e": 29352, "s": 29239, "text": "Following section would give you an idea on different concepts, which are closely related to tariff definition −" }, { "code": null, "e": 29514, "s": 29352, "text": "There may be situation, when an operator would like to charge their customers in advance for some services and at the end of every month for some other services." }, { "code": null, "e": 29677, "s": 29514, "text": "Charges taken in advance before providing the services are called in-advance charging and charges taken after providing the services are called in-arrear charges." }, { "code": null, "e": 29854, "s": 29677, "text": "For in-arrears charging, the product charges are applied for a period up to at least the day before the current nominal bill date (or bill request date for non-periodic bills)." }, { "code": null, "e": 30080, "s": 29854, "text": "So while configuring different charges, billing system should give a provision to configure charges in advance and it is always optional for the operators if they want to configure a particular price in-advance or in-arrears." }, { "code": null, "e": 30388, "s": 30080, "text": "NOTE − Usage charges can not be taken in advance until they are lump-sum because you never know how much usage a customer is going to generate in the coming month. If they are lump-sum amount, then you can take that amount in advance and let the customers use unlimited services based on their requirements." }, { "code": null, "e": 30853, "s": 30388, "text": "Consider a situation, when a customer takes phone connection in the middle of the month and his invoice needs to be generated on the first day of every month. If prices are non-proratable, billing system would charge the customer for the whole, month which would not be fair with the customer. Same apply at the termination, if customer terminates a service in the middle of the month, then operator may not be willing to charge the customer for rest of the month." }, { "code": null, "e": 31137, "s": 30853, "text": "Pro-ratable pricing means that they would apply only for the number of days customer is going to use the service. For example, if monthly product rental is $30 and customer used this product for 10 days only, then billing system should charge the customer only $10 for those 10 days." }, { "code": null, "e": 31312, "s": 31137, "text": "So billing system should provide an option to configure the particular prices to be pro-ratable as well as non-proratable and let the operators choose what suites them best." }, { "code": null, "e": 31500, "s": 31312, "text": "Now, let us consider a situation where an operator is charging a customer in advance for the whole month, but customer leaves in the middle of the month after using a service for 10 days." }, { "code": null, "e": 31831, "s": 31500, "text": "If prices were configured as non-refundable, then they would not be refunded to the customer, but if they were configured as refundable, then they would be refunded to the customer. Second rule, if prices were configured as pro-ratable, then they would be refunded based on pro-ration, otherwise they would be refunded as a whole." }, { "code": null, "e": 31940, "s": 31831, "text": "A good billing system provides an option to override base prices at the time they are given to the customer." }, { "code": null, "e": 32322, "s": 31940, "text": "For example, for a particular product base prices in the catalogue are defined $30 per month but customer is not ready to pay $30 per month, and based on some bargaining, he is ready to pay $25 per month. In such a situation, customer service representative (CSR) should be able to override defined base price $30 and add them as $25 at the time of customer creation in the system." }, { "code": null, "e": 32562, "s": 32322, "text": "Billing system should give an optional provision to the operators if a particular price can be overridden or not and let the operators decide if they want to override some charges at the time of sale or they are fixed in all the situation." }, { "code": null, "e": 32691, "s": 32562, "text": "All the operators would like to know how much they have earned using a particular product, its rental, suspension or usage, etc." }, { "code": null, "e": 32956, "s": 32691, "text": "While defining different prices in the catalogue, billing system should give a provision to associate some kind of revenue codes or keywords with different types of charges. This helps in generating different reports based on the codes associated with the revenue." }, { "code": null, "e": 33298, "s": 32956, "text": "An operator may define different tariffs, which can be offered to different people having different credit classes. For example, a 5mbps data line at a cost of $100 per month can be offered to a customer having monthly income more than $1000/month and a 1mbps data line can be offered to a customer having minimum monthly income $500/month." }, { "code": null, "e": 33514, "s": 33298, "text": "All the billing systems give options to define different credit classes, which can be assigned to customers based on their credit history and income and may be based on some other parameters defined by the operator." }, { "code": null, "e": 33670, "s": 33514, "text": "All the products and services can have different tariff plans, which can be offered to different classes of people ranging from general class to VIP class." }, { "code": null, "e": 33764, "s": 33670, "text": "There are number of parameters, which can be used while defining usage charges. For example −" }, { "code": null, "e": 33907, "s": 33764, "text": "Calls in daytime, usually called peak time, will be charged on higher rate and in night time, i.e., off peak time rate will be relatively low." }, { "code": null, "e": 34050, "s": 33907, "text": "Calls in daytime, usually called peak time, will be charged on higher rate and in night time, i.e., off peak time rate will be relatively low." }, { "code": null, "e": 34172, "s": 34050, "text": "If calls are terminating within the same network, usually called on-net calls, would be charged at relatively low prices." }, { "code": null, "e": 34294, "s": 34172, "text": "If calls are terminating within the same network, usually called on-net calls, would be charged at relatively low prices." }, { "code": null, "e": 34366, "s": 34294, "text": "Calls during weekend, i.e., Sat and Sun would be charged at low prices." }, { "code": null, "e": 34438, "s": 34366, "text": "Calls during weekend, i.e., Sat and Sun would be charged at low prices." }, { "code": null, "e": 34505, "s": 34438, "text": "Calls to a particular destination would be charged at high prices." }, { "code": null, "e": 34572, "s": 34505, "text": "Calls to a particular destination would be charged at high prices." }, { "code": null, "e": 34635, "s": 34572, "text": "Calls during some festival would be charged at special prices." }, { "code": null, "e": 34698, "s": 34635, "text": "Calls during some festival would be charged at special prices." }, { "code": null, "e": 34758, "s": 34698, "text": "Data download from a particular site would be free of cost." }, { "code": null, "e": 34818, "s": 34758, "text": "Data download from a particular site would be free of cost." }, { "code": null, "e": 34882, "s": 34818, "text": "Sending SMS to a particular code would be charged at high rate." }, { "code": null, "e": 34946, "s": 34882, "text": "Sending SMS to a particular code would be charged at high rate." }, { "code": null, "e": 35062, "s": 34946, "text": "Calls within a particular group of numbers, usually called closed user group (CUG), would be charged at zero price." }, { "code": null, "e": 35178, "s": 35062, "text": "Calls within a particular group of numbers, usually called closed user group (CUG), would be charged at zero price." }, { "code": null, "e": 35253, "s": 35178, "text": "Sending international or national MMS would be charged at the same prices." }, { "code": null, "e": 35328, "s": 35253, "text": "Sending international or national MMS would be charged at the same prices." }, { "code": null, "e": 35470, "s": 35328, "text": "Billing systems provide lots of flexibility to define various such rules to charge voice, data, SMS, or MMS usage generated by the customer." }, { "code": null, "e": 35684, "s": 35470, "text": "Now, we have all the products, services, and associated tariffs available in the billing system. In the next chapter, we will see how to sell these products to the end-users and create their records in the system." }, { "code": null, "e": 36014, "s": 35684, "text": "A customer is a \"legal entity\" (that can be either an individual or a company) that takes the products and services offered by the service provider and responsible for paying the bills. In a residential billing scenario, a customer might be a single householder. In a business billing scenario, a customer might be a corporation." }, { "code": null, "e": 36220, "s": 36014, "text": "Individual customer − An individual customer is a single person (or household), who buys one or more products and pay the bills. There would not be any hierarchy required to maintain customer or account." }, { "code": null, "e": 36426, "s": 36220, "text": "Individual customer − An individual customer is a single person (or household), who buys one or more products and pay the bills. There would not be any hierarchy required to maintain customer or account." }, { "code": null, "e": 36641, "s": 36426, "text": "Company customers − A company customer is a single company or branch of a company. There could be a typical parent and child type of customer hierarchy representing different branches or departments of the company." }, { "code": null, "e": 36856, "s": 36641, "text": "Company customers − A company customer is a single company or branch of a company. There could be a typical parent and child type of customer hierarchy representing different branches or departments of the company." }, { "code": null, "e": 37111, "s": 36856, "text": "Customer Acquisition is the process of identifying, attracting and retaining the potentially profitable customers. This is a handled using system called Customer Relationship Management (CRM), which is one of the important business support systems (BSS)." }, { "code": null, "e": 37288, "s": 37111, "text": "A CRM system would always be connected with various systems including billing system and feeds customer personal data and product and service information to the billing system." }, { "code": null, "e": 37443, "s": 37288, "text": "A customer, who is purchasing the products & services, needs to be activated in the system and for this, various details about the customer are required −" }, { "code": null, "e": 37524, "s": 37443, "text": "The customer may have to fill up an application form providing personal details." }, { "code": null, "e": 37605, "s": 37524, "text": "The customer may have to fill up an application form providing personal details." }, { "code": null, "e": 37670, "s": 37605, "text": "Validate the identity of the customer in order to prevent fraud." }, { "code": null, "e": 37735, "s": 37670, "text": "Validate the identity of the customer in order to prevent fraud." }, { "code": null, "e": 37887, "s": 37735, "text": "Service Provider needs to carry out a credit check on the customer and assign appropriate credit class based on credit history and monthly income, etc." }, { "code": null, "e": 38039, "s": 37887, "text": "Service Provider needs to carry out a credit check on the customer and assign appropriate credit class based on credit history and monthly income, etc." }, { "code": null, "e": 38128, "s": 38039, "text": "Offer appropriate products, which are provisioned at the network to provide the service." }, { "code": null, "e": 38217, "s": 38128, "text": "Offer appropriate products, which are provisioned at the network to provide the service." }, { "code": null, "e": 38315, "s": 38217, "text": "Once the customer is acquired, it is required to manage and retain the customer, which involves −" }, { "code": null, "e": 38398, "s": 38315, "text": "Interacting & communicating with the customer for sales and collection activities." }, { "code": null, "e": 38481, "s": 38398, "text": "Interacting & communicating with the customer for sales and collection activities." }, { "code": null, "e": 38724, "s": 38481, "text": "These interactions can be recorded in different formats like Notes, voice recordings, etc. This data can be used to analyze the behavior of the customer and helps the service provider to provide better services in order to retain the customer" }, { "code": null, "e": 38967, "s": 38724, "text": "These interactions can be recorded in different formats like Notes, voice recordings, etc. This data can be used to analyze the behavior of the customer and helps the service provider to provide better services in order to retain the customer" }, { "code": null, "e": 39246, "s": 38967, "text": "Handling trouble tickets raised by the customers against any problem they face with the network or invoice, etc. This data can also be used to analyze the behavior of the customer and helps the service provider for the betterment of the services in order to retain the customer." }, { "code": null, "e": 39525, "s": 39246, "text": "Handling trouble tickets raised by the customers against any problem they face with the network or invoice, etc. This data can also be used to analyze the behavior of the customer and helps the service provider for the betterment of the services in order to retain the customer." }, { "code": null, "e": 39621, "s": 39525, "text": "Handling any bill disputes and adjustments raised in between the customer and service provider." }, { "code": null, "e": 39717, "s": 39621, "text": "Handling any bill disputes and adjustments raised in between the customer and service provider." }, { "code": null, "e": 39789, "s": 39717, "text": "A typical customer life cycle is shown below in the following diagram −" }, { "code": null, "e": 39856, "s": 39789, "text": "All the phases comprising a customer life cycle are briefed here −" }, { "code": null, "e": 40055, "s": 39856, "text": "Customer Engagement − The customer contacts the CSR (Customer Service Representative) and the CSR engages the customer with the various products and services offered by selling them to the customer." }, { "code": null, "e": 40254, "s": 40055, "text": "Customer Engagement − The customer contacts the CSR (Customer Service Representative) and the CSR engages the customer with the various products and services offered by selling them to the customer." }, { "code": null, "e": 40481, "s": 40254, "text": "Order Creation and Fulfilment − The customer takes the product(s) and services(s) and the CSR creates and completes the order into the system, which is then fulfilled by supplying required product and services to the customer." }, { "code": null, "e": 40708, "s": 40481, "text": "Order Creation and Fulfilment − The customer takes the product(s) and services(s) and the CSR creates and completes the order into the system, which is then fulfilled by supplying required product and services to the customer." }, { "code": null, "e": 41007, "s": 40708, "text": "Service Provisioning − The products and services are provisioned at the network using a system called Provisioning System. The Provisioning System informs the network about the customer's information and the services they are authorized to use. In fact, this activates the customer on the network." }, { "code": null, "e": 41306, "s": 41007, "text": "Service Provisioning − The products and services are provisioned at the network using a system called Provisioning System. The Provisioning System informs the network about the customer's information and the services they are authorized to use. In fact, this activates the customer on the network." }, { "code": null, "e": 41472, "s": 41306, "text": "Products Utilization − Once the customer is activated on the network, the customer starts using the products & services including, making a call, data download, etc." }, { "code": null, "e": 41638, "s": 41472, "text": "Products Utilization − Once the customer is activated on the network, the customer starts using the products & services including, making a call, data download, etc." }, { "code": null, "e": 41862, "s": 41638, "text": "Products and services usage is Rated & Billed − Customer usage is collected from the network and then it is rated based on the defined rate plans and billed to apply product rentals and required discounts, adjustments, etc." }, { "code": null, "e": 42086, "s": 41862, "text": "Products and services usage is Rated & Billed − Customer usage is collected from the network and then it is rated based on the defined rate plans and billed to apply product rentals and required discounts, adjustments, etc." }, { "code": null, "e": 42221, "s": 42086, "text": "Bill Delivery − Once a bill is generated, it is delivered to the end customer demanding for the revenue against the services provided." }, { "code": null, "e": 42356, "s": 42221, "text": "Bill Delivery − Once a bill is generated, it is delivered to the end customer demanding for the revenue against the services provided." }, { "code": null, "e": 42432, "s": 42356, "text": "Bill Payments − Customer makes the payments against the received invoices." }, { "code": null, "e": 42508, "s": 42432, "text": "Bill Payments − Customer makes the payments against the received invoices." }, { "code": null, "e": 42828, "s": 42508, "text": "Dunning & Collection − There may be many customers, who will not pay their bills on time. For such type of customers, different dunning letters are sent to remind them about their payments. If a customer does not pay on time, then different collections are taken starting from stopping the customer services one by one." }, { "code": null, "e": 43148, "s": 42828, "text": "Dunning & Collection − There may be many customers, who will not pay their bills on time. For such type of customers, different dunning letters are sent to remind them about their payments. If a customer does not pay on time, then different collections are taken starting from stopping the customer services one by one." }, { "code": null, "e": 43384, "s": 43148, "text": "Customer Termination − There may be various reasons when it is required to terminate a customer in the system. For example, customer may be migrating to different location, or customer may not be happy with the services provided, etc." }, { "code": null, "e": 43620, "s": 43384, "text": "Customer Termination − There may be various reasons when it is required to terminate a customer in the system. For example, customer may be migrating to different location, or customer may not be happy with the services provided, etc." }, { "code": null, "e": 43821, "s": 43620, "text": "On a given date, total number of active customers in the system are called the customer base. Adding a customer into the system, and terminating a customer from the system, is known as customer churn." }, { "code": null, "e": 43899, "s": 43821, "text": "Typically, there are following types of customers in today's telecom market −" }, { "code": null, "e": 44114, "s": 43899, "text": "Mobile Pre-Paid Customers − These are the customers, who use Mobile services by paying their charges in advance. For example, GSM, GPRS phone users. These customers recharge their phone based on their requirements." }, { "code": null, "e": 44329, "s": 44114, "text": "Mobile Pre-Paid Customers − These are the customers, who use Mobile services by paying their charges in advance. For example, GSM, GPRS phone users. These customers recharge their phone based on their requirements." }, { "code": null, "e": 44565, "s": 44329, "text": "Mobile Post-Paid Customers − These are the customers, who use Mobile services by paying their charges after every invoice they receive. For example, GSM, GPRS phone users. These customers pay their bills on monthly or bi-monthly basis." }, { "code": null, "e": 44801, "s": 44565, "text": "Mobile Post-Paid Customers − These are the customers, who use Mobile services by paying their charges after every invoice they receive. For example, GSM, GPRS phone users. These customers pay their bills on monthly or bi-monthly basis." }, { "code": null, "e": 45038, "s": 44801, "text": "Fixed Pre-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges in advance. For example, PSTN, WiMax phone users. These customers recharge their phones based on their requirements." }, { "code": null, "e": 45275, "s": 45038, "text": "Fixed Pre-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges in advance. For example, PSTN, WiMax phone users. These customers recharge their phones based on their requirements." }, { "code": null, "e": 45532, "s": 45275, "text": "Fixed Post-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges after every invoice they receive. For example, PSTN, WiMax phone users. These customers pay their bills on monthly or bi-monthly basis." }, { "code": null, "e": 45789, "s": 45532, "text": "Fixed Post-Paid Customers − These are the customers, who use Fixed line, i.e., landline services by paying their charges after every invoice they receive. For example, PSTN, WiMax phone users. These customers pay their bills on monthly or bi-monthly basis." }, { "code": null, "e": 46115, "s": 45789, "text": "Now, we have customers in our billing system along with products and services. Customer starts utilizing all the products and services bought and start generating national and international, data and voice calls, which will be rated and billed by the billing system and we will discuss those processes in subsequent chapters." }, { "code": null, "e": 46390, "s": 46115, "text": "A customer starts generating usage at Network as soon as he/she starts using the products and services sold by the operator. A network element is a combination of software plus hardware and responsible for overall service control and metering events for any type of service." }, { "code": null, "e": 46726, "s": 46390, "text": "An event is a single billable occurrence of product usage, typically captured electronically by a network. For example, when a mobile phone user makes a telephone call, an event is generated, which contains information about that phone call, such as the call duration, the time of day the call was made, and the number that was called." }, { "code": null, "e": 47044, "s": 46726, "text": "An event along with all its attributes is called Call Detail Record (CDR). A data collector in the network switch captures the usage in the form of Call Detail Record (CDR)/Usage Detail Record (UDR). These raw CDRs/UDRs are in turn converted by the mediation system into a format understandable by the Billing System." }, { "code": null, "e": 47183, "s": 47044, "text": "There could be different network elements controlling the services and producing different types of CDRs; for example, for GSM telephony −" }, { "code": null, "e": 47246, "s": 47183, "text": "Voice calls are captured by the MSC (Mobile Switching Centre)." }, { "code": null, "e": 47283, "s": 47246, "text": "SMS traffic is captured by the SMSC." }, { "code": null, "e": 47321, "s": 47283, "text": "Data traffic is captured by the GGSN." }, { "code": null, "e": 47358, "s": 47321, "text": "MMS traffic is captured by the MMSC." }, { "code": null, "e": 47425, "s": 47358, "text": "Roaming CDRs are captured by roaming partner's switching element." }, { "code": null, "e": 47522, "s": 47425, "text": "For more information on GSM, MSC, SMS, SMSC, GGSN, MMS, MMSC, please refer to our GSM tutorials." }, { "code": null, "e": 47695, "s": 47522, "text": "The following diagram shows the Network elements capturing Usage data and sending Raw UDRs to the Mediation System and finally to the Billing System for rating and billing." }, { "code": null, "e": 47837, "s": 47695, "text": "As mentioned above, a CDR keeps usage details along with various other useful information. Below are the most important attributes of a CDR −" }, { "code": null, "e": 47863, "s": 47837, "text": "Calling Party (A number)." }, { "code": null, "e": 47889, "s": 47863, "text": "Calling Party (A number)." }, { "code": null, "e": 47914, "s": 47889, "text": "Called Party (B number)." }, { "code": null, "e": 47939, "s": 47914, "text": "Called Party (B number)." }, { "code": null, "e": 47967, "s": 47939, "text": "Call Start (date and time)." }, { "code": null, "e": 47995, "s": 47967, "text": "Call Start (date and time)." }, { "code": null, "e": 48029, "s": 47995, "text": "How long the call was (duration)." }, { "code": null, "e": 48063, "s": 48029, "text": "How long the call was (duration)." }, { "code": null, "e": 48097, "s": 48063, "text": "Call Type (Voice, SMS, Data etc)." }, { "code": null, "e": 48131, "s": 48097, "text": "Call Type (Voice, SMS, Data etc)." }, { "code": null, "e": 48180, "s": 48131, "text": "A unique sequence number identifying the record." }, { "code": null, "e": 48229, "s": 48180, "text": "A unique sequence number identifying the record." }, { "code": null, "e": 48293, "s": 48229, "text": "Additionally, a CDR may also record other information such as −" }, { "code": null, "e": 48335, "s": 48293, "text": "The identifier of the telephone exchange." }, { "code": null, "e": 48377, "s": 48335, "text": "The identifier of the telephone exchange." }, { "code": null, "e": 48439, "s": 48377, "text": "The result of the call (whether it was answered, busy, etc.)." }, { "code": null, "e": 48501, "s": 48439, "text": "The result of the call (whether it was answered, busy, etc.)." }, { "code": null, "e": 48542, "s": 48501, "text": "Trunk or route used to connect the call." }, { "code": null, "e": 48583, "s": 48542, "text": "Trunk or route used to connect the call." }, { "code": null, "e": 48616, "s": 48583, "text": "Any fault condition encountered." }, { "code": null, "e": 48649, "s": 48616, "text": "Any fault condition encountered." }, { "code": null, "e": 48739, "s": 48649, "text": "Indicators that note the use of features such as call forwarding, three-way calling, etc." }, { "code": null, "e": 48829, "s": 48739, "text": "Indicators that note the use of features such as call forwarding, three-way calling, etc." }, { "code": null, "e": 48906, "s": 48829, "text": "Any facilities used during the call, such as call waiting or call diversion." }, { "code": null, "e": 48983, "s": 48906, "text": "Any facilities used during the call, such as call waiting or call diversion." }, { "code": null, "e": 49035, "s": 48983, "text": "Various other attributes depending on requirement." }, { "code": null, "e": 49087, "s": 49035, "text": "Various other attributes depending on requirement." }, { "code": null, "e": 49391, "s": 49087, "text": "The accurate recording of all required information in a UDR depends on the logic of the switch vendor plus the switch specific table entries. If either of these cannot record the data accurately, the mediation system will not be able to recognize the completed calls and pass them to the billing system." }, { "code": null, "e": 49604, "s": 49391, "text": "The Mediation System collects CDRs from different network elements in different formats. Various network elements generate CDRs in ASN.1 format and some network elements have their own proprietary format of CDRs." }, { "code": null, "e": 50001, "s": 49604, "text": "The Mediation System processes all the CDRs and converts them into a format compatible to the down stream system, which is usually a Billing System. The Mediation System applies various rules on CDRs to process them; for example, mediation system marks the international calls based on the dialed number (B-Number), same way mediation system marks the on-net calls based on A-Number and B-Number." }, { "code": null, "e": 50404, "s": 50001, "text": "There may be a requirement to filter out all the calls, which are having call duration less than 5 seconds, the best place to filter out such types of calls will be at Mediation System level. Same way, if some extra information is required in the CDRs, which is critical to billing, then Mediation System will help in providing such information based on some other attributes available within the CDRs." }, { "code": null, "e": 50585, "s": 50404, "text": "Once the collected CDRs are processed, Mediation System pushes all the CDRs to the Billing System using FTP because usually Mediation and Billing systems run on different machines." }, { "code": null, "e": 50759, "s": 50585, "text": "Well, now you have captured customer generated usage. The next chapter will cover how we can rate this captured usage so that due revenue can be collected from the end-user." }, { "code": null, "e": 51038, "s": 50759, "text": "Rate is the charge/price for the occurrence of an event. Examples of rate include charge for the duration of the telephone call: For example: \"0.40 INR per 1 minute\" or a specific quantity. For example: 10.00 INR for 1MB download or it can be charged for the quality of service." }, { "code": null, "e": 51247, "s": 51038, "text": "We already explained that Event is a single occurrence of product/service usage. The events are captured by the network elements in the form of CDRS/UDRs and passed to the Billing system for rating & billing." }, { "code": null, "e": 51415, "s": 51247, "text": "Rating is the process of determining the charge/price of individual events. For example, the price for 2 minutes call is 0.80 INR with the rate of 0.40 INR per minute." }, { "code": null, "e": 51501, "s": 51415, "text": "Rating Engine, which is part of the Billing system, carries out this rating function." }, { "code": null, "e": 51845, "s": 51501, "text": "Rating Engine receives the events in the form of data records called as Call Detail Records (CDRs) or Usage Detail Records (UDRs), which describe the use of a product/service. A CDR is a string of data that contains call information such as call date and time, call length, calling party, called party, etc., which are used to rate the events." }, { "code": null, "e": 51906, "s": 51845, "text": "There is a list of basic functions of Rating/Rating Engine −" }, { "code": null, "e": 52020, "s": 51906, "text": "Accepting CDRs from the Mediation System or other service providers or roaming partners in case of roaming usage." }, { "code": null, "e": 52134, "s": 52020, "text": "Accepting CDRs from the Mediation System or other service providers or roaming partners in case of roaming usage." }, { "code": null, "e": 52271, "s": 52134, "text": "Validating the CDRs and eliminating any duplicate records. These duplicate events are stored in a database table for later verification." }, { "code": null, "e": 52408, "s": 52271, "text": "Validating the CDRs and eliminating any duplicate records. These duplicate events are stored in a database table for later verification." }, { "code": null, "e": 52684, "s": 52408, "text": "To determine the customer account that has to be charged for the event. Here, Rate process picks up the event source ( Mobile Number or IP Address, etc.) and checks the database to verify if this event source is associated with any account. This step is called Event Guiding." }, { "code": null, "e": 52960, "s": 52684, "text": "To determine the customer account that has to be charged for the event. Here, Rate process picks up the event source ( Mobile Number or IP Address, etc.) and checks the database to verify if this event source is associated with any account. This step is called Event Guiding." }, { "code": null, "e": 53139, "s": 52960, "text": "If the event can not be guided, then this event will be rejected and can be put in suspense category. These rejected events are stored in a database table for later verification." }, { "code": null, "e": 53318, "s": 53139, "text": "If the event can not be guided, then this event will be rejected and can be put in suspense category. These rejected events are stored in a database table for later verification." }, { "code": null, "e": 53414, "s": 53318, "text": "To calculate the cost/price of the event as per the rating tariff (also referred as rate plan)." }, { "code": null, "e": 53510, "s": 53414, "text": "To calculate the cost/price of the event as per the rating tariff (also referred as rate plan)." }, { "code": null, "e": 53704, "s": 53510, "text": "To apply any applicable rating time discounts. This could be first five minutes free and after that call will be charged at normal rate. Such type of discounts are called rating time discounts." }, { "code": null, "e": 53898, "s": 53704, "text": "To apply any applicable rating time discounts. This could be first five minutes free and after that call will be charged at normal rate. Such type of discounts are called rating time discounts." }, { "code": null, "e": 54008, "s": 53898, "text": "To store the rated event in the database for a billing purpose or send it to the external system for billing." }, { "code": null, "e": 54118, "s": 54008, "text": "To store the rated event in the database for a billing purpose or send it to the external system for billing." }, { "code": null, "e": 54208, "s": 54118, "text": "The following image shows an overview of the Rating Engine and its associated functions −" }, { "code": null, "e": 54531, "s": 54208, "text": "The customer's information determines the rate plan (rating tariff) to use in charge/price calculation. The rating engine uses the rating tables, and the event information from the CDRs (e.g. distance, time of day, location of the call, duration or volume of the event, etc.) to calculate the actual charge for each call." }, { "code": null, "e": 54652, "s": 54531, "text": "A duplicate event is defined as any unbilled event that relates to another unbilled event in all of the following ways −" }, { "code": null, "e": 54687, "s": 54652, "text": "The account numbers are identical." }, { "code": null, "e": 54720, "s": 54687, "text": "The event sources are identical." }, { "code": null, "e": 54754, "s": 54720, "text": "The event type IDs are identical." }, { "code": null, "e": 54795, "s": 54754, "text": "The event dates and times are identical." }, { "code": null, "e": 54986, "s": 54795, "text": "Any other criteria can be defined in the billing system to identify duplicate events. There are a number of situations that may cause duplicate events to be submitted to the Billing system −" }, { "code": null, "e": 55043, "s": 54986, "text": "A failure of the mediation system's filtering mechanism." }, { "code": null, "e": 55091, "s": 55043, "text": "Coding errors in the mediation system software." }, { "code": null, "e": 55171, "s": 55091, "text": "A repetition of all or part of an event file being passed to the Rating Engine." }, { "code": null, "e": 55331, "s": 55171, "text": "When Billing System encounters a problem with a particular event, the offending event is rejected. Rejection may be due to problems with any of the following −" }, { "code": null, "e": 55349, "s": 55331, "text": "The event itself." }, { "code": null, "e": 55364, "s": 55349, "text": "The rate plan." }, { "code": null, "e": 55391, "s": 55364, "text": "Customer and account data." }, { "code": null, "e": 55411, "s": 55391, "text": "Configuration data." }, { "code": null, "e": 55465, "s": 55411, "text": "There are three main reasons for rejecting an event −" }, { "code": null, "e": 55662, "s": 55465, "text": "Parsing errors prevent the Billing System from reading the information in the event detail record. A parsing error may occur because the data in the event record is corrupt or in the wrong format." }, { "code": null, "e": 55859, "s": 55662, "text": "Parsing errors prevent the Billing System from reading the information in the event detail record. A parsing error may occur because the data in the event record is corrupt or in the wrong format." }, { "code": null, "e": 56072, "s": 55859, "text": "Unguideable errors prevent Geneva from identifying the event source or account associated with the event. An unguideable error may occur because the event source does not yet exist in the Billing System database." }, { "code": null, "e": 56285, "s": 56072, "text": "Unguideable errors prevent Geneva from identifying the event source or account associated with the event. An unguideable error may occur because the event source does not yet exist in the Billing System database." }, { "code": null, "e": 56433, "s": 56285, "text": "Unrateable errors prevent Billing System from calculating a cost for the event. An unrateable error may occur because of problems with a rate plan." }, { "code": null, "e": 56581, "s": 56433, "text": "Unrateable errors prevent Billing System from calculating a cost for the event. An unrateable error may occur because of problems with a rate plan." }, { "code": null, "e": 56957, "s": 56581, "text": "All the rejected events are posted to a special account, which is called internal account or suspense account and these rejected events are called suspense events. Finance department keeps track of all the rejected events and count them as a part of revenue loss. IT department always gives alot of attention to resolve rejected events and rate them properly to save revenue." }, { "code": null, "e": 57213, "s": 56957, "text": "If a rejected event cannot be fixed and the Operator does not want to post it to an internal account, the event can be discarded. When an event is discarded, it will not be submitted to the Rating Engine and no further attempts to rate it will take place." }, { "code": null, "e": 57549, "s": 57213, "text": "Real-time rating is the process of taking events as they occur and rating them immediately, with as little delay as possible between event generation and costing. Real-time rating can be contrasted with file-based rating, where event details are stored in a file buffer for hours, days, or weeks before the whole file is finally rated." }, { "code": null, "e": 57759, "s": 57549, "text": "Real-time system process includes e-commerce transactions and data download. Any application where events must be rated and applied quickly to a customer's account is a suitable candidate for real-time rating." }, { "code": null, "e": 57855, "s": 57759, "text": "There are several situations in which it may be necessary to rerate events. For example, when −" }, { "code": null, "e": 57925, "s": 57855, "text": "An error in the rate plan used resulted in incorrectly priced events." }, { "code": null, "e": 57995, "s": 57925, "text": "An error in the rate plan used resulted in incorrectly priced events." }, { "code": null, "e": 58090, "s": 57995, "text": "The events were loaded against the wrong account (due to incorrect event source registration)." }, { "code": null, "e": 58185, "s": 58090, "text": "The events were loaded against the wrong account (due to incorrect event source registration)." }, { "code": null, "e": 58279, "s": 58185, "text": "An existing rate plan was replaced at some point between the last and the next billing dates." }, { "code": null, "e": 58373, "s": 58279, "text": "An existing rate plan was replaced at some point between the last and the next billing dates." }, { "code": null, "e": 58464, "s": 58373, "text": "The rate plan, price plan, or event source for a product has been retrospectively changed." }, { "code": null, "e": 58555, "s": 58464, "text": "The rate plan, price plan, or event source for a product has been retrospectively changed." }, { "code": null, "e": 58625, "s": 58555, "text": "The process for rerating events is very simple and it is as follows −" }, { "code": null, "e": 58784, "s": 58625, "text": "Unload/Unrate all the events from the database using provided utility. Most of the billing system provides a utility to unload or unrate all the rated events." }, { "code": null, "e": 58943, "s": 58784, "text": "Unload/Unrate all the events from the database using provided utility. Most of the billing system provides a utility to unload or unrate all the rated events." }, { "code": null, "e": 58977, "s": 58943, "text": "Fix the problem wherever it lies." }, { "code": null, "e": 59011, "s": 58977, "text": "Fix the problem wherever it lies." }, { "code": null, "e": 59064, "s": 59011, "text": "Resubmit the events for rating by the Rating Engine." }, { "code": null, "e": 59117, "s": 59064, "text": "Resubmit the events for rating by the Rating Engine." }, { "code": null, "e": 59207, "s": 59117, "text": "Partial events allow a customer's balance to be maintained while an event is in progress." }, { "code": null, "e": 59536, "s": 59207, "text": "For example, in case of a long data download, mediation system will keep sending partial events to the billing system so that billing system keep rating them instead of waiting for event completion, and as soon as customer's credit limit breach, account will be barred and Network element will be informed to terminate the call." }, { "code": null, "e": 59678, "s": 59536, "text": "The Rating Engine can automatically check to see if any rating time thresholds, including rating time discount thresholds, have been reached." }, { "code": null, "e": 59950, "s": 59678, "text": "Rating time thresholds help in protecting operators from lots of revenue loss. For example, a customer may not be willing to pay more than his credit limit, in such a case, it becomes necessary to terminate customer's call as soon as it reaches to credit limit threshold." }, { "code": null, "e": 60066, "s": 59950, "text": "If it is required to take rating time action, then it is important to have as much as real time rating as possible." }, { "code": null, "e": 60232, "s": 60066, "text": "So far, we have seen how a customer generates usage and how mediation system pushes that usage (CDRs) to the Billing System and how a Billing System rate those CDRs." }, { "code": null, "e": 60436, "s": 60232, "text": "In the next chapter, we will discuss how to collect all the rated CDRs for the whole month and generate final invoice/bill, which is sent to the end customer to collect revenue for the provided services." }, { "code": null, "e": 60640, "s": 60436, "text": "Billing is the aggregation of all non-recurring, periodic, and chargeable events on an account-by-account basis. It is also the calculation of all outstanding charges and available discounts and bonuses." }, { "code": null, "e": 60845, "s": 60640, "text": "The output from billing process is a stream of tagged bill data that can be used to create a bill on paper, disk, or any other media. Billing Engine, which is part of the Billing System, creates invoices." }, { "code": null, "e": 60940, "s": 60845, "text": "The following diagram shows the basic diagram of the Billing Engine and associated functions −" }, { "code": null, "e": 61066, "s": 60940, "text": "The Billing Engine picks up an account to generate a bill and the following associated information to generate invoice data −" }, { "code": null, "e": 61131, "s": 61066, "text": "All the rated CDRs for the customer within the month of invoice." }, { "code": null, "e": 61196, "s": 61131, "text": "All the rated CDRs for the customer within the month of invoice." }, { "code": null, "e": 61339, "s": 61196, "text": "All types of charges (initiation, installation, periodic, suspension, termination, etc.,) applicable for the customer's products and services." }, { "code": null, "e": 61482, "s": 61339, "text": "All types of charges (initiation, installation, periodic, suspension, termination, etc.,) applicable for the customer's products and services." }, { "code": null, "e": 61538, "s": 61482, "text": "If there is any refund or any other charges applicable." }, { "code": null, "e": 61594, "s": 61538, "text": "If there is any refund or any other charges applicable." }, { "code": null, "e": 61633, "s": 61594, "text": "Total outstanding from previous bills." }, { "code": null, "e": 61672, "s": 61633, "text": "Total outstanding from previous bills." }, { "code": null, "e": 61728, "s": 61672, "text": "Total payments made by the customer in the given month." }, { "code": null, "e": 61784, "s": 61728, "text": "Total payments made by the customer in the given month." }, { "code": null, "e": 61858, "s": 61784, "text": "Total adjustment passed in favor of the customer or against the customer." }, { "code": null, "e": 61932, "s": 61858, "text": "Total adjustment passed in favor of the customer or against the customer." }, { "code": null, "e": 61970, "s": 61932, "text": "Total discount given to the customer." }, { "code": null, "e": 62008, "s": 61970, "text": "Total discount given to the customer." }, { "code": null, "e": 62071, "s": 62008, "text": "Total taxes applicable on customer's usage and rental charges." }, { "code": null, "e": 62134, "s": 62071, "text": "Total taxes applicable on customer's usage and rental charges." }, { "code": null, "e": 62238, "s": 62134, "text": "Billing configuration parameter required to run the Billing Engine; for example, payment due date, etc." }, { "code": null, "e": 62342, "s": 62238, "text": "Billing configuration parameter required to run the Billing Engine; for example, payment due date, etc." }, { "code": null, "e": 62473, "s": 62342, "text": "The above-mentioned information is just an indicative and may vary from billing system to billing system and operator to operator." }, { "code": null, "e": 62657, "s": 62473, "text": "Billing Engine produces raw data having all the information required to generate a final bill and this raw data can be used to generate a final invoice to be sent to the end customer." }, { "code": null, "e": 62855, "s": 62657, "text": "When a customer is added into the Billing System, system assigns the customer a predefined Bill Cycle. A bill cycle is a date on which Billing Engine runs and produces bills for a set of customers." }, { "code": null, "e": 63074, "s": 62855, "text": "If there are many customers, then they are divided into different billing cycles. For example, a group of customers can have billing data as 1st of every month; another can have the billing date on 15th of every month." }, { "code": null, "e": 63341, "s": 63074, "text": "If a customer is assigned to run a bill on 1st of the month, this would be called customer's nominal bill date. But because of various reasons, many times bill run becomes delayed and actual bill gets generated on a later date, this would be called actual bill date." }, { "code": null, "e": 63459, "s": 63341, "text": "There could be various types of bills available for a user. Few of them may not be supported by some Billing Systems." }, { "code": null, "e": 63475, "s": 63459, "text": "Initiation bill" }, { "code": null, "e": 63590, "s": 63475, "text": "Normally, only requested as the first bill on an account. Includes product charges and adjustments, but no events." }, { "code": null, "e": 63604, "s": 63590, "text": "Periodic bill" }, { "code": null, "e": 63691, "s": 63604, "text": "Produced at regular intervals. Includes all periodic charges, events, and adjustments." }, { "code": null, "e": 63704, "s": 63691, "text": "Interim bill" }, { "code": null, "e": 63863, "s": 63704, "text": "An extra bill that contains charges due to events processed for the account since the last bill. Includes all events and adjustments, but no periodic charges." }, { "code": null, "e": 63879, "s": 63863, "text": "Suspension bill" }, { "code": null, "e": 63976, "s": 63879, "text": "Sent when an account has been suspended. Includes all periodic charges, events, and adjustments." }, { "code": null, "e": 63987, "s": 63976, "text": "Final bill" }, { "code": null, "e": 64192, "s": 63987, "text": "Sent when an account has been terminated to bill all outstanding charges that are due. Includes all periodic charges, events, and adjustments, along with any refunds; for example, the return of a deposit." }, { "code": null, "e": 64208, "s": 64192, "text": "Post-final bill" }, { "code": null, "e": 64384, "s": 64208, "text": "Sent when a terminated account has receivables outstanding after the production of a final bill. Includes any post-termination events and adjustments, but no periodic charges." }, { "code": null, "e": 64396, "s": 64384, "text": "Credit note" }, { "code": null, "e": 64495, "s": 64396, "text": "An extra bill that contains all adjustments in the customer's favor generated since the last bill." }, { "code": null, "e": 64514, "s": 64495, "text": "Summary Statements" }, { "code": null, "e": 64765, "s": 64514, "text": "A summary statement can be produced for a customer-driven billing hierarchy. It can summarize all the bills produced by all accounts associated with the respective customer. Optionally, they can also concatenate all the bills into a single statement." }, { "code": null, "e": 64836, "s": 64765, "text": "Bills are produced either automatically or on request from a customer." }, { "code": null, "e": 64900, "s": 64836, "text": "A Billing System can generate bills in two modes, for example −" }, { "code": null, "e": 65144, "s": 64900, "text": "Test (what if?) billing mode − This mode if used to produce formatted test bills whilst leaving the database unchanged. These bills are useful to make sure that system is working fine and test after making changes to bill templates or tariffs." }, { "code": null, "e": 65388, "s": 65144, "text": "Test (what if?) billing mode − This mode if used to produce formatted test bills whilst leaving the database unchanged. These bills are useful to make sure that system is working fine and test after making changes to bill templates or tariffs." }, { "code": null, "e": 65581, "s": 65388, "text": "When running the Billing Engine in test mode, commits are not made to the database. So there would not be any impact on customer's profile even after running test billing many number of times." }, { "code": null, "e": 65774, "s": 65581, "text": "When running the Billing Engine in test mode, commits are not made to the database. So there would not be any impact on customer's profile even after running test billing many number of times." }, { "code": null, "e": 65917, "s": 65774, "text": "Test bills are usually run for a sample set of customers. If you are satisfied with the test bills, then you can proceed for production bills." }, { "code": null, "e": 66060, "s": 65917, "text": "Test bills are usually run for a sample set of customers. If you are satisfied with the test bills, then you can proceed for production bills." }, { "code": null, "e": 66214, "s": 66060, "text": "Production (live) billing mode − This mode is used to produce normal production bills. Most of the time, this is the default mode for the Billing Engine." }, { "code": null, "e": 66368, "s": 66214, "text": "Production (live) billing mode − This mode is used to produce normal production bills. Most of the time, this is the default mode for the Billing Engine." }, { "code": null, "e": 66551, "s": 66368, "text": "Once a production bill is generated, Billing Engine updates customer's profile in the database with the total outstanding balance to be paid by the customer, and next bill date, etc." }, { "code": null, "e": 66734, "s": 66551, "text": "Once a production bill is generated, Billing Engine updates customer's profile in the database with the total outstanding balance to be paid by the customer, and next bill date, etc." }, { "code": null, "e": 66887, "s": 66734, "text": "Billing Engine assigns different invoice numbers to all the production bills which help in keeping track of different payments made against the invoice." }, { "code": null, "e": 67025, "s": 66887, "text": "There may be a situation when it is not worth to generate a bill and better to suppress the bill. Following are such type of situations −" }, { "code": null, "e": 67124, "s": 67025, "text": "Suppressing bills for accounts with zero (zero activity bills) or very little value (small bills)." }, { "code": null, "e": 67223, "s": 67124, "text": "Suppressing bills for accounts with zero (zero activity bills) or very little value (small bills)." }, { "code": null, "e": 67412, "s": 67223, "text": "A particular type of bill can also be suppressed if multiple bill types are requested/scheduled at the same time and therefore preventing unnecessary bills from being sent to the customer." }, { "code": null, "e": 67601, "s": 67412, "text": "A particular type of bill can also be suppressed if multiple bill types are requested/scheduled at the same time and therefore preventing unnecessary bills from being sent to the customer." }, { "code": null, "e": 67884, "s": 67601, "text": "A small bill is a bill that falls between the ranges defined by the minimum positive bill amount and the maximum negative bill amount, exceptional bill conditions. Small valued bills are produced and then removed from the billing process, so that they are not sent out to customers." }, { "code": null, "e": 68195, "s": 67884, "text": "Examples of possible exceptional bills are unusually high bills or bills, which exceed the account's credit limit by a set multiplier. The Billing Engine performs some basic checks on the bill data that it produces. These involve testing the total being billed to ensure that the following conditions are met −" }, { "code": null, "e": 68260, "s": 68195, "text": "The bill total is greater than the minimum negative bill amount." }, { "code": null, "e": 68325, "s": 68260, "text": "The bill total is greater than the minimum negative bill amount." }, { "code": null, "e": 68387, "s": 68325, "text": "The bill total is less than the maximum positive bill amount." }, { "code": null, "e": 68449, "s": 68387, "text": "The bill total is less than the maximum positive bill amount." }, { "code": null, "e": 68543, "s": 68449, "text": "The bill total is less than account's credit limit multiplied by the credit limit multiplier." }, { "code": null, "e": 68637, "s": 68543, "text": "The bill total is less than account's credit limit multiplied by the credit limit multiplier." }, { "code": null, "e": 68780, "s": 68637, "text": "All the above conditions vary from billing system to billing system and operator to operator and they are called exceptional bills conditions." }, { "code": null, "e": 68968, "s": 68780, "text": "By default, all the invoices provide a detailed summary of product and service charges along with usage charges. But it does not provide the details on all the calls made by the customer." }, { "code": null, "e": 69231, "s": 68968, "text": "An itemized bill means giving complete details of all the calls made by the customer. This needs more number of papers to be printed. Recent trend is to send itemized bill through electronic e-mail and summary statement is sent using a physical copy of the bill." }, { "code": null, "e": 69355, "s": 69231, "text": "There are Billing Systems, which provide Billing Formatting utilities, which can be used to generate final formatted bills." }, { "code": null, "e": 69531, "s": 69355, "text": "Bill formatters take the output data produced by the Billing Engine and usually generate either Post Script file or a PDF file, which can be used by the Bill Printing Company." }, { "code": null, "e": 69777, "s": 69531, "text": "If Billing System is not capable enough to generate formatted bills, then system generates a set of tagged files along with billing information and any external Bill Formatter can use that tagged information to generate a well-formatted invoice." }, { "code": null, "e": 70147, "s": 69777, "text": "No matter, if Billing System generates formatted invoice or we use an external tool to generate these formatted invoice using raw data generated by the billing engine, finally these invoices are sent to the bill printing company, who takes care of generating final copy of generating invoice. We will discuss it in detail in the subsequent chapter \"Invoice Generation.\"" }, { "code": null, "e": 70342, "s": 70147, "text": "Next chapter would explain discount process, which is actually a part of rating and billing process, but we kept it as a separate section because of the various that items need more explanation." }, { "code": null, "e": 70456, "s": 70342, "text": "We will discuss different types of discount hierarchies and which can be given at the time of rating and billing." }, { "code": null, "e": 70830, "s": 70456, "text": "All discounts alter (most commonly to reduce) the price to be paid for a set of events and/or products. Discount is a way of giving customer money off. Discount defines a set amount of money (percentage or monetary) to be applied to products or usage that meet certain criteria. For example, all the local calls made on a particular day say 01-01-2010 are charged at $0.20." }, { "code": null, "e": 70923, "s": 70830, "text": "Discounts can be calculated either during the rating process or during the billing process −" }, { "code": null, "e": 71135, "s": 70923, "text": "Rating Time Discount − All the discounts given at the time of rating process. These discounts can be given at usage only. An example of rating time discount is \"5% off the first hour of all international calls\"." }, { "code": null, "e": 71347, "s": 71135, "text": "Rating Time Discount − All the discounts given at the time of rating process. These discounts can be given at usage only. An example of rating time discount is \"5% off the first hour of all international calls\"." }, { "code": null, "e": 71598, "s": 71347, "text": "Billing Time Discount − All the discounts given at the time of billing process. These discounts can be given on rated usage as well as on product & service charges. An example of billing time discount is \"5% off if you spend over $15 within a month\"." }, { "code": null, "e": 71849, "s": 71598, "text": "Billing Time Discount − All the discounts given at the time of billing process. These discounts can be given on rated usage as well as on product & service charges. An example of billing time discount is \"5% off if you spend over $15 within a month\"." }, { "code": null, "e": 72228, "s": 71849, "text": "A pre-itemization discount is one that modifies the price of each event to which it applies to determine a rerated price. This discount also comes in billing time discount category, but this is related to rating of the calls. Other billing time discounts leave the price of the event unmodified. A pre-itemization discount cannot incorporate product charges, only event charges." }, { "code": null, "e": 72414, "s": 72228, "text": "The size of a discount is determined using a series of discount steps and thresholds. Discount steps allow the size of the discount to be changed when particular thresholds are reached." }, { "code": null, "e": 72589, "s": 72414, "text": "For example, a discount for telephony events could depend upon the number of minutes spent calling with 10 percent off after 100 minutes and 20 percent off after 200 minutes." }, { "code": null, "e": 72856, "s": 72589, "text": "Each discount should have at least one step. Further steps can be added if the discount is required to become more or less favorable with greater volumes. Each discount step can have its discount expressed as either an amount of money or a percentage (but not both)." }, { "code": null, "e": 73055, "s": 72856, "text": "There could be infinite types of discounts given to the end customer, but it depends on what your billing supports. Following are the simple, but very good types of discounts, which can be offered −" }, { "code": null, "e": 73174, "s": 73055, "text": "These are the discounts where a set of products & events determine the discounts for another set of products & events." }, { "code": null, "e": 73380, "s": 73174, "text": "For example, \"10 SMS free if more than $30 is spent on mobile calls\". Here mobile calls determine the discount and SMS product gets the discounts, such type of discounts are called cross product discounts." }, { "code": null, "e": 73695, "s": 73380, "text": "These are only applicable to the portion of the set of events or money spent that falls between the assigned discount thresholds. For example, in the following diagram, 0% off for a spend of $0-$100 threshold or 0-100 events threshold, 5% off for a spend of $100-$200 threshold or 100-200 events threshold, etc." }, { "code": null, "e": 73943, "s": 73695, "text": "These are the discounts based on the number of events or product charges that a certain product generates. For example, in the following diagram, 5% off for a spend of $100 or 100 events, etc. As seen, the greater the spend, the more the discount." }, { "code": null, "e": 74085, "s": 73943, "text": "Tax discounts provide an alternative method for dealing with some tax exemptions. They are calculated and applied when the account is billed." }, { "code": null, "e": 74236, "s": 74085, "text": "Most discounts have a discount period associated with them, which can be any number of days, weeks, or months. This period can be used in three ways −" }, { "code": null, "e": 74309, "s": 74236, "text": "To specify the time over which a threshold value is meant to be reached." }, { "code": null, "e": 74382, "s": 74309, "text": "To specify the time over which a threshold value is meant to be reached." }, { "code": null, "e": 74463, "s": 74382, "text": "To specify the frequency with which an absolute discount is meant to be applied." }, { "code": null, "e": 74544, "s": 74463, "text": "To specify the frequency with which an absolute discount is meant to be applied." }, { "code": null, "e": 74648, "s": 74544, "text": "To specify how often the highest usage is determined for discounts with highest usage filters attached." }, { "code": null, "e": 74752, "s": 74648, "text": "To specify how often the highest usage is determined for discounts with highest usage filters attached." }, { "code": null, "e": 75061, "s": 74752, "text": "Discounts could be pro-rated and non-prorated based on the requirement. If discount is pro-rated, then discount will be calculated based on the number of days service has been under use, and in case of non-proration discount, it will be calculated for the whole period for which discount has been configured." }, { "code": null, "e": 75282, "s": 75061, "text": "Bonus schemes are methods of giving the customer free events, where the number of free events is determined by the prior usage of or charge for one or more products over a period of time (for example, the previous year)." }, { "code": null, "e": 75436, "s": 75282, "text": "For example, \"Take the Super deal telephony package and get $10 of free calls for every three hours of international calls made in the previous quarter.\"" }, { "code": null, "e": 75621, "s": 75436, "text": "There are other ways of giving customers money off, for example, giving a more favorable price plan via a package, reducing the unit rate of a product as the quantity taken increases." }, { "code": null, "e": 75738, "s": 75621, "text": "Calling circle Groups define a relationship between users, who are modelled as members and (by default) non-members." }, { "code": null, "e": 75935, "s": 75738, "text": "Within this model, a call made by a member of the circle to another member of the circle would be priced using a different rate to that applied to a non-member (or associate) making the same call." }, { "code": null, "e": 76187, "s": 75935, "text": "The relationship between the calling parties is determined by the combination of caller identities. Calling circles can span networks if the networks belong to the same operator and a single calling circle can include both mobile and fixed-line users." }, { "code": null, "e": 76389, "s": 76187, "text": "We already have covered Billing Processes in the previous chapter. In the next chapter, we will discuss the last part of Invoice Generation starting from raw invoice data to structured bill formation." }, { "code": null, "e": 76681, "s": 76389, "text": "Most of the billing systems generate structured ASCII text containing the information content of the bill. The bill data for each bill is written initially to either database or flat text files. The format of the data at this stage is the same, regardless of how the data is to be processed." }, { "code": null, "e": 76831, "s": 76681, "text": "This bill data can then be processed by one of a number of formatting engines to produce output in the desired form. For example, paper, CD-ROM, etc." }, { "code": null, "e": 77093, "s": 76831, "text": "There are Billing Systems available, which provide internal Bill Formatting tools. If a billing system does not provide capable tool to generate formatted bills, then there are third party tools available like DOC1, which is one of the most commonly used tools." }, { "code": null, "e": 77157, "s": 77093, "text": "Here is a typical diagram showing the flow of bill formatting −" }, { "code": null, "e": 77245, "s": 77157, "text": "Following is the snapshot of a bill data taken from Convergy's Infinys Billing System −" }, { "code": null, "e": 78870, "s": 77245, "text": "DOCSTART_85\nDOCTYPE BILL\nGENEVAVERSION 5.0\nBILLSTYLE 1\nBILLTYPE 1\nBILLTEMPLATE 85\nBILLSEQ 1\nBILLVERSION 1\nACCCURRENCYCODE BEF\nBILLLANGID 2\nBILLLANGNAME English (US)\nBILLLANGLOCALE us\nPAYMETHODID 1\nFORMATREQ A30001001/0001\nCOPYBILLNUM 0\nBILLPURPOSE 1\nADDRESSNAME Dr D Jackson\nPOSITION Project Manager\nDEPARTMENT Recruitment\nADDRESS1 12 South Street\nADDRESS2 Detroit\nADDRESS3 Michigan\nZIPCODE 12345\nCOUNTRY United States\nBSTARTACCFADDR\nACCFADDR_1 United States\nACCFADDR_2 Michigan\nACCFADDR_3 12345\nACCFADDR_4 12 South Street\nACCFADDR_5 Detroit\nACCFADDR_6 Dr D Jackson\nBENDACCFADDR\nCUSTOMERREF C30001\nCUSTOMERTYPE Standard\nACCTAXSTATUS Exclusive\nINVOICINGCONAME Invoicing company for English (US)\nINVOICINGCOADDRESS1 Company House\nINVOICINGCOADDRESS2 Atlanta\nINVOICINGCOVATREG taxref000576\nACCOUNTNO A30001001\nBENDBFPAYSUMMARY\nBALOUT 0.00\nCHARGES 142.00\nNEWBAL 142.00\nBSTARTBFPAYDETAILS\nACCDEPPREVTOT 0.00\nACCDEPCHANGE 0.00\nACCDEPCURRTOT 0.00\nBENDBFPAYDETAILS\nBENDBFSTATEMENT\nBILLREF A30001001@0001\nBILLDATE 02/20/99\nNEXTBILLDATE 03/20/99\nBSTARTPAYMENTDUEINFO\nPAYMENTDUEDATE 03/04/99\nDEBTSTARTDATE 02/25/99\nPAYMENTTERMDESC Payment due 7 days after the bill date\nPAYMENTDUEDAYS 7\nBENDPAYMENTDUEINFO\nGIROREF 34\nGIROACCOUNT 404 7800\nOCRREF 1300010019\nOCRSORTCODE V6344047800\nGIROAMOUNT 142.00\nOCRAMOUNT 000142000\nINVOICEACTUALDATE 02/25/99\nINVOICETAXDATE 02/25/99\nINVOICESTART 01/03/99\nINVOICEEND 02/19/99\nTAXTYPE 1,2.00,\nTENDTAXTYPE\nINVTOTALTAX 2.00\nBENDTAXDETAILS\nINVTOTAL 142.00\nINVTOTALROUNDED 142.00\nTOTALSAVE -11.00\nPERIODEND 02/25/99\nPOINTSBALANCE 0\nPOINTSEARNED 0\nPOINTSREDEEMED 0\nPOINTSADJUST 0\nNEWPOINTSBALANCE 0\nDOCEND\n" }, { "code": null, "e": 78954, "s": 78870, "text": "Bill data consists of succession of lines of ASCII text. Each line takes the form −" }, { "code": null, "e": 78972, "s": 78954, "text": "TAGNAME tagvalue\n" }, { "code": null, "e": 79189, "s": 78972, "text": "TAGNAME and tag value are separated by a tag separator (tagsep) of a space. The tagvalue can be either a single value or a list of values separated by delimiters (sep). The delimiter used is a comma unless specified." }, { "code": null, "e": 79487, "s": 79189, "text": "A Billing Engine may not be able to generate all the information required in the bill or there may be a requirement to perform some special calculation on the data provided in the invoice. This is called Bill Post Processing and usually done by a custom component called Bill Post Processor (BPP)." }, { "code": null, "e": 79673, "s": 79487, "text": "A BPP can be written in your preferred programming language, which reads a raw invoice file and performs required modification into this file before passing it for the final formatting." }, { "code": null, "e": 79952, "s": 79673, "text": "There is none billing systems available which provide out-of-the-box BPP functionality because requirements vary operator to operator and this process can not be standardized. At most, billing system can provide a plug-in point to plug your custom BPP along with Billing Engine." }, { "code": null, "e": 80090, "s": 79952, "text": "DOC1 is very famous Bill Formatter tool available from PitneyBowes Company, which helps in bill formatting into PDF or Post Script files." }, { "code": null, "e": 80381, "s": 80090, "text": "As mentioned above, the output of the Billing Engine is structured ASCII text containing the information content of the bill. A mapping is established between source invoice file tags generated by the billing system and tags required by DOC1. DOC1 requires fixed length tags as shown below." }, { "code": null, "e": 80453, "s": 80381, "text": "The following is a hypothetical sample from the invoice file provided −" }, { "code": null, "e": 80804, "s": 80453, "text": "ACCOUNTNO ACC0010000\nACCUMBONUSPOINTS_1 BON0050100\nACCUMBONUSPOINTS_2 BON0050100\nACCUMBONUSPOINTS_3 BON0050100\nACCUMBONUSPOINTS_4 BON0050100\nACCUMBONUSPOINTS_5 BON0050100\nADDRESS1 ACC0030000\nADDRESS2 ACC0040000\nADDRESS3 ACC0050000\nADDRESS4 ACC0060000\nADDRESS5 ACC0070000\nADDRESSNAME ACC0020000\nBUSINESSNAME ACC0120000\nTSTARTADJ ADJ0000000\n..........\n" }, { "code": null, "e": 80964, "s": 80804, "text": "Now using the above translations, a final file would be generated for DOC1 and DOC1 will take care of generating final invoice using the information provided." }, { "code": null, "e": 81159, "s": 80964, "text": "Some modifications can also be performed at DOC1 level, but it does not provide much flexibility to modify the invoice. You can try latest version, which can help you much more the expectations." }, { "code": null, "e": 81339, "s": 81159, "text": "Once all the accounts are billed and invoices are formatted using either internal or external bill formatter, these invoices are sent to the Bill Print Company for final printing." }, { "code": null, "e": 81514, "s": 81339, "text": "If an operator is using Electronic e-mail facility to send a bill to their customer, then a copy of the same bill can be sent to e-mail system to send it to the end customer." }, { "code": null, "e": 81633, "s": 81514, "text": "Tier 1 operators (having 20-30 million or more customer base) usually outsource this task including bill distribution." }, { "code": null, "e": 81813, "s": 81633, "text": "After generating invoices, they are sent to the end customers. Now, it is time to collect revenue from the customer. We would discuss revenue collection process after one chapter." }, { "code": null, "e": 81947, "s": 81813, "text": "Before we proceed further, let us cover Credit Control Part, which is very important and should be covered before revenue collection." }, { "code": null, "e": 82118, "s": 81947, "text": "All the operators provide their services and collect revenue from the end customers to survive in the business. There may be two possible ways to charge an end customer −" }, { "code": null, "e": 82304, "s": 82118, "text": "In-Advance − An operator charges the customers in advance before providing the service. This leads to less customer satisfaction, but operator is more secure from revenue point of view." }, { "code": null, "e": 82490, "s": 82304, "text": "In-Advance − An operator charges the customers in advance before providing the service. This leads to less customer satisfaction, but operator is more secure from revenue point of view." }, { "code": null, "e": 82720, "s": 82490, "text": "In-Arrears − An operator pushes himself on risk and charges the customer at the end of every month after providing required services. This leads to more customer satisfaction, but operator is on a risk of collecting less revenue." }, { "code": null, "e": 82950, "s": 82720, "text": "In-Arrears − An operator pushes himself on risk and charges the customer at the end of every month after providing required services. This leads to more customer satisfaction, but operator is on a risk of collecting less revenue." }, { "code": null, "e": 83155, "s": 82950, "text": "There is always a threshold up to what an operator can tolerate revenue loss associated with a particular customer; same time, there is a threshold of risk an operator can take with a particular customer." }, { "code": null, "e": 83492, "s": 83155, "text": "For example, if a customer's income is $10,000/month, then operator can provide him their services very easily up to $1000 - $2000 but for the same operator it would be difficult to provide him a service, which would cost almost $10,000/month because in such a situation, it would be difficult for the customer to make monthly payment." }, { "code": null, "e": 83659, "s": 83492, "text": "Keeping the same concept, operators define different credit classes, which they use to classify their customers and associate different credit and collection actions." }, { "code": null, "e": 83934, "s": 83659, "text": "The credit class defines a category of the customer and associated risk of revenue can be taken with that customer. A credit class also defines which collections schedule is to be applied to the customer, should its owner fail to make the (undisputed) payments that are due." }, { "code": null, "e": 84150, "s": 83934, "text": "All the Billing Systems provide facility to define various credit classes, which can be assigned to different customers at the time of adding them into the system. Some examples of credit classes are as follows −" }, { "code": null, "e": 84255, "s": 84150, "text": "VIP Credit Class − This can be assigned to VIP customers and would have very high value of credit limit." }, { "code": null, "e": 84360, "s": 84255, "text": "VIP Credit Class − This can be assigned to VIP customers and would have very high value of credit limit." }, { "code": null, "e": 84469, "s": 84360, "text": "General Public Class − This is the most common credit class and would have almost $100 or $200 credit limit." }, { "code": null, "e": 84578, "s": 84469, "text": "General Public Class − This is the most common credit class and would have almost $100 or $200 credit limit." }, { "code": null, "e": 84766, "s": 84578, "text": "Segment Specific Class − These classes can be defined based on different segments such as police, military, or bank officers, etc. Operator can define credit limit based on their comfort." }, { "code": null, "e": 84954, "s": 84766, "text": "Segment Specific Class − These classes can be defined based on different segments such as police, military, or bank officers, etc. Operator can define credit limit based on their comfort." }, { "code": null, "e": 85068, "s": 84954, "text": "There could be infinite number of credit classes defined based on the requirements and category of the customers." }, { "code": null, "e": 85173, "s": 85068, "text": "There are mainly two stages where credit can be controlled for a particular type of customer category −" }, { "code": null, "e": 85508, "s": 85173, "text": "This is rating time control, which is done by the Rating Processes. Here, customer's usage and total charges are checked against the assigned credit limit, and if customer starts approaching towards the assigned credit limit, customer is informed about the same and after breaching the credit limit an appropriate action can be taken." }, { "code": null, "e": 85950, "s": 85508, "text": "There are operators, who would like to bar (i.e., temporarily stop) the services if customer is breaching the credit limit and they would be unbarred once the payment is done. For example, a customer having a credit limit of $200 will be informed on 80% of usage by a means of SMS, on reaching a threshold of 90% might be informed by means of a reminder call, etc., and when 100% credit limit has been reached, then outgoing might be barred." }, { "code": null, "e": 86134, "s": 85950, "text": "To control the credit, operators like to bar only outgoing calls in case of Voice and SMS usage, but in case of data download, customer would not be able to perform any data download." }, { "code": null, "e": 86270, "s": 86134, "text": "This is usually done after sending the invoices and more related to revenue collection process, which we would discuss in next chapter." }, { "code": null, "e": 86688, "s": 86270, "text": "To control the credit at rating time, it is important to keep rating as real time as possible. If usage is not being captured in real time and it is being rated after a long gap, then there is a possibility that customers would have crossed their credit limit and legally customer may not be able to pay the amount beyond their assigned credit limits, but this varies from country to country and operator to operator." }, { "code": null, "e": 86860, "s": 86688, "text": "There are billing systems, which support deposits to be held against accounts. Deposits are held alongside the account balance and cash can be transferred between the two." }, { "code": null, "e": 86987, "s": 86860, "text": "There could be different level of deposits to provide different kinds of services, which can be maintained against an account." }, { "code": null, "e": 87087, "s": 86987, "text": "Deposits help operators to cover their revenue in case customer is not able to make their payments." }, { "code": null, "e": 87379, "s": 87087, "text": "Hope you have some idea on how to control credit given to the different classes of customers. Still there would be various customers, who would not pay on time even after giving them a credit within their capacity. There are various customers, who do not pay at all after using the services." }, { "code": null, "e": 87534, "s": 87379, "text": "In the next chapter, we will explain how we define different revenue collection processes and schedules to collect the revenue for the services provided." }, { "code": null, "e": 87959, "s": 87534, "text": "After an invoice is generated and dispatched to the customer, ideally, all customers will receive their bills and pay promptly. However, there may be some customers, who do not pay their bills and there may be an unacceptable delay in paying the bill and hence the service providers must take some action needed to remedy the situation and collect the outstanding balance due (called account receivable, abbreviated as A/R)." }, { "code": null, "e": 88176, "s": 87959, "text": "Collection is the process of chasing past due receivables on customer account. This usually involves sending notifications to the customer and taking appropriate actions in absence of due payments after the due date." }, { "code": null, "e": 88453, "s": 88176, "text": "Billing Systems support dunning (receivables chasing) both at the invoice level where receivables are chased on an invoice by invoice basis and at the account level whereby all overdue amounts for an account, across several invoices, can be handled by a single dunning action." }, { "code": null, "e": 88609, "s": 88453, "text": "The dunning model to be used for an account will be assigned on the basis of its credit class. A core collection process includes the following two items −" }, { "code": null, "e": 88885, "s": 88609, "text": "Collections Aging Tracking − This is the process of tracking the customer invoices that have not been paid within the specified payment period due date. It deals with the \"age of account receivables\"; for example, invoices that are 0-30 days overdue, 30-60 days overdue, etc." }, { "code": null, "e": 89161, "s": 88885, "text": "Collections Aging Tracking − This is the process of tracking the customer invoices that have not been paid within the specified payment period due date. It deals with the \"age of account receivables\"; for example, invoices that are 0-30 days overdue, 30-60 days overdue, etc." }, { "code": null, "e": 89391, "s": 89161, "text": "Collections Actions − Collection action is the action that is performed when the account receivable reaches a particular age. For example, reminder messages to the customer to be mailed or recorded audio message should be played." }, { "code": null, "e": 89621, "s": 89391, "text": "Collections Actions − Collection action is the action that is performed when the account receivable reaches a particular age. For example, reminder messages to the customer to be mailed or recorded audio message should be played." }, { "code": null, "e": 89686, "s": 89621, "text": "Normally, collections actions are taken in the following steps −" }, { "code": null, "e": 89868, "s": 89686, "text": "Send reminder mail and/or call: The customer service department contacts the customer reminding the payment. Still if there is no payment received, then proceed for the next action." }, { "code": null, "e": 90050, "s": 89868, "text": "Send reminder mail and/or call: The customer service department contacts the customer reminding the payment. Still if there is no payment received, then proceed for the next action." }, { "code": null, "e": 90193, "s": 90050, "text": "Send red letter − For example, a \"Pay in seven days\" letter is issued. Still if the payment is not received, then proceed for the next action." }, { "code": null, "e": 90336, "s": 90193, "text": "Send red letter − For example, a \"Pay in seven days\" letter is issued. Still if the payment is not received, then proceed for the next action." }, { "code": null, "e": 90417, "s": 90336, "text": "Disconnect the service − The network management department suspends the service." }, { "code": null, "e": 90498, "s": 90417, "text": "Disconnect the service − The network management department suspends the service." }, { "code": null, "e": 90656, "s": 90498, "text": "Collections schedules define collections actions, which should be carried out and the times at which they should be carried out when a customer does not pay." }, { "code": null, "e": 90778, "s": 90656, "text": "The collections schedule specifies the series of stages that make up the collections process. For each stage, it covers −" }, { "code": null, "e": 90943, "s": 90778, "text": "The effective age that the receivables have to be for an action to take place. The effective age of receivable is calculated by taking the actual age of receivable." }, { "code": null, "e": 91108, "s": 90943, "text": "The effective age that the receivables have to be for an action to take place. The effective age of receivable is calculated by taking the actual age of receivable." }, { "code": null, "e": 91255, "s": 91108, "text": "The action to be taken. This might be an action that Billing System is to perform, for example, sending out a dunning notice on a particular date." }, { "code": null, "e": 91402, "s": 91255, "text": "The action to be taken. This might be an action that Billing System is to perform, for example, sending out a dunning notice on a particular date." }, { "code": null, "e": 91541, "s": 91402, "text": "Whether or not the action is mandatory. If an action is mandatory, subsequent actions cannot take place until this one has been performed." }, { "code": null, "e": 91680, "s": 91541, "text": "Whether or not the action is mandatory. If an action is mandatory, subsequent actions cannot take place until this one has been performed." }, { "code": null, "e": 91755, "s": 91680, "text": "The minimum receivables amount below which the action will not take place." }, { "code": null, "e": 91830, "s": 91755, "text": "The minimum receivables amount below which the action will not take place." }, { "code": null, "e": 92024, "s": 91830, "text": "In the early stages of the collections process, the soft collection action will typically be to send a number of dunning notices, which are simple reminder letters and requests for the payment." }, { "code": null, "e": 92267, "s": 92024, "text": "After a number of dunning notices have been sent at various stages, other actions are typically scheduled. For example, you can specify that a customer services representative (CSR) should telephone the customer to ask why they have not paid." }, { "code": null, "e": 92513, "s": 92267, "text": "If the initial attempts fail, then more aggressive actions can be taken like barring the services, or disconnecting the services or hot-lining (hot-lining is the process of re-directing all calls of delinquent customers to collections operator)." }, { "code": null, "e": 92946, "s": 92513, "text": "If all the attempts to collect the dues fail, then the service provider may write-off the account and marks the due amount as bad debt or may hand over (sell off) the account to a collection agency. Collection agencies work on a percentage of collected revenue. However, once the uncollected account invoices are sold off to a collection agency, the service provider is not allowed to work with the customer regarding the payments." }, { "code": null, "e": 93148, "s": 92946, "text": "Here, write-off means service provider (operator) clears the dues on behalf of the customer and closes the account forever. This is done for accounting purpose, otherwise it is a loss for the operator." }, { "code": null, "e": 93362, "s": 93148, "text": "The service provider maintains the history of the write-off accounts, also called blacklist customers so that they are not re-activated again and informs the credit checking/reporting agencies about such accounts." }, { "code": null, "e": 93490, "s": 93362, "text": "Most of the customers make their payment before the due date. There can be different channels, which are used to make payments." }, { "code": null, "e": 93616, "s": 93490, "text": "In the next chapter, we will discuss different types of payments and their end-to-end processing to settle down the invoices." }, { "code": null, "e": 93799, "s": 93616, "text": "Once the invoices are sent to the customers, the customers start making payments of their bills. The processing of bill payments into the billing system is called payment processing." }, { "code": null, "e": 94026, "s": 93799, "text": "The payments made by the customers are posted to the customers' account. If there are any outstanding invoices, then which invoice is paid depends on the account's accounting method. There are two types of accounting methods −" }, { "code": null, "e": 94244, "s": 94026, "text": "Balance forward accounting − Using this method, if a number of invoices are outstanding, payments received are allocated to invoices according to the age of the receivable, with the oldest invoice being created first." }, { "code": null, "e": 94462, "s": 94244, "text": "Balance forward accounting − Using this method, if a number of invoices are outstanding, payments received are allocated to invoices according to the age of the receivable, with the oldest invoice being created first." }, { "code": null, "e": 94652, "s": 94462, "text": "Open item accounting − This method allows payments to be allocated to specific invoices. Open item accounting is particularly useful when dealing with payments from the business customers." }, { "code": null, "e": 94842, "s": 94652, "text": "Open item accounting − This method allows payments to be allocated to specific invoices. Open item accounting is particularly useful when dealing with payments from the business customers." }, { "code": null, "e": 95099, "s": 94842, "text": "A customer can make payment using different payment methods that are supported by the service provider; for example, the customer can make payments using the payment methods such as cheque, credit card, debit card or wire transfers, or direct cash deposit." }, { "code": null, "e": 95334, "s": 95099, "text": "An operator may have multiple bank accounts into which it will receive payment done through bank accounts directly. These bank accounts are referred to as holding accounts and sends payment details to the billing system in text files." }, { "code": null, "e": 95523, "s": 95334, "text": "If payments are received outside the billing system either manually or electronically, then those payments are uploaded into the system using automated process to settle down the invoices." }, { "code": null, "e": 95653, "s": 95523, "text": "Billing Systems provide facility to capture credit card or debit card information and automatic payment methods on monthly basis." }, { "code": null, "e": 95902, "s": 95653, "text": "If payment method is set automatic using either credit card or debit card, payment requests are generated automatically after every invoice or on a given date and these requests are sent to the payment gateways (or banks) for payment authorization." }, { "code": null, "e": 96015, "s": 95902, "text": "Once all the payments are authorized, they are uploaded into the billing system to settle down the due invoices." }, { "code": null, "e": 96297, "s": 96015, "text": "If the payments are made using cash or cheque, then either it can be entered into the system upfront the customer or if this is collected by some agencies, then all such payments are collected and posted to the billing system using automated methods provided by the billing system." }, { "code": null, "e": 96524, "s": 96297, "text": "For all the payments received, payment files are prepared with a predefined format and then they are pushed automatically to a predefined location from where Billing System picks them up and uploads into the billing database." }, { "code": null, "e": 96792, "s": 96524, "text": "There may be a situation, when a payment made by credit card or cheque does not go through. If this payment is already posted into the system, then it needs a cancellation to adjust the amount. Billing System provides utilities to handle failed or cancelled payments." }, { "code": null, "e": 96980, "s": 96792, "text": "An interface is a bound between the billing system and any other external system to receive the payment. Interface allows two systems to communicate with other based on predefined rules." }, { "code": null, "e": 97185, "s": 96980, "text": "For example, a simple text file could be a payment interface between a bank and the billing system. If interface is file based, banks keep sending payment details using payment files in predefined format." }, { "code": null, "e": 97396, "s": 97185, "text": "There could be an online API-based interface between a bank and the billing system. If an online interface is in place, then bank will call the provided API to post the payment directly into the billing system." }, { "code": null, "e": 97514, "s": 97396, "text": "Similar way, there could be file-based or online interfaces provided for third party involved in collecting payments." }, { "code": null, "e": 97708, "s": 97514, "text": "So far, we have almost gone through the complete life cycle of a telecom customer. The next chapter is important to understand the dispute situation that arises between operators and customers." }, { "code": null, "e": 97894, "s": 97708, "text": "A dispute is a record of a query about an amount of money on an account. Normally, a dispute will be recorded when a customer queries some aspect of their bill. Disputes can be raised −" }, { "code": null, "e": 97928, "s": 97894, "text": "Against an invoice on an account." }, { "code": null, "e": 97962, "s": 97928, "text": "Against an invoice on an account." }, { "code": null, "e": 98102, "s": 97962, "text": "Against a particular rated event on the account. For example, if a customer disputes a particular pay-per-view TV event due to a power cut." }, { "code": null, "e": 98242, "s": 98102, "text": "Against a particular rated event on the account. For example, if a customer disputes a particular pay-per-view TV event due to a power cut." }, { "code": null, "e": 98327, "s": 98242, "text": "After a dispute is recorded, it would be investigated, verified in order to either −" }, { "code": null, "e": 98462, "s": 98327, "text": "Accept − If the raised dispute is valid from customer side, then the dispute would be accepted, and would be refunded to the customer." }, { "code": null, "e": 98597, "s": 98462, "text": "Accept − If the raised dispute is valid from customer side, then the dispute would be accepted, and would be refunded to the customer." }, { "code": null, "e": 98685, "s": 98597, "text": "Reject − If the dispute found to be not acceptable, then the dispute would be rejected." }, { "code": null, "e": 98773, "s": 98685, "text": "Reject − If the dispute found to be not acceptable, then the dispute would be rejected." }, { "code": null, "e": 98854, "s": 98773, "text": "Cancel − If the dispute is entered in error, then the dispute would be canceled." }, { "code": null, "e": 98935, "s": 98854, "text": "Cancel − If the dispute is entered in error, then the dispute would be canceled." }, { "code": null, "e": 99039, "s": 98935, "text": "The following points should be noted for the dispute and a billing system should support these points −" }, { "code": null, "e": 99174, "s": 99039, "text": "Collections actions are not escalated while amounts have a dispute status of pending, but the collections are aged during this period." }, { "code": null, "e": 99309, "s": 99174, "text": "Collections actions are not escalated while amounts have a dispute status of pending, but the collections are aged during this period." }, { "code": null, "e": 99440, "s": 99309, "text": "Disputed events are not included in collections calculation until they are billed. After this, the collections are aged as normal." }, { "code": null, "e": 99571, "s": 99440, "text": "Disputed events are not included in collections calculation until they are billed. After this, the collections are aged as normal." }, { "code": null, "e": 99784, "s": 99571, "text": "An adjustment is a method of crediting or debiting an account with an arbitrary amount of money. Adjustments can be lodged against either an account as a whole or against a particular rated event on that account." }, { "code": null, "e": 99956, "s": 99784, "text": "A Billing System allows to create different types of adjustments, which can be used in different situations and each adjustment flows through different stages of approval." }, { "code": null, "e": 100220, "s": 99956, "text": "If a dispute is accepted, an adjustment is created to credit the account with the disputed amount. Adjustments should not affect the balance of an account until they are approved. Adjustments with a status of pending approval do not affect billing or collections." }, { "code": null, "e": 100396, "s": 100220, "text": "Disputes and adjustments that are made for tax inclusive accounts are assumed to be inclusive of tax. The gross amount is entered and will be available for output on the bill." }, { "code": null, "e": 100615, "s": 100396, "text": "In the next chapter, we will discuss different types of reports required for the management. There could be a list of reports available out-of-the-box and there may be some reports, which would need custom development." }, { "code": null, "e": 100885, "s": 100615, "text": "Various reports are generated to provide valuable information to management on finance, sales and performance of the system. Different kinds of reports like financial reports, management reports, reconciliation reports, network activity reports, etc., can be generated." }, { "code": null, "e": 101066, "s": 100885, "text": "Reports contain information that drives business success and help to monitor the health of business, identify any problem areas so that appropriate corrective actions can be taken." }, { "code": null, "e": 101309, "s": 101066, "text": "Reporting is one of the areas where none of the Billing Systems can meet 100% requirements out-of-the-box. Definitely marketing or finance departments will come up with such reporting requirements, which would need lots of custom development." }, { "code": null, "e": 101553, "s": 101309, "text": "If your Billing System is pushing data on Data Warehouse (DWH), then you can transfer reporting activities towards DWH system, but still many departments would like to have important reports from the source system, which is the Billing System." }, { "code": null, "e": 101601, "s": 101553, "text": "We can categorize reports into two categories −" }, { "code": null, "e": 101764, "s": 101601, "text": "Core/Canned Reports − These reports are provided by the Billing System as core functionality of the system. Sometimes, they are called canned or standard reports." }, { "code": null, "e": 101927, "s": 101764, "text": "Core/Canned Reports − These reports are provided by the Billing System as core functionality of the system. Sometimes, they are called canned or standard reports." }, { "code": null, "e": 102083, "s": 101927, "text": "Custom Reports − These reports would not be available directly from the system and it would need some development using PL/SQL, PERL, or Shell script, etc." }, { "code": null, "e": 102239, "s": 102083, "text": "Custom Reports − These reports would not be available directly from the system and it would need some development using PL/SQL, PERL, or Shell script, etc." }, { "code": null, "e": 102457, "s": 102239, "text": "Different billing systems provide different types of reports in different areas. Interconnect Billing Systems are required to provide more functionalities related to reporting because they deal with wholesale billing." }, { "code": null, "e": 102526, "s": 102457, "text": "Following is the list of reports required by different departments −" }, { "code": null, "e": 102727, "s": 102526, "text": "Payment reports provide information on the customer's account payments during a period of time. Account Receivables aging reports provide information on the account receivables, outstanding dues, etc." }, { "code": null, "e": 102933, "s": 102727, "text": "Disputes & adjustment reports help in identifying the pattern of reasons for disputes & adjustments and help to understand the reason for such disputes & adjustments and take appropriate corrective action." }, { "code": null, "e": 103155, "s": 102933, "text": "Management reports provide information on customers, their products & services usage, call patterns, customer feedback, etc. These reports help to take appropriate steps to reduce customer churn to introduce new services." }, { "code": null, "e": 103479, "s": 103155, "text": "Churn is the process of customers disconnecting from one service provider and moving to another service provider and this can be due to many reasons like inadequate customer service or lack of competitive products or lack of competitive charges or it can be due to a natural reason of geographic relocation of the customer." }, { "code": null, "e": 103829, "s": 103479, "text": "These reports provide Revenue Assurance (RA) information ensuring that all the sources of revenue and expenses are under observation and there is no leakage of any sort of revenues. For example, revenue can be lost due to many reasons like leakage in network system or mediation or billing mistakes, demand for introducing new services quickly, etc." }, { "code": null, "e": 103935, "s": 103829, "text": "Revenue assurance reports help to identify where the leakage is so that appropriate actions can be taken." }, { "code": null, "e": 104126, "s": 103935, "text": "These reports provide information to identify the areas of network congestion so that corrective measures (rerouting or adding more resources) can be accomplished to overcome these problems." }, { "code": null, "e": 104241, "s": 104126, "text": "The following is further an imaginary list of a few other reports, which can be required out of a Billing System −" }, { "code": null, "e": 104510, "s": 104241, "text": "There could be a list of reports, which is required on monthly, weekly, or daily basis. So, such type of reports are developed if they are not available and scheduled within the system, so that they can be sent in end user's e-mail box without any manual intervention." }, { "code": null, "e": 104737, "s": 104510, "text": "There will a demand of different reports time to time based on some requirements, such type of reports cannot be imagined and developed in advance. So these reports are developed and sent based on demand from different users." }, { "code": null, "e": 104863, "s": 104737, "text": "Starting from the next chapter, we will cover different types of billing; for example, retail, wholesale, MVNO, roaming, etc." }, { "code": null, "e": 105058, "s": 104863, "text": "Most of the operators provide two options to their customers, to go for a postpaid or a prepaid connection. A Postpaid as well as prepaid connections have their own advantages and disadvantages." }, { "code": null, "e": 105274, "s": 105058, "text": "Usually, an operator will have 70%-80% customer base comprising of pre-paid customers and rest of the customer base will come from post-paid side. For an operator, it is always good to have more post-paid customers." }, { "code": null, "e": 105442, "s": 105274, "text": "You might be willing to know about the differences between the two types of customers, services and systems. Let us list down a few major differences between the two −" }, { "code": null, "e": 105780, "s": 105442, "text": "Service Payments − This is the most important factor, which differentiates between two customer bases. Pre-paid customers make payment in advance before using the service, whereas post-paid customers use offered services throughout of the month, and at the end of the month, customer receives the bill to pay within the given time frame." }, { "code": null, "e": 106118, "s": 105780, "text": "Service Payments − This is the most important factor, which differentiates between two customer bases. Pre-paid customers make payment in advance before using the service, whereas post-paid customers use offered services throughout of the month, and at the end of the month, customer receives the bill to pay within the given time frame." }, { "code": null, "e": 106299, "s": 106118, "text": "Charging & Billing − For pre-paid customer, it is required to charge the customer in real time for all the usage whereas post-paid customers can be charged at the end of the month." }, { "code": null, "e": 106480, "s": 106299, "text": "Charging & Billing − For pre-paid customer, it is required to charge the customer in real time for all the usage whereas post-paid customers can be charged at the end of the month." }, { "code": null, "e": 106791, "s": 106480, "text": "Service Offerings − Post-paid billing systems provide more flexibilities in comparison of real time charging systems. For example, real time charging system is not flexible to maintain a complex business customers' hierarchy, where as a post-paid billing system can handle a customer hierarchy up to N level." }, { "code": null, "e": 107102, "s": 106791, "text": "Service Offerings − Post-paid billing systems provide more flexibilities in comparison of real time charging systems. For example, real time charging system is not flexible to maintain a complex business customers' hierarchy, where as a post-paid billing system can handle a customer hierarchy up to N level." }, { "code": null, "e": 107430, "s": 107102, "text": "Support & Maintenance − An operator needs to give same at tention to both the businesses. If, for a pre-paid business, operator needs to have skilled manpower to control the operation, same time operator needs a great staff to handle post-paid customer's queries related to their charging, bills, and fixing operational issues." }, { "code": null, "e": 107758, "s": 107430, "text": "Support & Maintenance − An operator needs to give same at tention to both the businesses. If, for a pre-paid business, operator needs to have skilled manpower to control the operation, same time operator needs a great staff to handle post-paid customer's queries related to their charging, bills, and fixing operational issues." }, { "code": null, "e": 108136, "s": 107758, "text": "Supported Network − A long time ago, the network of the prepaid and the postpaid connections were different. This used to invoke complaints that the prepaid connection would offer better connectivity than the postpaid or vice versa. This is the age of convergent billing and operators are running their business with the same network without compromising communication quality." }, { "code": null, "e": 108514, "s": 108136, "text": "Supported Network − A long time ago, the network of the prepaid and the postpaid connections were different. This used to invoke complaints that the prepaid connection would offer better connectivity than the postpaid or vice versa. This is the age of convergent billing and operators are running their business with the same network without compromising communication quality." }, { "code": null, "e": 108696, "s": 108514, "text": "Network elements (like switches, SMSC) produce raw usage called Usage Detail Records (UDRs) or Call Detail Records (CDRs), which contain information required by the billing system −" }, { "code": null, "e": 108722, "s": 108696, "text": "Calling number (A number)" }, { "code": null, "e": 108748, "s": 108722, "text": "Calling number (A number)" }, { "code": null, "e": 108805, "s": 108748, "text": "Called number (the number receiving the call) (B number)" }, { "code": null, "e": 108862, "s": 108805, "text": "Called number (the number receiving the call) (B number)" }, { "code": null, "e": 108900, "s": 108862, "text": "when the call started (date and time)" }, { "code": null, "e": 108938, "s": 108900, "text": "when the call started (date and time)" }, { "code": null, "e": 108952, "s": 108938, "text": "Call duration" }, { "code": null, "e": 108966, "s": 108952, "text": "Call duration" }, { "code": null, "e": 109074, "s": 108966, "text": "Call Type (MOC, MTC, etc., MOC stands for Mobile Originated Call and MTC stands for Mobile Terminated Call)" }, { "code": null, "e": 109182, "s": 109074, "text": "Call Type (MOC, MTC, etc., MOC stands for Mobile Originated Call and MTC stands for Mobile Terminated Call)" }, { "code": null, "e": 109530, "s": 109182, "text": "The above raw UDRs from network elements and also from other service providers are received by the billing system and the billing system converts these into a format understandable by the system. The above formatted/converted UDR is then guided to find the customer/account to which the call should be charged and then rate the event accordingly." }, { "code": null, "e": 109775, "s": 109530, "text": "The above rated UDRs are then stored in the billing data store, and on the billing cycle date, the billing process picks up these rated UDRs and processes these and renders bill/invoice, taking into account, the payments, taxes, discounts, etc." }, { "code": null, "e": 109937, "s": 109775, "text": "The customer then pays the bill and the billing system is updated with the payment details. Following is the diagram showing the above standard billing process −" }, { "code": null, "e": 109997, "s": 109937, "text": "Steps involved in prepaid billing in brief are as follows −" }, { "code": null, "e": 110146, "s": 109997, "text": "When customer makes a call, prepaid switching gateway captures the calling number and sends the account information to the real time billing system." }, { "code": null, "e": 110295, "s": 110146, "text": "When customer makes a call, prepaid switching gateway captures the calling number and sends the account information to the real time billing system." }, { "code": null, "e": 110567, "s": 110295, "text": "Real time billing systems using the above information, authenticates the identity of the user, calculates the customer account's remaining balance using the rating tariff table and maximum allowable duration of the call, and sends this information to the prepaid gateway." }, { "code": null, "e": 110839, "s": 110567, "text": "Real time billing systems using the above information, authenticates the identity of the user, calculates the customer account's remaining balance using the rating tariff table and maximum allowable duration of the call, and sends this information to the prepaid gateway." }, { "code": null, "e": 110873, "s": 110839, "text": "The gateway establishes the call." }, { "code": null, "e": 110907, "s": 110873, "text": "The gateway establishes the call." }, { "code": null, "e": 111018, "s": 110907, "text": "During the call, gateway monitors the call so that the user do not exceed the maximum allowable call duration." }, { "code": null, "e": 111129, "s": 111018, "text": "During the call, gateway monitors the call so that the user do not exceed the maximum allowable call duration." }, { "code": null, "e": 111336, "s": 111129, "text": "When the call is over, the gateway sends the actual call duration to the prepaid billing system, which then calculates the actual call cost and updates the account balance, decreasing the remaining balance." }, { "code": null, "e": 111543, "s": 111336, "text": "When the call is over, the gateway sends the actual call duration to the prepaid billing system, which then calculates the actual call cost and updates the account balance, decreasing the remaining balance." }, { "code": null, "e": 111609, "s": 111543, "text": "The following figure shows the general prepaid billing scenario −" }, { "code": null, "e": 111764, "s": 111609, "text": "Prepaid billing process involves the following important steps along with account information gathering and updating account after the call is completed −" }, { "code": null, "e": 112050, "s": 111764, "text": "Authenticating − Authentication is the process of verifying that a user is who he or she claims to be. The user supplies a user ID and an authentication credential, such as a password. The system accepts these as inputs and verifies that the user is valid and has access to the system." }, { "code": null, "e": 112336, "s": 112050, "text": "Authenticating − Authentication is the process of verifying that a user is who he or she claims to be. The user supplies a user ID and an authentication credential, such as a password. The system accepts these as inputs and verifies that the user is valid and has access to the system." }, { "code": null, "e": 112578, "s": 112336, "text": "Authorizing − Authorization is the process of verifying what an authenticated user is allowed to do. Generally, Remote Access Dial In User Server (RADIUS) protocol is used to limit access to the system to registered and authorized customers." }, { "code": null, "e": 112820, "s": 112578, "text": "Authorizing − Authorization is the process of verifying what an authenticated user is allowed to do. Generally, Remote Access Dial In User Server (RADIUS) protocol is used to limit access to the system to registered and authorized customers." }, { "code": null, "e": 113101, "s": 112820, "text": "Providing advice of charge (AOC) − This gives information about the actual cost of the call either prior to or after the event. AOC provides the ability of a telecommunications system to advice of the actual costs of the event either prior to or after the occurrence of the event." }, { "code": null, "e": 113382, "s": 113101, "text": "Providing advice of charge (AOC) − This gives information about the actual cost of the call either prior to or after the event. AOC provides the ability of a telecommunications system to advice of the actual costs of the event either prior to or after the occurrence of the event." }, { "code": null, "e": 113530, "s": 113382, "text": "When we talk about telecom billing then by default it is about retail billing. As discussed earlier, telecom retail billing is defined as follows −" }, { "code": null, "e": 113784, "s": 113530, "text": "\"Telecom Billing is a process of collecting usage, aggregating it, applying required usage and rental charges, and finally generating invoices for the customers. Telecom Billing process also includes receiving and recording payments from the customers.\"" }, { "code": null, "e": 114027, "s": 113784, "text": "Retail billing deals directly with the end customer and comes with lots of challenges to meet the end customer expectations and regulatory obligations. A billing is assumed to be successful as long as it is fulfilling the following criteria −" }, { "code": null, "e": 114314, "s": 114027, "text": "Timely Billing − End customer's invoice is being generated on time, i.e., nominal date. There may be some circumstances when the end customer does not get his/her invoices on time because of some logistic issues, but it is IT's responsibility to generate all the due bills on due date." }, { "code": null, "e": 114601, "s": 114314, "text": "Timely Billing − End customer's invoice is being generated on time, i.e., nominal date. There may be some circumstances when the end customer does not get his/her invoices on time because of some logistic issues, but it is IT's responsibility to generate all the due bills on due date." }, { "code": null, "e": 114902, "s": 114601, "text": "Billing Accuracy − This is the most important factor for the customer satisfaction and from regulatory obligation point of view. If billing system is not generating accurate bills, then it can lead to serious business issues from legality point of view as well as leaving a customer in unhappy state." }, { "code": null, "e": 115203, "s": 114902, "text": "Billing Accuracy − This is the most important factor for the customer satisfaction and from regulatory obligation point of view. If billing system is not generating accurate bills, then it can lead to serious business issues from legality point of view as well as leaving a customer in unhappy state." }, { "code": null, "e": 115401, "s": 115203, "text": "Retail billing deals with the end customer and billing an individual customer, whereas wholesale billing deals with billing to the following entities depending on situation and nature of business −" }, { "code": null, "e": 115455, "s": 115401, "text": "Billing resellers associated with a telecom operator." }, { "code": null, "e": 115509, "s": 115455, "text": "Billing resellers associated with a telecom operator." }, { "code": null, "e": 115616, "s": 115509, "text": "Billing interconnect partners for providing interconnection to make calls to another operator's customers." }, { "code": null, "e": 115723, "s": 115616, "text": "Billing interconnect partners for providing interconnection to make calls to another operator's customers." }, { "code": null, "e": 115839, "s": 115723, "text": "Billing roaming partners for providing services to their customers when they roamed in an operator's coverage area." }, { "code": null, "e": 115955, "s": 115839, "text": "Billing roaming partners for providing services to their customers when they roamed in an operator's coverage area." }, { "code": null, "e": 116359, "s": 115955, "text": "Wholesale billing is easy in comparison to retail billing and allows a big level of threshold of tolerance, whereas retail billing always needs to be 100% accurate. Wholesale billing can never be 100% accurate because of various reasons like difference in prices configured in two operators' systems or difference in number of calls rated because some of the calls may get missed at any network element." }, { "code": null, "e": 116592, "s": 116359, "text": "There are specialized billing systems, which are being used to handle retail billing like Convergys and Amdocs Billing systems are famous for retail billing, whereas ASCADE and INTEC billing systems are famous for wholesale billing." }, { "code": null, "e": 116862, "s": 116592, "text": "Wholesale billing can also be settled using retail billing systems by using simple reports because they do not deal with too many discounts and promotion types, whereas retail billing needs all these complications and can not be handled using wholesale billing systems." }, { "code": null, "e": 117051, "s": 116862, "text": "All the concepts discussed so far in this tutorial were related to retail billing and subsequent chapters will discuss about interconnect billing, roaming billing, and other billing types." }, { "code": null, "e": 117239, "s": 117051, "text": "Interconnect is the process of handling calls for other service providers. This allows the customers of one service provider to communicate with the customers of another service provider." }, { "code": null, "e": 117400, "s": 117239, "text": "If two operators A and B are not interconnect partners, then it would not be possible for a customer of Operator A to communicate with a customer of operator B." }, { "code": null, "e": 117725, "s": 117400, "text": "Usually, operators keep their agreements with each other to allow their customers to communicate with each other. This gives good business opportunity to all the operators engaged in interconnection. Any interconnection point at which the parties agree to connect their respective Networks is called \"Interconnection Point\"." }, { "code": null, "e": 117763, "s": 117725, "text": "Examples of interconnection include −" }, { "code": null, "e": 117887, "s": 117763, "text": "Two adjacent, non-competing telephone networks interconnect so that subscribers on one network can call those on the other." }, { "code": null, "e": 118011, "s": 117887, "text": "Two adjacent, non-competing telephone networks interconnect so that subscribers on one network can call those on the other." }, { "code": null, "e": 118191, "s": 118011, "text": "Long-distance carriers obtain access to the facilities of a local service provider and compete against that provider in providing long-distance services to a common customer base." }, { "code": null, "e": 118371, "s": 118191, "text": "Long-distance carriers obtain access to the facilities of a local service provider and compete against that provider in providing long-distance services to a common customer base." }, { "code": null, "e": 118548, "s": 118371, "text": "Traditional wireline telephone and new wireless mobile carriers interconnect so that subscribers of the traditional phone service can call wireless subscribers, and vice versa." }, { "code": null, "e": 118725, "s": 118548, "text": "Traditional wireline telephone and new wireless mobile carriers interconnect so that subscribers of the traditional phone service can call wireless subscribers, and vice versa." }, { "code": null, "e": 118952, "s": 118725, "text": "New competitive local telephone carriers interconnect with the incumbent carrier so that they can attract subscribers in the common service territory and enable those subscribers to call subscribers on the incumbent's network." }, { "code": null, "e": 119179, "s": 118952, "text": "New competitive local telephone carriers interconnect with the incumbent carrier so that they can attract subscribers in the common service territory and enable those subscribers to call subscribers on the incumbent's network." }, { "code": null, "e": 119337, "s": 119179, "text": "Customers of the incumbent telephone carrier make calls to their dial-up Internet Service Provider, which in turn is a customer of a competing local carrier." }, { "code": null, "e": 119495, "s": 119337, "text": "Customers of the incumbent telephone carrier make calls to their dial-up Internet Service Provider, which in turn is a customer of a competing local carrier." }, { "code": null, "e": 119637, "s": 119495, "text": "This is process of the production of invoices to send to an interconnect partner relating to incoming interconnect call detail records (CDR)." }, { "code": null, "e": 119998, "s": 119637, "text": "Interconnect Billing concerned with calculating the amounts to be paid to and received from each of the network operators that our infrastructure connects in order for the successful call origination and termination. The CDR for interconnecting calls keep the call routing information as a group of valid values to identify the carrier and the country details." }, { "code": null, "e": 120070, "s": 119998, "text": "Note that the set of Interconnect CDRs includes the following details −" }, { "code": null, "e": 120207, "s": 120070, "text": "CDRs are those billable to retail and wholesale customers. It is revenue for the telecom provider. It is also referred as local billing." }, { "code": null, "e": 120344, "s": 120207, "text": "CDRs are those billable to retail and wholesale customers. It is revenue for the telecom provider. It is also referred as local billing." }, { "code": null, "e": 120561, "s": 120344, "text": "CDRs that are only billable for Interconnect providers. Eg: Outgoing calls, Outgoing Transit calls, Incoming calls, etc. The Outgoing calls are the expense and Incoming calls are the revenue for the Telecom Provider." }, { "code": null, "e": 120778, "s": 120561, "text": "CDRs that are only billable for Interconnect providers. Eg: Outgoing calls, Outgoing Transit calls, Incoming calls, etc. The Outgoing calls are the expense and Incoming calls are the revenue for the Telecom Provider." }, { "code": null, "e": 121152, "s": 120778, "text": "Interconnect Billing systems do pricing of all incoming and outgoing interconnect CDRs. Usually, an interconnect price is determined for both incoming and outgoing interconnect CDRs on the basis of the incoming or outgoing trunk interconnect route that carries the call. Most commonly, a trunk ID represents a unique interconnect partner in the interconnect Billing System." }, { "code": null, "e": 121331, "s": 121152, "text": "The Settlement Process will be used to settle the Network Operator/Carrier involved in carrying calls from Interconnect Owner to Other Network Operator destination or vice versa." }, { "code": null, "e": 121472, "s": 121331, "text": "The Process will bring the Outgoing (Expense to Interconnect Owner) and Incoming (Revenue to Interconnect Owner) traffic for the settlement." }, { "code": null, "e": 121645, "s": 121472, "text": "Settlement can be done on monthly or bi-weekly basis using manual or automated process. It depends on billing system to billing system how it supports partner's settlement." }, { "code": null, "e": 121868, "s": 121645, "text": "Netting used to perform after the settlement is completed for the agreed Provider/Carrier. The netting is done by multiple settlement period for the multiple services, which it supports the same currency in Operator level." }, { "code": null, "e": 121909, "s": 121868, "text": "There are two types of netting methods −" }, { "code": null, "e": 122037, "s": 121909, "text": "AFTER − After for Netting of Operator's Interconnecting cost after subtracting the amount between operator and Provider/Carrier" }, { "code": null, "e": 122165, "s": 122037, "text": "AFTER − After for Netting of Operator's Interconnecting cost after subtracting the amount between operator and Provider/Carrier" }, { "code": null, "e": 122305, "s": 122165, "text": "BEFORE − Before for Netting of Operator's Interconnecting cost without any subtracting of the amount between operator and Provider/Carrier." }, { "code": null, "e": 122445, "s": 122305, "text": "BEFORE − Before for Netting of Operator's Interconnecting cost without any subtracting of the amount between operator and Provider/Carrier." }, { "code": null, "e": 122566, "s": 122445, "text": "This is the process of the reconciliation of invoices coming from an interconnect partner which relate to outgoing CDRs." }, { "code": null, "e": 122730, "s": 122566, "text": "Every month interconnect partners exchange their CDRs for reconciliation purpose. It is very common to have discrepancies in the CDRs provided by the two partners." }, { "code": null, "e": 123024, "s": 122730, "text": "Billing Systems provide reports facilitating reconciliation of incoming and outgoing interconnect CDRs. These reports keep parameters such as call type, destination, cost band, and duration so that these CDRs can be used by both operators to match those parameters and identify missing CDRs." }, { "code": null, "e": 123335, "s": 123024, "text": "There may be a situation, when some CDRs are found missing at either of the operators' side. After doing required reconciliation if matter does not settle, then various negotiations happen between the partners, and finally, matter is settled by paying some nominal amount to the impacted interconnect partner." }, { "code": null, "e": 123493, "s": 123335, "text": "There could be various interconnect call scenarios depending on type of agreement between different operators. Let us try to cover a few most commonly used −" }, { "code": null, "e": 123621, "s": 123493, "text": "Operator A's customer makes national call to Operator B's customer. In this case operator A will pay some amount to operator B." }, { "code": null, "e": 123749, "s": 123621, "text": "Operator A's customer makes national call to Operator B's customer. In this case operator A will pay some amount to operator B." }, { "code": null, "e": 124030, "s": 123749, "text": "Operator A's customer makes international call through Operator B, because operator A does not have direct agreement with any international operator. In this case, operator A will pay some amount to operator B and operator B will take care of settling down international operator." }, { "code": null, "e": 124311, "s": 124030, "text": "Operator A's customer makes international call through Operator B, because operator A does not have direct agreement with any international operator. In this case, operator A will pay some amount to operator B and operator B will take care of settling down international operator." }, { "code": null, "e": 124482, "s": 124311, "text": "Operator A's customer makes international call directly using an international operator. In this case, operator A will pay some amount to international operator directly." }, { "code": null, "e": 124653, "s": 124482, "text": "Operator A's customer makes international call directly using an international operator. In this case, operator A will pay some amount to international operator directly." }, { "code": null, "e": 124714, "s": 124653, "text": "All the above calls could be voice, SMS, MMS, and data, etc." }, { "code": null, "e": 124879, "s": 124714, "text": "To have a successful interconnection, the following issues should be dealt with in the interconnection agreement or by rule or order from the regulatory authority −" }, { "code": null, "e": 125151, "s": 124879, "text": "Prices and adjustments − This includes the initial level of interconnection charges, a definition of the currency in which interconnection charges are to be paid and how prices will adjust over the term of the agreement to account for exchange rate changes and inflation." }, { "code": null, "e": 125423, "s": 125151, "text": "Prices and adjustments − This includes the initial level of interconnection charges, a definition of the currency in which interconnection charges are to be paid and how prices will adjust over the term of the agreement to account for exchange rate changes and inflation." }, { "code": null, "e": 125592, "s": 125423, "text": "Points of interconnection − The physical locations, where interconnection will take place and the technical standards to be employed in the interconnection are defined." }, { "code": null, "e": 125761, "s": 125592, "text": "Points of interconnection − The physical locations, where interconnection will take place and the technical standards to be employed in the interconnection are defined." }, { "code": null, "e": 125902, "s": 125761, "text": "Transport and traffic routing − Some definition must be made for how calls will be routed and what will be transported to deliver the calls." }, { "code": null, "e": 126043, "s": 125902, "text": "Transport and traffic routing − Some definition must be made for how calls will be routed and what will be transported to deliver the calls." }, { "code": null, "e": 126232, "s": 126043, "text": "Quality of service − Quality standards are defined, particularly for time to provision circuits and for call blocking levels, and remedies are defined for when those standards are not met." }, { "code": null, "e": 126421, "s": 126232, "text": "Quality of service − Quality standards are defined, particularly for time to provision circuits and for call blocking levels, and remedies are defined for when those standards are not met." }, { "code": null, "e": 126571, "s": 126421, "text": "Billing and collection − When and how to collect traffic data, when and how to exchange bills, and when and how to make payment should be specified." }, { "code": null, "e": 126721, "s": 126571, "text": "Billing and collection − When and how to collect traffic data, when and how to exchange bills, and when and how to make payment should be specified." }, { "code": null, "e": 127013, "s": 126721, "text": "Reconciliation − A process for reconciling traffic data and for making inquiries to the other party and for handling claims also should be incorporated. A procedure for resolving discrepancies is useful which often involves seeking recourse to arbitration, the regulator, or to the courts." }, { "code": null, "e": 127305, "s": 127013, "text": "Reconciliation − A process for reconciling traffic data and for making inquiries to the other party and for handling claims also should be incorporated. A procedure for resolving discrepancies is useful which often involves seeking recourse to arbitration, the regulator, or to the courts." }, { "code": null, "e": 127419, "s": 127305, "text": "Numbering Plan − Access of each operator to the country's numbering plan and numbering resources must be defined." }, { "code": null, "e": 127533, "s": 127419, "text": "Numbering Plan − Access of each operator to the country's numbering plan and numbering resources must be defined." }, { "code": null, "e": 127676, "s": 127533, "text": "Traffic Load − Capacity to deliver and receive the traffic that flows between the interconnecting networks should be discussed and documented." }, { "code": null, "e": 127819, "s": 127676, "text": "Traffic Load − Capacity to deliver and receive the traffic that flows between the interconnecting networks should be discussed and documented." }, { "code": null, "e": 127944, "s": 127819, "text": "Operators can have different types of agreements to exchange their traffic. Most commonly used agreements are listed below −" }, { "code": null, "e": 128378, "s": 127944, "text": "Bi-Lateral Agreement − Under this agreement, each party agrees to exchange digital communications traffic with the other party over its Network at the Interconnection Points and/or in one or more direct interconnections. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement. As per this agreement, both the operators can originate and terminate their calls in each other's network." }, { "code": null, "e": 128812, "s": 128378, "text": "Bi-Lateral Agreement − Under this agreement, each party agrees to exchange digital communications traffic with the other party over its Network at the Interconnection Points and/or in one or more direct interconnections. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement. As per this agreement, both the operators can originate and terminate their calls in each other's network." }, { "code": null, "e": 129088, "s": 128812, "text": "Uni-Lateral Agreement − Under this agreement, one party sends his traffic to other party's Network at the Interconnection and does not take traffic back from other party. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement." }, { "code": null, "e": 129364, "s": 129088, "text": "Uni-Lateral Agreement − Under this agreement, one party sends his traffic to other party's Network at the Interconnection and does not take traffic back from other party. Payment settlement among different partners happens on monthly or bi-monthly basis as per the agreement." }, { "code": null, "e": 129652, "s": 129364, "text": "Roaming is the ability for a customer of mobile communications to automatically make and receive telephone calls, send and receive data, or access other services while travelling outside the geographical coverage area of the home network, by means of using a network of another operator." }, { "code": null, "e": 130088, "s": 129652, "text": "Roaming can be either national roaming or international roaming. National roaming means that mobile subscribers make use of another network in geographical areas, where their own operator does not have coverage. This is, for example, used by operators, who do not have complete coverage in a country. International roaming is used when mobile subscribers travel abroad and make use of the network of an operator in the foreign country." }, { "code": null, "e": 130467, "s": 130088, "text": "How does it actually take place? If a service provider does not have a network coverage in a particular city or country, then this service provider makes a roaming agreement with another service provider having network in that city or country. As per this agreement, another service provider provides all the available services to the roaming customer of first service provider." }, { "code": null, "e": 130772, "s": 130467, "text": "CDRs generated in one roaming partner's area are collected and rated by that roaming partner and finally they are sent to the actual service provider of the roaming customer. Actual service provider charges the end customer for all the roaming services provided based on their predefined service charges." }, { "code": null, "e": 130901, "s": 130772, "text": "Two roaming partners settle their financials on monthly basis by exchanging actual roaming CDRs and reports based on those CDRs." }, { "code": null, "e": 131083, "s": 130901, "text": "The Home Public Mobile Network is the network from the operator by which a mobile subscriber has a subscription. The term is used as opposed to Visited Public Mobile Network (VPMN)." }, { "code": null, "e": 131241, "s": 131083, "text": "The Visited Public Mobile Network is the network used by a mobile subscriber while roaming. The term is used as opposed to Home Public Mobile Network (HPMN)." }, { "code": null, "e": 131422, "s": 131241, "text": "There are well known bodies like MACH who interface between different roaming partners to help them to exchange their CDRs, setting up roaming agreements and resolving any dispute." }, { "code": null, "e": 131620, "s": 131422, "text": "Clearing houses receive billing records from one roaming partner for the inbound roamers and submit billing records to another roaming partner for which this roamer would be called outbound roamer." }, { "code": null, "e": 131966, "s": 131620, "text": "Transferred Account Procedure version 3 (TAP3) is the process that allows a visited network operator (VPMN) to send billing records of roaming subscribers to their respective home network operator (HPMN). TAP3 is the latest version of the standard and will enable billing for a host of new services that networks intend to offer their customers." }, { "code": null, "e": 132212, "s": 131966, "text": "Clearing house uses TAP3 protocol to exchange all the CDRs between different roaming partners. TAP3 defines how and what information on roamed usage must be passed between Network Operators. These files are exchanged using simple FTP connection." }, { "code": null, "e": 132438, "s": 132212, "text": "There are different versions of TAP. TAP evolved from TAP1 through TAP2 and TAP2+ to TAP3. The latest release, TAP3, includes support for inter-standard roaming in a satellite network, WLAN and UMTS and other 3G technologies." }, { "code": null, "e": 132736, "s": 132438, "text": "GSM TAP Standard TD.57 − GSM Transferred Account Procedure (TAP) defines the format and validation rules for transferring roaming usage information between mobile operators in different countries. TAP3 is the third specification version of the standard. The files transferred are termed TAP files." }, { "code": null, "e": 133034, "s": 132736, "text": "GSM TAP Standard TD.57 − GSM Transferred Account Procedure (TAP) defines the format and validation rules for transferring roaming usage information between mobile operators in different countries. TAP3 is the third specification version of the standard. The files transferred are termed TAP files." }, { "code": null, "e": 133304, "s": 133034, "text": "GSM RAP Standard TD.32 − GSM Returned Accounts Procedure (RAP) defines the format for returning information on errors found within transferred TAP files/events and thereby rejecting financial liability for those files/events. The files transferred are termed RAP files." }, { "code": null, "e": 133574, "s": 133304, "text": "GSM RAP Standard TD.32 − GSM Returned Accounts Procedure (RAP) defines the format for returning information on errors found within transferred TAP files/events and thereby rejecting financial liability for those files/events. The files transferred are termed RAP files." }, { "code": null, "e": 133932, "s": 133574, "text": "Mobile subscriber travels to another country and creates usage on the foreign network. In order to bill the subscriber, this information has to be passed back to the subscriber's home network. The foreign network will collect information on the usage from it's switches, etc., and then creates TAP files containing the information set out in the standard." }, { "code": null, "e": 134315, "s": 133932, "text": "The files are then EXPORTED (on a regular basis, generally at least one file per day) to the home operator, who will IMPORT them and then use the information to invoice the subscriber. The foreign operator will rate the calls and then charge the subscribers home network for all the calls within a file. The home operator can mark up or re-rate the calls in order to make revenue." }, { "code": null, "e": 134632, "s": 134315, "text": "MVNO stands for Mobile Virtual Network Operator. A mobile virtual network operator (MVNO) is a company that provides mobile phone services, but does not have its own licensed frequency allocation of radio spectrum, nor does it necessarily have all of the infrastructure required to provide mobile telephone service." }, { "code": null, "e": 135026, "s": 134632, "text": "MVNE stands for Mobile Virtual Network Enabler, which is a company that provides services to mobile virtual network operators such as billing, network element provisioning, administration, operations, support of base station subsystems and operations support systems, and provision of back end network elements, to enable provision of mobile network services like cellular phone connectivity." }, { "code": null, "e": 135145, "s": 135026, "text": "An MVNO in reality is a reseller of mobile products and services from an actual operator, but under a different brand." }, { "code": null, "e": 135429, "s": 135145, "text": "For example, there is an operator A having all the infrastructure including network, switches, billing systems, provisioning system and customer care systems, etc. Now, if someone wants to start a telecom business by doing some minimum investment, then MVNO is the option to proceed." }, { "code": null, "e": 135732, "s": 135429, "text": "An MVNO will buy services in bulk from a well-established operator and change the brand name as per their convenience and market those products and services as an operator. Actual operator would remain transparent from the end customer and customer will have feeling like to be an end customer of MVNO." }, { "code": null, "e": 136084, "s": 135732, "text": "Depending on the situation, an MVNO can buy one or more infrastructure components from an operator and pay them accordingly. For example, an MVNO may like to use only network from the operator or an MVNO can use network and charging system from the operator and rest of the components like customer care, provisioning, etc., can be set up by the MVNO." }, { "code": null, "e": 136188, "s": 136084, "text": "MVNO's have full control over the SIM card, branding, marketing, billing, and customer care operations." }, { "code": null, "e": 136350, "s": 136188, "text": "The first commercially successful MVNO in the UK was Virgin Mobile UK, [3] launched in the United Kingdom in 1999 and now has over 4 million customers in the UK." }, { "code": null, "e": 136754, "s": 136350, "text": "MVNOs typically do not have their own infrastructure, but some leading MVNO's deploy their own mobile IN infrastructure in order to facilitate the means to offer value-added services. MNVO's can treat incumbent infrastructure such as radio equipment as a commodity, while the MVNO offers its own advanced and differentiated services based on exploitation of their own intelligent network infrastructure." }, { "code": null, "e": 136929, "s": 136754, "text": "In this way, each MVNO and the network operator could focus on their own niche markets and form customized detailed services that would expand their customer reach and brand." }, { "code": null, "e": 137122, "s": 136929, "text": "Most of the MVNOs come in the market to target only pre-paid customers and provide them only pre-paid services like voice, SMS, MMS, data, broadband, etc., with some nice value-added services." }, { "code": null, "e": 137315, "s": 137122, "text": "Assuming an incumbent operator sells their infrastructure to an MVNO, there could be different business models and agreements between incumbent and MVNO. Following are the most commonly used −" }, { "code": null, "e": 137498, "s": 137315, "text": "MVNO can brand their services and sell them in the market and MVNE will help in providing those services to the end customer. Here, a fixed percent of commission will go to the MVNE." }, { "code": null, "e": 137681, "s": 137498, "text": "MVNO can brand their services and sell them in the market and MVNE will help in providing those services to the end customer. Here, a fixed percent of commission will go to the MVNE." }, { "code": null, "e": 137813, "s": 137681, "text": "MVNO can buy products and services in bulk at special discounted prices and then brand them with their name and sell in the market." }, { "code": null, "e": 137945, "s": 137813, "text": "MVNO can buy products and services in bulk at special discounted prices and then brand them with their name and sell in the market." }, { "code": null, "e": 138071, "s": 137945, "text": "MVNO sells the products and services, and based on the usage generated by the end customers, MVNO pays an amount to the MVNE." }, { "code": null, "e": 138197, "s": 138071, "text": "MVNO sells the products and services, and based on the usage generated by the end customers, MVNO pays an amount to the MVNE." }, { "code": null, "e": 138367, "s": 138197, "text": "In all the cases, MVNO may be required to pay some amount of security deposit to the MVNE and then monthly settlement happens using simple reports generated by the MVNE." }, { "code": null, "e": 138665, "s": 138367, "text": "An MVNE can add an MVNO in its billing system as a corporate customer as long as MVNO is providing post-paid services and can add all the products and services provided to MVNO. By the end of every month or usually after every two weeks, invoice can be generated and collection can be followed up." }, { "code": null, "e": 139042, "s": 138665, "text": "But usually, most of the MVNOs provide pre-paid services, which are handled in Pre-Paid system. In such a case, MVNO functionality is achieved either using built-in functionality in the pre-paid system or by simply defining a separate service class. All the usage CDRs and other information is dumped into data warehouse from where reports can be generated to prepare invoice." }, { "code": null, "e": 139344, "s": 139042, "text": "Assume an operator is providing different services mobile voice, fixed voice, data, IPTV, broadband, pre-paid, and post-paid, etc. A customer can have one or more of these services from the same operator. A typical customer would definitely like to have single invoice and single view of his account." }, { "code": null, "e": 139663, "s": 139344, "text": "A convergent billing is the integration of all service charges onto a single customer invoice and a unified view of the customer. Customer should call a call center and should get complete account information for all the services opted. Customer receives a single bill and makes a single payment for all the services." }, { "code": null, "e": 139890, "s": 139663, "text": "A truly Convergent Billing System should be able to consolidate any number and combination of products and services onto a single bill, regardless of the type of product and market segment, i.e., prepaid and postpaid services." }, { "code": null, "e": 140038, "s": 139890, "text": "Another important parameter contributing in convergent billing is a single product and price catalogue for pre-paid as well as post-paid customers." }, { "code": null, "e": 140122, "s": 140038, "text": "Convergent billing would help operators in achieving the following major benefits −" }, { "code": null, "e": 140223, "s": 140122, "text": "Single product and service catalogue gives better time to market and reduced cost of implementation." }, { "code": null, "e": 140324, "s": 140223, "text": "Single product and service catalogue gives better time to market and reduced cost of implementation." }, { "code": null, "e": 140452, "s": 140324, "text": "A unified bill enables cross-service discounts, so that customers who order multiple services can receive preferential pricing." }, { "code": null, "e": 140580, "s": 140452, "text": "A unified bill enables cross-service discounts, so that customers who order multiple services can receive preferential pricing." }, { "code": null, "e": 140766, "s": 140580, "text": "Convergent billing enables multi-service packaging and pricing, whereby existing customers are enticed to add new services and new customers are attracted by innovative service bundles." }, { "code": null, "e": 140952, "s": 140766, "text": "Convergent billing enables multi-service packaging and pricing, whereby existing customers are enticed to add new services and new customers are attracted by innovative service bundles." }, { "code": null, "e": 141044, "s": 140952, "text": "Centralized customer care and support for both type of customers ( pre-paid and post-paid)." }, { "code": null, "e": 141136, "s": 141044, "text": "Centralized customer care and support for both type of customers ( pre-paid and post-paid)." }, { "code": null, "e": 141413, "s": 141136, "text": "So far, it has been a dream of all the big telecom operators to achieve true convergence. May be tomorrow some billing system would come which will support true convergence of all the product and services, but today it has the following obstacles to achieve real convergence −" }, { "code": null, "e": 141817, "s": 141413, "text": "Real time Charging Systems like Ericsson IN or Nokia Siemens Charging System are very popular systems to provide solution for pre-paid product and services. These systems are not flexible enough to handle various functionalities required for post-paid customers for example: complex customer hierarchies, CDR re-rating, volume discounts, flexible reporting, roaming charging, interconnect charging, etc." }, { "code": null, "e": 142221, "s": 141817, "text": "Real time Charging Systems like Ericsson IN or Nokia Siemens Charging System are very popular systems to provide solution for pre-paid product and services. These systems are not flexible enough to handle various functionalities required for post-paid customers for example: complex customer hierarchies, CDR re-rating, volume discounts, flexible reporting, roaming charging, interconnect charging, etc." }, { "code": null, "e": 142529, "s": 142221, "text": "Post paid billing systems like Convergys Infinys or Amdocs Billing Systems are great for post-paid product and services. These systems are not capable to handle pre-paid traffic and charge the calls in real time. Importantly these systems can not be made highly available because of their base architecture." }, { "code": null, "e": 142837, "s": 142529, "text": "Post paid billing systems like Convergys Infinys or Amdocs Billing Systems are great for post-paid product and services. These systems are not capable to handle pre-paid traffic and charge the calls in real time. Importantly these systems can not be made highly available because of their base architecture." }, { "code": null, "e": 143250, "s": 142837, "text": "Keeping the two above-mentioned constraints together, if we merge both the systems by doing a kind of interfacing between pre-paid and post-paid systems, then it may be possible to achieve a true convergence. Companies like Convergys and Ericsson are working in the same direction to merge the two systems and use required functionalities from both type of systems and make them single Convergent Billing System." }, { "code": null, "e": 143608, "s": 143250, "text": "Support and maintenance is an integral and the most important part of a telecom operation. Customer satisfaction directly depends on how efficient and how good support is being provided to them. If customer is being put in the loop and he is not getting good response for the problem/issue raised, simply customer would switch to another available operator." }, { "code": null, "e": 143667, "s": 143608, "text": "Support and maintenance covers the following major areas −" }, { "code": null, "e": 144005, "s": 143667, "text": "System support and maintenance − This includes keeping the BSS (Business Support Systems) and OSS (Operation Support Systems) running in good health. If there is any issue in any of the systems ( Billing, Provisioning, Network, Mediation, Customer Care, etc.,), then it is looked by the specialists and fixed within a minimum time frame." }, { "code": null, "e": 144343, "s": 144005, "text": "System support and maintenance − This includes keeping the BSS (Business Support Systems) and OSS (Operation Support Systems) running in good health. If there is any issue in any of the systems ( Billing, Provisioning, Network, Mediation, Customer Care, etc.,), then it is looked by the specialists and fixed within a minimum time frame." }, { "code": null, "e": 144670, "s": 144343, "text": "Customer Support − This includes fixing all the issues related to customers. A customer complains through customer care or call center and then issue flows at different stages. This issue could be related to signals, call drop, voice or data download quality, wrong bill, some dispute, service activation, or termination, etc." }, { "code": null, "e": 144997, "s": 144670, "text": "Customer Support − This includes fixing all the issues related to customers. A customer complains through customer care or call center and then issue flows at different stages. This issue could be related to signals, call drop, voice or data download quality, wrong bill, some dispute, service activation, or termination, etc." }, { "code": null, "e": 145330, "s": 144997, "text": "System upgrades − This includes upgrading an existing system with the latest version to provide more stability and flexibility in the business. New version of any system comes along with new features to cater new business requirements. This also includes hardware upgrade to maintain system performance and for more storage as well." }, { "code": null, "e": 145663, "s": 145330, "text": "System upgrades − This includes upgrading an existing system with the latest version to provide more stability and flexibility in the business. New version of any system comes along with new features to cater new business requirements. This also includes hardware upgrade to maintain system performance and for more storage as well." }, { "code": null, "e": 145885, "s": 145663, "text": "There are always different levels of support kept in place by the service providers. These levels handle different types of issues depending on their nature and severity. Most commonly used support levels are as follows −" }, { "code": null, "e": 146343, "s": 145885, "text": "Level 1 − Customer contacts the customer support, which could be a call center and customer support specialist listens to customer problem and suggests a solution on the spot. For example, there could be some problems, which can be resolved by simply restarting the phone. So, an efficient customer care specialist knows about such type of problems and can suggest a solution without escalating the issue (usually called a trouble ticket) to the next level." }, { "code": null, "e": 146801, "s": 146343, "text": "Level 1 − Customer contacts the customer support, which could be a call center and customer support specialist listens to customer problem and suggests a solution on the spot. For example, there could be some problems, which can be resolved by simply restarting the phone. So, an efficient customer care specialist knows about such type of problems and can suggest a solution without escalating the issue (usually called a trouble ticket) to the next level." }, { "code": null, "e": 147387, "s": 146801, "text": "Level 2 − If a customer care specialist is not able to resolve a problem, then issue is escalated to second level support, which is a group of technical specialists. These specialists belong to Information Technology (IT) department, and if they are able to understand the problem, then they can suggest a solution and send the issue back to level 1, otherwise they check the nature of issue to understand if issue is related to network or billing system or provisioning system or hardware, etc., and based on the nature of the issue, issue is assigned to next level, i.e., department." }, { "code": null, "e": 147973, "s": 147387, "text": "Level 2 − If a customer care specialist is not able to resolve a problem, then issue is escalated to second level support, which is a group of technical specialists. These specialists belong to Information Technology (IT) department, and if they are able to understand the problem, then they can suggest a solution and send the issue back to level 1, otherwise they check the nature of issue to understand if issue is related to network or billing system or provisioning system or hardware, etc., and based on the nature of the issue, issue is assigned to next level, i.e., department." }, { "code": null, "e": 148630, "s": 147973, "text": "Level 3 − These are different departments specialized in their areas like core engineering, radio planning, billing, provisioning, order management, etc. If issue is escalated to them, then they analyze the problem and try to find out the root cause of the problem. Most of the times, issue will be diagnosed and fixed by third level support because they are highly skilled engineers specialized in their area. There may be situation, when issue cannot be fixed at 3rd level support because it may be related to core functionality of the system, which is not modifiable by 3rd level support. In such a case, issue is further escalated to 4th level support." }, { "code": null, "e": 149287, "s": 148630, "text": "Level 3 − These are different departments specialized in their areas like core engineering, radio planning, billing, provisioning, order management, etc. If issue is escalated to them, then they analyze the problem and try to find out the root cause of the problem. Most of the times, issue will be diagnosed and fixed by third level support because they are highly skilled engineers specialized in their area. There may be situation, when issue cannot be fixed at 3rd level support because it may be related to core functionality of the system, which is not modifiable by 3rd level support. In such a case, issue is further escalated to 4th level support." }, { "code": null, "e": 149774, "s": 149287, "text": "Level 4 − These are actual vendors of the systems supporting business, for example, billing system, network switch, provisioning system, etc. So, if issue is found to be related to the core functionality of billing system, for example, billing system is not able to apply correct discount, then it would be escalated to the billing system vendor, and if issue is related to the core functionality of the provisioning system, then it would be escalated to the provisioning system vendor." }, { "code": null, "e": 150261, "s": 149774, "text": "Level 4 − These are actual vendors of the systems supporting business, for example, billing system, network switch, provisioning system, etc. So, if issue is found to be related to the core functionality of billing system, for example, billing system is not able to apply correct discount, then it would be escalated to the billing system vendor, and if issue is related to the core functionality of the provisioning system, then it would be escalated to the provisioning system vendor." }, { "code": null, "e": 150438, "s": 150261, "text": "Support departments always work with a predefined service level agreement called SLA. These SLAs are defined and kept in place keeping various parameters in mind. For example −" }, { "code": null, "e": 150481, "s": 150438, "text": "Severity of the issue or operational task." }, { "code": null, "e": 150524, "s": 150481, "text": "Severity of the issue or operational task." }, { "code": null, "e": 150574, "s": 150524, "text": "Business impact of the issue or operational task." }, { "code": null, "e": 150624, "s": 150574, "text": "Business impact of the issue or operational task." }, { "code": null, "e": 150712, "s": 150624, "text": "Whether issue or operational task is impacting a single customer or multiple customers." }, { "code": null, "e": 150800, "s": 150712, "text": "Whether issue or operational task is impacting a single customer or multiple customers." }, { "code": null, "e": 150900, "s": 150800, "text": "Whether the issue or operational task is directly related to revenue loss or customer satisfaction." }, { "code": null, "e": 151000, "s": 150900, "text": "Whether the issue or operational task is directly related to revenue loss or customer satisfaction." }, { "code": null, "e": 151238, "s": 151000, "text": "Based on such type of parameters, different priorities are defined and assigned to different issues or operational tasks. Operational task could be report generation, invoice generation, database cleanup activities, or backup activities." }, { "code": null, "e": 151659, "s": 151238, "text": "Finally, each issue and operational task comes along with an assigned priority and each priority will have associated SLA. For example, if there is a problem in creating customer order, then it would be assumed a high priority issue because it is directly impacting business. Such type of issues need to be resolved as soon as possible by the assigned department. So, a very tight SLA is defined for high priority issue." }, { "code": null, "e": 151803, "s": 151659, "text": "SLAs are discussed and finalized with mutual agreement keeping business need on top priority. Usually, an SLA keeps the following information −" }, { "code": null, "e": 152001, "s": 151803, "text": "Parameters to qualify the nature of the issue whether it is priority 1st issue or 2nd priority issue or 3rd or 4th priority issue. Lower the priority number, higher is the criticality of the issue." }, { "code": null, "e": 152199, "s": 152001, "text": "Parameters to qualify the nature of the issue whether it is priority 1st issue or 2nd priority issue or 3rd or 4th priority issue. Lower the priority number, higher is the criticality of the issue." }, { "code": null, "e": 152292, "s": 152199, "text": "For a given type of priority and severity, how much time it would take to resolve the issue." }, { "code": null, "e": 152385, "s": 152292, "text": "For a given type of priority and severity, how much time it would take to resolve the issue." }, { "code": null, "e": 152446, "s": 152385, "text": "In case of failure of an SLA, what penalty would be applied." }, { "code": null, "e": 152507, "s": 152446, "text": "In case of failure of an SLA, what penalty would be applied." }, { "code": null, "e": 152563, "s": 152507, "text": "Contact points of escalation for each level of support." }, { "code": null, "e": 152619, "s": 152563, "text": "Contact points of escalation for each level of support." }, { "code": null, "e": 152682, "s": 152619, "text": "Process flow and communication medium during issue resolution." }, { "code": null, "e": 152745, "s": 152682, "text": "Process flow and communication medium during issue resolution." }, { "code": null, "e": 152827, "s": 152745, "text": "Infrastructure availability and other constraints impacting the issue resolution." }, { "code": null, "e": 152909, "s": 152827, "text": "Infrastructure availability and other constraints impacting the issue resolution." }, { "code": null, "e": 153056, "s": 152909, "text": "SLAs can be defined between different departments, between vendor and operator and between different operators as well in case of interconnection." }, { "code": null, "e": 153232, "s": 153056, "text": "The following diagram shows a typical architecture of a Billing System. This chapter will give a brief introduction of all the interfacing systems starting from top to bottom." }, { "code": null, "e": 153444, "s": 153232, "text": "This is the first system from where a customer order is captured and customer is created into the system. CRM stand for Customer Relationship Management and OMOF stands for Order Management and Order Fulfilment." }, { "code": null, "e": 153700, "s": 153444, "text": "There are systems like Siebel, which provides modules for CRM as well as OMOF. The CRM system keeps customer-related information along with product and services. The OMOF module is responsible to track order starting from its creation till its completion." }, { "code": null, "e": 153734, "s": 153700, "text": "Here, we have two possibilities −" }, { "code": null, "e": 154020, "s": 153734, "text": "CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 154306, "s": 154020, "text": "CRM (Customer Relationship Management)/OMOF (Order Management and Order Fulfilment) system contacts with the billing system and billing system contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 154505, "s": 154306, "text": "Second possibility could be that CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 154704, "s": 154505, "text": "Second possibility could be that CRM/OMOF system itself contacts with provisioning system to provision the services and network inventory system as well to assign phone numbers or IP addresses, etc." }, { "code": null, "e": 154917, "s": 154704, "text": "This system takes commands either from the Billing System or CRM/OMOF System to activate, deactivate and suspend the services. Both the architectures are valid and depend on how architect designs the whole setup." }, { "code": null, "e": 155205, "s": 154917, "text": "After taking provisioning commands, this system contacts with core network system to activate, deactivate or suspend the services. After a successful provisioning, this system sends a response back to either the Billing System or the CRM system depending on who sent it the last command." }, { "code": null, "e": 155376, "s": 155205, "text": "This system maintains all the network identifiers like phone numbers, MSISDN, IP addresses, e-mail addresses, etc., and technically it is called Network Inventory System." }, { "code": null, "e": 155563, "s": 155376, "text": "Depending on the system architecture, either CRM/OMOF or Billing System contacts NIS to obtain a required network identifier and assigns it to the customer at the time of order creation." }, { "code": null, "e": 155779, "s": 155563, "text": "This system is responsible to maintain the life cycle of network identifiers, which starts with available and then flows through different stages like activation, suspend, terminate, quarantine, and again available." }, { "code": null, "e": 156123, "s": 155779, "text": "Generally, Billing System does not interact with network switches. Network switches are responsible to provide all the services to the end customers based on what services have been provisioned for the customer. These systems are responsible for controlling calls, data download, SMS transfer, etc., and finally generating Call Detail Records." }, { "code": null, "e": 156271, "s": 156123, "text": "Network Switches include MSC, SMSC, GGSN and MMSC. For more information on GSM, MSC, SMS, SMSC, GGSN, MMS, MMSC, please refer to our GSM tutorials." }, { "code": null, "e": 156484, "s": 156271, "text": "The Mediation System collects CDRs from different network elements in different formats. Various network elements generate CDRs in ASN.1 format and some network elements have their own proprietary format of CDRs." }, { "code": null, "e": 156880, "s": 156484, "text": "The Mediation System processes all the CDRs and converts them into a format compatible to the downstream system, which is usually a Billing System. The Mediation System applies various rules on CDRs to process them; for example, mediation system marks the international calls based on the dialed number (B-Number), same way mediation system marks the on-net calls based on A-Number and B-Number." }, { "code": null, "e": 157282, "s": 156880, "text": "There may be a requirement to filter out all the calls, which are having call duration less than 5 seconds, the best place to filter out such type of calls will be at Mediation System level. Same way, if some extra information is required in the CDRs, which is critical to billing, then Mediation System will help in providing such information based on some other attributes available within the CDRs." }, { "code": null, "e": 157463, "s": 157282, "text": "Once the collected CDRs are processed, Mediation System pushes all the CDRs to the Billing System using FTP because usually Mediation and Billing systems run on different machines." }, { "code": null, "e": 157746, "s": 157463, "text": "This is a downstream system for the Billing System and usually keeps tons of historical data related to the customers. Billing System dumps various customer information into the DWH system. This information includes service usage, invoices, payments, discounts and adjustments, etc." }, { "code": null, "e": 157867, "s": 157746, "text": "All this information is used to generate various types of management reports and for business intelligence and forecast." }, { "code": null, "e": 158083, "s": 157867, "text": "DWH system is always meant to work on bulk and huge data, and if there is a need for any small report, then it is always worth to generate it from the billing system directly instead of abusing DWH for a small task." }, { "code": null, "e": 158217, "s": 158083, "text": "An Enterprise Resource Planning (ERP) system provides modules to handle Financials, Human Resources and Supply Chain Management, etc." }, { "code": null, "e": 158348, "s": 158217, "text": "Billing System interface with this system is used to post all the financial transactions like invoices, payments, and adjustments." }, { "code": null, "e": 158491, "s": 158348, "text": "This system works like a general ledger for the finance department and gives complete revenue information at any point in time it is required." }, { "code": null, "e": 158719, "s": 158491, "text": "As such, this is not necessarily a complete system, but it could be a kind of custom component, which sits in between the Billing System and different payment channels like banks, credit card gateway, shops, and retailers, etc." }, { "code": null, "e": 158837, "s": 158719, "text": "All the payment channels use payment gateway to post payments to the billing system to settle down customer invoices." }, { "code": null, "e": 159051, "s": 158837, "text": "Usually, Payment gateway exposes a kind of API (Application Programming Interface) to the outside world to post the payments to the Billing System. The API can be used by any external resource to post the payment." }, { "code": null, "e": 159058, "s": 159051, "text": " Print" }, { "code": null, "e": 159069, "s": 159058, "text": " Add Notes" } ]
How to perform jQuery Callback after submitting the form ?
23 Apr, 2020 The after-form-submit is the set of code that is executed after a submit button is fired. Usually, it is used to blank out the form, once the submit is given. For Example, When the login credentials are wrong, the input becomes blank in the form. Approach: First, the elements in a form must be ensured if it is loaded.Then, the submit method is added a callback function.Once the submit button is clicked, it should prevent successive callbacks.Followed by that, a timeout is given because of a need for delay. If there is no delay, the actions that should happen after would happen at the beginning itself. Like before validating the password, the input form shouldn’t blank out.Then the actions that need to be performed are given at the end. First, the elements in a form must be ensured if it is loaded. Then, the submit method is added a callback function. Once the submit button is clicked, it should prevent successive callbacks. Followed by that, a timeout is given because of a need for delay. If there is no delay, the actions that should happen after would happen at the beginning itself. Like before validating the password, the input form shouldn’t blank out. Then the actions that need to be performed are given at the end. How to implement in Javascript ? A callback to the jQuery method can be done using the submit button.Once the submit button of the form is clicked, the callback function is fired. But, before that, the DOM (document object manipulation) must be loaded. Once the DOM is loaded, it then calls any of these methods. ( window.on(‘load’) or document.ready() or window.ready() can be used).The preventDefault() method prevents the method from firing multiple times.We use setTimeout method to perform after submit with few milliseconds. A callback to the jQuery method can be done using the submit button. Once the submit button of the form is clicked, the callback function is fired. But, before that, the DOM (document object manipulation) must be loaded. Once the DOM is loaded, it then calls any of these methods. ( window.on(‘load’) or document.ready() or window.ready() can be used). The preventDefault() method prevents the method from firing multiple times. We use setTimeout method to perform after submit with few milliseconds. Note: The window.ready() method is called when all the resources are loaded and document.ready() method is called when DOM is loaded. Example: <!DOCTYPE html><html> <head> <title> How to perform jQuery Callback after submitting the form ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(window).ready(function () { $("form").submit(function (e) { e.preventDefault(); var name = $("#name").val(); setTimeout(function () { console.log("After timeout"); $('#name').val(''); }, 100); alert(name + " has submitted"); }) }) </script></head> <body> <form action=""> <input type="text" id="name"> <input type="submit"> </form></body> </html> Output: This form submit method triggers the callback method, which at first prevents further callbacks. Then after a time interval of 100 milliseconds, the alert method is called with the text input value. HTML-Misc jQuery-Misc Picked HTML JavaScript JQuery Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2020" }, { "code": null, "e": 275, "s": 28, "text": "The after-form-submit is the set of code that is executed after a submit button is fired. Usually, it is used to blank out the form, once the submit is given. For Example, When the login credentials are wrong, the input becomes blank in the form." }, { "code": null, "e": 285, "s": 275, "text": "Approach:" }, { "code": null, "e": 774, "s": 285, "text": "First, the elements in a form must be ensured if it is loaded.Then, the submit method is added a callback function.Once the submit button is clicked, it should prevent successive callbacks.Followed by that, a timeout is given because of a need for delay. If there is no delay, the actions that should happen after would happen at the beginning itself. Like before validating the password, the input form shouldn’t blank out.Then the actions that need to be performed are given at the end." }, { "code": null, "e": 837, "s": 774, "text": "First, the elements in a form must be ensured if it is loaded." }, { "code": null, "e": 891, "s": 837, "text": "Then, the submit method is added a callback function." }, { "code": null, "e": 966, "s": 891, "text": "Once the submit button is clicked, it should prevent successive callbacks." }, { "code": null, "e": 1202, "s": 966, "text": "Followed by that, a timeout is given because of a need for delay. If there is no delay, the actions that should happen after would happen at the beginning itself. Like before validating the password, the input form shouldn’t blank out." }, { "code": null, "e": 1267, "s": 1202, "text": "Then the actions that need to be performed are given at the end." }, { "code": null, "e": 1300, "s": 1267, "text": "How to implement in Javascript ?" }, { "code": null, "e": 1798, "s": 1300, "text": "A callback to the jQuery method can be done using the submit button.Once the submit button of the form is clicked, the callback function is fired. But, before that, the DOM (document object manipulation) must be loaded. Once the DOM is loaded, it then calls any of these methods. ( window.on(‘load’) or document.ready() or window.ready() can be used).The preventDefault() method prevents the method from firing multiple times.We use setTimeout method to perform after submit with few milliseconds." }, { "code": null, "e": 1867, "s": 1798, "text": "A callback to the jQuery method can be done using the submit button." }, { "code": null, "e": 2151, "s": 1867, "text": "Once the submit button of the form is clicked, the callback function is fired. But, before that, the DOM (document object manipulation) must be loaded. Once the DOM is loaded, it then calls any of these methods. ( window.on(‘load’) or document.ready() or window.ready() can be used)." }, { "code": null, "e": 2227, "s": 2151, "text": "The preventDefault() method prevents the method from firing multiple times." }, { "code": null, "e": 2299, "s": 2227, "text": "We use setTimeout method to perform after submit with few milliseconds." }, { "code": null, "e": 2433, "s": 2299, "text": "Note: The window.ready() method is called when all the resources are loaded and document.ready() method is called when DOM is loaded." }, { "code": null, "e": 2442, "s": 2433, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to perform jQuery Callback after submitting the form ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(window).ready(function () { $(\"form\").submit(function (e) { e.preventDefault(); var name = $(\"#name\").val(); setTimeout(function () { console.log(\"After timeout\"); $('#name').val(''); }, 100); alert(name + \" has submitted\"); }) }) </script></head> <body> <form action=\"\"> <input type=\"text\" id=\"name\"> <input type=\"submit\"> </form></body> </html>", "e": 3207, "s": 2442, "text": null }, { "code": null, "e": 3215, "s": 3207, "text": "Output:" }, { "code": null, "e": 3414, "s": 3215, "text": "This form submit method triggers the callback method, which at first prevents further callbacks. Then after a time interval of 100 milliseconds, the alert method is called with the text input value." }, { "code": null, "e": 3424, "s": 3414, "text": "HTML-Misc" }, { "code": null, "e": 3436, "s": 3424, "text": "jQuery-Misc" }, { "code": null, "e": 3443, "s": 3436, "text": "Picked" }, { "code": null, "e": 3448, "s": 3443, "text": "HTML" }, { "code": null, "e": 3459, "s": 3448, "text": "JavaScript" }, { "code": null, "e": 3466, "s": 3459, "text": "JQuery" }, { "code": null, "e": 3483, "s": 3466, "text": "Web Technologies" }, { "code": null, "e": 3510, "s": 3483, "text": "Web technologies Questions" }, { "code": null, "e": 3526, "s": 3510, "text": "Write From Home" }, { "code": null, "e": 3531, "s": 3526, "text": "HTML" } ]
How to enable Button based on If statement in React.js ?
09 Oct, 2020 In order to display the button conditionally using the if and else statement, we can use state in react.js. Declare the state in the constructor method because it loads first when the component is loaded. In order to toggle between user and admin, we need to use an event handler. Using this event handler, we can toggle the state of the user. Below is the implementation of the code for displaying it. Example: demo.js: JavascriptJavascriptimport React, {Component} from 'react' class DemoUser extends Component { constructor(){ super() this.state = { isAdmin: true } this.toggleState = this.toggleState.bind(this); } toggleState() { this.setState ({ isAdmin:!this.state.isAdmin } ) } render(){ if(this.state.isAdmin){ return( <div> <h3> Welcome Admin </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } else{ return( <div> <h3> Welcome User </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } } } export default DemoUser demo.js: Javascript import React, {Component} from 'react' class DemoUser extends Component { constructor(){ super() this.state = { isAdmin: true } this.toggleState = this.toggleState.bind(this); } toggleState() { this.setState ({ isAdmin:!this.state.isAdmin } ) } render(){ if(this.state.isAdmin){ return( <div> <h3> Welcome Admin </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } else{ return( <div> <h3> Welcome User </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } } } export default DemoUser index.js:JavascriptJavascriptimport React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker';import DemoUser from './demo' ReactDOM.render( <React.StrictMode> <DemoUser /> </React.StrictMode>, document.getElementById('root')); serviceWorker.unregister(); index.js: Javascript import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker';import DemoUser from './demo' ReactDOM.render( <React.StrictMode> <DemoUser /> </React.StrictMode>, document.getElementById('root')); serviceWorker.unregister(); Output: Picked react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Oct, 2020" }, { "code": null, "e": 432, "s": 28, "text": "In order to display the button conditionally using the if and else statement, we can use state in react.js. Declare the state in the constructor method because it loads first when the component is loaded. In order to toggle between user and admin, we need to use an event handler. Using this event handler, we can toggle the state of the user. Below is the implementation of the code for displaying it. " }, { "code": null, "e": 442, "s": 432, "text": "Example: " }, { "code": null, "e": 1401, "s": 442, "text": "demo.js: JavascriptJavascriptimport React, {Component} from 'react' class DemoUser extends Component { constructor(){ super() this.state = { isAdmin: true } this.toggleState = this.toggleState.bind(this); } toggleState() { this.setState ({ isAdmin:!this.state.isAdmin } ) } render(){ if(this.state.isAdmin){ return( <div> <h3> Welcome Admin </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } else{ return( <div> <h3> Welcome User </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } } } export default DemoUser" }, { "code": null, "e": 1411, "s": 1401, "text": "demo.js: " }, { "code": null, "e": 1422, "s": 1411, "text": "Javascript" }, { "code": "import React, {Component} from 'react' class DemoUser extends Component { constructor(){ super() this.state = { isAdmin: true } this.toggleState = this.toggleState.bind(this); } toggleState() { this.setState ({ isAdmin:!this.state.isAdmin } ) } render(){ if(this.state.isAdmin){ return( <div> <h3> Welcome Admin </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } else{ return( <div> <h3> Welcome User </h3><span > Is the user admin : {this.state.isAdmin.toString()}</span> <br/> <button onClick={this.toggleState}> Toggle between user and admin </button> </div> ) } } } export default DemoUser", "e": 2352, "s": 1422, "text": null }, { "code": null, "e": 2708, "s": 2352, "text": "index.js:JavascriptJavascriptimport React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker';import DemoUser from './demo' ReactDOM.render( <React.StrictMode> <DemoUser /> </React.StrictMode>, document.getElementById('root')); serviceWorker.unregister();" }, { "code": null, "e": 2718, "s": 2708, "text": "index.js:" }, { "code": null, "e": 2729, "s": 2718, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker';import DemoUser from './demo' ReactDOM.render( <React.StrictMode> <DemoUser /> </React.StrictMode>, document.getElementById('root')); serviceWorker.unregister();", "e": 3056, "s": 2729, "text": null }, { "code": null, "e": 3065, "s": 3056, "text": "Output: " }, { "code": null, "e": 3072, "s": 3065, "text": "Picked" }, { "code": null, "e": 3081, "s": 3072, "text": "react-js" }, { "code": null, "e": 3098, "s": 3081, "text": "Web Technologies" } ]
Python | sympy.isprime() method
25 Aug, 2021 In simpy module, we can test whether a given number n is prime or not using sympy.isprime() function. For n < 2^64 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. Note that Negative numbers (e.g. -13) are not considered as prime number. Syntax: sympy.isprime() Parameter: n; number to be tested Return: bool value result Code #1: Python3 # Python program to check prime number# using sympy.isprime() method # importing sympy modulefrom sympy import * # calling isprime function on different numbersisprime(30)isprime(13)isprime(2) Output: False True True Code #2: Python3 # Python program to check prime number# using sympy.isprime() method # importing sympy moduleimport sympy.ntheory as nt # calling isprime function on different numbersnt.isprime(30)nt.isprime(13)nt.isprime(2) Output: False True True anikakapoor SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 243, "s": 28, "text": "In simpy module, we can test whether a given number n is prime or not using sympy.isprime() function. For n < 2^64 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. " }, { "code": null, "e": 317, "s": 243, "text": "Note that Negative numbers (e.g. -13) are not considered as prime number." }, { "code": null, "e": 405, "s": 317, "text": "Syntax: sympy.isprime()\nParameter: n; number to be tested\nReturn: bool value result " }, { "code": null, "e": 416, "s": 405, "text": "Code #1: " }, { "code": null, "e": 424, "s": 416, "text": "Python3" }, { "code": "# Python program to check prime number# using sympy.isprime() method # importing sympy modulefrom sympy import * # calling isprime function on different numbersisprime(30)isprime(13)isprime(2)", "e": 617, "s": 424, "text": null }, { "code": null, "e": 626, "s": 617, "text": "Output: " }, { "code": null, "e": 642, "s": 626, "text": "False\nTrue\nTrue" }, { "code": null, "e": 653, "s": 642, "text": "Code #2: " }, { "code": null, "e": 661, "s": 653, "text": "Python3" }, { "code": "# Python program to check prime number# using sympy.isprime() method # importing sympy moduleimport sympy.ntheory as nt # calling isprime function on different numbersnt.isprime(30)nt.isprime(13)nt.isprime(2)", "e": 870, "s": 661, "text": null }, { "code": null, "e": 879, "s": 870, "text": "Output: " }, { "code": null, "e": 895, "s": 879, "text": "False\nTrue\nTrue" }, { "code": null, "e": 909, "s": 897, "text": "anikakapoor" }, { "code": null, "e": 915, "s": 909, "text": "SymPy" }, { "code": null, "e": 922, "s": 915, "text": "Python" } ]
Normalizing Textual Data with Python
07 Jul, 2021 In this article, we will learn How to Normalizing Textual Data with Python. Let’s discuss some concepts : Textual data ask systematically collected material consisting of written, printed, or electronically published words, typically either purposefully written or transcribed from speech. Text normalization is that the method of transforming text into one canonical form that it’d not have had before. Normalizing text before storing or processing it allows for separation of concerns since the input is sure to be consistent before operations are performed thereon. Text normalization requires being conscious of what sort of text is to be normalized and the way it’s to be processed afterwards; there’s no all-purpose normalization procedure. Steps Required Here, we will discuss some basic steps need for Text normalization. Input text String, Convert all letters of the string to one case(either lower or upper case), If numbers are essential to convert to words else remove all numbers, Remove punctuations, other formalities of grammar, Remove white spaces, Remove stop words, And any other computations. We are doing Text normalization with above-mentioned steps, every step can be done in some ways. So we will discuss each and everything in this whole process. Text String Python3 # input stringstring = " Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows)."print(string) Output: ” Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2’s end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).” Case Conversion (Lower Case) In Python, lower() is a built-in method used for string handling. The lower() methods returns the lowercased string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string. Python3 # input stringstring = " Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows)." # convert to lower caselower_string = string.lower()print(lower_string) Output: ” python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much python 2 code does not run unmodified on python 3. with python 2’s end-of-life, only python 3.6.x[30] and later are supported, with older versions still supporting e.g. windows 7 (and old installers not restricted to 64-bit windows).” Removing Numbers Remove numbers if they’re not relevant to your analyses. Usually, regular expressions are used to remove numbers. Python3 # import regeximport re # input stringstring = " Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows)." # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\d+','',lower_string)print(no_number_string) Output: ” python ., released in , was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python . with python ‘s end-of-life, only python ..x[] and later are supported, with older versions still supporting e.g. windows (and old installers not restricted to -bit windows).” Removing punctuation The part of replacing with punctuation can also be performed using regex. In this, we replace all punctuation by empty string using certain regex. Python3 # import regeximport re # input stringstring = " Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows)." # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\d+','',lower_string) # remove all punctuation except words and spaceno_punc_string = re.sub(r'[^\w\s]','', no_number_string)print(no_punc_string) Output: ‘ python released in was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python with python s endoflife only python x and later are supported with older versions still supporting eg windows and old installers not restricted to bit windows’ Removing White space The strip() function is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). Python3 # import regeximport re # input stringstring = " Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows)." # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\d+','',lower_string) # remove all punctuation except words and spaceno_punc_string = re.sub(r'[^\w\s]','', no_number_string) # remove white spacesno_wspace_string = no_punc_string.strip()print(no_wspace_string) Output: ‘python released in was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python with python s endoflife only python x and later are supported with older versions still supporting eg windows and old installers not restricted to bit windows’ Removing Stop Words Stop words” are the foremost common words during a language like “the”, “a”, “on”, “is”, “all”. These words don’t carry important meaning and are usually faraway from texts. It is possible to get rid of stop words using tongue Toolkit (NLTK), a set of libraries and programs for symbolic and statistical tongue processing. Python3 # download stpwordsimport nltknltk.download('stopwords') # import nltk for stopwordsfrom nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))print(stop_words) # assign stringno_wspace_string='python released in was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python with python s endoflife only python x and later are supported with older versions still supporting eg windows and old installers not restricted to bit windows' # convert string to list of wordslst_string = [no_wspace_string][0].split()print(lst_string) # remove stopwordsno_stpwords_string=""for i in lst_string: if not i in stop_words: no_stpwords_string += i+' ' # removing last spaceno_stpwords_string = no_stpwords_string[:-1]print(no_stpwords_string) Output: In this, we can normalize the textual data using Python. Below is the complete python program: Python3 # import regeximport re # download stpwordsimport nltknltk.download('stopwords') # import nltk for stopwordsfrom nltk.corpus import stopwordsstop_words = set(stopwords.words('english')) # input stringstring = " Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows)." # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\d+','',lower_string) # remove all punctuation except words and spaceno_punc_string = re.sub(r'[^\w\s]','', no_number_string) # remove white spacesno_wspace_string = no_punc_string.strip()no_wspace_string # convert string to list of wordslst_string = [no_wspace_string][0].split()print(lst_string) # remove stopwordsno_stpwords_string=""for i in lst_string: if not i in stop_words: no_stpwords_string += i+' ' # removing last spaceno_stpwords_string = no_stpwords_string[:-1] # outputprint(no_stpwords_string) Output: adnanirshad158 Picked python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2021" }, { "code": null, "e": 134, "s": 28, "text": "In this article, we will learn How to Normalizing Textual Data with Python. Let’s discuss some concepts :" }, { "code": null, "e": 318, "s": 134, "text": "Textual data ask systematically collected material consisting of written, printed, or electronically published words, typically either purposefully written or transcribed from speech." }, { "code": null, "e": 775, "s": 318, "text": "Text normalization is that the method of transforming text into one canonical form that it’d not have had before. Normalizing text before storing or processing it allows for separation of concerns since the input is sure to be consistent before operations are performed thereon. Text normalization requires being conscious of what sort of text is to be normalized and the way it’s to be processed afterwards; there’s no all-purpose normalization procedure." }, { "code": null, "e": 790, "s": 775, "text": "Steps Required" }, { "code": null, "e": 858, "s": 790, "text": "Here, we will discuss some basic steps need for Text normalization." }, { "code": null, "e": 877, "s": 858, "text": "Input text String," }, { "code": null, "e": 952, "s": 877, "text": "Convert all letters of the string to one case(either lower or upper case)," }, { "code": null, "e": 1022, "s": 952, "text": "If numbers are essential to convert to words else remove all numbers," }, { "code": null, "e": 1073, "s": 1022, "text": "Remove punctuations, other formalities of grammar," }, { "code": null, "e": 1094, "s": 1073, "text": "Remove white spaces," }, { "code": null, "e": 1113, "s": 1094, "text": "Remove stop words," }, { "code": null, "e": 1141, "s": 1113, "text": "And any other computations." }, { "code": null, "e": 1300, "s": 1141, "text": "We are doing Text normalization with above-mentioned steps, every step can be done in some ways. So we will discuss each and everything in this whole process." }, { "code": null, "e": 1312, "s": 1300, "text": "Text String" }, { "code": null, "e": 1320, "s": 1312, "text": "Python3" }, { "code": "# input stringstring = \" Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).\"print(string)", "e": 1718, "s": 1320, "text": null }, { "code": null, "e": 1726, "s": 1718, "text": "Output:" }, { "code": null, "e": 2088, "s": 1726, "text": "” Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2’s end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).”" }, { "code": null, "e": 2117, "s": 2088, "text": "Case Conversion (Lower Case)" }, { "code": null, "e": 2373, "s": 2117, "text": "In Python, lower() is a built-in method used for string handling. The lower() methods returns the lowercased string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string." }, { "code": null, "e": 2381, "s": 2373, "text": "Python3" }, { "code": "# input stringstring = \" Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).\" # convert to lower caselower_string = string.lower()print(lower_string)", "e": 2838, "s": 2381, "text": null }, { "code": null, "e": 2846, "s": 2838, "text": "Output:" }, { "code": null, "e": 3208, "s": 2846, "text": "” python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much python 2 code does not run unmodified on python 3. with python 2’s end-of-life, only python 3.6.x[30] and later are supported, with older versions still supporting e.g. windows 7 (and old installers not restricted to 64-bit windows).”" }, { "code": null, "e": 3225, "s": 3208, "text": "Removing Numbers" }, { "code": null, "e": 3339, "s": 3225, "text": "Remove numbers if they’re not relevant to your analyses. Usually, regular expressions are used to remove numbers." }, { "code": null, "e": 3347, "s": 3339, "text": "Python3" }, { "code": "# import regeximport re # input stringstring = \" Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).\" # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\\d+','',lower_string)print(no_number_string)", "e": 3898, "s": 3347, "text": null }, { "code": null, "e": 3906, "s": 3898, "text": "Output:" }, { "code": null, "e": 4252, "s": 3906, "text": "” python ., released in , was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python . with python ‘s end-of-life, only python ..x[] and later are supported, with older versions still supporting e.g. windows (and old installers not restricted to -bit windows).”" }, { "code": null, "e": 4273, "s": 4252, "text": "Removing punctuation" }, { "code": null, "e": 4420, "s": 4273, "text": "The part of replacing with punctuation can also be performed using regex. In this, we replace all punctuation by empty string using certain regex." }, { "code": null, "e": 4428, "s": 4420, "text": "Python3" }, { "code": "# import regeximport re # input stringstring = \" Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).\" # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\\d+','',lower_string) # remove all punctuation except words and spaceno_punc_string = re.sub(r'[^\\w\\s]','', no_number_string)print(no_punc_string)", "e": 5081, "s": 4428, "text": null }, { "code": null, "e": 5089, "s": 5081, "text": "Output:" }, { "code": null, "e": 5416, "s": 5089, "text": "‘ python released in was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python with python s endoflife only python x and later are supported with older versions still supporting eg windows and old installers not restricted to bit windows’" }, { "code": null, "e": 5437, "s": 5416, "text": "Removing White space" }, { "code": null, "e": 5635, "s": 5437, "text": "The strip() function is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed)." }, { "code": null, "e": 5643, "s": 5635, "text": "Python3" }, { "code": "# import regeximport re # input stringstring = \" Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).\" # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\\d+','',lower_string) # remove all punctuation except words and spaceno_punc_string = re.sub(r'[^\\w\\s]','', no_number_string) # remove white spacesno_wspace_string = no_punc_string.strip()print(no_wspace_string)", "e": 6361, "s": 5643, "text": null }, { "code": null, "e": 6369, "s": 6361, "text": "Output:" }, { "code": null, "e": 6689, "s": 6369, "text": "‘python released in was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python with python s endoflife only python x and later are supported with older versions still supporting eg windows and old installers not restricted to bit windows’" }, { "code": null, "e": 6709, "s": 6689, "text": "Removing Stop Words" }, { "code": null, "e": 7032, "s": 6709, "text": "Stop words” are the foremost common words during a language like “the”, “a”, “on”, “is”, “all”. These words don’t carry important meaning and are usually faraway from texts. It is possible to get rid of stop words using tongue Toolkit (NLTK), a set of libraries and programs for symbolic and statistical tongue processing." }, { "code": null, "e": 7040, "s": 7032, "text": "Python3" }, { "code": "# download stpwordsimport nltknltk.download('stopwords') # import nltk for stopwordsfrom nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))print(stop_words) # assign stringno_wspace_string='python released in was a major revision of the language that is not completely backward compatible and much python code does not run unmodified on python with python s endoflife only python x and later are supported with older versions still supporting eg windows and old installers not restricted to bit windows' # convert string to list of wordslst_string = [no_wspace_string][0].split()print(lst_string) # remove stopwordsno_stpwords_string=\"\"for i in lst_string: if not i in stop_words: no_stpwords_string += i+' ' # removing last spaceno_stpwords_string = no_stpwords_string[:-1]print(no_stpwords_string)", "e": 7885, "s": 7040, "text": null }, { "code": null, "e": 7894, "s": 7885, "text": "Output: " }, { "code": null, "e": 7989, "s": 7894, "text": "In this, we can normalize the textual data using Python. Below is the complete python program:" }, { "code": null, "e": 7997, "s": 7989, "text": "Python3" }, { "code": "# import regeximport re # download stpwordsimport nltknltk.download('stopwords') # import nltk for stopwordsfrom nltk.corpus import stopwordsstop_words = set(stopwords.words('english')) # input stringstring = \" Python 3.0, released in 2008, was a major revision of the language that is not completely backward compatible and much Python 2 code does not run unmodified on Python 3. With Python 2's end-of-life, only Python 3.6.x[30] and later are supported, with older versions still supporting e.g. Windows 7 (and old installers not restricted to 64-bit Windows).\" # convert to lower caselower_string = string.lower() # remove numbersno_number_string = re.sub(r'\\d+','',lower_string) # remove all punctuation except words and spaceno_punc_string = re.sub(r'[^\\w\\s]','', no_number_string) # remove white spacesno_wspace_string = no_punc_string.strip()no_wspace_string # convert string to list of wordslst_string = [no_wspace_string][0].split()print(lst_string) # remove stopwordsno_stpwords_string=\"\"for i in lst_string: if not i in stop_words: no_stpwords_string += i+' ' # removing last spaceno_stpwords_string = no_stpwords_string[:-1] # outputprint(no_stpwords_string)", "e": 9194, "s": 7997, "text": null }, { "code": null, "e": 9202, "s": 9194, "text": "Output:" }, { "code": null, "e": 9219, "s": 9204, "text": "adnanirshad158" }, { "code": null, "e": 9226, "s": 9219, "text": "Picked" }, { "code": null, "e": 9240, "s": 9226, "text": "python-string" }, { "code": null, "e": 9247, "s": 9240, "text": "Python" } ]
Java Program for Topological Sorting
17 Jan, 2018 Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges). // A Java program to print topological sorting of a DAGimport java.io.*;import java.util.*; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; // Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // A recursive function used by topologicalSort void topologicalSortUtil(int v, boolean visited[], Stack stack) { // Mark the current node as visited. visited[v] = true; Integer i; // Recur for all the vertices adjacent to this // vertex Iterator<Integer> it = adj[v].iterator(); while (it.hasNext()) { i = it.next(); if (!visited[i]) topologicalSortUtil(i, visited, stack); } // Push current vertex to stack which stores result stack.push(new Integer(v)); } // The function to do Topological Sort. It uses // recursive topologicalSortUtil() void topologicalSort() { Stack stack = new Stack(); // Mark all the vertices as not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store // Topological Sort starting from all vertices // one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, stack); // Print contents of stack while (stack.empty()==false) System.out.print(stack.pop() + " "); } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); System.out.println("Following is a Topological " + "sort of the given graph"); g.topologicalSort(); }}// This code is contributed by Aakash Hasija Output: Following is a Topological Sort of the given graph 5 4 2 3 1 0 Please refer complete article on Topological Sorting for more details! Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jan, 2018" }, { "code": null, "e": 294, "s": 54, "text": "Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG." }, { "code": null, "e": 627, "s": 294, "text": "For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges)." }, { "code": "// A Java program to print topological sorting of a DAGimport java.io.*;import java.util.*; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; // Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // A recursive function used by topologicalSort void topologicalSortUtil(int v, boolean visited[], Stack stack) { // Mark the current node as visited. visited[v] = true; Integer i; // Recur for all the vertices adjacent to this // vertex Iterator<Integer> it = adj[v].iterator(); while (it.hasNext()) { i = it.next(); if (!visited[i]) topologicalSortUtil(i, visited, stack); } // Push current vertex to stack which stores result stack.push(new Integer(v)); } // The function to do Topological Sort. It uses // recursive topologicalSortUtil() void topologicalSort() { Stack stack = new Stack(); // Mark all the vertices as not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store // Topological Sort starting from all vertices // one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, stack); // Print contents of stack while (stack.empty()==false) System.out.print(stack.pop() + \" \"); } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); System.out.println(\"Following is a Topological \" + \"sort of the given graph\"); g.topologicalSort(); }}// This code is contributed by Aakash Hasija", "e": 2965, "s": 627, "text": null }, { "code": null, "e": 2973, "s": 2965, "text": "Output:" }, { "code": null, "e": 3036, "s": 2973, "text": "Following is a Topological Sort of the given graph\n5 4 2 3 1 0" }, { "code": null, "e": 3107, "s": 3036, "text": "Please refer complete article on Topological Sorting for more details!" }, { "code": null, "e": 3121, "s": 3107, "text": "Java Programs" } ]
JavaFX Tutorial
11 Feb, 2022 JavaFX is a Java library and a GUI toolkit designed to develop and facilitate Rich Internet applications, web applications, and desktop applications. The most significant perk of using JavaFX is that the applications written using this library can run on multiple operating systems like Windows, Linux, iOS, Android, and several platforms like Desktops, Web, Mobile Phones, TVs, Tablets, etc. This characteristic of the JavaFX library makes it very versatile across operating systems and different platforms. Sun Microsystems (now acquired by Oracle Corporation) released a toolkit known as JavaFX to promote desktop and rich internet applications (RIA) that can be accessed from the category of devices. After the arrival of JavaFX, Java developers and programmers were able to develop the GUI applications more effectively and more productively. Note: Rich Internet Applications are those web applications that allow alike characteristics and expertise as that of desktop applications. These applications contribute more satisfying visual experience to the users when compared to the standard web applications. JavaFX was introduced to supersede the Java Swing GUI framework. Nevertheless, the JavaFX provides more enhanced functionalities and features than the Java Swing. Similar to the Java Swing, the JavaFX also implements its own components. The components of the JavaFX are irrespective of the Operating system. JavaFX is considered to be lightweight and hardware stimulated. According to a report, after using the JavaFX for the development of Rich Internet applications (RIA), the browser penetration rate recorded for these applications was 76%. Before JavaFX, developing the client base applications was a very complicated and cumbersome task. Programmers and developers used to require several libraries for adding various functionalities like media, UI controls, animations and effects, 2D and 3D shapes, etc., in their applications. This issue was resolved when JavaFX came into the picture, which changed the whole scenario of the development of web applications by bringing in all the peculiarities into one single library. Apart from this, the programmers can also utilize all the existing perks of the older libraries like Java Swing and Advanced Windowing Tool Kit. JavaFX also displays a valuable collection of graphics and various media APIs, which can further help in designing smooth applications. JavaFX also leverages the improved Graphical Processing Unit (GUI) with the help of hardware-accelerated graphics. If a developer wants to combine the graphics animations and UI control in their applications, then they can use the various interfaces provided by the JavaFX. History of JavaFX JavaFX was formerly developed by Chris Oliver. At that time, he was serving for a company named See Beyond Technology Corporation. Initially, the JavaFX project was recognized as Form Follows Functions (F3). This project was designed with the aim of providing richer interfaces for developing GUI applications. Later in June 2005, Sun Micro-systems took the F3 project and changed its name from F3 to JavaFX. Timeline of JavaFX 2005 – Sun Microsystems took over the See Beyond company in June 2005 and acquired the F3 project as JavaFX. 2007 – JavaFX was officially declared at Java One, a worldwide web conference that is held yearly. 2008 – Net Beans integration with JavaFX was made open. The Java Standard Development Kit for JavaFX 1.0 was also released in the same year. 2009 – The next version of JavaFX was released, i.e., JavaFX 1.2, and the support for JavaFX Mobile was also introduced. In the same year only, Oracle Corporation also acquired Sun Microsystems. 2010 – JavaFX version 1.3 was released in 2010. 2011 – In 2011, JavaFX version 2.0 came out. 2012 – The support for JavaFX Mac OS for desktop was introduced. 2014 – The most advanced version of JavaFX, i.e., JavaFX 8, was released as an indispensable part of Java on the 18th of March 2014. JavaFX is an open-source framework based on Java, used for advancing rich client applications. JavaFX is recognized as the replacement or successor of the Java Swing in the field of graphical user interface (GUI) development technology in the platform of Java. The JavaFX library is available as a public Java application programming interface (API). The JavaFX library comprises numerous peculiarities that make it a handpicked option for developers to develop rich client applications. These features are as follows: Java Library – JavaFX is a Java library, which allows the user to gain the support of all the Java characteristics such as multithreading, generics, lambda expressions, and many more. The user can also use any of the Java editors or IDE’s of their choice, such as Eclipse, NetBeans, to write, compile, run, debug, and package their JavaFX application. Platform Independent – The rich internet applications made using JavaFX are platform-independent. The JavaFX library is open for all the scripting languages that can be administered on a JVM, which comprise – Java, Groovy, Scala, and JRuby. FXML – JavaFX emphasizes an HTML-like declarative markup language known as FXML. FXML is based on extensible markup language (XML). The sole objective of this markup language is to specify a user interface (UI). In FXML, the programming can be done to accommodate the user with an improved GUI. Scene Builder – JavaFX also implements a tool named Scene Builder, which is a visual editor for FXML. Scene Builder generates FXML mark-ups that can be transmitted to the IDE’s like Eclipse and NetBeans, which further helps the user to combine the business logic to their applications. The users can also use the drag and drop design interface, which is used to design FXML applications (just like the Drag & Drop feature of the Java Swing and DreamWeaver Applications). Hardware-accelerated Graphics Pipeline – The graphics of the JavaFX applications are based on the hardware-accelerated graphics rendering pipeline, commonly known as Prism. The Prism engine offers smooth JavaFX graphics that can be rendered quickly when utilized with a supported graphics card or graphics processing unit (GPU). In the case where the system does not hold the graphic cards, then the prism engine defaults to the software rendering stack. WebView – JavaFX applications can also insert web pages. To embed web pages, Web View of JavaFX uses a new HTML rendering engine technology known as WebKitHTML. WebView is used to make it possible to insert web pages within a JavaFX application. JavaScript running in WebView can call Java APIs and vice-versa. Built-in UI controls – JavaFX comprises all the major built-in UI controls that help in developing well-featured applications. These built-in UI components are not operating system-dependent. In simple words, these controls do not depend on any of the Operating systems like Windows, iOS, Android, etc. These built-in controls are single-handedly ample to perform a whole implementation of the applications. CSS Styling – Just like websites use CSS for styling, JavaFX also provides the feature to integrate the application with CSS styling. The users can enhance the styling of their applications and can also improve the outlook of their implementation by having simple knowledge and understanding of CSS styling. Rich set of APIs – JavaFX library also presents a valuable collection of APIs that helps in developing GUI applications, 2D and 3D graphics, and many more. This collection of APIs also includes all the characteristics of the Java platform. Hence, working with this API, a user can access the specialties of Java languages such as Generics, Annotations, Multithreading, and Lambda Expressions, and many other features as well. In JavaFX, the popular Java Collections library was also improved, and notions like lists and maps were introduced. Using these APIs, the users can witness the variations in the data models. High-Performance media engine – Like the graphics pipeline, JavaFX also possesses a media pipeline that advances stable internet multimedia playback at low latency. This high-performance media engine or media pipeline is based on a multimedia framework known as Gstreamer. Java Library – JavaFX is a Java library, which allows the user to gain the support of all the Java characteristics such as multithreading, generics, lambda expressions, and many more. The user can also use any of the Java editors or IDE’s of their choice, such as Eclipse, NetBeans, to write, compile, run, debug, and package their JavaFX application. Platform Independent – The rich internet applications made using JavaFX are platform-independent. The JavaFX library is open for all the scripting languages that can be administered on a JVM, which comprise – Java, Groovy, Scala, and JRuby. FXML – JavaFX emphasizes an HTML-like declarative markup language known as FXML. FXML is based on extensible markup language (XML). The sole objective of this markup language is to specify a user interface (UI). In FXML, the programming can be done to accommodate the user with an improved GUI. Scene Builder – JavaFX also implements a tool named Scene Builder, which is a visual editor for FXML. Scene Builder generates FXML mark-ups that can be transmitted to the IDE’s like Eclipse and NetBeans, which further helps the user to combine the business logic to their applications. The users can also use the drag and drop design interface, which is used to design FXML applications (just like the Drag & Drop feature of the Java Swing and DreamWeaver Applications). Hardware-accelerated Graphics Pipeline – The graphics of the JavaFX applications are based on the hardware-accelerated graphics rendering pipeline, commonly known as Prism. The Prism engine offers smooth JavaFX graphics that can be rendered quickly when utilized with a supported graphics card or graphics processing unit (GPU). In the case where the system does not hold the graphic cards, then the prism engine defaults to the software rendering stack. WebView – JavaFX applications can also insert web pages. To embed web pages, Web View of JavaFX uses a new HTML rendering engine technology known as WebKitHTML. WebView is used to make it possible to insert web pages within a JavaFX application. JavaScript running in WebView can call Java APIs and vice-versa. Built-in UI controls – JavaFX comprises all the major built-in UI controls that help in developing well-featured applications. These built-in UI components are not operating system-dependent. In simple words, these controls do not depend on any of the Operating systems like Windows, iOS, Android, etc. These built-in controls are single-handedly ample to perform a whole implementation of the applications. CSS Styling – Just like websites use CSS for styling, JavaFX also provides the feature to integrate the application with CSS styling. The users can enhance the styling of their applications and can also improve the outlook of their implementation by having simple knowledge and understanding of CSS styling. Rich set of APIs – JavaFX library also presents a valuable collection of APIs that helps in developing GUI applications, 2D and 3D graphics, and many more. This collection of APIs also includes all the characteristics of the Java platform. Hence, working with this API, a user can access the specialties of Java languages such as Generics, Annotations, Multithreading, and Lambda Expressions, and many other features as well. In JavaFX, the popular Java Collections library was also improved, and notions like lists and maps were introduced. Using these APIs, the users can witness the variations in the data models. High-Performance media engine – Like the graphics pipeline, JavaFX also possesses a media pipeline that advances stable internet multimedia playback at low latency. This high-performance media engine or media pipeline is based on a multimedia framework known as Gstreamer. JavaFX has numerous built-in elements that are interconnected with each other. JavaFX library comprises a valuable collection of APIs, classes, and interfaces that are more than sufficient to produce rich internet applications and GUI applications with intense graphics that can run consistently over multiple platforms. The subsequent figure displays the complete architecture of the JavaFX platform. Here you can examine the elements that support JavaFX API. As we can see in the above figure that, JavaFX architecture comprises many different components. These components are briefly described as follows: JavaFX API – The topmost layer of JavaFX architecture holds a JavaFX public API that implements all the required classes that are capable of producing a full-featured JavaFX application with rich graphics. The list of all the important packages of this API is as follows.javafx.animation: It includes classes that are used to combine transition-based animations such as fill, fade, rotate, scale and translation, to the JavaFX nodes (collection of nodes makes a scene graph). javafx.css − It comprises classes that are used to append CSS–like styling to the JavaFX GUI applications.javafx.geometry − It contains classes that are used to represent 2D figures and execute methods on them.javafx.scene − This package of JavaFX API implements classes and interfaces to establish the scene graph. In extension, it also renders sub-packages such as canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web, etc. These are the diverse elements that sustain this precious API of JavaFX.javafx.application − This package includes a collection of classes that are responsible for the life cycle of the JavaFX application.javafx.event − It includes classes and interfaces that are used to perform and manage JavaFX events.javafx.stage − This package of JavaFX API accommodates the top-level container classes used for the JavaFX application.Scene Graph – A Scene Graph is the starting point of the development of any of the GUI Applications. In JavaFX, all the GUI Applications are made using a Scene Graph only. The Scene Graph includes the primitives of the rich internet applications that are known as nodes. In simple words, a single component in a scene graph is known as a node. In general, a scene graph is made up of a collection of nodes. All these nodes are organized in the form of a hierarchical tree that describes all of the visual components of the application’s user interface (UI). A node instance can be appended to a scene graph only once. The nodes of a scene graph can have numerous segments like Effects, Opacity, Transforms, Event Handlers, Application Specific States. The nodes are of three general types. JavaFX API – The topmost layer of JavaFX architecture holds a JavaFX public API that implements all the required classes that are capable of producing a full-featured JavaFX application with rich graphics. The list of all the important packages of this API is as follows. javafx.animation: It includes classes that are used to combine transition-based animations such as fill, fade, rotate, scale and translation, to the JavaFX nodes (collection of nodes makes a scene graph). javafx.css − It comprises classes that are used to append CSS–like styling to the JavaFX GUI applications. javafx.geometry − It contains classes that are used to represent 2D figures and execute methods on them. javafx.scene − This package of JavaFX API implements classes and interfaces to establish the scene graph. In extension, it also renders sub-packages such as canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web, etc. These are the diverse elements that sustain this precious API of JavaFX. javafx.application − This package includes a collection of classes that are responsible for the life cycle of the JavaFX application. javafx.event − It includes classes and interfaces that are used to perform and manage JavaFX events. javafx.stage − This package of JavaFX API accommodates the top-level container classes used for the JavaFX application. Scene Graph – A Scene Graph is the starting point of the development of any of the GUI Applications. In JavaFX, all the GUI Applications are made using a Scene Graph only. The Scene Graph includes the primitives of the rich internet applications that are known as nodes. In simple words, a single component in a scene graph is known as a node. In general, a scene graph is made up of a collection of nodes. All these nodes are organized in the form of a hierarchical tree that describes all of the visual components of the application’s user interface (UI). A node instance can be appended to a scene graph only once. The nodes of a scene graph can have numerous segments like Effects, Opacity, Transforms, Event Handlers, Application Specific States. The nodes are of three general types. These are as follows: Root Node – A root node is a node that does not have any node as its parent. Leaf Node – A leaf node is a node that does not contain any node as its children. Branch Node – A branch node is a node that contains a node as its parent and also has a node as its children. 10. Quantum Toolkit – Quantum Toolkit is used to connect prism and glass windowing tool kits collectively and makes them prepared for the above layers in the stack. In simple words, it ties Prism and GWT together and makes them available to JavaFX. 11. Prism – The graphics of the JavaFX applications are based on the hardware-accelerated graphics rendering pipeline, commonly known as Prism. The Prism engine supports smooth JavaFX graphics that can be executed swiftly when utilized with a backed graphics card or graphics processing unit (GPU). In the situation where the system does not contain the graphic cards, then the prism engine defaults to the software rendering stack. To interpret graphics, a Prism practice − DirectX 9 on Windows XP and Vista. DirectX 11 on Windows 7. OpenGL on Mac and Linux, Embedded Systems. 12. Glass Windowing Toolkit – Glass Windowing Toolkit or simply Glass is a platform-dependent layer that assists in connecting the JavaFX platform to the primary operating system (OS). Glass Windowing Toolkit is very useful as it provides services such as controlling the windows, events, timers, and surfaces to the native operating system. 13. WebView – JavaFX applications can also insert web pages. To embed web pages, Web View of JavaFX uses a new HTML rendering engine technology known as WebKitHTML. WebView is used to make it possible to insert web pages within a JavaFX application. JavaScript appearing in WebView can call Java APIs and vice-versa. This element promotes different web technologies like HTML5, CSS, JavaScript, DOM, and SVG. Using web view, we can execute the HTML content from the JavaFX application and can also implement some CSS styles to the user interface (UI) part of the application. 14. Media Engine – Like the graphics pipeline, JavaFX also possesses a media pipeline that advances stable internet multimedia playback at low latency. This high-performance media engine or media pipeline is based on a multimedia framework known as Gstreamer. By applying the Media engine, the JavaFX application can support the playback of audio and video media files. The package javafx.scene.media covers all the classes and interfaces that can provide media functionalities to JavaFX applications. The foregoing were the components that constitute the architecture of JavaFX. There are in total three life cycle methods of a JavaFX Application class. These methods are – start() – The start() method is the entry point method of the JavaFX application where all the graphics code of JavaFX is to be written. init() – The init() method is an empty method that can be overridden. In this method, the user cannot create a stage or a scene. stop() – The stop() method is an empty method that can also be overridden, just like the init() method. In this method, the user can write the code to halt the application. Other than these methods, the JavaFX application also implements a static method known as launch(). This launch() method is used to launch the JavaFX application. As stated earlier, the launch() method is static, the user should call it from a static method only. Generally, that static method, which calls the launch() method, is the main() method only. Whenever a user launches a JavaFX application, there are few actions that are carried out in a particular manner only. The following is the order given in which a JavaFX application is launched. Firstly, an instance of the application class is created.After that, the init() method is called.After the init() method, the start() method is called.After calling the start() method, the launcher waits for the JavaFX application to end and then calls the stop() method. Firstly, an instance of the application class is created. After that, the init() method is called. After the init() method, the start() method is called. After calling the start() method, the launcher waits for the JavaFX application to end and then calls the stop() method. Terminating the JavaFX application As soon as the last window of the JavaFX application is closed, the JavaFX application is stopped implicitly. The user can turn off this function by passing the Boolean value “False” to the static method setImplicitExit(). This method should always be called from a static context only. The user can also stop a JavaFX application explicitly by practicing any of the two methods, Platform.exit() or System.exit(int). User Interface (UI) Components of JavaFX JavaFX comprises all the major built-in UI components that help in developing well-featured applications. These built-in UI components are not operating system-dependent. In simple words, these controls do not depend on any of the Operating systems like Windows, iOS, Android, etc. These built-in controls are single-handedly ample to perform a whole implementation of the applications. The users can add numerous components to their applications to make them look more advanced and rich in graphics. These segments are defined as follows: Any geometrical shape that can be represented on the coordinate system using two planes, which are X and Y planes, is known as a two-dimensional shape or a 2D shape. Examples of 2D shapes are line, square, rectangle, circle, eclipse, and many more. JavaFX gives the flexibility to the user to add and create these 2D shapes in their JavaFX applications. There are several classes in JavaFX API that are used to execute 2D shapes in the JavaFX application. All these classes of 2D shapes are part of the javafx.scene.shape package. The class named Shape is the root class of all the 2-Dimensional shapes in JavaFX. There are many classes in this package that contains various sorts of 2D shapes.Steps to create a 2D shape are as follows: Step 1: The first step to add a 2D shape in a JavaFX application is to instantiate the corresponding class of the needed shape. For illustration purposes consider if a user wants to add a line to their JavaFX application, they should first instantiate the javafx.scene.shape.line class. They also need to instantiate an object of the same class like as defined below: Line line = new Line(); Step 2: After the instantiation of the class and the object, the user should also set the properties of the required shape using the setter functions. For illustration purposes consider if a user wants to add a line to their JavaFX application, then after instantiation, they should set the X and Y coordinates of the starting and ending point of the line as defined below as follows: line.setStartX(0); line.setStartY(0); line.setEndX(100); line.setEndY(200); Step 3: After doing the above two steps, the third step for the user is to add the object instantiated of the required shape to the group by declaring it as a parameter of the constructor. For illustration purposes consider if in order to get a line in the JavaFX application, the user should add the instantiated object of line shape to the group, then it is defined as follows: Group root = new Group(); root.getChildren().add(line); Types of 2D shapes In the javafx.scene.shape package of JavaFX, there are numerous shapes available which the user can use in their application. The following is the list of various classes of the 2D shapes that are provided by JavaFX. Line – A geometrical structure that joins two coordinates (X and Y) on a 2D coordinate system is known as a Line. If a user wants to create a line in their JavaFX application, then they should instantiate the javafx.scene.shape.Line class. Rectangle – A Rectangle is a geometrical shape that has two sets of two identical sides and four right angles at their joint. If a user wants to create a rectangle in their JavaFX application, then they should instantiate the javafx.scene.shape.Rectangle class. Ellipse – In general, an ellipse can be defined as a curve with two focal points. In an ellipse, the sum of the distances to the focal points is constant from each point of the ellipse. If a user wants to create an ellipse in their JavaFX application, then they should instantiate the javafx.scene.shape.Ellipse class. Circle – In general, a specific sort of Ellipse that has both of its focal points at the same location is known as a circle. If a user wants to create a circle in their JavaFX application, then they should instantiate the javafx.scene.shape.Circle class. Arc – An arc can be defined as the portion of the circumference of the circle or an ellipse. If a user wants to create an arc in their JavaFX application, then they should instantiate the javafx.scene.shape.Arc class. Polygon – In general, a Polygon is a geometrical shape that can be formed by joining the various Co-planner line segments. If a user wants to create a polygon in their JavaFX application, then they should instantiate the javafx.scene.shape.Polygon class. Cubic Curve – A curve of degree 3 in the XY plane is known as a cubic curve. If a user wants to create a cubic curve in their JavaFX application, then they should instantiate the javafx.scene.shape.CubicCurve class. Quad Curve – A curve of degree 2 in the XY plane is known as a quad curve. If a user wants to create a quad curve in their JavaFX application, then they should instantiate the javafx.scene.shape.QuadCurve class. Any behavior or movement that improves the presentation of the graphics is known as an Effect. In JavaFX, we can say that any algorithm that is applied to nodes to enhance their appearance visually is an effect. In order to specify the effect, the effect property of the Node class is used. JavaFX gives the flexibility to the user to add various effects such as bloom, blur, and glow in their JavaFX applications. There are several classes in JavaFX API that are used to execute these effects in the JavaFX application. All these classes of effects are part of the javafx.scene.effects package. The class named Effect is the root class of all the effects in JavaFX. There are many classes in this package that contains various sorts of effects. In order to add an effect to a Node, the user needs to sequentially follow these steps as follows: Step 1: The first step to applying an effect to a Node is to create all the nodes in a JavaFX application by instantiating their individual classes. For illustration purposes consider if a user wants to apply the glow effect to an image in their application, then they should create an image node first by instantiating the Image class. After that, they should set its view just as shown below as follows: // Creating an image Image img = new Image(“https://media.geeksforgeeks.org/wp-content/uploads/20210224040124/JSBinCollaborativeJavaScriptDebugging6.png”); // Setting the image view ImageView imgView = new ImageView(img); // Setting the position of the image imgView.setX(100); imgView.setY(100); // Setting the fit height and width of the image view imgView.setFitHeight(200); imgView.setFitWidth(400); // Setting the preserve ratio of the image view imgView.setPreserveRatio(true); Step 2: After creating the image node and setting the image view, the user should instantiate the class representing the required effect that is needed to be applied to the node created. For illustration purposes of considering if the user wants to apply the glow effect in their application, then they need to instantiate the Glow class as shown below as follows: Glow glow = new Glow(); Step 3: After instantiating the class of the required effect, the user needs to set the attributes for the instantiated effect using its setter methods. For illustration purposes consider as if the user can set the attributed of the Glow effect using the below-shown method as follows: // Setting the level property glow.setLevel(0.9); Step 4: After the above three steps, the user can finally apply the required effect to the node using the setEffect() method. For example – The user can set the glow effect to the image node by passing the object of the Glow class to this method as follows – imgView.setEffect(glow); In the javafx.scene.effect package of JavaFX, there are numerous effects available which the user can use in their application. The following is the list of various classes of these effects that are provided by JavaFX. Blend – A mixture of two or more different things or substances is known as a Blend. If the user applies the blend effect, then, this effect takes the pixels of the two distinct inputs, at the same location and creates a blended (combined) output based on the blend mode. The class javafx.scene.effect.Blend represents the blend effect. Glow – The Glow effect of JavaFX makes the provided input image glow. Using this effect, the bright pixels of the input can be made brighter. The class javafx.scene.effect.Glow represents the glow effect. Bloom – Just like the Glow effect, in the Bloom effect also the pixels in some parts of the node are produced to glow. The class javafx.scene.effect.Bloom represents the bloom effect. Shadow – The shadow effect is an effect that generates a duplicate of the given node with some blurry edges. The class javafx.scene.effect.Shadow represents the shadow effect. Reflection – In the reflection effect of JavaFX, whenever a user applies this effect to a specified node, then a reflection of the node is appended at the bottom of the node.The class javafx.scene.effect.Reflection represents the reflection effect. Color Adjust – In JavaFX, a user can also alter the color of an image by implementing the color adjust effect to it. This effect involves the adjustment of the hue, saturation, brightness, and contrast on every pixel. The class javafx.scene.effect.ColorAdjust represents the Color Adjust effect. SepiaTone – In JavaFX, when the Sepia tone effect is applied to a node of JavaFX (image in most cases), then that node is toned with a reddish-brown color. The class javafx.scene.effect.SepiaTone represents the Sepia Tone effect. Lighting – The effect which is used to resemble a light from a light source is known as the Lighting effect. In JavaFX, there can be various sorts of light sources specifically point, distant, and spot. The class javafx.scene.effect.Lighting represents the Lighting effect. InnerShadow – When a user applies this effect to a node, then a shadow of that node will be generated inside the edges of the node. The class javafx.scene.effect.InnerShadow represents the Inner shadow effect. Blend – A mixture of two or more different things or substances is known as a Blend. If the user applies the blend effect, then, this effect takes the pixels of the two distinct inputs, at the same location and creates a blended (combined) output based on the blend mode. The class javafx.scene.effect.Blend represents the blend effect. Glow – The Glow effect of JavaFX makes the provided input image glow. Using this effect, the bright pixels of the input can be made brighter. The class javafx.scene.effect.Glow represents the glow effect. Bloom – Just like the Glow effect, in the Bloom effect also the pixels in some parts of the node are produced to glow. The class javafx.scene.effect.Bloom represents the bloom effect. Shadow – The shadow effect is an effect that generates a duplicate of the given node with some blurry edges. The class javafx.scene.effect.Shadow represents the shadow effect. Reflection – In the reflection effect of JavaFX, whenever a user applies this effect to a specified node, then a reflection of the node is appended at the bottom of the node.The class javafx.scene.effect.Reflection represents the reflection effect. Color Adjust – In JavaFX, a user can also alter the color of an image by implementing the color adjust effect to it. This effect involves the adjustment of the hue, saturation, brightness, and contrast on every pixel. The class javafx.scene.effect.ColorAdjust represents the Color Adjust effect. SepiaTone – In JavaFX, when the Sepia tone effect is applied to a node of JavaFX (image in most cases), then that node is toned with a reddish-brown color. The class javafx.scene.effect.SepiaTone represents the Sepia Tone effect. Lighting – The effect which is used to resemble a light from a light source is known as the Lighting effect. In JavaFX, there can be various sorts of light sources specifically point, distant, and spot. The class javafx.scene.effect.Lighting represents the Lighting effect. InnerShadow – When a user applies this effect to a node, then a shadow of that node will be generated inside the edges of the node. The class javafx.scene.effect.InnerShadow represents the Inner shadow effect. Just like several shapes and effects, a user can also create a node for applying different texts in JavaFX. The text node is expressed by the class named Text, which belongs to the javafx.scene.text package. This Text class includes numerous characteristics to generate text in JavaFX and alter its appearance. Another feature of the text class is that this class also inherits the Shape class of JavaFX which belongs to the javafx.scene.shape package. Hence, in extension to the characteristics of the text like font, alignment, line spacing, text, etc., it also acquires the basic shape node properties such as strokeFill, stroke, strokeWidth, strokeType, etc. To create a text node, the user needs to follow certain steps as follows: Step 1: The first step to create a text node in a JavaFX application is to instantiate the corresponding class of the text node. Illustration: The class Text of the package javafx.scene.text denotes the text node in JavaFX. A user can create a text by instantiating this class as given below as follows: Text txt = new Text(); Step 2: After instantiating the corresponding class of the text node, the second step to create a text node in JavaFX is to set the properties of the required text using the setter functions. Illustration: After instantiating the Text class, the user needs to set the value to this property using the setText() method as shown below as follows: String text = "Hello how are you" txt.setText(text); txt.setX(50); txt.setY(50); Step 3: After doing the above two steps, the third step for the user is to add the object instantiated of the required text to the group by declaring it as a parameter of the constructor. Illustration: In order to get a text in the JavaFX application, the user should add the instantiated object of the text node to the group. Group root = new Group(); root.getChildren().add(txt); The attributes of the JavaFX Text are represented in the table below. The transition which produces the myth of motion for an object is known as animation. Animations can also be defined as the set of transformations implemented on an object over the specified duration sequentially so that the object can be displayed as it is in action. This can be achieved by the rapid display of frames. In JavaFX, the package javafx.animation includes all the classes that assist in applying the animations onto the nodes. All the classes of this package extend the class javafx.animation.Animation. JavaFX provides the classes for the transitions like RotateTransition, ScaleTransition, TranslateTransition, FadeTransition, FillTransition, StrokeTransition, etc. Steps to apply animations to the target node are as follows: To apply a special animation to a target node, a user should follow the below-given steps as follows: Step 1: The first step to applying an animation to a specific node is to create that node using the respective class of the node. Square sqr = new Square(100,100,100,100); sqr.setFill(Color.GREEN); Step 2: After creating the node, the next step is to instantiate the respective animation class that is to be applied to the created node. RotateTransition rotate = new RotateTransition(); Step 3: After instantiating the respective animation class, in the step, the user should set the properties of the animation. rotate.setDuration(Duration.millis(2000)); rotate.setAxis(Rotate.Y_Axis); rotate.setCycleCount(1000); Step 4: In the next step, the user should set the target node on which the animation will be applied. rotate.setNode(sqr); Step 5: After following all the above steps, the last step to apply an animation to a target node is to play the applied animation using the play() method of the Animation class. rotate.play(); In the javafx.animation package of JavaFX, there are numerous transitions available which the user can use in their application. The following is the list of various animations that are provided by JavaFX. Scale Transition – The Scale transition is used to animate the scaling of the selective node over a specific duration of time. If a user wants to implement the scale transition to a node in their JavaFX application, then they should instantiate the javafx.animation.ScaleTransition class. Translate Transition – The Translate transition is used to translate the selective node from one location to another over a specific duration of time. If a user wants to implement the translate transition to a node in their JavaFX application, then they should instantiate the javafx.animation.TranslateTransition class. Rotate Transition – The Rotate transition is used to rotate the selective node by one of the axes over a specific duration of time. If a user wants to implement the rotate transition to a node in their JavaFX application, then they should instantiate the javafx.animation.RotateTransition class. Fade Transition – The Fade transition is used to animate the opacity of the node. In simple words, we can say that the fade transition keeps refreshing the opacity of the node over a specific duration of time in order to reach the final opacity value. If a user wants to implement the fade transition to a node in their JavaFX application, then they should instantiate the javafx.animation.FadeTransition class. Stroke Transition – The Stroke transition is used to animate the node’s stroke color so that the stroke color of the node varies between the two color values over a specific duration of time. If a user wants to implement the stroke transition to a node in their JavaFX application, then they should instantiate the javafx.animation.StrokeTransition class. Parallel Transition – The Parallel transition is used to perform a number of animations on a selective node in a parallel manner. If a user wants to implement the parallel transition to a node in their JavaFX application, then they should instantiate the javafx.animation.ParallelTransition class. Fill Transition – The Fill transition is used to animate the selective node’s fill color so that the fill color of the node varies between the two color values over a specific duration of time. If a user wants to implement the fill transition to a node in their JavaFX application, then they should instantiate the javafx.animation.FillTransition class. Path Transition – The Path transition is used to move the selective node along the specified path over a specific duration of time. If a user wants to implement the path transition to a node in their JavaFX application, then they should instantiate the javafx.animation.PathTransition class. Any solid geometrical figure that can be represented on the coordinate system using three planes, which are X, Y, and Z planes, is known as a three-dimensional shape or a 3D shape. The main difference between the 3D shapes and 2D shapes is that the 3D shapes always need to have an extra coordinate value Z as compared to 2D shapes, in order to be drawn on a coordinate system. There are many basic 3D shapes which we see on a daily basis such as cylinders, spheres, boxes, cubes, pyramids, etc. Nevertheless, JavaFX implements only 3 classes to create 3D shapes. These classes include spheres, cylinders, and boxes. These classes are defined in the javafx.scene.shape package. This package provides all the methods to deal with the 3D shapes. The class Shape3D of the package javafx.scene.shape is the base class of all the 3D shape classes in javafx. Types of 3D shapes in JavaFX In JavaFX, 3D shapes are characterized in two separate types. These are: 1. Predefined 3D shapes: Predefined 3D shapes are the shapes whose classes are already present in the JavaFX API. These shapes are Cylinder, Sphere, and Box. In order to create these shapes in the JavaFX application, the user just needs to instantiate these classes. These classes include several properties and methods that are needed to be used in order to generate the proper shapes. 2. User Defined 3D shapes: JavaFX provides the class javafx.scene.shape.TriangleMesh which extends the abstract class javafx.scene.shape.Mesh. This class facilitates the user to define their own points, texture coordinates, and faces as the properties of the class. As mentioned above, there are different classes for the different 3D shapes in JavaFX. In order to create 3D shapes, the user just needs to instantiate those classes. The user can use the following steps to generate proper shapes in their JavaFX application. 1. The first step is to instantiate the class of the respective 3D shape which the user wants to build. For Example – If a user wishes to create a Box, then he should instantiate the Box class of the JavaFX. Box box = new Box(); 2. After instantiating the class, the next step is to set of properties of the instantiated class. For Example – If a user has instantiated the Box class of JavaFX, then he should set the properties such as Height, width, and depth of the Box class. box.setHeight(100.0); box.setDepth(80.0); box.setWidth(60.0); 3. After the above two steps, the user should set the camera for the scene. In simple words, the user can set the camera to a particular position for the camera view. However, this step is optional. A user can set the camera view using the following code – PerspectiveCamera cam = new PerspectiveCamera(); cam.setTranslateX(100.0); cam.setTranslateY(80.0); cam.setTranslateZ(-50.0); scene.setCamera(cam) 4. The last step to creating a 3D shape for the JavaFX application is to attach the 3D shape to the Scene graph and set the relevant properties for the Scene and stage. For example: If a user has instantiated the box class, then he should link that class with the Scene graph and the stage. Group root = new Group(); root.getChildren().add(box); Scene scene = new Scene(root,500,500); primaryStage.setScene(scene); primaryStage.setTitle("3D shape Example"); primaryStage.show(); Different classes of JavaFX 3D shapes In JavaFX, there are basically 3 predefined 3D shapes classes that are available for the user to use in their application. The following is a brief introduction of various 3D shapes that are provided by JavaFX. Sphere – A sphere can be defined as a perfectly round solid 3D object. In JavaFX, the class javafx.scene.shape.Sphere represents Sphere. Box – In general, a box can be defined as a three-dimensional shape having all the faces in a rectangular shape. The three dimensions of Box are height, width, and depth. In JavaFX, the class javafx.scene.shape.Box represents Box. Cylinder – A Cylinder can be defined as a three-dimensional solid having two parallel circular bases connected by a curved surface. It has two main properties as radius and height. In JavaFX, the class javafx.scene.shape.Cylinder is used to denote cylinder. Transformation implies modifying some graphics into something different by implementing various rules. In JavaFX there are different sorts of transformations such as Translation, Scaling Up or Down, Rotation, Shearing, etc. Using JavaFX, a user can implement transformations on nodes such as rotation, scaling, and translation. All these transformations are expressed by several classes and these classes belong to the package javafx.scene.transform. Different classes of JavaFX Transformations In JavaFX, there are basically 4 predefined JavaFX transformations classes that are available for the user to use in their application. The following is a brief introduction of various transformations that are provided by JavaFX. Rotation – Rotation is used to rotate the object from its source by a certain angle. The class javafx.scene.transform.Rotate represents rotation. Translation – Translation is used to modify the location of the node. The class javafx.scene.transform.Translate represents the translation. Scaling – Scaling is used to modify the size of the node. The class javafx.scene.transform.Scale represents Scaling. Shearing – Shearing is used to altering the slope of the object in a particular direction. The class javafx.scene.transform.Shear represents Shearing. Steps to apply transformations to the target node are as follows: To apply a special transformation to a target node, a user should follow the below-given steps: 1. The first step is to instantiate the class of the respective transformation which the user wants to apply. For example – If a user wants to apply a translate transformation on a specific node, then he should instantiate the translate class. TranslateTransition translate = new TranslateTransition(); 2. After instantiating the class, the next step is to set of properties of the instantiated class. For example – If a user has instantiated the translate transformation class of JavaFX, then he should set the properties such as translate byX, translate byY, duration, and cycle count of the translated class. translate.setByX(400); translate.setDuration(Duration.millis(1000)); translate.setCycleCount(500); 3. Set the transformation to the respective node and play the transformation using the method play(). For Example: Let us assume that the user wants to translate a specific node then after instantiating a transformation class and setting its value, the user should set the node using the name of the node that should play the translation. translate.setNode(name of the node); translate.play(); The UI controls are the elements that are truly exposed to the user for intercommunication or information exchange. A layout represents the structure of the UI elements on the screen. The response is the reaction of the UI component when some event has happened on it. However, the package javafx.scene.control implements all the required classes for the UI elements like Button, Label, etc. Every class describes a particular UI control and explains few methods for their styling. Different classes of JavaFX UI controls In JavaFX, there are many UI controls that are used by the users in their applications. Below is the list of usually used UI controls while the GUI is designed using JavaFX. Button – The button is a component that controls the function of the application. The Button class is practiced to produce a specified button. It is represented by the javafx.scene.control.Button class. Label – Label is an element that is applied to describe plain text on the screen. Typically, a label is set with the node, it represents. It is represented by the javafx.scene.control.Label class. TextField – Text Field is usually used to take the input from the user in the form of text. It is represented by the javafx.scene.control.TextField class. ProgressBar – Progress Bar is used to display the output process to the user. It is represented by the javafx.scene.control.ProgressBar class. RadioButton – The Radio Button is used to provide various options to the user. The user can only choose one option among all. A radio button has two options, it can either be selective or deselective. It is represented by the javafx.scene.control.RadioButton class. CheckBox – Check Box is used to get the kind of information from the user which contains various choices. The user marked the checkbox either on (true) or off(false). The CheckBox in JavaFX is expressed by the javafx.scene.control.CheckBox class. Slider – Slider is used to provide a pane of options to the user in a graphical form where the user needs to move a slider over the range of values to select one of them. It is represented by the javafx.scene.control.Slider class. Menu – JavaFX provides a Menu class to implement menus. The menu is the main component of any application. It is represented by the javafx.scene.control.Menu class. PasswordField – PasswordField is practiced to take the user’s password. Whatever the user types in the password field, that is not displayed on the screen to anyone. It is expressed by the javafx.scene.control.PasswordField class. ScrollBar – JavaFX Scroll Bar is used to implement a scroll bar to the user so that the user can scroll down the application pages. It is represented by the javafx.scene.control.ScrollBar class. In general, the chart can be defined as the graph or diagram which represents the data in the form of symbols. Charts are mainly used to represent large quantities of data and the relationship between parts of the data. We can create different kinds of charts to represent different kinds of information. In JavaFX, we can create the charts by using the classes provided by the package javafx.scene.chart. Types of charts Charts in JavaFX can be classified into the subsequent types: Pie Chart – In Pie Chart, the areas of a circle are used to define several proportions of the complete information. In JavaFX, the class javafx.scene.chart.PieChart is used to deal with the pie chart. XYChart – In XYChart, the data is sketched on the XY (horizontal and vertical) axes. The X-axis depicts one type of value while the Y-axis depicts the other type of value. The mapping is done between the values plotted on X and Y charts to display the appropriate information. In JavaFX, the class javafx.scene.chart.XYChart is practiced to deal with the XYChart. Pie Chart – In Pie Chart, the areas of a circle are used to define several proportions of the complete information. In JavaFX, the class javafx.scene.chart.PieChart is used to deal with the pie chart. XYChart – In XYChart, the data is sketched on the XY (horizontal and vertical) axes. The X-axis depicts one type of value while the Y-axis depicts the other type of value. The mapping is done between the values plotted on X and Y charts to display the appropriate information. In JavaFX, the class javafx.scene.chart.XYChart is practiced to deal with the XYChart. Types of Axis In Charts, there can be different types of axis other than the X and Y-axis. These are – Category Axis – The category axis is used to describe the various sections of the information. This axis is distinct from the value axis in the sense that the specific values are not displayed on the category axis. In JavaFX, the class javafx.scene.chart.CategoryAxis depicts the category axis. A user just requires to instantiate this class in order to generate the category axis. Number Axis – The Number axis is used to express the specific range of values. In JavaFX, the class javafx.scene.chart.NumberAxis represents the value axis. A user just requires to instantiate this class in order to generate the Number axis. Category Axis – The category axis is used to describe the various sections of the information. This axis is distinct from the value axis in the sense that the specific values are not displayed on the category axis. In JavaFX, the class javafx.scene.chart.CategoryAxis depicts the category axis. A user just requires to instantiate this class in order to generate the category axis. Number Axis – The Number axis is used to express the specific range of values. In JavaFX, the class javafx.scene.chart.NumberAxis represents the value axis. A user just requires to instantiate this class in order to generate the Number axis. Different classes of JavaFX Charts In JavaFX, there are many charts that are used by the users in their applications. Below is the list of usually used charts while the GUI is designed using JavaFX. Pie Chart – In Pie Chart, the areas of a circle are used to define several proportions of the complete information. In JavaFX, the class javafx.scene.chart.PieChart is used to deal with the pie chart. Bar Chart – A bar chart is used to describe assorted data using rectangular bars. The length of these bars represents the values. The bars can be plotted both vertically and horizontally in the bar chart. In JavaFX, a Bar chart is represented by a class named javafx.scene.chart.BarChart. Line Chart – A line chart is applied to display the information as a list of data points (markers) connected by straight line segments. Line Chart explains how the data varies at regular time frequencies. In JavaFX, a line chart is represented by a class named javafx.scene.chart.LineChart. Area Chart – Area charts are applied to draw area-based charts. It plots the area between the given set of points and the axis. In general, this chart is used to differentiate two quantities. In JavaFX, an area chart is represented by a class named javafx.scene.chart.AreaChart. JavaFX Layouts Layouts are the top-level container classes that describe the UI styles for objects of the scene graph. The JavaFX layout can be seen as the father node to all the separate nodes. JavaFX presents several layout panes that promote various styles of layouts. In JavaFX, Layout describes the process in which the elements are to be viewed on the screen. It primarily establishes the scene-graph nodes. There are various built-in layout panes in JavaFX that are HBox, VBox, StackPane, FlowBox, AnchorPane, etc. Each Built-in layout is represented by a separate class that requires to be instantiated in order to implement that specific layout pane. All these classes belong to the javafx.scene.layout package. The javafx.scene.layout.Pane class is the root class for all the built-in classes of JavaFX layouts. Steps to create a JavaFX layout In order to create the layouts, we need to follow the following steps – 1. The first step to creating a layout in JavaFX application is that the user should instantiate the respective layout class, For example – If a user wants to create an HBox layout, then he should instantiate the HBox Class of JavaFX layout. HBox root = new HBox(); 2. After instantiating the respective class, the next step is to set the properties for the layout. root.setSpacing(20); 3. After the above two steps, the last step of creating a layout in the JavaFX application is to add nodes to the layout object. root.getChildren().addAll(<NodeObjects>); Different classes of JavaFX Layouts In JavaFX, there are various JavaFX Layout classes that are available for the user to use in their application. The following is a brief introduction of various layouts that are provided by JavaFX. HBox – The HBox layout is used to arrange all the nodes in the JavaFX application in a particular horizontal row. In JavaFX, an HBox layout is represented by a class named javafx.scene.layout.HBox. BorderPane – The Border Pane layout is used to arrange the nodes in the JavaFX application in the top, left, right, bottom, and center positions. In JavaFX, a BorderPane layout is represented by a class named javafx.scene.layout.BorderPane. GridPane – The Grid Pane layout is used to arranges the nodes in the JavaFX application as a grid of rows and columns. This layout is very convenient in designing forms using JavaFX. In JavaFX, a GridPane layout is represented by a class named javafx.scene.layout.GridPane. FlowPane – The flow pane layout is used to wrap all the nodes in a flow. A horizontal flow pane wraps the components of the pane at its height, while a vertical flow pane wraps the components at its width. In JavaFX, a FlowPane layout is represented by a class named javafx.scene.layout.FlowPane. StackPane – The stack pane layout is used to arrange the nodes in the JavaFX application on top of another just like in a stack. The node appended first is ordered at the bottom of the stack and the next node is stored on top of it. In JavaFX, a StackPane layout is represented by a class named javafx.scene.layout.StackPane. VBox – The VBox layout is used to arrange all the nodes in the JavaFX application in a single vertical column. In JavaFX, a VBox layout is represented by a class named javafx.scene.layout.VBox. JavaFX Event Handling JavaFX grants users the adaptability to generate numerous types of applications such as Desktop Applications, Web applications, and graphical applications. In recent-day applications, the users perform an essential role in the precise execution of the application. The user needs to interact with the application in most cases. In JavaFX, An event occurs whenever the user interacts with the application nodes. There are multiple references by using which, the user can create the event. For example, the user can make use of a mouse or it can press any button on the keyboard or it can scroll any page of the application in order to generate an event. Hence, we can say that the events are fundamentally the announcements that tell us that something has happened at the user’s end. A perfect Application is the one that takes the least amount of time in handling the events. Processing Events in JavaFX In JavaFX, events are primarily used to inform the application regarding the actions chosen by the user. JavaFX implements the tool to achieve the events, route the event to its target, and granting the application to handle the events. JavaFX presents the class javafx.event.Event which includes all the subclasses describing the varieties of events that can be created in JavaFX. Any event is an instance of the class Event or any of its subclasses. There are several events in JavaFX i.e. MouseEvent, KeyEvent, ScrollEvent, DragEvent, etc. A user can further specify their personal event by inheriting the class javafx.event.Event. Types of Events In general, the JavaFX events are principally grouped into the subsequent types – Foreground Events – Foreground events are essentially happened due to the straightforward communication of the user with the GUI of the application. For example, clicking the button, pressing a key, selecting an item from the list, scrolling the page, etc. Background Events – Background events don’t need the user’s interaction with the application. These events mainly occur due to the operating system interrupts failure, operation completion, etc. Foreground Events – Foreground events are essentially happened due to the straightforward communication of the user with the GUI of the application. For example, clicking the button, pressing a key, selecting an item from the list, scrolling the page, etc. Background Events – Background events don’t need the user’s interaction with the application. These events mainly occur due to the operating system interrupts failure, operation completion, etc. Different classes of JavaFX Event Handling JavaFX grants support to handle a wide variety of events. The class javafx.event.Event is the base class for every event. An instance of any of its subclass is an event. JavaFX provides a wide mixture of events. Some of them are placed below – KeyEvent – KeyEvent is an input event that symbolizes the keystroke that occurred on a node. This event includes actions like key pressed, key released and key typed. It is represented by the class named javafx.event.Event.KeyEvent. MouseEvent – MouseEvent is also an input event that happens when a mouse is clicked. It includes actions like mouse clicked, mouse pressed, mouse released, the mouse moved, mouse entered target, mouse exited target, etc. It is expressed by the class called javafx.event.Event.MouseEvent. WindowEvent – WindowEvent is an event associated with window showing and window hiding actions. It includes actions like window hiding, the window is shown, window hidden, window showing, etc. It is represented by the class named javafx.event.Event.WindowEvent. DragEvent – DragEventis an input event that occurs when the mouse is dragged. It involves activities like drag entered, drag dropped, drag entered target, drag exited target, drag over, etc. It is represented by the class named javafx.event.Event.DragEvent. The above were the different UI components of the JavaFX API. Setting up JavaFX in IDE We need to configure JavaFX in our IDE n order to use it for which here we are illustrating with the help of Eclipse IDE as it is widely used by Java developers. Step 1: Go to ‘Help’ section on by clicking the top right bar and further go into ‘Eclipse Marketplace’ as shown in below media. Step 2: Now write initials ‘fx’ and press enter. Below window will pop-up then install the e(fx)clipse 3.6.0 as shown below which will appear in top search as later on continue installing by accepting terms and conditions and press ‘Next’. It will take a little bit of time. Step 3: Restart the IDE and now open new ‘File’ new –> ‘Others’ and here you will find JavaFX plugin which earlier was not present here as depicted below as follows: Step 4: Choose JavaFX project and choose ‘Next’ Just likely naming normal project so do create JavaFX project and choose settings as per requirements, further click on ‘Next‘ later on ‘Finish‘. You will see this window where the keynote is that our IDE(eclipse) does not know where the JavaFX is as of now we only have set up JavaFX to work in eclipse only but have not been downloaded JavaFX. Step5: Download JavaFX by extracting it to a location on the system and do remember the specified path where you have extracted it. While downloading one can pick a long-term support version or the latest release version but the long-term version is recommended if one is new to JavaFX as the latest release can throw some errors. as per your operating system. Step 6: Create a user library Go to Windows –> Preferences and there type user and go to User Libraries. Here add a new user library and name t relevantly not necessarily to named JavaFX or retaining some previous counter names. to Step 7: Now go to ‘Add External JAR’ and do copy the path retained above where JavaFX is installed in the local directory and select all of them as shown below as follows: Click on ‘Apply and Close’ Step 8: Resolve unwanted errors that pop up by right-clicking the project and go to Build path –> Configure Build Path. Now go to Library –> Classpath and Add library. here you will find all user library and the name will pop up which was given earlier to the library. Click on Finish –> Apply –> Apply and Close and yu will see all the errors are gone by now. Step 9: Now configure Run configurations. Go to Run –> Java Application –> Main –> Arguments. keynote is here you need to pass the argument as shown in the image below but the path varies as per where you have installed JavaFX. --module-path "YOUR\PATH\lib" --add-modules javafx.controls,javafx.fxml After this one can start off with JavaFX operations as a window will be popped up by now. Cheers! The performance of both Java Swing and Java FX is supported in the graphics business. However, both of them are very different from each other. Some of the key differences between Java Swing and Java FX are given below – Java Swing JavaFX These are the main points of difference between JavaFX and Java Swing There are many real-world applications that were made using JavaFX. Some of the applications and their area of use are given below – JavaFX is a Java library and a GUI toolkit designed to develop and facilitate Rich Internet applications, web applications, and desktop applications. The most significant perk of using JavaFX is that the applications written using this library can run on multiple operating systems like Windows, Linux, iOS, Android, and several platforms like Desktops, Web, Mobile Phones, TVs, Tablets, etc. nishkarshgandhi JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Feb, 2022" }, { "code": null, "e": 562, "s": 52, "text": "JavaFX is a Java library and a GUI toolkit designed to develop and facilitate Rich Internet applications, web applications, and desktop applications. The most significant perk of using JavaFX is that the applications written using this library can run on multiple operating systems like Windows, Linux, iOS, Android, and several platforms like Desktops, Web, Mobile Phones, TVs, Tablets, etc. This characteristic of the JavaFX library makes it very versatile across operating systems and different platforms. " }, { "code": null, "e": 901, "s": 562, "text": "Sun Microsystems (now acquired by Oracle Corporation) released a toolkit known as JavaFX to promote desktop and rich internet applications (RIA) that can be accessed from the category of devices. After the arrival of JavaFX, Java developers and programmers were able to develop the GUI applications more effectively and more productively." }, { "code": null, "e": 1166, "s": 901, "text": "Note: Rich Internet Applications are those web applications that allow alike characteristics and expertise as that of desktop applications. These applications contribute more satisfying visual experience to the users when compared to the standard web applications." }, { "code": null, "e": 1711, "s": 1166, "text": "JavaFX was introduced to supersede the Java Swing GUI framework. Nevertheless, the JavaFX provides more enhanced functionalities and features than the Java Swing. Similar to the Java Swing, the JavaFX also implements its own components. The components of the JavaFX are irrespective of the Operating system. JavaFX is considered to be lightweight and hardware stimulated. According to a report, after using the JavaFX for the development of Rich Internet applications (RIA), the browser penetration rate recorded for these applications was 76%." }, { "code": null, "e": 2340, "s": 1711, "text": "Before JavaFX, developing the client base applications was a very complicated and cumbersome task. Programmers and developers used to require several libraries for adding various functionalities like media, UI controls, animations and effects, 2D and 3D shapes, etc., in their applications. This issue was resolved when JavaFX came into the picture, which changed the whole scenario of the development of web applications by bringing in all the peculiarities into one single library. Apart from this, the programmers can also utilize all the existing perks of the older libraries like Java Swing and Advanced Windowing Tool Kit." }, { "code": null, "e": 2769, "s": 2340, "text": "JavaFX also displays a valuable collection of graphics and various media APIs, which can further help in designing smooth applications. JavaFX also leverages the improved Graphical Processing Unit (GUI) with the help of hardware-accelerated graphics. If a developer wants to combine the graphics animations and UI control in their applications, then they can use the various interfaces provided by the JavaFX. History of JavaFX" }, { "code": null, "e": 3178, "s": 2769, "text": "JavaFX was formerly developed by Chris Oliver. At that time, he was serving for a company named See Beyond Technology Corporation. Initially, the JavaFX project was recognized as Form Follows Functions (F3). This project was designed with the aim of providing richer interfaces for developing GUI applications. Later in June 2005, Sun Micro-systems took the F3 project and changed its name from F3 to JavaFX." }, { "code": null, "e": 3197, "s": 3178, "text": "Timeline of JavaFX" }, { "code": null, "e": 3306, "s": 3197, "text": "2005 – Sun Microsystems took over the See Beyond company in June 2005 and acquired the F3 project as JavaFX." }, { "code": null, "e": 3405, "s": 3306, "text": "2007 – JavaFX was officially declared at Java One, a worldwide web conference that is held yearly." }, { "code": null, "e": 3546, "s": 3405, "text": "2008 – Net Beans integration with JavaFX was made open. The Java Standard Development Kit for JavaFX 1.0 was also released in the same year." }, { "code": null, "e": 3741, "s": 3546, "text": "2009 – The next version of JavaFX was released, i.e., JavaFX 1.2, and the support for JavaFX Mobile was also introduced. In the same year only, Oracle Corporation also acquired Sun Microsystems." }, { "code": null, "e": 3789, "s": 3741, "text": "2010 – JavaFX version 1.3 was released in 2010." }, { "code": null, "e": 3834, "s": 3789, "text": "2011 – In 2011, JavaFX version 2.0 came out." }, { "code": null, "e": 3899, "s": 3834, "text": "2012 – The support for JavaFX Mac OS for desktop was introduced." }, { "code": null, "e": 4032, "s": 3899, "text": "2014 – The most advanced version of JavaFX, i.e., JavaFX 8, was released as an indispensable part of Java on the 18th of March 2014." }, { "code": null, "e": 4384, "s": 4032, "text": "JavaFX is an open-source framework based on Java, used for advancing rich client applications. JavaFX is recognized as the replacement or successor of the Java Swing in the field of graphical user interface (GUI) development technology in the platform of Java. The JavaFX library is available as a public Java application programming interface (API). " }, { "code": null, "e": 4552, "s": 4384, "text": "The JavaFX library comprises numerous peculiarities that make it a handpicked option for developers to develop rich client applications. These features are as follows:" }, { "code": null, "e": 8283, "s": 4552, "text": "Java Library – JavaFX is a Java library, which allows the user to gain the support of all the Java characteristics such as multithreading, generics, lambda expressions, and many more. The user can also use any of the Java editors or IDE’s of their choice, such as Eclipse, NetBeans, to write, compile, run, debug, and package their JavaFX application. Platform Independent – The rich internet applications made using JavaFX are platform-independent. The JavaFX library is open for all the scripting languages that can be administered on a JVM, which comprise – Java, Groovy, Scala, and JRuby. FXML – JavaFX emphasizes an HTML-like declarative markup language known as FXML. FXML is based on extensible markup language (XML). The sole objective of this markup language is to specify a user interface (UI). In FXML, the programming can be done to accommodate the user with an improved GUI. Scene Builder – JavaFX also implements a tool named Scene Builder, which is a visual editor for FXML. Scene Builder generates FXML mark-ups that can be transmitted to the IDE’s like Eclipse and NetBeans, which further helps the user to combine the business logic to their applications. The users can also use the drag and drop design interface, which is used to design FXML applications (just like the Drag & Drop feature of the Java Swing and DreamWeaver Applications). Hardware-accelerated Graphics Pipeline – The graphics of the JavaFX applications are based on the hardware-accelerated graphics rendering pipeline, commonly known as Prism. The Prism engine offers smooth JavaFX graphics that can be rendered quickly when utilized with a supported graphics card or graphics processing unit (GPU). In the case where the system does not hold the graphic cards, then the prism engine defaults to the software rendering stack. WebView – JavaFX applications can also insert web pages. To embed web pages, Web View of JavaFX uses a new HTML rendering engine technology known as WebKitHTML. WebView is used to make it possible to insert web pages within a JavaFX application. JavaScript running in WebView can call Java APIs and vice-versa. Built-in UI controls – JavaFX comprises all the major built-in UI controls that help in developing well-featured applications. These built-in UI components are not operating system-dependent. In simple words, these controls do not depend on any of the Operating systems like Windows, iOS, Android, etc. These built-in controls are single-handedly ample to perform a whole implementation of the applications. CSS Styling – Just like websites use CSS for styling, JavaFX also provides the feature to integrate the application with CSS styling. The users can enhance the styling of their applications and can also improve the outlook of their implementation by having simple knowledge and understanding of CSS styling. Rich set of APIs – JavaFX library also presents a valuable collection of APIs that helps in developing GUI applications, 2D and 3D graphics, and many more. This collection of APIs also includes all the characteristics of the Java platform. Hence, working with this API, a user can access the specialties of Java languages such as Generics, Annotations, Multithreading, and Lambda Expressions, and many other features as well. In JavaFX, the popular Java Collections library was also improved, and notions like lists and maps were introduced. Using these APIs, the users can witness the variations in the data models. High-Performance media engine – Like the graphics pipeline, JavaFX also possesses a media pipeline that advances stable internet multimedia playback at low latency. This high-performance media engine or media pipeline is based on a multimedia framework known as Gstreamer." }, { "code": null, "e": 8636, "s": 8283, "text": "Java Library – JavaFX is a Java library, which allows the user to gain the support of all the Java characteristics such as multithreading, generics, lambda expressions, and many more. The user can also use any of the Java editors or IDE’s of their choice, such as Eclipse, NetBeans, to write, compile, run, debug, and package their JavaFX application. " }, { "code": null, "e": 8878, "s": 8636, "text": "Platform Independent – The rich internet applications made using JavaFX are platform-independent. The JavaFX library is open for all the scripting languages that can be administered on a JVM, which comprise – Java, Groovy, Scala, and JRuby. " }, { "code": null, "e": 9174, "s": 8878, "text": "FXML – JavaFX emphasizes an HTML-like declarative markup language known as FXML. FXML is based on extensible markup language (XML). The sole objective of this markup language is to specify a user interface (UI). In FXML, the programming can be done to accommodate the user with an improved GUI. " }, { "code": null, "e": 9646, "s": 9174, "text": "Scene Builder – JavaFX also implements a tool named Scene Builder, which is a visual editor for FXML. Scene Builder generates FXML mark-ups that can be transmitted to the IDE’s like Eclipse and NetBeans, which further helps the user to combine the business logic to their applications. The users can also use the drag and drop design interface, which is used to design FXML applications (just like the Drag & Drop feature of the Java Swing and DreamWeaver Applications). " }, { "code": null, "e": 10102, "s": 9646, "text": "Hardware-accelerated Graphics Pipeline – The graphics of the JavaFX applications are based on the hardware-accelerated graphics rendering pipeline, commonly known as Prism. The Prism engine offers smooth JavaFX graphics that can be rendered quickly when utilized with a supported graphics card or graphics processing unit (GPU). In the case where the system does not hold the graphic cards, then the prism engine defaults to the software rendering stack. " }, { "code": null, "e": 10414, "s": 10102, "text": "WebView – JavaFX applications can also insert web pages. To embed web pages, Web View of JavaFX uses a new HTML rendering engine technology known as WebKitHTML. WebView is used to make it possible to insert web pages within a JavaFX application. JavaScript running in WebView can call Java APIs and vice-versa. " }, { "code": null, "e": 10823, "s": 10414, "text": "Built-in UI controls – JavaFX comprises all the major built-in UI controls that help in developing well-featured applications. These built-in UI components are not operating system-dependent. In simple words, these controls do not depend on any of the Operating systems like Windows, iOS, Android, etc. These built-in controls are single-handedly ample to perform a whole implementation of the applications. " }, { "code": null, "e": 11132, "s": 10823, "text": "CSS Styling – Just like websites use CSS for styling, JavaFX also provides the feature to integrate the application with CSS styling. The users can enhance the styling of their applications and can also improve the outlook of their implementation by having simple knowledge and understanding of CSS styling. " }, { "code": null, "e": 11750, "s": 11132, "text": "Rich set of APIs – JavaFX library also presents a valuable collection of APIs that helps in developing GUI applications, 2D and 3D graphics, and many more. This collection of APIs also includes all the characteristics of the Java platform. Hence, working with this API, a user can access the specialties of Java languages such as Generics, Annotations, Multithreading, and Lambda Expressions, and many other features as well. In JavaFX, the popular Java Collections library was also improved, and notions like lists and maps were introduced. Using these APIs, the users can witness the variations in the data models. " }, { "code": null, "e": 12023, "s": 11750, "text": "High-Performance media engine – Like the graphics pipeline, JavaFX also possesses a media pipeline that advances stable internet multimedia playback at low latency. This high-performance media engine or media pipeline is based on a multimedia framework known as Gstreamer." }, { "code": null, "e": 12344, "s": 12023, "text": "JavaFX has numerous built-in elements that are interconnected with each other. JavaFX library comprises a valuable collection of APIs, classes, and interfaces that are more than sufficient to produce rich internet applications and GUI applications with intense graphics that can run consistently over multiple platforms." }, { "code": null, "e": 12484, "s": 12344, "text": "The subsequent figure displays the complete architecture of the JavaFX platform. Here you can examine the elements that support JavaFX API." }, { "code": null, "e": 12632, "s": 12484, "text": "As we can see in the above figure that, JavaFX architecture comprises many different components. These components are briefly described as follows:" }, { "code": null, "e": 14793, "s": 12632, "text": "JavaFX API – The topmost layer of JavaFX architecture holds a JavaFX public API that implements all the required classes that are capable of producing a full-featured JavaFX application with rich graphics. The list of all the important packages of this API is as follows.javafx.animation: It includes classes that are used to combine transition-based animations such as fill, fade, rotate, scale and translation, to the JavaFX nodes (collection of nodes makes a scene graph). javafx.css − It comprises classes that are used to append CSS–like styling to the JavaFX GUI applications.javafx.geometry − It contains classes that are used to represent 2D figures and execute methods on them.javafx.scene − This package of JavaFX API implements classes and interfaces to establish the scene graph. In extension, it also renders sub-packages such as canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web, etc. These are the diverse elements that sustain this precious API of JavaFX.javafx.application − This package includes a collection of classes that are responsible for the life cycle of the JavaFX application.javafx.event − It includes classes and interfaces that are used to perform and manage JavaFX events.javafx.stage − This package of JavaFX API accommodates the top-level container classes used for the JavaFX application.Scene Graph – A Scene Graph is the starting point of the development of any of the GUI Applications. In JavaFX, all the GUI Applications are made using a Scene Graph only. The Scene Graph includes the primitives of the rich internet applications that are known as nodes. In simple words, a single component in a scene graph is known as a node. In general, a scene graph is made up of a collection of nodes. All these nodes are organized in the form of a hierarchical tree that describes all of the visual components of the application’s user interface (UI). A node instance can be appended to a scene graph only once. The nodes of a scene graph can have numerous segments like Effects, Opacity, Transforms, Event Handlers, Application Specific States. The nodes are of three general types." }, { "code": null, "e": 15065, "s": 14793, "text": "JavaFX API – The topmost layer of JavaFX architecture holds a JavaFX public API that implements all the required classes that are capable of producing a full-featured JavaFX application with rich graphics. The list of all the important packages of this API is as follows." }, { "code": null, "e": 15271, "s": 15065, "text": "javafx.animation: It includes classes that are used to combine transition-based animations such as fill, fade, rotate, scale and translation, to the JavaFX nodes (collection of nodes makes a scene graph)." }, { "code": null, "e": 15379, "s": 15271, "text": " javafx.css − It comprises classes that are used to append CSS–like styling to the JavaFX GUI applications." }, { "code": null, "e": 15484, "s": 15379, "text": "javafx.geometry − It contains classes that are used to represent 2D figures and execute methods on them." }, { "code": null, "e": 15816, "s": 15484, "text": "javafx.scene − This package of JavaFX API implements classes and interfaces to establish the scene graph. In extension, it also renders sub-packages such as canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web, etc. These are the diverse elements that sustain this precious API of JavaFX." }, { "code": null, "e": 15950, "s": 15816, "text": "javafx.application − This package includes a collection of classes that are responsible for the life cycle of the JavaFX application." }, { "code": null, "e": 16051, "s": 15950, "text": "javafx.event − It includes classes and interfaces that are used to perform and manage JavaFX events." }, { "code": null, "e": 16171, "s": 16051, "text": "javafx.stage − This package of JavaFX API accommodates the top-level container classes used for the JavaFX application." }, { "code": null, "e": 16962, "s": 16171, "text": "Scene Graph – A Scene Graph is the starting point of the development of any of the GUI Applications. In JavaFX, all the GUI Applications are made using a Scene Graph only. The Scene Graph includes the primitives of the rich internet applications that are known as nodes. In simple words, a single component in a scene graph is known as a node. In general, a scene graph is made up of a collection of nodes. All these nodes are organized in the form of a hierarchical tree that describes all of the visual components of the application’s user interface (UI). A node instance can be appended to a scene graph only once. The nodes of a scene graph can have numerous segments like Effects, Opacity, Transforms, Event Handlers, Application Specific States. The nodes are of three general types." }, { "code": null, "e": 16984, "s": 16962, "text": "These are as follows:" }, { "code": null, "e": 17061, "s": 16984, "text": "Root Node – A root node is a node that does not have any node as its parent." }, { "code": null, "e": 17143, "s": 17061, "text": "Leaf Node – A leaf node is a node that does not contain any node as its children." }, { "code": null, "e": 17253, "s": 17143, "text": "Branch Node – A branch node is a node that contains a node as its parent and also has a node as its children." }, { "code": null, "e": 17502, "s": 17253, "text": "10. Quantum Toolkit – Quantum Toolkit is used to connect prism and glass windowing tool kits collectively and makes them prepared for the above layers in the stack. In simple words, it ties Prism and GWT together and makes them available to JavaFX." }, { "code": null, "e": 17977, "s": 17502, "text": "11. Prism – The graphics of the JavaFX applications are based on the hardware-accelerated graphics rendering pipeline, commonly known as Prism. The Prism engine supports smooth JavaFX graphics that can be executed swiftly when utilized with a backed graphics card or graphics processing unit (GPU). In the situation where the system does not contain the graphic cards, then the prism engine defaults to the software rendering stack. To interpret graphics, a Prism practice −" }, { "code": null, "e": 18012, "s": 17977, "text": "DirectX 9 on Windows XP and Vista." }, { "code": null, "e": 18037, "s": 18012, "text": "DirectX 11 on Windows 7." }, { "code": null, "e": 18080, "s": 18037, "text": "OpenGL on Mac and Linux, Embedded Systems." }, { "code": null, "e": 18422, "s": 18080, "text": "12. Glass Windowing Toolkit – Glass Windowing Toolkit or simply Glass is a platform-dependent layer that assists in connecting the JavaFX platform to the primary operating system (OS). Glass Windowing Toolkit is very useful as it provides services such as controlling the windows, events, timers, and surfaces to the native operating system." }, { "code": null, "e": 18998, "s": 18422, "text": "13. WebView – JavaFX applications can also insert web pages. To embed web pages, Web View of JavaFX uses a new HTML rendering engine technology known as WebKitHTML. WebView is used to make it possible to insert web pages within a JavaFX application. JavaScript appearing in WebView can call Java APIs and vice-versa. This element promotes different web technologies like HTML5, CSS, JavaScript, DOM, and SVG. Using web view, we can execute the HTML content from the JavaFX application and can also implement some CSS styles to the user interface (UI) part of the application." }, { "code": null, "e": 19500, "s": 18998, "text": "14. Media Engine – Like the graphics pipeline, JavaFX also possesses a media pipeline that advances stable internet multimedia playback at low latency. This high-performance media engine or media pipeline is based on a multimedia framework known as Gstreamer. By applying the Media engine, the JavaFX application can support the playback of audio and video media files. The package javafx.scene.media covers all the classes and interfaces that can provide media functionalities to JavaFX applications." }, { "code": null, "e": 19579, "s": 19500, "text": "The foregoing were the components that constitute the architecture of JavaFX. " }, { "code": null, "e": 19676, "s": 19579, "text": "There are in total three life cycle methods of a JavaFX Application class. These methods are – " }, { "code": null, "e": 19813, "s": 19676, "text": "start() – The start() method is the entry point method of the JavaFX application where all the graphics code of JavaFX is to be written." }, { "code": null, "e": 19942, "s": 19813, "text": "init() – The init() method is an empty method that can be overridden. In this method, the user cannot create a stage or a scene." }, { "code": null, "e": 20115, "s": 19942, "text": "stop() – The stop() method is an empty method that can also be overridden, just like the init() method. In this method, the user can write the code to halt the application." }, { "code": null, "e": 20471, "s": 20115, "text": "Other than these methods, the JavaFX application also implements a static method known as launch(). This launch() method is used to launch the JavaFX application. As stated earlier, the launch() method is static, the user should call it from a static method only. Generally, that static method, which calls the launch() method, is the main() method only. " }, { "code": null, "e": 20666, "s": 20471, "text": "Whenever a user launches a JavaFX application, there are few actions that are carried out in a particular manner only. The following is the order given in which a JavaFX application is launched." }, { "code": null, "e": 20938, "s": 20666, "text": "Firstly, an instance of the application class is created.After that, the init() method is called.After the init() method, the start() method is called.After calling the start() method, the launcher waits for the JavaFX application to end and then calls the stop() method." }, { "code": null, "e": 20996, "s": 20938, "text": "Firstly, an instance of the application class is created." }, { "code": null, "e": 21037, "s": 20996, "text": "After that, the init() method is called." }, { "code": null, "e": 21092, "s": 21037, "text": "After the init() method, the start() method is called." }, { "code": null, "e": 21213, "s": 21092, "text": "After calling the start() method, the launcher waits for the JavaFX application to end and then calls the stop() method." }, { "code": null, "e": 21248, "s": 21213, "text": "Terminating the JavaFX application" }, { "code": null, "e": 21535, "s": 21248, "text": "As soon as the last window of the JavaFX application is closed, the JavaFX application is stopped implicitly. The user can turn off this function by passing the Boolean value “False” to the static method setImplicitExit(). This method should always be called from a static context only." }, { "code": null, "e": 21665, "s": 21535, "text": "The user can also stop a JavaFX application explicitly by practicing any of the two methods, Platform.exit() or System.exit(int)." }, { "code": null, "e": 21706, "s": 21665, "text": "User Interface (UI) Components of JavaFX" }, { "code": null, "e": 22093, "s": 21706, "text": "JavaFX comprises all the major built-in UI components that help in developing well-featured applications. These built-in UI components are not operating system-dependent. In simple words, these controls do not depend on any of the Operating systems like Windows, iOS, Android, etc. These built-in controls are single-handedly ample to perform a whole implementation of the applications." }, { "code": null, "e": 22246, "s": 22093, "text": "The users can add numerous components to their applications to make them look more advanced and rich in graphics. These segments are defined as follows:" }, { "code": null, "e": 22496, "s": 22246, "text": "Any geometrical shape that can be represented on the coordinate system using two planes, which are X and Y planes, is known as a two-dimensional shape or a 2D shape. Examples of 2D shapes are line, square, rectangle, circle, eclipse, and many more. " }, { "code": null, "e": 22984, "s": 22496, "text": "JavaFX gives the flexibility to the user to add and create these 2D shapes in their JavaFX applications. There are several classes in JavaFX API that are used to execute 2D shapes in the JavaFX application. All these classes of 2D shapes are part of the javafx.scene.shape package. The class named Shape is the root class of all the 2-Dimensional shapes in JavaFX. There are many classes in this package that contains various sorts of 2D shapes.Steps to create a 2D shape are as follows:" }, { "code": null, "e": 23352, "s": 22984, "text": "Step 1: The first step to add a 2D shape in a JavaFX application is to instantiate the corresponding class of the needed shape. For illustration purposes consider if a user wants to add a line to their JavaFX application, they should first instantiate the javafx.scene.shape.line class. They also need to instantiate an object of the same class like as defined below:" }, { "code": null, "e": 23376, "s": 23352, "text": "Line line = new Line();" }, { "code": null, "e": 23761, "s": 23376, "text": "Step 2: After the instantiation of the class and the object, the user should also set the properties of the required shape using the setter functions. For illustration purposes consider if a user wants to add a line to their JavaFX application, then after instantiation, they should set the X and Y coordinates of the starting and ending point of the line as defined below as follows:" }, { "code": null, "e": 23851, "s": 23761, "text": "line.setStartX(0); \nline.setStartY(0); \nline.setEndX(100); \nline.setEndY(200);" }, { "code": null, "e": 24231, "s": 23851, "text": "Step 3: After doing the above two steps, the third step for the user is to add the object instantiated of the required shape to the group by declaring it as a parameter of the constructor. For illustration purposes consider if in order to get a line in the JavaFX application, the user should add the instantiated object of line shape to the group, then it is defined as follows:" }, { "code": null, "e": 24288, "s": 24231, "text": "Group root = new Group();\nroot.getChildren().add(line); " }, { "code": null, "e": 24307, "s": 24288, "text": "Types of 2D shapes" }, { "code": null, "e": 24525, "s": 24307, "text": "In the javafx.scene.shape package of JavaFX, there are numerous shapes available which the user can use in their application. The following is the list of various classes of the 2D shapes that are provided by JavaFX. " }, { "code": null, "e": 24765, "s": 24525, "text": "Line – A geometrical structure that joins two coordinates (X and Y) on a 2D coordinate system is known as a Line. If a user wants to create a line in their JavaFX application, then they should instantiate the javafx.scene.shape.Line class." }, { "code": null, "e": 25027, "s": 24765, "text": "Rectangle – A Rectangle is a geometrical shape that has two sets of two identical sides and four right angles at their joint. If a user wants to create a rectangle in their JavaFX application, then they should instantiate the javafx.scene.shape.Rectangle class." }, { "code": null, "e": 25346, "s": 25027, "text": "Ellipse – In general, an ellipse can be defined as a curve with two focal points. In an ellipse, the sum of the distances to the focal points is constant from each point of the ellipse. If a user wants to create an ellipse in their JavaFX application, then they should instantiate the javafx.scene.shape.Ellipse class." }, { "code": null, "e": 25602, "s": 25346, "text": "Circle – In general, a specific sort of Ellipse that has both of its focal points at the same location is known as a circle. If a user wants to create a circle in their JavaFX application, then they should instantiate the javafx.scene.shape.Circle class." }, { "code": null, "e": 25821, "s": 25602, "text": "Arc – An arc can be defined as the portion of the circumference of the circle or an ellipse. If a user wants to create an arc in their JavaFX application, then they should instantiate the javafx.scene.shape.Arc class." }, { "code": null, "e": 26076, "s": 25821, "text": "Polygon – In general, a Polygon is a geometrical shape that can be formed by joining the various Co-planner line segments. If a user wants to create a polygon in their JavaFX application, then they should instantiate the javafx.scene.shape.Polygon class." }, { "code": null, "e": 26292, "s": 26076, "text": "Cubic Curve – A curve of degree 3 in the XY plane is known as a cubic curve. If a user wants to create a cubic curve in their JavaFX application, then they should instantiate the javafx.scene.shape.CubicCurve class." }, { "code": null, "e": 26504, "s": 26292, "text": "Quad Curve – A curve of degree 2 in the XY plane is known as a quad curve. If a user wants to create a quad curve in their JavaFX application, then they should instantiate the javafx.scene.shape.QuadCurve class." }, { "code": null, "e": 26796, "s": 26504, "text": "Any behavior or movement that improves the presentation of the graphics is known as an Effect. In JavaFX, we can say that any algorithm that is applied to nodes to enhance their appearance visually is an effect. In order to specify the effect, the effect property of the Node class is used. " }, { "code": null, "e": 27251, "s": 26796, "text": "JavaFX gives the flexibility to the user to add various effects such as bloom, blur, and glow in their JavaFX applications. There are several classes in JavaFX API that are used to execute these effects in the JavaFX application. All these classes of effects are part of the javafx.scene.effects package. The class named Effect is the root class of all the effects in JavaFX. There are many classes in this package that contains various sorts of effects." }, { "code": null, "e": 27350, "s": 27251, "text": "In order to add an effect to a Node, the user needs to sequentially follow these steps as follows:" }, { "code": null, "e": 27756, "s": 27350, "text": "Step 1: The first step to applying an effect to a Node is to create all the nodes in a JavaFX application by instantiating their individual classes. For illustration purposes consider if a user wants to apply the glow effect to an image in their application, then they should create an image node first by instantiating the Image class. After that, they should set its view just as shown below as follows:" }, { "code": null, "e": 27777, "s": 27756, "text": "// Creating an image" }, { "code": null, "e": 27912, "s": 27777, "text": "Image img = new Image(“https://media.geeksforgeeks.org/wp-content/uploads/20210224040124/JSBinCollaborativeJavaScriptDebugging6.png”);" }, { "code": null, "e": 27938, "s": 27912, "text": "// Setting the image view" }, { "code": null, "e": 27978, "s": 27938, "text": "ImageView imgView = new ImageView(img);" }, { "code": null, "e": 28015, "s": 27978, "text": "// Setting the position of the image" }, { "code": null, "e": 28034, "s": 28015, "text": "imgView.setX(100);" }, { "code": null, "e": 28053, "s": 28034, "text": "imgView.setY(100);" }, { "code": null, "e": 28107, "s": 28053, "text": "// Setting the fit height and width of the image view" }, { "code": null, "e": 28134, "s": 28107, "text": "imgView.setFitHeight(200);" }, { "code": null, "e": 28160, "s": 28134, "text": "imgView.setFitWidth(400);" }, { "code": null, "e": 28208, "s": 28160, "text": "// Setting the preserve ratio of the image view" }, { "code": null, "e": 28240, "s": 28208, "text": "imgView.setPreserveRatio(true);" }, { "code": null, "e": 28605, "s": 28240, "text": "Step 2: After creating the image node and setting the image view, the user should instantiate the class representing the required effect that is needed to be applied to the node created. For illustration purposes of considering if the user wants to apply the glow effect in their application, then they need to instantiate the Glow class as shown below as follows:" }, { "code": null, "e": 28629, "s": 28605, "text": "Glow glow = new Glow();" }, { "code": null, "e": 28915, "s": 28629, "text": "Step 3: After instantiating the class of the required effect, the user needs to set the attributes for the instantiated effect using its setter methods. For illustration purposes consider as if the user can set the attributed of the Glow effect using the below-shown method as follows:" }, { "code": null, "e": 28965, "s": 28915, "text": "// Setting the level property\nglow.setLevel(0.9);" }, { "code": null, "e": 29092, "s": 28965, "text": "Step 4: After the above three steps, the user can finally apply the required effect to the node using the setEffect() method. " }, { "code": null, "e": 29225, "s": 29092, "text": "For example – The user can set the glow effect to the image node by passing the object of the Glow class to this method as follows –" }, { "code": null, "e": 29251, "s": 29225, "text": "imgView.setEffect(glow); " }, { "code": null, "e": 29471, "s": 29251, "text": "In the javafx.scene.effect package of JavaFX, there are numerous effects available which the user can use in their application. The following is the list of various classes of these effects that are provided by JavaFX. " }, { "code": null, "e": 31632, "s": 29471, "text": "Blend – A mixture of two or more different things or substances is known as a Blend. If the user applies the blend effect, then, this effect takes the pixels of the two distinct inputs, at the same location and creates a blended (combined) output based on the blend mode. The class javafx.scene.effect.Blend represents the blend effect. Glow – The Glow effect of JavaFX makes the provided input image glow. Using this effect, the bright pixels of the input can be made brighter. The class javafx.scene.effect.Glow represents the glow effect. Bloom – Just like the Glow effect, in the Bloom effect also the pixels in some parts of the node are produced to glow. The class javafx.scene.effect.Bloom represents the bloom effect. Shadow – The shadow effect is an effect that generates a duplicate of the given node with some blurry edges. The class javafx.scene.effect.Shadow represents the shadow effect. Reflection – In the reflection effect of JavaFX, whenever a user applies this effect to a specified node, then a reflection of the node is appended at the bottom of the node.The class javafx.scene.effect.Reflection represents the reflection effect. Color Adjust – In JavaFX, a user can also alter the color of an image by implementing the color adjust effect to it. This effect involves the adjustment of the hue, saturation, brightness, and contrast on every pixel. The class javafx.scene.effect.ColorAdjust represents the Color Adjust effect. SepiaTone – In JavaFX, when the Sepia tone effect is applied to a node of JavaFX (image in most cases), then that node is toned with a reddish-brown color. The class javafx.scene.effect.SepiaTone represents the Sepia Tone effect. Lighting – The effect which is used to resemble a light from a light source is known as the Lighting effect. In JavaFX, there can be various sorts of light sources specifically point, distant, and spot. The class javafx.scene.effect.Lighting represents the Lighting effect. InnerShadow – When a user applies this effect to a node, then a shadow of that node will be generated inside the edges of the node. The class javafx.scene.effect.InnerShadow represents the Inner shadow effect." }, { "code": null, "e": 31970, "s": 31632, "text": "Blend – A mixture of two or more different things or substances is known as a Blend. If the user applies the blend effect, then, this effect takes the pixels of the two distinct inputs, at the same location and creates a blended (combined) output based on the blend mode. The class javafx.scene.effect.Blend represents the blend effect. " }, { "code": null, "e": 32176, "s": 31970, "text": "Glow – The Glow effect of JavaFX makes the provided input image glow. Using this effect, the bright pixels of the input can be made brighter. The class javafx.scene.effect.Glow represents the glow effect. " }, { "code": null, "e": 32361, "s": 32176, "text": "Bloom – Just like the Glow effect, in the Bloom effect also the pixels in some parts of the node are produced to glow. The class javafx.scene.effect.Bloom represents the bloom effect. " }, { "code": null, "e": 32538, "s": 32361, "text": "Shadow – The shadow effect is an effect that generates a duplicate of the given node with some blurry edges. The class javafx.scene.effect.Shadow represents the shadow effect. " }, { "code": null, "e": 32788, "s": 32538, "text": "Reflection – In the reflection effect of JavaFX, whenever a user applies this effect to a specified node, then a reflection of the node is appended at the bottom of the node.The class javafx.scene.effect.Reflection represents the reflection effect. " }, { "code": null, "e": 33085, "s": 32788, "text": "Color Adjust – In JavaFX, a user can also alter the color of an image by implementing the color adjust effect to it. This effect involves the adjustment of the hue, saturation, brightness, and contrast on every pixel. The class javafx.scene.effect.ColorAdjust represents the Color Adjust effect. " }, { "code": null, "e": 33316, "s": 33085, "text": "SepiaTone – In JavaFX, when the Sepia tone effect is applied to a node of JavaFX (image in most cases), then that node is toned with a reddish-brown color. The class javafx.scene.effect.SepiaTone represents the Sepia Tone effect. " }, { "code": null, "e": 33591, "s": 33316, "text": "Lighting – The effect which is used to resemble a light from a light source is known as the Lighting effect. In JavaFX, there can be various sorts of light sources specifically point, distant, and spot. The class javafx.scene.effect.Lighting represents the Lighting effect. " }, { "code": null, "e": 33801, "s": 33591, "text": "InnerShadow – When a user applies this effect to a node, then a shadow of that node will be generated inside the edges of the node. The class javafx.scene.effect.InnerShadow represents the Inner shadow effect." }, { "code": null, "e": 34464, "s": 33801, "text": "Just like several shapes and effects, a user can also create a node for applying different texts in JavaFX. The text node is expressed by the class named Text, which belongs to the javafx.scene.text package. This Text class includes numerous characteristics to generate text in JavaFX and alter its appearance. Another feature of the text class is that this class also inherits the Shape class of JavaFX which belongs to the javafx.scene.shape package. Hence, in extension to the characteristics of the text like font, alignment, line spacing, text, etc., it also acquires the basic shape node properties such as strokeFill, stroke, strokeWidth, strokeType, etc." }, { "code": null, "e": 34538, "s": 34464, "text": "To create a text node, the user needs to follow certain steps as follows:" }, { "code": null, "e": 34668, "s": 34538, "text": "Step 1: The first step to create a text node in a JavaFX application is to instantiate the corresponding class of the text node. " }, { "code": null, "e": 34843, "s": 34668, "text": "Illustration: The class Text of the package javafx.scene.text denotes the text node in JavaFX. A user can create a text by instantiating this class as given below as follows:" }, { "code": null, "e": 34866, "s": 34843, "text": "Text txt = new Text();" }, { "code": null, "e": 35058, "s": 34866, "text": "Step 2: After instantiating the corresponding class of the text node, the second step to create a text node in JavaFX is to set the properties of the required text using the setter functions." }, { "code": null, "e": 35211, "s": 35058, "text": "Illustration: After instantiating the Text class, the user needs to set the value to this property using the setText() method as shown below as follows:" }, { "code": null, "e": 35296, "s": 35211, "text": "String text = \"Hello how are you\" \ntxt.setText(text);\ntxt.setX(50); \ntxt.setY(50);" }, { "code": null, "e": 35484, "s": 35296, "text": "Step 3: After doing the above two steps, the third step for the user is to add the object instantiated of the required text to the group by declaring it as a parameter of the constructor." }, { "code": null, "e": 35623, "s": 35484, "text": "Illustration: In order to get a text in the JavaFX application, the user should add the instantiated object of the text node to the group." }, { "code": null, "e": 35679, "s": 35623, "text": "Group root = new Group();\nroot.getChildren().add(txt); " }, { "code": null, "e": 35750, "s": 35679, "text": "The attributes of the JavaFX Text are represented in the table below. " }, { "code": null, "e": 36433, "s": 35750, "text": "The transition which produces the myth of motion for an object is known as animation. Animations can also be defined as the set of transformations implemented on an object over the specified duration sequentially so that the object can be displayed as it is in action. This can be achieved by the rapid display of frames. In JavaFX, the package javafx.animation includes all the classes that assist in applying the animations onto the nodes. All the classes of this package extend the class javafx.animation.Animation. JavaFX provides the classes for the transitions like RotateTransition, ScaleTransition, TranslateTransition, FadeTransition, FillTransition, StrokeTransition, etc." }, { "code": null, "e": 36494, "s": 36433, "text": "Steps to apply animations to the target node are as follows:" }, { "code": null, "e": 36596, "s": 36494, "text": "To apply a special animation to a target node, a user should follow the below-given steps as follows:" }, { "code": null, "e": 36726, "s": 36596, "text": "Step 1: The first step to applying an animation to a specific node is to create that node using the respective class of the node." }, { "code": null, "e": 36800, "s": 36726, "text": "Square sqr = new Square(100,100,100,100); \nsqr.setFill(Color.GREEN); " }, { "code": null, "e": 36939, "s": 36800, "text": "Step 2: After creating the node, the next step is to instantiate the respective animation class that is to be applied to the created node." }, { "code": null, "e": 36991, "s": 36939, "text": "RotateTransition rotate = new RotateTransition(); " }, { "code": null, "e": 37117, "s": 36991, "text": "Step 3: After instantiating the respective animation class, in the step, the user should set the properties of the animation." }, { "code": null, "e": 37227, "s": 37117, "text": "rotate.setDuration(Duration.millis(2000)); \nrotate.setAxis(Rotate.Y_Axis); \nrotate.setCycleCount(1000); " }, { "code": null, "e": 37329, "s": 37227, "text": "Step 4: In the next step, the user should set the target node on which the animation will be applied." }, { "code": null, "e": 37352, "s": 37329, "text": "rotate.setNode(sqr); " }, { "code": null, "e": 37531, "s": 37352, "text": "Step 5: After following all the above steps, the last step to apply an animation to a target node is to play the applied animation using the play() method of the Animation class." }, { "code": null, "e": 37548, "s": 37531, "text": "rotate.play(); " }, { "code": null, "e": 37755, "s": 37548, "text": "In the javafx.animation package of JavaFX, there are numerous transitions available which the user can use in their application. The following is the list of various animations that are provided by JavaFX. " }, { "code": null, "e": 38045, "s": 37755, "text": "Scale Transition – The Scale transition is used to animate the scaling of the selective node over a specific duration of time. If a user wants to implement the scale transition to a node in their JavaFX application, then they should instantiate the javafx.animation.ScaleTransition class. " }, { "code": null, "e": 38367, "s": 38045, "text": "Translate Transition – The Translate transition is used to translate the selective node from one location to another over a specific duration of time. If a user wants to implement the translate transition to a node in their JavaFX application, then they should instantiate the javafx.animation.TranslateTransition class. " }, { "code": null, "e": 38664, "s": 38367, "text": "Rotate Transition – The Rotate transition is used to rotate the selective node by one of the axes over a specific duration of time. If a user wants to implement the rotate transition to a node in their JavaFX application, then they should instantiate the javafx.animation.RotateTransition class. " }, { "code": null, "e": 39078, "s": 38664, "text": "Fade Transition – The Fade transition is used to animate the opacity of the node. In simple words, we can say that the fade transition keeps refreshing the opacity of the node over a specific duration of time in order to reach the final opacity value. If a user wants to implement the fade transition to a node in their JavaFX application, then they should instantiate the javafx.animation.FadeTransition class. " }, { "code": null, "e": 39435, "s": 39078, "text": "Stroke Transition – The Stroke transition is used to animate the node’s stroke color so that the stroke color of the node varies between the two color values over a specific duration of time. If a user wants to implement the stroke transition to a node in their JavaFX application, then they should instantiate the javafx.animation.StrokeTransition class. " }, { "code": null, "e": 39734, "s": 39435, "text": "Parallel Transition – The Parallel transition is used to perform a number of animations on a selective node in a parallel manner. If a user wants to implement the parallel transition to a node in their JavaFX application, then they should instantiate the javafx.animation.ParallelTransition class. " }, { "code": null, "e": 40089, "s": 39734, "text": "Fill Transition – The Fill transition is used to animate the selective node’s fill color so that the fill color of the node varies between the two color values over a specific duration of time. If a user wants to implement the fill transition to a node in their JavaFX application, then they should instantiate the javafx.animation.FillTransition class. " }, { "code": null, "e": 40381, "s": 40089, "text": "Path Transition – The Path transition is used to move the selective node along the specified path over a specific duration of time. If a user wants to implement the path transition to a node in their JavaFX application, then they should instantiate the javafx.animation.PathTransition class." }, { "code": null, "e": 40759, "s": 40381, "text": "Any solid geometrical figure that can be represented on the coordinate system using three planes, which are X, Y, and Z planes, is known as a three-dimensional shape or a 3D shape. The main difference between the 3D shapes and 2D shapes is that the 3D shapes always need to have an extra coordinate value Z as compared to 2D shapes, in order to be drawn on a coordinate system." }, { "code": null, "e": 41234, "s": 40759, "text": "There are many basic 3D shapes which we see on a daily basis such as cylinders, spheres, boxes, cubes, pyramids, etc. Nevertheless, JavaFX implements only 3 classes to create 3D shapes. These classes include spheres, cylinders, and boxes. These classes are defined in the javafx.scene.shape package. This package provides all the methods to deal with the 3D shapes. The class Shape3D of the package javafx.scene.shape is the base class of all the 3D shape classes in javafx." }, { "code": null, "e": 41263, "s": 41234, "text": "Types of 3D shapes in JavaFX" }, { "code": null, "e": 41336, "s": 41263, "text": "In JavaFX, 3D shapes are characterized in two separate types. These are:" }, { "code": null, "e": 41989, "s": 41336, "text": "1. Predefined 3D shapes: Predefined 3D shapes are the shapes whose classes are already present in the JavaFX API. These shapes are Cylinder, Sphere, and Box. In order to create these shapes in the JavaFX application, the user just needs to instantiate these classes. These classes include several properties and methods that are needed to be used in order to generate the proper shapes. 2. User Defined 3D shapes: JavaFX provides the class javafx.scene.shape.TriangleMesh which extends the abstract class javafx.scene.shape.Mesh. This class facilitates the user to define their own points, texture coordinates, and faces as the properties of the class." }, { "code": null, "e": 42352, "s": 41989, "text": "As mentioned above, there are different classes for the different 3D shapes in JavaFX. In order to create 3D shapes, the user just needs to instantiate those classes. The user can use the following steps to generate proper shapes in their JavaFX application. 1. The first step is to instantiate the class of the respective 3D shape which the user wants to build." }, { "code": null, "e": 42456, "s": 42352, "text": "For Example – If a user wishes to create a Box, then he should instantiate the Box class of the JavaFX." }, { "code": null, "e": 42479, "s": 42456, "text": "Box box = new Box(); " }, { "code": null, "e": 42578, "s": 42479, "text": "2. After instantiating the class, the next step is to set of properties of the instantiated class." }, { "code": null, "e": 42729, "s": 42578, "text": "For Example – If a user has instantiated the Box class of JavaFX, then he should set the properties such as Height, width, and depth of the Box class." }, { "code": null, "e": 42799, "s": 42729, "text": "box.setHeight(100.0); \nbox.setDepth(80.0); \nbox.setWidth(60.0); " }, { "code": null, "e": 43056, "s": 42799, "text": "3. After the above two steps, the user should set the camera for the scene. In simple words, the user can set the camera to a particular position for the camera view. However, this step is optional. A user can set the camera view using the following code –" }, { "code": null, "e": 43215, "s": 43056, "text": "PerspectiveCamera cam = new PerspectiveCamera(); \ncam.setTranslateX(100.0); \ncam.setTranslateY(80.0); \ncam.setTranslateZ(-50.0); \nscene.setCamera(cam) " }, { "code": null, "e": 43384, "s": 43215, "text": "4. The last step to creating a 3D shape for the JavaFX application is to attach the 3D shape to the Scene graph and set the relevant properties for the Scene and stage." }, { "code": null, "e": 43506, "s": 43384, "text": "For example: If a user has instantiated the box class, then he should link that class with the Scene graph and the stage." }, { "code": null, "e": 43708, "s": 43506, "text": "Group root = new Group(); \nroot.getChildren().add(box); \nScene scene = new Scene(root,500,500); \nprimaryStage.setScene(scene); \nprimaryStage.setTitle(\"3D shape Example\"); \nprimaryStage.show();" }, { "code": null, "e": 43746, "s": 43708, "text": "Different classes of JavaFX 3D shapes" }, { "code": null, "e": 43957, "s": 43746, "text": "In JavaFX, there are basically 3 predefined 3D shapes classes that are available for the user to use in their application. The following is a brief introduction of various 3D shapes that are provided by JavaFX." }, { "code": null, "e": 44094, "s": 43957, "text": "Sphere – A sphere can be defined as a perfectly round solid 3D object. In JavaFX, the class javafx.scene.shape.Sphere represents Sphere." }, { "code": null, "e": 44326, "s": 44094, "text": "Box – In general, a box can be defined as a three-dimensional shape having all the faces in a rectangular shape. The three dimensions of Box are height, width, and depth. In JavaFX, the class javafx.scene.shape.Box represents Box." }, { "code": null, "e": 44584, "s": 44326, "text": "Cylinder – A Cylinder can be defined as a three-dimensional solid having two parallel circular bases connected by a curved surface. It has two main properties as radius and height. In JavaFX, the class javafx.scene.shape.Cylinder is used to denote cylinder." }, { "code": null, "e": 44808, "s": 44584, "text": "Transformation implies modifying some graphics into something different by implementing various rules. In JavaFX there are different sorts of transformations such as Translation, Scaling Up or Down, Rotation, Shearing, etc." }, { "code": null, "e": 45036, "s": 44808, "text": "Using JavaFX, a user can implement transformations on nodes such as rotation, scaling, and translation. All these transformations are expressed by several classes and these classes belong to the package javafx.scene.transform. " }, { "code": null, "e": 45080, "s": 45036, "text": "Different classes of JavaFX Transformations" }, { "code": null, "e": 45311, "s": 45080, "text": "In JavaFX, there are basically 4 predefined JavaFX transformations classes that are available for the user to use in their application. The following is a brief introduction of various transformations that are provided by JavaFX. " }, { "code": null, "e": 45457, "s": 45311, "text": "Rotation – Rotation is used to rotate the object from its source by a certain angle. The class javafx.scene.transform.Rotate represents rotation." }, { "code": null, "e": 45598, "s": 45457, "text": "Translation – Translation is used to modify the location of the node. The class javafx.scene.transform.Translate represents the translation." }, { "code": null, "e": 45715, "s": 45598, "text": "Scaling – Scaling is used to modify the size of the node. The class javafx.scene.transform.Scale represents Scaling." }, { "code": null, "e": 45866, "s": 45715, "text": "Shearing – Shearing is used to altering the slope of the object in a particular direction. The class javafx.scene.transform.Shear represents Shearing." }, { "code": null, "e": 45932, "s": 45866, "text": "Steps to apply transformations to the target node are as follows:" }, { "code": null, "e": 46138, "s": 45932, "text": "To apply a special transformation to a target node, a user should follow the below-given steps: 1. The first step is to instantiate the class of the respective transformation which the user wants to apply." }, { "code": null, "e": 46272, "s": 46138, "text": "For example – If a user wants to apply a translate transformation on a specific node, then he should instantiate the translate class." }, { "code": null, "e": 46333, "s": 46272, "text": "TranslateTransition translate = new TranslateTransition(); " }, { "code": null, "e": 46432, "s": 46333, "text": "2. After instantiating the class, the next step is to set of properties of the instantiated class." }, { "code": null, "e": 46642, "s": 46432, "text": "For example – If a user has instantiated the translate transformation class of JavaFX, then he should set the properties such as translate byX, translate byY, duration, and cycle count of the translated class." }, { "code": null, "e": 46755, "s": 46642, "text": "translate.setByX(400); \ntranslate.setDuration(Duration.millis(1000)); \ntranslate.setCycleCount(500); " }, { "code": null, "e": 46857, "s": 46755, "text": "3. Set the transformation to the respective node and play the transformation using the method play()." }, { "code": null, "e": 47094, "s": 46857, "text": "For Example: Let us assume that the user wants to translate a specific node then after instantiating a transformation class and setting its value, the user should set the node using the name of the node that should play the translation." }, { "code": null, "e": 47153, "s": 47094, "text": "translate.setNode(name of the node); \ntranslate.play(); " }, { "code": null, "e": 47422, "s": 47153, "text": "The UI controls are the elements that are truly exposed to the user for intercommunication or information exchange. A layout represents the structure of the UI elements on the screen. The response is the reaction of the UI component when some event has happened on it." }, { "code": null, "e": 47636, "s": 47422, "text": "However, the package javafx.scene.control implements all the required classes for the UI elements like Button, Label, etc. Every class describes a particular UI control and explains few methods for their styling. " }, { "code": null, "e": 47676, "s": 47636, "text": "Different classes of JavaFX UI controls" }, { "code": null, "e": 47851, "s": 47676, "text": "In JavaFX, there are many UI controls that are used by the users in their applications. Below is the list of usually used UI controls while the GUI is designed using JavaFX. " }, { "code": null, "e": 48054, "s": 47851, "text": "Button – The button is a component that controls the function of the application. The Button class is practiced to produce a specified button. It is represented by the javafx.scene.control.Button class." }, { "code": null, "e": 48252, "s": 48054, "text": "Label – Label is an element that is applied to describe plain text on the screen. Typically, a label is set with the node, it represents. It is represented by the javafx.scene.control.Label class." }, { "code": null, "e": 48407, "s": 48252, "text": "TextField – Text Field is usually used to take the input from the user in the form of text. It is represented by the javafx.scene.control.TextField class." }, { "code": null, "e": 48550, "s": 48407, "text": "ProgressBar – Progress Bar is used to display the output process to the user. It is represented by the javafx.scene.control.ProgressBar class." }, { "code": null, "e": 48816, "s": 48550, "text": "RadioButton – The Radio Button is used to provide various options to the user. The user can only choose one option among all. A radio button has two options, it can either be selective or deselective. It is represented by the javafx.scene.control.RadioButton class." }, { "code": null, "e": 49064, "s": 48816, "text": "CheckBox – Check Box is used to get the kind of information from the user which contains various choices. The user marked the checkbox either on (true) or off(false). The CheckBox in JavaFX is expressed by the javafx.scene.control.CheckBox class." }, { "code": null, "e": 49295, "s": 49064, "text": "Slider – Slider is used to provide a pane of options to the user in a graphical form where the user needs to move a slider over the range of values to select one of them. It is represented by the javafx.scene.control.Slider class." }, { "code": null, "e": 49460, "s": 49295, "text": "Menu – JavaFX provides a Menu class to implement menus. The menu is the main component of any application. It is represented by the javafx.scene.control.Menu class." }, { "code": null, "e": 49691, "s": 49460, "text": "PasswordField – PasswordField is practiced to take the user’s password. Whatever the user types in the password field, that is not displayed on the screen to anyone. It is expressed by the javafx.scene.control.PasswordField class." }, { "code": null, "e": 49888, "s": 49691, "text": "ScrollBar – JavaFX Scroll Bar is used to implement a scroll bar to the user so that the user can scroll down the application pages. It is represented by the javafx.scene.control.ScrollBar class. " }, { "code": null, "e": 50294, "s": 49888, "text": "In general, the chart can be defined as the graph or diagram which represents the data in the form of symbols. Charts are mainly used to represent large quantities of data and the relationship between parts of the data. We can create different kinds of charts to represent different kinds of information. In JavaFX, we can create the charts by using the classes provided by the package javafx.scene.chart." }, { "code": null, "e": 50310, "s": 50294, "text": "Types of charts" }, { "code": null, "e": 50372, "s": 50310, "text": "Charts in JavaFX can be classified into the subsequent types:" }, { "code": null, "e": 50937, "s": 50372, "text": "Pie Chart – In Pie Chart, the areas of a circle are used to define several proportions of the complete information. In JavaFX, the class javafx.scene.chart.PieChart is used to deal with the pie chart. XYChart – In XYChart, the data is sketched on the XY (horizontal and vertical) axes. The X-axis depicts one type of value while the Y-axis depicts the other type of value. The mapping is done between the values plotted on X and Y charts to display the appropriate information. In JavaFX, the class javafx.scene.chart.XYChart is practiced to deal with the XYChart." }, { "code": null, "e": 51139, "s": 50937, "text": "Pie Chart – In Pie Chart, the areas of a circle are used to define several proportions of the complete information. In JavaFX, the class javafx.scene.chart.PieChart is used to deal with the pie chart. " }, { "code": null, "e": 51503, "s": 51139, "text": "XYChart – In XYChart, the data is sketched on the XY (horizontal and vertical) axes. The X-axis depicts one type of value while the Y-axis depicts the other type of value. The mapping is done between the values plotted on X and Y charts to display the appropriate information. In JavaFX, the class javafx.scene.chart.XYChart is practiced to deal with the XYChart." }, { "code": null, "e": 51517, "s": 51503, "text": "Types of Axis" }, { "code": null, "e": 51608, "s": 51517, "text": "In Charts, there can be different types of axis other than the X and Y-axis. These are – " }, { "code": null, "e": 52232, "s": 51608, "text": "Category Axis – The category axis is used to describe the various sections of the information. This axis is distinct from the value axis in the sense that the specific values are not displayed on the category axis. In JavaFX, the class javafx.scene.chart.CategoryAxis depicts the category axis. A user just requires to instantiate this class in order to generate the category axis. Number Axis – The Number axis is used to express the specific range of values. In JavaFX, the class javafx.scene.chart.NumberAxis represents the value axis. A user just requires to instantiate this class in order to generate the Number axis." }, { "code": null, "e": 52615, "s": 52232, "text": "Category Axis – The category axis is used to describe the various sections of the information. This axis is distinct from the value axis in the sense that the specific values are not displayed on the category axis. In JavaFX, the class javafx.scene.chart.CategoryAxis depicts the category axis. A user just requires to instantiate this class in order to generate the category axis. " }, { "code": null, "e": 52857, "s": 52615, "text": "Number Axis – The Number axis is used to express the specific range of values. In JavaFX, the class javafx.scene.chart.NumberAxis represents the value axis. A user just requires to instantiate this class in order to generate the Number axis." }, { "code": null, "e": 52893, "s": 52857, "text": "Different classes of JavaFX Charts " }, { "code": null, "e": 53058, "s": 52893, "text": "In JavaFX, there are many charts that are used by the users in their applications. Below is the list of usually used charts while the GUI is designed using JavaFX. " }, { "code": null, "e": 53260, "s": 53058, "text": "Pie Chart – In Pie Chart, the areas of a circle are used to define several proportions of the complete information. In JavaFX, the class javafx.scene.chart.PieChart is used to deal with the pie chart. " }, { "code": null, "e": 53550, "s": 53260, "text": "Bar Chart – A bar chart is used to describe assorted data using rectangular bars. The length of these bars represents the values. The bars can be plotted both vertically and horizontally in the bar chart. In JavaFX, a Bar chart is represented by a class named javafx.scene.chart.BarChart. " }, { "code": null, "e": 53842, "s": 53550, "text": "Line Chart – A line chart is applied to display the information as a list of data points (markers) connected by straight line segments. Line Chart explains how the data varies at regular time frequencies. In JavaFX, a line chart is represented by a class named javafx.scene.chart.LineChart. " }, { "code": null, "e": 54121, "s": 53842, "text": "Area Chart – Area charts are applied to draw area-based charts. It plots the area between the given set of points and the axis. In general, this chart is used to differentiate two quantities. In JavaFX, an area chart is represented by a class named javafx.scene.chart.AreaChart." }, { "code": null, "e": 54138, "s": 54121, "text": "JavaFX Layouts " }, { "code": null, "e": 54395, "s": 54138, "text": "Layouts are the top-level container classes that describe the UI styles for objects of the scene graph. The JavaFX layout can be seen as the father node to all the separate nodes. JavaFX presents several layout panes that promote various styles of layouts." }, { "code": null, "e": 54783, "s": 54395, "text": "In JavaFX, Layout describes the process in which the elements are to be viewed on the screen. It primarily establishes the scene-graph nodes. There are various built-in layout panes in JavaFX that are HBox, VBox, StackPane, FlowBox, AnchorPane, etc. Each Built-in layout is represented by a separate class that requires to be instantiated in order to implement that specific layout pane." }, { "code": null, "e": 54946, "s": 54783, "text": "All these classes belong to the javafx.scene.layout package. The javafx.scene.layout.Pane class is the root class for all the built-in classes of JavaFX layouts. " }, { "code": null, "e": 54978, "s": 54946, "text": "Steps to create a JavaFX layout" }, { "code": null, "e": 55051, "s": 54978, "text": "In order to create the layouts, we need to follow the following steps – " }, { "code": null, "e": 55179, "s": 55051, "text": "1. The first step to creating a layout in JavaFX application is that the user should instantiate the respective layout class, " }, { "code": null, "e": 55295, "s": 55179, "text": "For example – If a user wants to create an HBox layout, then he should instantiate the HBox Class of JavaFX layout." }, { "code": null, "e": 55319, "s": 55295, "text": "HBox root = new HBox();" }, { "code": null, "e": 55419, "s": 55319, "text": "2. After instantiating the respective class, the next step is to set the properties for the layout." }, { "code": null, "e": 55440, "s": 55419, "text": "root.setSpacing(20);" }, { "code": null, "e": 55571, "s": 55440, "text": "3. After the above two steps, the last step of creating a layout in the JavaFX application is to add nodes to the layout object. " }, { "code": null, "e": 55613, "s": 55571, "text": "root.getChildren().addAll(<NodeObjects>);" }, { "code": null, "e": 55651, "s": 55613, "text": "Different classes of JavaFX Layouts " }, { "code": null, "e": 55850, "s": 55651, "text": "In JavaFX, there are various JavaFX Layout classes that are available for the user to use in their application. The following is a brief introduction of various layouts that are provided by JavaFX. " }, { "code": null, "e": 56049, "s": 55850, "text": "HBox – The HBox layout is used to arrange all the nodes in the JavaFX application in a particular horizontal row. In JavaFX, an HBox layout is represented by a class named javafx.scene.layout.HBox. " }, { "code": null, "e": 56291, "s": 56049, "text": "BorderPane – The Border Pane layout is used to arrange the nodes in the JavaFX application in the top, left, right, bottom, and center positions. In JavaFX, a BorderPane layout is represented by a class named javafx.scene.layout.BorderPane. " }, { "code": null, "e": 56566, "s": 56291, "text": "GridPane – The Grid Pane layout is used to arranges the nodes in the JavaFX application as a grid of rows and columns. This layout is very convenient in designing forms using JavaFX. In JavaFX, a GridPane layout is represented by a class named javafx.scene.layout.GridPane. " }, { "code": null, "e": 56864, "s": 56566, "text": "FlowPane – The flow pane layout is used to wrap all the nodes in a flow. A horizontal flow pane wraps the components of the pane at its height, while a vertical flow pane wraps the components at its width. In JavaFX, a FlowPane layout is represented by a class named javafx.scene.layout.FlowPane. " }, { "code": null, "e": 57191, "s": 56864, "text": "StackPane – The stack pane layout is used to arrange the nodes in the JavaFX application on top of another just like in a stack. The node appended first is ordered at the bottom of the stack and the next node is stored on top of it. In JavaFX, a StackPane layout is represented by a class named javafx.scene.layout.StackPane. " }, { "code": null, "e": 57386, "s": 57191, "text": "VBox – The VBox layout is used to arrange all the nodes in the JavaFX application in a single vertical column. In JavaFX, a VBox layout is represented by a class named javafx.scene.layout.VBox. " }, { "code": null, "e": 57408, "s": 57386, "text": "JavaFX Event Handling" }, { "code": null, "e": 57736, "s": 57408, "text": "JavaFX grants users the adaptability to generate numerous types of applications such as Desktop Applications, Web applications, and graphical applications. In recent-day applications, the users perform an essential role in the precise execution of the application. The user needs to interact with the application in most cases." }, { "code": null, "e": 58285, "s": 57736, "text": "In JavaFX, An event occurs whenever the user interacts with the application nodes. There are multiple references by using which, the user can create the event. For example, the user can make use of a mouse or it can press any button on the keyboard or it can scroll any page of the application in order to generate an event. Hence, we can say that the events are fundamentally the announcements that tell us that something has happened at the user’s end. A perfect Application is the one that takes the least amount of time in handling the events. " }, { "code": null, "e": 58313, "s": 58285, "text": "Processing Events in JavaFX" }, { "code": null, "e": 58550, "s": 58313, "text": "In JavaFX, events are primarily used to inform the application regarding the actions chosen by the user. JavaFX implements the tool to achieve the events, route the event to its target, and granting the application to handle the events." }, { "code": null, "e": 58765, "s": 58550, "text": "JavaFX presents the class javafx.event.Event which includes all the subclasses describing the varieties of events that can be created in JavaFX. Any event is an instance of the class Event or any of its subclasses." }, { "code": null, "e": 58948, "s": 58765, "text": "There are several events in JavaFX i.e. MouseEvent, KeyEvent, ScrollEvent, DragEvent, etc. A user can further specify their personal event by inheriting the class javafx.event.Event." }, { "code": null, "e": 58964, "s": 58948, "text": "Types of Events" }, { "code": null, "e": 59046, "s": 58964, "text": "In general, the JavaFX events are principally grouped into the subsequent types –" }, { "code": null, "e": 59498, "s": 59046, "text": "Foreground Events – Foreground events are essentially happened due to the straightforward communication of the user with the GUI of the application. For example, clicking the button, pressing a key, selecting an item from the list, scrolling the page, etc. Background Events – Background events don’t need the user’s interaction with the application. These events mainly occur due to the operating system interrupts failure, operation completion, etc." }, { "code": null, "e": 59756, "s": 59498, "text": "Foreground Events – Foreground events are essentially happened due to the straightforward communication of the user with the GUI of the application. For example, clicking the button, pressing a key, selecting an item from the list, scrolling the page, etc. " }, { "code": null, "e": 59951, "s": 59756, "text": "Background Events – Background events don’t need the user’s interaction with the application. These events mainly occur due to the operating system interrupts failure, operation completion, etc." }, { "code": null, "e": 59994, "s": 59951, "text": "Different classes of JavaFX Event Handling" }, { "code": null, "e": 60239, "s": 59994, "text": "JavaFX grants support to handle a wide variety of events. The class javafx.event.Event is the base class for every event. An instance of any of its subclass is an event. JavaFX provides a wide mixture of events. Some of them are placed below – " }, { "code": null, "e": 60473, "s": 60239, "text": "KeyEvent – KeyEvent is an input event that symbolizes the keystroke that occurred on a node. This event includes actions like key pressed, key released and key typed. It is represented by the class named javafx.event.Event.KeyEvent. " }, { "code": null, "e": 60762, "s": 60473, "text": "MouseEvent – MouseEvent is also an input event that happens when a mouse is clicked. It includes actions like mouse clicked, mouse pressed, mouse released, the mouse moved, mouse entered target, mouse exited target, etc. It is expressed by the class called javafx.event.Event.MouseEvent. " }, { "code": null, "e": 61025, "s": 60762, "text": "WindowEvent – WindowEvent is an event associated with window showing and window hiding actions. It includes actions like window hiding, the window is shown, window hidden, window showing, etc. It is represented by the class named javafx.event.Event.WindowEvent. " }, { "code": null, "e": 61283, "s": 61025, "text": "DragEvent – DragEventis an input event that occurs when the mouse is dragged. It involves activities like drag entered, drag dropped, drag entered target, drag exited target, drag over, etc. It is represented by the class named javafx.event.Event.DragEvent." }, { "code": null, "e": 61345, "s": 61283, "text": "The above were the different UI components of the JavaFX API." }, { "code": null, "e": 61370, "s": 61345, "text": "Setting up JavaFX in IDE" }, { "code": null, "e": 61532, "s": 61370, "text": "We need to configure JavaFX in our IDE n order to use it for which here we are illustrating with the help of Eclipse IDE as it is widely used by Java developers." }, { "code": null, "e": 61661, "s": 61532, "text": "Step 1: Go to ‘Help’ section on by clicking the top right bar and further go into ‘Eclipse Marketplace’ as shown in below media." }, { "code": null, "e": 61936, "s": 61661, "text": "Step 2: Now write initials ‘fx’ and press enter. Below window will pop-up then install the e(fx)clipse 3.6.0 as shown below which will appear in top search as later on continue installing by accepting terms and conditions and press ‘Next’. It will take a little bit of time." }, { "code": null, "e": 62102, "s": 61936, "text": "Step 3: Restart the IDE and now open new ‘File’ new –> ‘Others’ and here you will find JavaFX plugin which earlier was not present here as depicted below as follows:" }, { "code": null, "e": 62150, "s": 62102, "text": "Step 4: Choose JavaFX project and choose ‘Next’" }, { "code": null, "e": 62296, "s": 62150, "text": "Just likely naming normal project so do create JavaFX project and choose settings as per requirements, further click on ‘Next‘ later on ‘Finish‘." }, { "code": null, "e": 62496, "s": 62296, "text": "You will see this window where the keynote is that our IDE(eclipse) does not know where the JavaFX is as of now we only have set up JavaFX to work in eclipse only but have not been downloaded JavaFX." }, { "code": null, "e": 62857, "s": 62496, "text": "Step5: Download JavaFX by extracting it to a location on the system and do remember the specified path where you have extracted it. While downloading one can pick a long-term support version or the latest release version but the long-term version is recommended if one is new to JavaFX as the latest release can throw some errors. as per your operating system." }, { "code": null, "e": 62887, "s": 62857, "text": "Step 6: Create a user library" }, { "code": null, "e": 63087, "s": 62887, "text": "Go to Windows –> Preferences and there type user and go to User Libraries. Here add a new user library and name t relevantly not necessarily to named JavaFX or retaining some previous counter names. " }, { "code": null, "e": 63091, "s": 63087, "text": "to " }, { "code": null, "e": 63263, "s": 63091, "text": "Step 7: Now go to ‘Add External JAR’ and do copy the path retained above where JavaFX is installed in the local directory and select all of them as shown below as follows:" }, { "code": null, "e": 63290, "s": 63263, "text": "Click on ‘Apply and Close’" }, { "code": null, "e": 63651, "s": 63290, "text": "Step 8: Resolve unwanted errors that pop up by right-clicking the project and go to Build path –> Configure Build Path. Now go to Library –> Classpath and Add library. here you will find all user library and the name will pop up which was given earlier to the library. Click on Finish –> Apply –> Apply and Close and yu will see all the errors are gone by now." }, { "code": null, "e": 63693, "s": 63651, "text": "Step 9: Now configure Run configurations." }, { "code": null, "e": 63879, "s": 63693, "text": "Go to Run –> Java Application –> Main –> Arguments. keynote is here you need to pass the argument as shown in the image below but the path varies as per where you have installed JavaFX." }, { "code": null, "e": 63951, "s": 63879, "text": "--module-path \"YOUR\\PATH\\lib\" --add-modules javafx.controls,javafx.fxml" }, { "code": null, "e": 64053, "s": 63951, "text": "After this one can start off with JavaFX operations as a window will be popped up by now. Cheers! " }, { "code": null, "e": 64275, "s": 64053, "text": "The performance of both Java Swing and Java FX is supported in the graphics business. However, both of them are very different from each other. Some of the key differences between Java Swing and Java FX are given below – " }, { "code": null, "e": 64286, "s": 64275, "text": "Java Swing" }, { "code": null, "e": 64293, "s": 64286, "text": "JavaFX" }, { "code": null, "e": 64363, "s": 64293, "text": "These are the main points of difference between JavaFX and Java Swing" }, { "code": null, "e": 64496, "s": 64363, "text": "There are many real-world applications that were made using JavaFX. Some of the applications and their area of use are given below –" }, { "code": null, "e": 64890, "s": 64496, "text": "JavaFX is a Java library and a GUI toolkit designed to develop and facilitate Rich Internet applications, web applications, and desktop applications. The most significant perk of using JavaFX is that the applications written using this library can run on multiple operating systems like Windows, Linux, iOS, Android, and several platforms like Desktops, Web, Mobile Phones, TVs, Tablets, etc. " }, { "code": null, "e": 64906, "s": 64890, "text": "nishkarshgandhi" }, { "code": null, "e": 64913, "s": 64906, "text": "JavaFX" }, { "code": null, "e": 64918, "s": 64913, "text": "Java" }, { "code": null, "e": 64923, "s": 64918, "text": "Java" } ]
How to Convert Categorical Variable to Numeric in Pandas? - GeeksforGeeks
01 Dec, 2021 In this article, we will learn how to convert a categorical variable into a Numeric by using pandas. When we look at the categorical data, the first question that arises to anyone is how to handle those data, because machine learning is always good at dealing with numeric values. We could make machine learning models by using text data. So, to make predictive models we have to convert categorical data into numeric form. Replacing is one of the methods to convert categorical terms into numeric. For example, We will take a dataset of people’s salaries based on their level of education. This is an ordinal type of categorical variable. We will convert their education levels into numeric terms. Syntax: replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’) Consider the given data: Data Python3 #import pandas import pandas as pd # read csv file df = pd.read_csv('data.csv') # replacing values df['Education'].replace(['Under-Graduate', 'Diploma '], [0, 1], inplace=True) Output: In the above program, we have replaced “under-graduate” as 0 and “Diploma” as 1. Replacing the values is not the most efficient way to convert them. Pandas provide a method called get_dummies which will return the dummy variable columns. Syntax: pandas.get_dummies(data, prefix=None, prefix_sep=’_’, dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None) Step 1: Create dummies columns get_dummies() method is called and the parameter name of the column is given. This method will return the dummy variable columns. In this case, we have 3 types of Categorical variables so, it returned three columns Step 2: Concatenate Syntax: pandas.concat(objs, axis=0, join=’outer’, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True The next step is to concatenate the dummies columns into the data frame. In pandas, there is a concat() method, which you can call to join two data frames. You should supply it with the name of two data frames and the axis. This will give you the merged data frame. Step 3: Drop columns We have to drop the original ‘education’ column because we have the dummy variable column and we don’t need the text column. And we might also drop one of the dummy variable columns So that we could avoid the dummy variable trap which could mess up the model. After dropping the columns, the desired dataframe is obtained We will implement this at code Python3 #import pandas import pandas as pd # read csv df = pd.read_csv('salary.csv') # get the dummies and store it in a variable dummies = pd.get_dummies(df.Education) # Concatenate the dummies to original dataframe merged = pd.concat([df, dummies], axis='columns') # drop the values merged.drop(['Education', 'Under-Graduate'], axis='columns') # print the dataframe print(merged) Output: anikakapoor Picked Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": 24284, "s": 24253, "text": " \n01 Dec, 2021\n" }, { "code": null, "e": 24385, "s": 24284, "text": "In this article, we will learn how to convert a categorical variable into a Numeric by using pandas." }, { "code": null, "e": 24708, "s": 24385, "text": "When we look at the categorical data, the first question that arises to anyone is how to handle those data, because machine learning is always good at dealing with numeric values. We could make machine learning models by using text data. So, to make predictive models we have to convert categorical data into numeric form." }, { "code": null, "e": 24984, "s": 24708, "text": "Replacing is one of the methods to convert categorical terms into numeric. For example, We will take a dataset of people’s salaries based on their level of education. This is an ordinal type of categorical variable. We will convert their education levels into numeric terms. " }, { "code": null, "e": 24992, "s": 24984, "text": "Syntax:" }, { "code": null, "e": 25083, "s": 24992, "text": "replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’)" }, { "code": null, "e": 25108, "s": 25083, "text": "Consider the given data:" }, { "code": null, "e": 25113, "s": 25108, "text": "Data" }, { "code": null, "e": 25121, "s": 25113, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n#import pandas\nimport pandas as pd\n \n# read csv file\ndf = pd.read_csv('data.csv')\n \n# replacing values\ndf['Education'].replace(['Under-Graduate', 'Diploma '],\n [0, 1], inplace=True)\n\n\n\n\n\n", "e": 25349, "s": 25131, "text": null }, { "code": null, "e": 25357, "s": 25349, "text": "Output:" }, { "code": null, "e": 25438, "s": 25357, "text": "In the above program, we have replaced “under-graduate” as 0 and “Diploma” as 1." }, { "code": null, "e": 25595, "s": 25438, "text": "Replacing the values is not the most efficient way to convert them. Pandas provide a method called get_dummies which will return the dummy variable columns." }, { "code": null, "e": 25731, "s": 25595, "text": "Syntax: pandas.get_dummies(data, prefix=None, prefix_sep=’_’, dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None)" }, { "code": null, "e": 25762, "s": 25731, "text": "Step 1: Create dummies columns" }, { "code": null, "e": 25977, "s": 25762, "text": "get_dummies() method is called and the parameter name of the column is given. This method will return the dummy variable columns. In this case, we have 3 types of Categorical variables so, it returned three columns" }, { "code": null, "e": 25998, "s": 25977, "text": "Step 2: Concatenate " }, { "code": null, "e": 26150, "s": 25998, "text": "Syntax: pandas.concat(objs, axis=0, join=’outer’, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True" }, { "code": null, "e": 26417, "s": 26150, "text": "The next step is to concatenate the dummies columns into the data frame. In pandas, there is a concat() method, which you can call to join two data frames. You should supply it with the name of two data frames and the axis. This will give you the merged data frame." }, { "code": null, "e": 26438, "s": 26417, "text": "Step 3: Drop columns" }, { "code": null, "e": 26761, "s": 26438, "text": "We have to drop the original ‘education’ column because we have the dummy variable column and we don’t need the text column. And we might also drop one of the dummy variable columns So that we could avoid the dummy variable trap which could mess up the model. After dropping the columns, the desired dataframe is obtained" }, { "code": null, "e": 26792, "s": 26761, "text": "We will implement this at code" }, { "code": null, "e": 26800, "s": 26792, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n#import pandas\nimport pandas as pd\n \n# read csv\ndf = pd.read_csv('salary.csv')\n \n# get the dummies and store it in a variable\ndummies = pd.get_dummies(df.Education)\n \n# Concatenate the dummies to original dataframe\nmerged = pd.concat([df, dummies], axis='columns')\n \n# drop the values\nmerged.drop(['Education', 'Under-Graduate'], axis='columns')\n \n# print the dataframe\nprint(merged)\n\n\n\n\n\n", "e": 27207, "s": 26810, "text": null }, { "code": null, "e": 27215, "s": 27207, "text": "Output:" }, { "code": null, "e": 27227, "s": 27215, "text": "anikakapoor" }, { "code": null, "e": 27236, "s": 27227, "text": "\nPicked\n" }, { "code": null, "e": 27252, "s": 27236, "text": "\nPython-pandas\n" }, { "code": null, "e": 27261, "s": 27252, "text": "\nPython\n" }, { "code": null, "e": 27466, "s": 27261, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27498, "s": 27466, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27554, "s": 27498, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27575, "s": 27554, "text": "Python OOPs Concepts" }, { "code": null, "e": 27614, "s": 27575, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27656, "s": 27614, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27683, "s": 27656, "text": "Python Classes and Objects" }, { "code": null, "e": 27714, "s": 27683, "text": "Python | os.path.join() method" }, { "code": null, "e": 27756, "s": 27714, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27792, "s": 27756, "text": "Python | Pandas dataframe.groupby()" } ]
Example Comprehensions in Python
With comprehensions you can construct python sequences. In this article we will see how to create and access such sequences. Below are the different types of comprehensions in python. List Comprehensions Dictionary Comprehensions Set Comprehensions Generator Comprehensions There are various ways we can create a list and access the elements in it. Live Demo # Cretae an empty list listA = [] # Append elements to the list for n in range(4, 9): listA.append(n ** 3) print("List using for loop:\n", listA) Running the above code gives us the following result − List using for loop: [64, 125, 216, 343, 512] We can also create a list form another list by directly assigning elements to the new list. Live Demo # Take a list listA = [12,9,32,45] #Given list print("Given list:\n ",listA) new_list = [n for n in listA if n % 3 == 0] print("New List:\n", new_list) Running the above code gives us the following result − Given list: [12, 9, 32, 45] New List: [12, 9, 45] A dictionary contains elements in form of pairs known as key-value pairs. In this article we will see how to create such dictionaries. We can take in two lists which can have keys and values. Then join them through comprehension to create a new dictionary. Live Demo Day = ['Mon', 'Tue', 'Wed',] Time= ['2pm','10am','11am'] # Create an empty dict dictA = {} # Use for loop for (key, value) in zip(Day, Time): dictA[key] = value print("Dictionary using for loop:\n",dictA) Running the above code gives us the following result − Dictionary using for loop: {'Mon': '2pm', 'Tue': '10am', 'Wed': '11am'} In this case we take a Python list and uses elements as key for the dictionary. Also derive the values for each key using an expression. Live Demo listA = [3,5,4,8,9,2] dictA = {} # Using for loop for key in listA: if key % 2 != 0: dictA[key] = key ** 3 print("Dictionary using for loop:\n",dictA) Running the above code gives us the following result − Dictionary using for loop: {3: 27, 5: 125, 9: 729} Python Set contains unique elements. It can be created in a similar manner as list. Here we take a list and apply a condition to fetch some elements from it. Then put those elements into to an empty set by using add method. Live Demo listA = [12, 4, 25, 12,4,9] setA = set() # Using for loop for x in listA: if x % 3 == 0: setA.add(x) print("Set using for loop:", setA) Running the above code gives us the following result − Set using for loop: {9, 12} In this method we directly use a for loop within {}. And assign the result into a set. Inside the follow we use elements from a list. Live Demo listA = [12, 4, 25, 12,4,9] # Using for loop setA = {x for x in listA if x % 2 == 0} print("Set using for loop:", setA) Running the above code gives us the following result − Set using for loop: {12, 4} In this approach we take the elements from a list and apply certain conditions on them and then put them into a for loop. The result is assigned to sequence. This method is called generator comprehension. Live Demo listA = [12, 4, 25, 12,4,9] genrtr = (var for var in listA if var % 2 == 0) print("Values using generator comprehensions:\n") for x in genrtr: print(x, end=',') Running the above code gives us the following result − Values using generator comprehensions: 12,4,12,4,
[ { "code": null, "e": 1187, "s": 1062, "text": "With comprehensions you can construct python sequences. In this article we will see how to create and access such sequences." }, { "code": null, "e": 1246, "s": 1187, "text": "Below are the different types of comprehensions in python." }, { "code": null, "e": 1266, "s": 1246, "text": "List Comprehensions" }, { "code": null, "e": 1292, "s": 1266, "text": "Dictionary Comprehensions" }, { "code": null, "e": 1311, "s": 1292, "text": "Set Comprehensions" }, { "code": null, "e": 1336, "s": 1311, "text": "Generator Comprehensions" }, { "code": null, "e": 1411, "s": 1336, "text": "There are various ways we can create a list and access the elements in it." }, { "code": null, "e": 1422, "s": 1411, "text": " Live Demo" }, { "code": null, "e": 1571, "s": 1422, "text": "# Cretae an empty list\nlistA = []\n# Append elements to the list\nfor n in range(4, 9):\n listA.append(n ** 3)\nprint(\"List using for loop:\\n\", listA)" }, { "code": null, "e": 1626, "s": 1571, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1672, "s": 1626, "text": "List using for loop:\n[64, 125, 216, 343, 512]" }, { "code": null, "e": 1764, "s": 1672, "text": "We can also create a list form another list by directly assigning elements to the new list." }, { "code": null, "e": 1775, "s": 1764, "text": " Live Demo" }, { "code": null, "e": 1927, "s": 1775, "text": "# Take a list\nlistA = [12,9,32,45]\n#Given list\nprint(\"Given list:\\n \",listA)\nnew_list = [n for n in listA if n % 3 == 0]\nprint(\"New List:\\n\", new_list)" }, { "code": null, "e": 1982, "s": 1927, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2032, "s": 1982, "text": "Given list:\n[12, 9, 32, 45]\nNew List:\n[12, 9, 45]" }, { "code": null, "e": 2167, "s": 2032, "text": "A dictionary contains elements in form of pairs known as key-value pairs. In this article we will see how to create such dictionaries." }, { "code": null, "e": 2289, "s": 2167, "text": "We can take in two lists which can have keys and values. Then join them through comprehension to create a new dictionary." }, { "code": null, "e": 2300, "s": 2289, "text": " Live Demo" }, { "code": null, "e": 2508, "s": 2300, "text": "Day = ['Mon', 'Tue', 'Wed',]\nTime= ['2pm','10am','11am']\n# Create an empty dict\ndictA = {}\n# Use for loop\nfor (key, value) in zip(Day, Time):\n dictA[key] = value\nprint(\"Dictionary using for loop:\\n\",dictA)" }, { "code": null, "e": 2563, "s": 2508, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2635, "s": 2563, "text": "Dictionary using for loop:\n{'Mon': '2pm', 'Tue': '10am', 'Wed': '11am'}" }, { "code": null, "e": 2772, "s": 2635, "text": "In this case we take a Python list and uses elements as key for the dictionary. Also derive the values for each key using an expression." }, { "code": null, "e": 2783, "s": 2772, "text": " Live Demo" }, { "code": null, "e": 2943, "s": 2783, "text": "listA = [3,5,4,8,9,2]\ndictA = {}\n# Using for loop\nfor key in listA:\n if key % 2 != 0:\n dictA[key] = key ** 3\nprint(\"Dictionary using for loop:\\n\",dictA)" }, { "code": null, "e": 2998, "s": 2943, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3049, "s": 2998, "text": "Dictionary using for loop:\n{3: 27, 5: 125, 9: 729}" }, { "code": null, "e": 3133, "s": 3049, "text": "Python Set contains unique elements. It can be created in a similar manner as list." }, { "code": null, "e": 3273, "s": 3133, "text": "Here we take a list and apply a condition to fetch some elements from it. Then put those elements into to an empty set by using add method." }, { "code": null, "e": 3284, "s": 3273, "text": " Live Demo" }, { "code": null, "e": 3429, "s": 3284, "text": "listA = [12, 4, 25, 12,4,9]\nsetA = set()\n# Using for loop\nfor x in listA:\n if x % 3 == 0:\n setA.add(x)\nprint(\"Set using for loop:\", setA)" }, { "code": null, "e": 3484, "s": 3429, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3512, "s": 3484, "text": "Set using for loop: {9, 12}" }, { "code": null, "e": 3646, "s": 3512, "text": "In this method we directly use a for loop within {}. And assign the result into a set. Inside the follow we use elements from a list." }, { "code": null, "e": 3657, "s": 3646, "text": " Live Demo" }, { "code": null, "e": 3777, "s": 3657, "text": "listA = [12, 4, 25, 12,4,9]\n# Using for loop\nsetA = {x for x in listA if x % 2 == 0}\nprint(\"Set using for loop:\", setA)" }, { "code": null, "e": 3832, "s": 3777, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3860, "s": 3832, "text": "Set using for loop: {12, 4}" }, { "code": null, "e": 4065, "s": 3860, "text": "In this approach we take the elements from a list and apply certain conditions on them and then put them into a for loop. The result is assigned to sequence. This method is called generator comprehension." }, { "code": null, "e": 4076, "s": 4065, "text": " Live Demo" }, { "code": null, "e": 4240, "s": 4076, "text": "listA = [12, 4, 25, 12,4,9]\ngenrtr = (var for var in listA if var % 2 == 0)\nprint(\"Values using generator comprehensions:\\n\")\nfor x in genrtr:\n print(x, end=',')" }, { "code": null, "e": 4295, "s": 4240, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 4345, "s": 4295, "text": "Values using generator comprehensions:\n12,4,12,4," } ]
What are static members of a Java class?
In Java, static members are those which belongs to the class and you can access these members without instantiating the class. The static keyword can be used with methods, fields, classes (inner/nested), blocks. Static Methods − You can create a static method by using the keyword static. Static methods can access only static fields, methods. To access static methods there is no need to instantiate the class, you can do it just using the class name as − Live Demo public class MyClass { public static void sample(){ System.out.println("Hello"); } public static void main(String args[]){ MyClass.sample(); } } Hello Static Fields − You can create a static field by using the keyword static. The static fields have the same value in all the instances of the class. These are created and initialized when the class is loaded for the first time. Just like static methods you can access static fields using the class name (without instantiation). Live Demo public class MyClass { public static int data = 20; public static void main(String args[]){ System.out.println(MyClass.data); } Java Arrays with Answers 27 } 20 Static Blocks − These are a block of codes with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading. Live Demo public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } } Hello this is a static block This is main method
[ { "code": null, "e": 1189, "s": 1062, "text": "In Java, static members are those which belongs to the class and you can access these members without instantiating the class." }, { "code": null, "e": 1274, "s": 1189, "text": "The static keyword can be used with methods, fields, classes (inner/nested), blocks." }, { "code": null, "e": 1519, "s": 1274, "text": "Static Methods − You can create a static method by using the keyword static. Static methods can access only static fields, methods. To access static methods there is no need to instantiate the class, you can do it just using the class name as −" }, { "code": null, "e": 1530, "s": 1519, "text": " Live Demo" }, { "code": null, "e": 1699, "s": 1530, "text": "public class MyClass {\n public static void sample(){\n System.out.println(\"Hello\");\n }\n public static void main(String args[]){\n MyClass.sample();\n }\n}" }, { "code": null, "e": 1706, "s": 1699, "text": "Hello\n" }, { "code": null, "e": 2033, "s": 1706, "text": "Static Fields − You can create a static field by using the keyword static. The static fields have the same value in all the instances of the class. These are created and initialized when the class is loaded for the first time. Just like static methods you can access static fields using the class name (without instantiation)." }, { "code": null, "e": 2044, "s": 2033, "text": " Live Demo" }, { "code": null, "e": 2223, "s": 2044, "text": "public class MyClass {\n public static int data = 20;\n public static void main(String args[]){\n System.out.println(MyClass.data);\n }\n Java Arrays with Answers\n 27\n}" }, { "code": null, "e": 2227, "s": 2223, "text": "20\n" }, { "code": null, "e": 2434, "s": 2227, "text": "Static Blocks − These are a block of codes with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading." }, { "code": null, "e": 2445, "s": 2434, "text": " Live Demo" }, { "code": null, "e": 2641, "s": 2445, "text": "public class MyClass {\n static{\n System.out.println(\"Hello this is a static block\");\n }\n public static void main(String args[]){\n System.out.println(\"This is main method\");\n }\n}" }, { "code": null, "e": 2691, "s": 2641, "text": "Hello this is a static block\nThis is main method\n" } ]
Doubly Linked List Tutorial - GeeksforGeeks
27 Dec, 2021 A Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in a singly linked list. Below are operations on the given DLL: Add a node at the front of DLL: The new node is always added before the head of the given Linked List. And the newly added node becomes the new head of DLL & maintaining a global variable for counting the total number of nodes at that time. Traversal of a Doubly linked listInsertion of a node: This can be done in three ways: At the beginning: The new created node is insert in before the head node and head points to the new node.At the end: The new created node is insert at the end of the list and tail points to the new node.At a given position: Traverse the given DLL to that position(let the node be X) then do the following: Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X.Deletion of a node: This can be done in three ways: At the beginning: Move head to the next node to delete the node at the beginning and make previous pointer of current head to NULL .At the last: Move tail to the previous node to delete the node at the end and make next pointer of tail node to NULL.At a given position: Let the prev node of Node at position pos be Node X and next node be Node Y, then do the following: Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X. Add a node at the front of DLL: The new node is always added before the head of the given Linked List. And the newly added node becomes the new head of DLL & maintaining a global variable for counting the total number of nodes at that time. Traversal of a Doubly linked list Insertion of a node: This can be done in three ways: At the beginning: The new created node is insert in before the head node and head points to the new node.At the end: The new created node is insert at the end of the list and tail points to the new node.At a given position: Traverse the given DLL to that position(let the node be X) then do the following: Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X. At the beginning: The new created node is insert in before the head node and head points to the new node. At the end: The new created node is insert at the end of the list and tail points to the new node. At a given position: Traverse the given DLL to that position(let the node be X) then do the following: Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X. Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X. Change the next pointer of new Node to the next pointer of Node X. Change the prev pointer of next Node of Node X to the new Node. Change the next pointer of node X to new Node. Change the prev pointer of new Node to the Node X. Deletion of a node: This can be done in three ways: At the beginning: Move head to the next node to delete the node at the beginning and make previous pointer of current head to NULL .At the last: Move tail to the previous node to delete the node at the end and make next pointer of tail node to NULL.At a given position: Let the prev node of Node at position pos be Node X and next node be Node Y, then do the following: Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X. At the beginning: Move head to the next node to delete the node at the beginning and make previous pointer of current head to NULL . At the last: Move tail to the previous node to delete the node at the end and make next pointer of tail node to NULL. At a given position: Let the prev node of Node at position pos be Node X and next node be Node Y, then do the following: Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X. Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X. Change the next pointer of Node X to Node Y. Change the previous pointer of Node Y to Node X. Below is the implementation of all the operations: CPP Python3 // C program to implement all functions// used in Doubly Linked List #include <stdio.h>#include <stdlib.h>int i = 0; // Node for Doubly Linked Listtypedef struct node { int key; struct node* prev; struct node* next; } node; // Head, Tail, first & temp Nodenode* head = NULL;node* first = NULL;node* temp = NULL;node* tail = NULL; // Function to add a node in the// Doubly Linked Listvoid addnode(int k){ // Allocating memory // to the Node ptr node* ptr = (node*)malloc(sizeof(node)); // Assign Key to value k ptr->key = k; // Next and prev pointer to NULL ptr->next = NULL; ptr->prev = NULL; // If Linked List is empty if (head == NULL) { head = ptr; first = head; tail = head; } // Else insert at the end of the // Linked List else { temp = ptr; first->next = temp; temp->prev = first; first = temp; tail = temp; } // Increment for number of Nodes // in the Doubly Linked List i++;} // Function to traverse the Doubly// Linked Listvoid traverse(){ // Nodes points towards head node node* ptr = head; // While pointer is not NULL, // traverse and print the node while (ptr != NULL) { // Print key of the node printf("%d ", ptr->key); ptr = ptr->next; } printf("\n");} // Function to insert a node at the// beginning of the linked listvoid insertatbegin(int k){ // Allocating memory // to the Node ptr node* ptr = (node*)malloc(sizeof(node)); // Assign Key to value k ptr->key = k; // Next and prev pointer to NULL ptr->next = NULL; ptr->prev = NULL; // If head is NULL if (head == NULL) { first = ptr; first = head; tail = head; } // Else insert at beginning and // change the head to current node else { temp = ptr; temp->next = head; head->prev = temp; head = temp; } i++;} // Function to insert Node at endvoid insertatend(int k){ // Allocating memory // to the Node ptr node* ptr = (node*)malloc(sizeof(node)); // Assign Key to value k ptr->key = k; // Next and prev pointer to NULL ptr->next = NULL; ptr->prev = NULL; // If head is NULL if (head == NULL) { first = ptr; first = head; tail = head; } // Else insert at the end else { temp = ptr; temp->prev = tail; tail->next = temp; tail = temp; } i++;} // Function to insert Node at any// position posvoid insertatpos(int k, int pos){ // For Invalid Position if (pos < 1 || pos > i + 1) { printf("Please enter a" " valid position\n"); } // If position is at the front, // then call insertatbegin() else if (pos == 1) { insertatbegin(k); } // Position is at length of Linked // list + 1, then insert at the end else if (pos == i + 1) { insertatend(k); } // Else traverse till position pos // and insert the Node else { node* src = head; // Move head pointer to pos while (pos--) { src = src->next; } // Allocate memory to new Node node **da, **ba; node* ptr = (node*)malloc( sizeof(node)); ptr->next = NULL; ptr->prev = NULL; ptr->key = k; // Change the previous and next // pointer of the nodes inserted // with previous and next node ba = &src; da = &(src->prev); ptr->next = (*ba); ptr->prev = (*da); (*da)->next = ptr; (*ba)->prev = ptr; i++; }} // Function to delete node at the// beginning of the listvoid delatbegin(){ // Move head to next and // decrease length by 1 head = head->next; i--;} // Function to delete at the end// of the listvoid delatend(){ // Mode tail to the prev and // decrease length by 1 tail = tail->prev; tail->next = NULL; i--;} // Function to delete the node at// a given position posvoid delatpos(int pos){ // If invalid position if (pos < 1 || pos > i + 1) { printf("Please enter a" " valid position\n"); } // If position is 1, then // call delatbegin() else if (pos == 1) { delatbegin(); } // If position is at the end, then // call delatend() else if (pos == i) { delatend(); } // Else traverse till pos, and // delete the node at pos else { // Src node to find which // node to be deleted node* src = head; pos--; // Traverse node till pos while (pos--) { src = src->next; } // previous and after node // of the src node node **pre, **aft; pre = &(src->prev); aft = &(src->next); // Change the next and prev // pointer of pre and aft node (*pre)->next = (*aft); (*aft)->prev = (*pre); // Decrease the length of the // Linked List i--; }} // Driver Codeint main(){ // Adding node to the linked List addnode(2); addnode(4); addnode(9); addnode(1); addnode(21); addnode(22); // To print the linked List printf("Linked List: "); traverse(); printf("\n"); // To insert node at the beginning insertatbegin(1); printf("Linked List after" " inserting 1 " "at beginning: "); traverse(); // To insert at the end insertatend(0); printf("Linked List after " "inserting 0 at end: "); traverse(); // To insert Node with // value 44 after 3rd Node insertatpos(44, 3); printf("Linked List after " "inserting 44 " "after 3rd Node: "); traverse(); printf("\n"); // To delete node at the beginning delatbegin(); printf("Linked List after " "deleting node " "at beginning: "); traverse(); // To delete at the end delatend(); printf("Linked List after " "deleting node at end: "); traverse(); // To delete Node at position 5 printf("Linked List after " "deleting node " "at position 5: "); delatpos(5); traverse(); return 0;} # Python3 program to implement all functions# used in Doubly Linked List i = 0 # Node for Doubly Linked Listclass node: def __init__(self, k=0, p=None, n=None): self.key = k self.prev = p self.next = n # Head, Tail, first & temp Nodehead = Nonefirst = Nonetemp = Nonetail = None # Function to add a node in the# Doubly Linked Listdef addnode(k: int): global i, head, first, tail # Allocating memory # to the Node ptr ptr = node(k) # If Linked List is empty if head == None: head = ptr first = head tail = head # Else insert at the end of the # Linked List else: temp = ptr first.next = temp temp.prev = first first = temp tail = temp # Increment for number of Nodes # in the Doubly Linked List i += 1 # Function to traverse the Doubly# Linked Listdef traverse(): # Nodes points towards head node ptr = head # While pointer is not None, # traverse and print the node while ptr != None: # Print key of the node print(ptr.key, end=" ") ptr = ptr.next print() # Function to insert a node at the# beginning of the linked listdef insertatbegin(k: int): global head, first, tail, i # Allocating memory # to the Node ptr ptr = node(k) # If head is None if head == None: first = ptr first = head tail = head # Else insert at beginning and # change the head to current node else: temp = ptr temp.next = head head.prev = temp head = temp i += 1 # Function to insert Node at enddef insertatend(k: int): global head, first, tail, i # Allocating memory # to the Node ptr ptr = node(k) # If head is None if head == None: first = ptr first = head tail = head # Else insert at the end else: temp = ptr temp.prev = tail tail.next = temp tail = temp i += 1 # Function to insert Node at any# position posdef insertatpos(k: int, pos: int): global i # For Invalid Position if pos < 1 or pos > i + 1: print("Please enter a" " valid position") # If position is at the front, # then call insertatbegin() elif pos == 1: insertatbegin(k) # Position is at length of Linked # list + 1, then insert at the end elif pos == i + 1: insertatend(k) # Else traverse till position pos # and insert the Node else: src = head # Move head pointer to pos while pos: pos -= 1 src = src.next # Allocate memory to new Node ptr = node(k) # Change the previous and next # pointer of the nodes inserted # with previous and next node ptr.next = src ptr.prev = src.prev src.prev.next = ptr src.prev = ptr i += 1 # Function to delete node at the# beginning of the listdef delatbegin(): # Move head to next and # decrease length by 1 global head, i head = head.next i -= 1 # Function to delete at the end# of the listdef delatend(): # Mode tail to the prev and # decrease length by 1 global tail, i tail = tail.prev tail.next = None i -= 1 # Function to delete the node at# a given position posdef delatpos(pos: int): global i # If invalid position if pos < 1 or pos > i + 1: print("Please enter a" " valid position") # If position is 1, then # call delatbegin() elif pos == 1: delatbegin() # If position is at the end, then # call delatend() elif pos == i: delatend() # Else traverse till pos, and # delete the node at pos else: # Src node to find which # node to be deleted src = head pos -= 1 # Traverse node till pos while pos: pos -= 1 src = src.next # Change the next and prev # pointer of pre and aft node src.prev.next = src.next src.next.prev = src.prev # Decrease the length of the # Linked List i -= 1 # Driver Codeif __name__ == "__main__": # Adding node to the linked List addnode(2) addnode(4) addnode(9) addnode(1) addnode(21) addnode(22) # To print the linked List print("Linked List: ") traverse() print("\n") # To insert node at the beginning insertatbegin(1) print("Linked List after inserting 1 at beginning: ") traverse() # To insert at the end insertatend(0) print("Linked List after inserting 0 at end: ") traverse() # To insert Node with # value 44 after 3rd Node insertatpos(44, 3) print("Linked List after inserting 44 after 3rd Node: ") traverse() print("\n") # To delete node at the beginning delatbegin() print("Linked List after deleting node at beginning: ") traverse() # To delete at the end delatend() print("Linked List after deleting node at end: ") traverse() # To delete Node at position 5 print("Linked List after deleting node at position 5: ") delatpos(5) traverse() sweetyty amartyaghoshgfg doubly linked list Programming Basics Algorithms Linked List Programming Language Write From Home Linked List Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 24275, "s": 24247, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24451, "s": 24275, "text": "A Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in a singly linked list. " }, { "code": null, "e": 24491, "s": 24451, "text": "Below are operations on the given DLL: " }, { "code": null, "e": 25864, "s": 24491, "text": "Add a node at the front of DLL: The new node is always added before the head of the given Linked List. And the newly added node becomes the new head of DLL & maintaining a global variable for counting the total number of nodes at that time. Traversal of a Doubly linked listInsertion of a node: This can be done in three ways: At the beginning: The new created node is insert in before the head node and head points to the new node.At the end: The new created node is insert at the end of the list and tail points to the new node.At a given position: Traverse the given DLL to that position(let the node be X) then do the following: Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X.Deletion of a node: This can be done in three ways: At the beginning: Move head to the next node to delete the node at the beginning and make previous pointer of current head to NULL .At the last: Move tail to the previous node to delete the node at the end and make next pointer of tail node to NULL.At a given position: Let the prev node of Node at position pos be Node X and next node be Node Y, then do the following: Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X." }, { "code": null, "e": 26106, "s": 25864, "text": "Add a node at the front of DLL: The new node is always added before the head of the given Linked List. And the newly added node becomes the new head of DLL & maintaining a global variable for counting the total number of nodes at that time. " }, { "code": null, "e": 26140, "s": 26106, "text": "Traversal of a Doubly linked list" }, { "code": null, "e": 26725, "s": 26140, "text": "Insertion of a node: This can be done in three ways: At the beginning: The new created node is insert in before the head node and head points to the new node.At the end: The new created node is insert at the end of the list and tail points to the new node.At a given position: Traverse the given DLL to that position(let the node be X) then do the following: Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X." }, { "code": null, "e": 26831, "s": 26725, "text": "At the beginning: The new created node is insert in before the head node and head points to the new node." }, { "code": null, "e": 26930, "s": 26831, "text": "At the end: The new created node is insert at the end of the list and tail points to the new node." }, { "code": null, "e": 27259, "s": 26930, "text": "At a given position: Traverse the given DLL to that position(let the node be X) then do the following: Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X." }, { "code": null, "e": 27485, "s": 27259, "text": "Change the next pointer of new Node to the next pointer of Node X.Change the prev pointer of next Node of Node X to the new Node.Change the next pointer of node X to new Node.Change the prev pointer of new Node to the Node X." }, { "code": null, "e": 27552, "s": 27485, "text": "Change the next pointer of new Node to the next pointer of Node X." }, { "code": null, "e": 27616, "s": 27552, "text": "Change the prev pointer of next Node of Node X to the new Node." }, { "code": null, "e": 27663, "s": 27616, "text": "Change the next pointer of node X to new Node." }, { "code": null, "e": 27714, "s": 27663, "text": "Change the prev pointer of new Node to the Node X." }, { "code": null, "e": 28229, "s": 27714, "text": "Deletion of a node: This can be done in three ways: At the beginning: Move head to the next node to delete the node at the beginning and make previous pointer of current head to NULL .At the last: Move tail to the previous node to delete the node at the end and make next pointer of tail node to NULL.At a given position: Let the prev node of Node at position pos be Node X and next node be Node Y, then do the following: Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X." }, { "code": null, "e": 28362, "s": 28229, "text": "At the beginning: Move head to the next node to delete the node at the beginning and make previous pointer of current head to NULL ." }, { "code": null, "e": 28480, "s": 28362, "text": "At the last: Move tail to the previous node to delete the node at the end and make next pointer of tail node to NULL." }, { "code": null, "e": 28694, "s": 28480, "text": "At a given position: Let the prev node of Node at position pos be Node X and next node be Node Y, then do the following: Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X." }, { "code": null, "e": 28787, "s": 28694, "text": "Change the next pointer of Node X to Node Y.Change the previous pointer of Node Y to Node X." }, { "code": null, "e": 28832, "s": 28787, "text": "Change the next pointer of Node X to Node Y." }, { "code": null, "e": 28881, "s": 28832, "text": "Change the previous pointer of Node Y to Node X." }, { "code": null, "e": 28933, "s": 28881, "text": "Below is the implementation of all the operations: " }, { "code": null, "e": 28937, "s": 28933, "text": "CPP" }, { "code": null, "e": 28945, "s": 28937, "text": "Python3" }, { "code": "// C program to implement all functions// used in Doubly Linked List #include <stdio.h>#include <stdlib.h>int i = 0; // Node for Doubly Linked Listtypedef struct node { int key; struct node* prev; struct node* next; } node; // Head, Tail, first & temp Nodenode* head = NULL;node* first = NULL;node* temp = NULL;node* tail = NULL; // Function to add a node in the// Doubly Linked Listvoid addnode(int k){ // Allocating memory // to the Node ptr node* ptr = (node*)malloc(sizeof(node)); // Assign Key to value k ptr->key = k; // Next and prev pointer to NULL ptr->next = NULL; ptr->prev = NULL; // If Linked List is empty if (head == NULL) { head = ptr; first = head; tail = head; } // Else insert at the end of the // Linked List else { temp = ptr; first->next = temp; temp->prev = first; first = temp; tail = temp; } // Increment for number of Nodes // in the Doubly Linked List i++;} // Function to traverse the Doubly// Linked Listvoid traverse(){ // Nodes points towards head node node* ptr = head; // While pointer is not NULL, // traverse and print the node while (ptr != NULL) { // Print key of the node printf(\"%d \", ptr->key); ptr = ptr->next; } printf(\"\\n\");} // Function to insert a node at the// beginning of the linked listvoid insertatbegin(int k){ // Allocating memory // to the Node ptr node* ptr = (node*)malloc(sizeof(node)); // Assign Key to value k ptr->key = k; // Next and prev pointer to NULL ptr->next = NULL; ptr->prev = NULL; // If head is NULL if (head == NULL) { first = ptr; first = head; tail = head; } // Else insert at beginning and // change the head to current node else { temp = ptr; temp->next = head; head->prev = temp; head = temp; } i++;} // Function to insert Node at endvoid insertatend(int k){ // Allocating memory // to the Node ptr node* ptr = (node*)malloc(sizeof(node)); // Assign Key to value k ptr->key = k; // Next and prev pointer to NULL ptr->next = NULL; ptr->prev = NULL; // If head is NULL if (head == NULL) { first = ptr; first = head; tail = head; } // Else insert at the end else { temp = ptr; temp->prev = tail; tail->next = temp; tail = temp; } i++;} // Function to insert Node at any// position posvoid insertatpos(int k, int pos){ // For Invalid Position if (pos < 1 || pos > i + 1) { printf(\"Please enter a\" \" valid position\\n\"); } // If position is at the front, // then call insertatbegin() else if (pos == 1) { insertatbegin(k); } // Position is at length of Linked // list + 1, then insert at the end else if (pos == i + 1) { insertatend(k); } // Else traverse till position pos // and insert the Node else { node* src = head; // Move head pointer to pos while (pos--) { src = src->next; } // Allocate memory to new Node node **da, **ba; node* ptr = (node*)malloc( sizeof(node)); ptr->next = NULL; ptr->prev = NULL; ptr->key = k; // Change the previous and next // pointer of the nodes inserted // with previous and next node ba = &src; da = &(src->prev); ptr->next = (*ba); ptr->prev = (*da); (*da)->next = ptr; (*ba)->prev = ptr; i++; }} // Function to delete node at the// beginning of the listvoid delatbegin(){ // Move head to next and // decrease length by 1 head = head->next; i--;} // Function to delete at the end// of the listvoid delatend(){ // Mode tail to the prev and // decrease length by 1 tail = tail->prev; tail->next = NULL; i--;} // Function to delete the node at// a given position posvoid delatpos(int pos){ // If invalid position if (pos < 1 || pos > i + 1) { printf(\"Please enter a\" \" valid position\\n\"); } // If position is 1, then // call delatbegin() else if (pos == 1) { delatbegin(); } // If position is at the end, then // call delatend() else if (pos == i) { delatend(); } // Else traverse till pos, and // delete the node at pos else { // Src node to find which // node to be deleted node* src = head; pos--; // Traverse node till pos while (pos--) { src = src->next; } // previous and after node // of the src node node **pre, **aft; pre = &(src->prev); aft = &(src->next); // Change the next and prev // pointer of pre and aft node (*pre)->next = (*aft); (*aft)->prev = (*pre); // Decrease the length of the // Linked List i--; }} // Driver Codeint main(){ // Adding node to the linked List addnode(2); addnode(4); addnode(9); addnode(1); addnode(21); addnode(22); // To print the linked List printf(\"Linked List: \"); traverse(); printf(\"\\n\"); // To insert node at the beginning insertatbegin(1); printf(\"Linked List after\" \" inserting 1 \" \"at beginning: \"); traverse(); // To insert at the end insertatend(0); printf(\"Linked List after \" \"inserting 0 at end: \"); traverse(); // To insert Node with // value 44 after 3rd Node insertatpos(44, 3); printf(\"Linked List after \" \"inserting 44 \" \"after 3rd Node: \"); traverse(); printf(\"\\n\"); // To delete node at the beginning delatbegin(); printf(\"Linked List after \" \"deleting node \" \"at beginning: \"); traverse(); // To delete at the end delatend(); printf(\"Linked List after \" \"deleting node at end: \"); traverse(); // To delete Node at position 5 printf(\"Linked List after \" \"deleting node \" \"at position 5: \"); delatpos(5); traverse(); return 0;}", "e": 35181, "s": 28945, "text": null }, { "code": "# Python3 program to implement all functions# used in Doubly Linked List i = 0 # Node for Doubly Linked Listclass node: def __init__(self, k=0, p=None, n=None): self.key = k self.prev = p self.next = n # Head, Tail, first & temp Nodehead = Nonefirst = Nonetemp = Nonetail = None # Function to add a node in the# Doubly Linked Listdef addnode(k: int): global i, head, first, tail # Allocating memory # to the Node ptr ptr = node(k) # If Linked List is empty if head == None: head = ptr first = head tail = head # Else insert at the end of the # Linked List else: temp = ptr first.next = temp temp.prev = first first = temp tail = temp # Increment for number of Nodes # in the Doubly Linked List i += 1 # Function to traverse the Doubly# Linked Listdef traverse(): # Nodes points towards head node ptr = head # While pointer is not None, # traverse and print the node while ptr != None: # Print key of the node print(ptr.key, end=\" \") ptr = ptr.next print() # Function to insert a node at the# beginning of the linked listdef insertatbegin(k: int): global head, first, tail, i # Allocating memory # to the Node ptr ptr = node(k) # If head is None if head == None: first = ptr first = head tail = head # Else insert at beginning and # change the head to current node else: temp = ptr temp.next = head head.prev = temp head = temp i += 1 # Function to insert Node at enddef insertatend(k: int): global head, first, tail, i # Allocating memory # to the Node ptr ptr = node(k) # If head is None if head == None: first = ptr first = head tail = head # Else insert at the end else: temp = ptr temp.prev = tail tail.next = temp tail = temp i += 1 # Function to insert Node at any# position posdef insertatpos(k: int, pos: int): global i # For Invalid Position if pos < 1 or pos > i + 1: print(\"Please enter a\" \" valid position\") # If position is at the front, # then call insertatbegin() elif pos == 1: insertatbegin(k) # Position is at length of Linked # list + 1, then insert at the end elif pos == i + 1: insertatend(k) # Else traverse till position pos # and insert the Node else: src = head # Move head pointer to pos while pos: pos -= 1 src = src.next # Allocate memory to new Node ptr = node(k) # Change the previous and next # pointer of the nodes inserted # with previous and next node ptr.next = src ptr.prev = src.prev src.prev.next = ptr src.prev = ptr i += 1 # Function to delete node at the# beginning of the listdef delatbegin(): # Move head to next and # decrease length by 1 global head, i head = head.next i -= 1 # Function to delete at the end# of the listdef delatend(): # Mode tail to the prev and # decrease length by 1 global tail, i tail = tail.prev tail.next = None i -= 1 # Function to delete the node at# a given position posdef delatpos(pos: int): global i # If invalid position if pos < 1 or pos > i + 1: print(\"Please enter a\" \" valid position\") # If position is 1, then # call delatbegin() elif pos == 1: delatbegin() # If position is at the end, then # call delatend() elif pos == i: delatend() # Else traverse till pos, and # delete the node at pos else: # Src node to find which # node to be deleted src = head pos -= 1 # Traverse node till pos while pos: pos -= 1 src = src.next # Change the next and prev # pointer of pre and aft node src.prev.next = src.next src.next.prev = src.prev # Decrease the length of the # Linked List i -= 1 # Driver Codeif __name__ == \"__main__\": # Adding node to the linked List addnode(2) addnode(4) addnode(9) addnode(1) addnode(21) addnode(22) # To print the linked List print(\"Linked List: \") traverse() print(\"\\n\") # To insert node at the beginning insertatbegin(1) print(\"Linked List after inserting 1 at beginning: \") traverse() # To insert at the end insertatend(0) print(\"Linked List after inserting 0 at end: \") traverse() # To insert Node with # value 44 after 3rd Node insertatpos(44, 3) print(\"Linked List after inserting 44 after 3rd Node: \") traverse() print(\"\\n\") # To delete node at the beginning delatbegin() print(\"Linked List after deleting node at beginning: \") traverse() # To delete at the end delatend() print(\"Linked List after deleting node at end: \") traverse() # To delete Node at position 5 print(\"Linked List after deleting node at position 5: \") delatpos(5) traverse()", "e": 40276, "s": 35181, "text": null }, { "code": null, "e": 40285, "s": 40276, "text": "sweetyty" }, { "code": null, "e": 40301, "s": 40285, "text": "amartyaghoshgfg" }, { "code": null, "e": 40320, "s": 40301, "text": "doubly linked list" }, { "code": null, "e": 40339, "s": 40320, "text": "Programming Basics" }, { "code": null, "e": 40350, "s": 40339, "text": "Algorithms" }, { "code": null, "e": 40362, "s": 40350, "text": "Linked List" }, { "code": null, "e": 40383, "s": 40362, "text": "Programming Language" }, { "code": null, "e": 40399, "s": 40383, "text": "Write From Home" }, { "code": null, "e": 40411, "s": 40399, "text": "Linked List" }, { "code": null, "e": 40422, "s": 40411, "text": "Algorithms" }, { "code": null, "e": 40520, "s": 40422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40529, "s": 40520, "text": "Comments" }, { "code": null, "e": 40542, "s": 40529, "text": "Old Comments" }, { "code": null, "e": 40567, "s": 40542, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 40623, "s": 40567, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 40666, "s": 40623, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 40695, "s": 40666, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 40729, "s": 40695, "text": "K means Clustering - Introduction" }, { "code": null, "e": 40764, "s": 40729, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 40803, "s": 40764, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 40825, "s": 40803, "text": "Reverse a linked list" }, { "code": null, "e": 40873, "s": 40825, "text": "Stack Data Structure (Introduction and Program)" } ]
Java - String Buffer delete() Method
This method removes the characters in a substring of this StringBuffer. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the StringBuffer if no such character exists. If start is equal to end, no changes are made. Here is the syntax of this method − public StringBuffer delete(int start, int end) Here is the detail of parameters − start − The beginning index, inclusive. start − The beginning index, inclusive. end − The ending index, exclusive. end − The ending index, exclusive. This method returns the StringBuffer object. public class Test { public static void main(String args[]) { StringBuffer sb = new StringBuffer("abcdefghijk"); sb.delete(3, 7); System.out.println(sb); } } This will produce the following result − abchijk 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": 2602, "s": 2377, "text": "This method removes the characters in a substring of this StringBuffer. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the StringBuffer if no such character exists." }, { "code": null, "e": 2649, "s": 2602, "text": "If start is equal to end, no changes are made." }, { "code": null, "e": 2685, "s": 2649, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2733, "s": 2685, "text": "public StringBuffer delete(int start, int end)\n" }, { "code": null, "e": 2768, "s": 2733, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2808, "s": 2768, "text": "start − The beginning index, inclusive." }, { "code": null, "e": 2848, "s": 2808, "text": "start − The beginning index, inclusive." }, { "code": null, "e": 2883, "s": 2848, "text": "end − The ending index, exclusive." }, { "code": null, "e": 2918, "s": 2883, "text": "end − The ending index, exclusive." }, { "code": null, "e": 2963, "s": 2918, "text": "This method returns the StringBuffer object." }, { "code": null, "e": 3149, "s": 2963, "text": "public class Test {\n\n public static void main(String args[]) {\n StringBuffer sb = new StringBuffer(\"abcdefghijk\");\n sb.delete(3, 7); \n System.out.println(sb); \n } \n}" }, { "code": null, "e": 3190, "s": 3149, "text": "This will produce the following result −" }, { "code": null, "e": 3199, "s": 3190, "text": "abchijk\n" }, { "code": null, "e": 3232, "s": 3199, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3248, "s": 3232, "text": " Malhar Lathkar" }, { "code": null, "e": 3281, "s": 3248, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3297, "s": 3281, "text": " Malhar Lathkar" }, { "code": null, "e": 3332, "s": 3297, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3346, "s": 3332, "text": " Anadi Sharma" }, { "code": null, "e": 3380, "s": 3346, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3394, "s": 3380, "text": " Tushar Kale" }, { "code": null, "e": 3431, "s": 3394, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3446, "s": 3431, "text": " Monica Mittal" }, { "code": null, "e": 3479, "s": 3446, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3498, "s": 3479, "text": " Arnab Chakraborty" }, { "code": null, "e": 3505, "s": 3498, "text": " Print" }, { "code": null, "e": 3516, "s": 3505, "text": " Add Notes" } ]
JavaScript String - slice() Method
This method extracts a section of a string and returns a new string. The syntax for slice() method is − string.slice( beginslice [, endSlice] ); beginSlice − The zero-based index at which to begin extraction. beginSlice − The zero-based index at which to begin extraction. endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string. endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string. If successful, slice returns the index of the regular expression inside the string. Otherwise, it returns -1. Try the following example. <html> <head> <title>JavaScript String slice() Method</title> </head> <body> <script type = "text/javascript"> var str = "Apples are round, and apples are juicy."; var sliced = str.slice(3, -2); document.write( sliced ); </script> </body> </html> les are round, and apples are juic 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2535, "s": 2466, "text": "This method extracts a section of a string and returns a new string." }, { "code": null, "e": 2570, "s": 2535, "text": "The syntax for slice() method is −" }, { "code": null, "e": 2612, "s": 2570, "text": "string.slice( beginslice [, endSlice] );\n" }, { "code": null, "e": 2676, "s": 2612, "text": "beginSlice − The zero-based index at which to begin extraction." }, { "code": null, "e": 2740, "s": 2676, "text": "beginSlice − The zero-based index at which to begin extraction." }, { "code": null, "e": 2853, "s": 2740, "text": "endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string." }, { "code": null, "e": 2966, "s": 2853, "text": "endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string." }, { "code": null, "e": 3076, "s": 2966, "text": "If successful, slice returns the index of the regular expression inside the string. Otherwise, it returns -1." }, { "code": null, "e": 3103, "s": 3076, "text": "Try the following example." }, { "code": null, "e": 3429, "s": 3103, "text": "<html>\n <head>\n <title>JavaScript String slice() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = \"Apples are round, and apples are juicy.\";\n var sliced = str.slice(3, -2); \n document.write( sliced );\n </script> \n </body>\n</html>" }, { "code": null, "e": 3465, "s": 3429, "text": "les are round, and apples are juic\n" }, { "code": null, "e": 3500, "s": 3465, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3514, "s": 3500, "text": " Anadi Sharma" }, { "code": null, "e": 3548, "s": 3514, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3562, "s": 3548, "text": " Lets Kode It" }, { "code": null, "e": 3597, "s": 3562, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3614, "s": 3597, "text": " Frahaan Hussain" }, { "code": null, "e": 3649, "s": 3614, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3666, "s": 3649, "text": " Frahaan Hussain" }, { "code": null, "e": 3699, "s": 3666, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3727, "s": 3699, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3761, "s": 3727, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3789, "s": 3761, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3796, "s": 3789, "text": " Print" }, { "code": null, "e": 3807, "s": 3796, "text": " Add Notes" } ]
How to Insert an Image in HTML?
04 Aug, 2021 We can use different fonts and lists in an HTML document. Similarly, we can add graphics to make the document look more attractive. Web browsers support a number of graphic formats. Some of the most widely used formats are: Graphics Interchange Format(GIF): GIF is the best format displaying images designed with a graphics program. This format uses a maximum of 256 colors and a combination of these to create more colors. Joint Photographic Expert Group(JPEG): JPEG is the best format for photographs as it contains 1 million colors. Portable Network Graphics(PNG): The format is best for images with transparency or the low color count. Use of <img>Tag The <img> tag specifies an image to be displayed in an HTML document. It is an element as it does not have an OFF tag. The image tag has the following attributes in the table: Specifies the alternative text for an image. This is displayed when the graphics feature is turned off in the browser or while The image is being downloaded. In some browsers, the ALT text is displayed as a tooltip for the image. The following HTML code will help you understand the <img>tag better. The resulting web page is shown in the output. HTML <!DOCTYPE html><html> <style> image{border:4px solid orange; width: 120px;height: 100px;} h1{text-transform:uppercase} </style><head> <title> HTML frame scrolling Attribute </title></head><body> <h1>INSERTING IMAGE</h1> <img src="5.png" alt="image is not available"></body></html> Output: HTML <!DOCTYPE html><html><head> <title> HTML frame scrolling Attribute </title></head><body> <h1>INSERTING IMAGE</h1> <img src="5.png" alt="image is not available" width="120px" height="100px"></body></html> Output: Supported browsers are: Google Chrome Internet Explorer Firefox Opera Safari simmytarika5 Picked class 7 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flora and Fauna of Ladakh Akbar's Policies Working of the Government in India Equality in Indian Democracy Components of Environment Libraries in Python What are Different Output Devices? Generations of Computers - Computer Fundamentals GeeksforGeeks School Reading Rows from a CSV File in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Aug, 2021" }, { "code": null, "e": 252, "s": 28, "text": "We can use different fonts and lists in an HTML document. Similarly, we can add graphics to make the document look more attractive. Web browsers support a number of graphic formats. Some of the most widely used formats are:" }, { "code": null, "e": 452, "s": 252, "text": "Graphics Interchange Format(GIF): GIF is the best format displaying images designed with a graphics program. This format uses a maximum of 256 colors and a combination of these to create more colors." }, { "code": null, "e": 564, "s": 452, "text": "Joint Photographic Expert Group(JPEG): JPEG is the best format for photographs as it contains 1 million colors." }, { "code": null, "e": 668, "s": 564, "text": "Portable Network Graphics(PNG): The format is best for images with transparency or the low color count." }, { "code": null, "e": 684, "s": 668, "text": "Use of <img>Tag" }, { "code": null, "e": 803, "s": 684, "text": "The <img> tag specifies an image to be displayed in an HTML document. It is an element as it does not have an OFF tag." }, { "code": null, "e": 860, "s": 803, "text": "The image tag has the following attributes in the table:" }, { "code": null, "e": 988, "s": 860, "text": "Specifies the alternative text for an image. This is displayed when the graphics feature is turned off in the browser or while " }, { "code": null, "e": 1092, "s": 988, "text": "The image is being downloaded. In some browsers, the ALT text is displayed as a tooltip for the image. " }, { "code": null, "e": 1209, "s": 1092, "text": "The following HTML code will help you understand the <img>tag better. The resulting web page is shown in the output." }, { "code": null, "e": 1214, "s": 1209, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <style> image{border:4px solid orange; width: 120px;height: 100px;} h1{text-transform:uppercase} </style><head> <title> HTML frame scrolling Attribute </title></head><body> <h1>INSERTING IMAGE</h1> <img src=\"5.png\" alt=\"image is not available\"></body></html>", "e": 1534, "s": 1214, "text": null }, { "code": null, "e": 1542, "s": 1534, "text": "Output:" }, { "code": null, "e": 1547, "s": 1542, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> HTML frame scrolling Attribute </title></head><body> <h1>INSERTING IMAGE</h1> <img src=\"5.png\" alt=\"image is not available\" width=\"120px\" height=\"100px\"></body></html>", "e": 1770, "s": 1547, "text": null }, { "code": null, "e": 1778, "s": 1770, "text": "Output:" }, { "code": null, "e": 1802, "s": 1778, "text": "Supported browsers are:" }, { "code": null, "e": 1816, "s": 1802, "text": "Google Chrome" }, { "code": null, "e": 1834, "s": 1816, "text": "Internet Explorer" }, { "code": null, "e": 1842, "s": 1834, "text": "Firefox" }, { "code": null, "e": 1848, "s": 1842, "text": "Opera" }, { "code": null, "e": 1855, "s": 1848, "text": "Safari" }, { "code": null, "e": 1868, "s": 1855, "text": "simmytarika5" }, { "code": null, "e": 1875, "s": 1868, "text": "Picked" }, { "code": null, "e": 1883, "s": 1875, "text": "class 7" }, { "code": null, "e": 1899, "s": 1883, "text": "School Learning" }, { "code": null, "e": 1918, "s": 1899, "text": "School Programming" }, { "code": null, "e": 2016, "s": 1918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2042, "s": 2016, "text": "Flora and Fauna of Ladakh" }, { "code": null, "e": 2059, "s": 2042, "text": "Akbar's Policies" }, { "code": null, "e": 2094, "s": 2059, "text": "Working of the Government in India" }, { "code": null, "e": 2123, "s": 2094, "text": "Equality in Indian Democracy" }, { "code": null, "e": 2149, "s": 2123, "text": "Components of Environment" }, { "code": null, "e": 2169, "s": 2149, "text": "Libraries in Python" }, { "code": null, "e": 2204, "s": 2169, "text": "What are Different Output Devices?" }, { "code": null, "e": 2253, "s": 2204, "text": "Generations of Computers - Computer Fundamentals" }, { "code": null, "e": 2274, "s": 2253, "text": "GeeksforGeeks School" } ]
JavaScript Array sort() Method
01 Jun, 2022 Below is the example of Array sort() method. Program 1: JavaScript <script>// JavaScript to illustrate sort() functionfunction func() { // Original string var arr = ["Geeks", "for", "Geeks"] document.write(arr); document.write("<br>"); // Sorting the array document.write(arr.sort());}func();</script> Output: Geeks,for,Geeks Geeks,Geeks,for The arr.sort() method is used to sort the array in place in a given order according to the compare() function. If the method is omitted then the array is sorted in ascending order. Syntax: arr.sort(compareFunction) Parameters: This method accept a single parameter as mentioned above and described below: compareFunction: This parameters is used to sort the elements according to different attributes and in the different order.compareFunction(a,b) < 0compareFunction(a,b) > 0compareFunction(a,b) = 0 compareFunction(a,b) < 0 compareFunction(a,b) > 0 compareFunction(a,b) = 0 Return value: This method returns the reference of the sorted original array. Below examples illustrate the JavaScript Array sort() method: Example 1: In this example the sort() method arranges the elements of the array in ascending order. var arr = [2, 5, 8, 1, 4] document.write(arr.sort()); document.write(arr); Output: 1,2,4,5,8 1,2,4,5,8 Example 2: In this example the sort() method the elements of the array are sorted according the function applied on each element. var arr = [2, 5, 8, 1, 4] document.write(arr.sort(function(a, b) { return a + 2 * b; })); document.write(arr); Output: 2,5,8,1,4 2,5,8,1,4 Example 3: In this example, we use the sort() method on the array of numbers & observe some unexpected behaviour . let numbers = [20,5.2,-120,100,30,0] console.log(numbers.sort()) Output: -120,0,100,20,30,5.2 Our output should be -120, 0, 5.2, 20, 30, 100 but it’s not so, why? Because as we apply directly sort() method, it would processes accordingly: 100 would be placed before 20, as ‘2’ is larger than ‘1’ and similarly in case of 30 & 5.2, as ‘5’ is larger than ‘3’ thus, 30 would be placed before 5.2. We can resolve this unexpected error by using sort() method for numerics using following compare function: let numbers = [20,5.2,-120,100,30,0]; /* Logic: 20 - (5.2) = +ve => 5.2 would be placed before 20, 20 - (-120) = +ve => -120 would be placed before 20, 20 - (100) = -ve => 100 would be placed after 20, 20 - (30) = -ve => 30 would be placed after 20, 20 - (0) = +ve => 0 would be placed before 20, Similarly for every element, we check and place them accordingly in iterations. */ function compare(a,b){ return a-b; } console.log(numbers.sort(compare)); Output: -120,0,5.2,20,30,100 Code for the above method is provided below: Program 1: JavaScript <script>// JavaScript to illustrate sort() functionfunction func() { //Original string var arr = [2, 5, 8, 1, 4] //Sorting the array document.write(arr.sort()); document.write("<br>"); document.write(arr);}func();</script> Output: 1,2,4,5,8 1,2,4,5,8 Program 2: JavaScript <script>// JavaScript to illustrate sort() function function func() { // Original array var arr = [2, 5, 8, 1, 4]; document.write(arr.sort(function(a, b) { return a + 2 * b;}));document.write("<br>");document.write(arr);}func();</script> Output: 4,1,8,5,2 4,1,8,5,2 Supported Browsers: The browsers supported by JavaScript Array sort() method are listed below: Google Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 5.5 and above Opera 4 and above Safari 1 and above Time Complexity: The time complexity of sort() method varies & depends on implementation.For example, in Firefox web browser, it uses the merge sort implementation which gives time complexity as O(nlog n). Whereas, in Google Chrome web browser, it uses the Timsort implementation (a hybrid of merge sort and insertion sort), gives time complexity is O(nlogn). ysachin2314 codeachalesh javascript-array JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2022" }, { "code": null, "e": 73, "s": 28, "text": "Below is the example of Array sort() method." }, { "code": null, "e": 85, "s": 73, "text": "Program 1: " }, { "code": null, "e": 96, "s": 85, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate sort() functionfunction func() { // Original string var arr = [\"Geeks\", \"for\", \"Geeks\"] document.write(arr); document.write(\"<br>\"); // Sorting the array document.write(arr.sort());}func();</script>", "e": 351, "s": 96, "text": null }, { "code": null, "e": 359, "s": 351, "text": "Output:" }, { "code": null, "e": 391, "s": 359, "text": "Geeks,for,Geeks\nGeeks,Geeks,for" }, { "code": null, "e": 580, "s": 391, "text": "The arr.sort() method is used to sort the array in place in a given order according to the compare() function. If the method is omitted then the array is sorted in ascending order. Syntax:" }, { "code": null, "e": 606, "s": 580, "text": "arr.sort(compareFunction)" }, { "code": null, "e": 696, "s": 606, "text": "Parameters: This method accept a single parameter as mentioned above and described below:" }, { "code": null, "e": 892, "s": 696, "text": "compareFunction: This parameters is used to sort the elements according to different attributes and in the different order.compareFunction(a,b) < 0compareFunction(a,b) > 0compareFunction(a,b) = 0" }, { "code": null, "e": 917, "s": 892, "text": "compareFunction(a,b) < 0" }, { "code": null, "e": 942, "s": 917, "text": "compareFunction(a,b) > 0" }, { "code": null, "e": 967, "s": 942, "text": "compareFunction(a,b) = 0" }, { "code": null, "e": 1107, "s": 967, "text": "Return value: This method returns the reference of the sorted original array. Below examples illustrate the JavaScript Array sort() method:" }, { "code": null, "e": 1207, "s": 1107, "text": "Example 1: In this example the sort() method arranges the elements of the array in ascending order." }, { "code": null, "e": 1282, "s": 1207, "text": "var arr = [2, 5, 8, 1, 4]\ndocument.write(arr.sort());\ndocument.write(arr);" }, { "code": null, "e": 1290, "s": 1282, "text": "Output:" }, { "code": null, "e": 1310, "s": 1290, "text": "1,2,4,5,8\n1,2,4,5,8" }, { "code": null, "e": 1440, "s": 1310, "text": "Example 2: In this example the sort() method the elements of the array are sorted according the function applied on each element." }, { "code": null, "e": 1553, "s": 1440, "text": "var arr = [2, 5, 8, 1, 4]\ndocument.write(arr.sort(function(a, b) {\n return a + 2 * b;\n}));\ndocument.write(arr);" }, { "code": null, "e": 1561, "s": 1553, "text": "Output:" }, { "code": null, "e": 1581, "s": 1561, "text": "2,5,8,1,4\n2,5,8,1,4" }, { "code": null, "e": 1696, "s": 1581, "text": "Example 3: In this example, we use the sort() method on the array of numbers & observe some unexpected behaviour ." }, { "code": null, "e": 1761, "s": 1696, "text": "let numbers = [20,5.2,-120,100,30,0]\nconsole.log(numbers.sort())" }, { "code": null, "e": 1769, "s": 1761, "text": "Output:" }, { "code": null, "e": 1790, "s": 1769, "text": "-120,0,100,20,30,5.2" }, { "code": null, "e": 2200, "s": 1790, "text": "Our output should be -120, 0, 5.2, 20, 30, 100 but it’s not so, why? Because as we apply directly sort() method, it would processes accordingly: 100 would be placed before 20, as ‘2’ is larger than ‘1’ and similarly in case of 30 & 5.2, as ‘5’ is larger than ‘3’ thus, 30 would be placed before 5.2. We can resolve this unexpected error by using sort() method for numerics using following compare function: " }, { "code": null, "e": 2678, "s": 2200, "text": "let numbers = [20,5.2,-120,100,30,0];\n\n/* Logic: \n 20 - (5.2) = +ve => 5.2 would be placed before 20,\n 20 - (-120) = +ve => -120 would be placed before 20,\n 20 - (100) = -ve => 100 would be placed after 20,\n 20 - (30) = -ve => 30 would be placed after 20,\n 20 - (0) = +ve => 0 would be placed before 20,\n Similarly for every element, we check and place them accordingly in iterations.\n*/\n\nfunction compare(a,b){\n return a-b;\n}\nconsole.log(numbers.sort(compare));" }, { "code": null, "e": 2686, "s": 2678, "text": "Output:" }, { "code": null, "e": 2707, "s": 2686, "text": "-120,0,5.2,20,30,100" }, { "code": null, "e": 2753, "s": 2707, "text": "Code for the above method is provided below: " }, { "code": null, "e": 2765, "s": 2753, "text": "Program 1: " }, { "code": null, "e": 2776, "s": 2765, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate sort() functionfunction func() { //Original string var arr = [2, 5, 8, 1, 4] //Sorting the array document.write(arr.sort()); document.write(\"<br>\"); document.write(arr);}func();</script>", "e": 3019, "s": 2776, "text": null }, { "code": null, "e": 3027, "s": 3019, "text": "Output:" }, { "code": null, "e": 3047, "s": 3027, "text": "1,2,4,5,8\n1,2,4,5,8" }, { "code": null, "e": 3059, "s": 3047, "text": "Program 2: " }, { "code": null, "e": 3070, "s": 3059, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate sort() function function func() { // Original array var arr = [2, 5, 8, 1, 4]; document.write(arr.sort(function(a, b) { return a + 2 * b;}));document.write(\"<br>\");document.write(arr);}func();</script>", "e": 3322, "s": 3070, "text": null }, { "code": null, "e": 3330, "s": 3322, "text": "Output:" }, { "code": null, "e": 3350, "s": 3330, "text": "4,1,8,5,2\n4,1,8,5,2" }, { "code": null, "e": 3445, "s": 3350, "text": "Supported Browsers: The browsers supported by JavaScript Array sort() method are listed below:" }, { "code": null, "e": 3471, "s": 3445, "text": "Google Chrome 1 and above" }, { "code": null, "e": 3489, "s": 3471, "text": "Edge 12 and above" }, { "code": null, "e": 3509, "s": 3489, "text": "Firefox 1 and above" }, { "code": null, "e": 3541, "s": 3509, "text": "Internet Explorer 5.5 and above" }, { "code": null, "e": 3559, "s": 3541, "text": "Opera 4 and above" }, { "code": null, "e": 3579, "s": 3559, "text": "Safari 1 and above " }, { "code": null, "e": 3939, "s": 3579, "text": "Time Complexity: The time complexity of sort() method varies & depends on implementation.For example, in Firefox web browser, it uses the merge sort implementation which gives time complexity as O(nlog n). Whereas, in Google Chrome web browser, it uses the Timsort implementation (a hybrid of merge sort and insertion sort), gives time complexity is O(nlogn)." }, { "code": null, "e": 3951, "s": 3939, "text": "ysachin2314" }, { "code": null, "e": 3964, "s": 3951, "text": "codeachalesh" }, { "code": null, "e": 3981, "s": 3964, "text": "javascript-array" }, { "code": null, "e": 4000, "s": 3981, "text": "JavaScript-Methods" }, { "code": null, "e": 4011, "s": 4000, "text": "JavaScript" }, { "code": null, "e": 4028, "s": 4011, "text": "Web Technologies" }, { "code": null, "e": 4126, "s": 4028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4187, "s": 4126, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4259, "s": 4187, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4299, "s": 4259, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4352, "s": 4299, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4404, "s": 4352, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 4466, "s": 4404, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4499, "s": 4466, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4560, "s": 4499, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4610, "s": 4560, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create a Scatter Plot with several colors in Matplotlib?
07 Feb, 2022 Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. In-order to create a scatter plot with several colors in matplotlib, we can use the various methods: Method #1: Using the parameter marker color i.e. c The possible values for marker color are: A single color format string. A 2-D array in which the rows are RGB or RGBA. Example: Using the c parameter to depict scatter plot with different colors. Python3 # import required moduleimport matplotlib.pyplot as plt # first data pointx = [1, 2, 3, 4]y = [4, 1, 3, 6] # depict first scatted plotplt.scatter(x, y, c='green') # second data pointx = [5, 6, 7, 8]y = [1, 3, 5, 2] # depict second scatted plotplt.scatter(x, y, c='red') # depict illustrationplt.show() Output: Method #2: Using the colormap Colormap instances are used to convert data values (floats) from the interval [0, 1] to the RGBA color. Example 1: Using the colormap to depict scatter plot with RGB colors. Python3 # import required modulesimport matplotlib.pyplot as pltimport numpy # assign data pointsa = numpy.array([[9, 1, 2, 7, 5, 8, 3, 4, 6], [4, 2, 3, 7, 9, 1, 6, 5, 8]]) # assign categoriescategories = numpy.array([0, 1, 2, 0, 1, 2, 0, 1, 2]) # use colormapcolormap = numpy.array(['r', 'g', 'b']) # depict illustrationplt.scatter(a[0], a[1], s=100, c=colormap[categories])plt.show() Output: Example 2: Here, we manually assign the colormap using color codes. Python3 # import required modulesimport matplotlib.pyplot as pltimport numpy # assign data pointsa = numpy.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1]]) # assign categoriescategories = numpy.array([0, 1, 1, 0, 0, 1, 1, 0, 1]) # assign colors using color codescolor1 = (0.69411766529083252, 0.3490196168422699, 0.15686275064945221, 1.0)color2 = (0.65098041296005249, 0.80784314870834351, 0.89019608497619629, 1.0) # assign colormapcolormap = numpy.array([color1, color2]) # depict illustrationplt.scatter(a[0], a[1], s=500, c=colormap[categories])plt.show() Output: anikakapoor kk9826225 Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Python map() function Read JSON file using Python Enumerate() in Python Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Deque in Python Stack in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Feb, 2022" }, { "code": null, "e": 307, "s": 28, "text": "Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc." }, { "code": null, "e": 408, "s": 307, "text": "In-order to create a scatter plot with several colors in matplotlib, we can use the various methods:" }, { "code": null, "e": 459, "s": 408, "text": "Method #1: Using the parameter marker color i.e. c" }, { "code": null, "e": 501, "s": 459, "text": "The possible values for marker color are:" }, { "code": null, "e": 531, "s": 501, "text": "A single color format string." }, { "code": null, "e": 578, "s": 531, "text": "A 2-D array in which the rows are RGB or RGBA." }, { "code": null, "e": 587, "s": 578, "text": "Example:" }, { "code": null, "e": 655, "s": 587, "text": "Using the c parameter to depict scatter plot with different colors." }, { "code": null, "e": 663, "s": 655, "text": "Python3" }, { "code": "# import required moduleimport matplotlib.pyplot as plt # first data pointx = [1, 2, 3, 4]y = [4, 1, 3, 6] # depict first scatted plotplt.scatter(x, y, c='green') # second data pointx = [5, 6, 7, 8]y = [1, 3, 5, 2] # depict second scatted plotplt.scatter(x, y, c='red') # depict illustrationplt.show()", "e": 965, "s": 663, "text": null }, { "code": null, "e": 973, "s": 965, "text": "Output:" }, { "code": null, "e": 1003, "s": 973, "text": "Method #2: Using the colormap" }, { "code": null, "e": 1107, "s": 1003, "text": "Colormap instances are used to convert data values (floats) from the interval [0, 1] to the RGBA color." }, { "code": null, "e": 1118, "s": 1107, "text": "Example 1:" }, { "code": null, "e": 1177, "s": 1118, "text": "Using the colormap to depict scatter plot with RGB colors." }, { "code": null, "e": 1185, "s": 1177, "text": "Python3" }, { "code": "# import required modulesimport matplotlib.pyplot as pltimport numpy # assign data pointsa = numpy.array([[9, 1, 2, 7, 5, 8, 3, 4, 6], [4, 2, 3, 7, 9, 1, 6, 5, 8]]) # assign categoriescategories = numpy.array([0, 1, 2, 0, 1, 2, 0, 1, 2]) # use colormapcolormap = numpy.array(['r', 'g', 'b']) # depict illustrationplt.scatter(a[0], a[1], s=100, c=colormap[categories])plt.show()", "e": 1579, "s": 1185, "text": null }, { "code": null, "e": 1587, "s": 1579, "text": "Output:" }, { "code": null, "e": 1598, "s": 1587, "text": "Example 2:" }, { "code": null, "e": 1655, "s": 1598, "text": "Here, we manually assign the colormap using color codes." }, { "code": null, "e": 1663, "s": 1655, "text": "Python3" }, { "code": "# import required modulesimport matplotlib.pyplot as pltimport numpy # assign data pointsa = numpy.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1]]) # assign categoriescategories = numpy.array([0, 1, 1, 0, 0, 1, 1, 0, 1]) # assign colors using color codescolor1 = (0.69411766529083252, 0.3490196168422699, 0.15686275064945221, 1.0)color2 = (0.65098041296005249, 0.80784314870834351, 0.89019608497619629, 1.0) # assign colormapcolormap = numpy.array([color1, color2]) # depict illustrationplt.scatter(a[0], a[1], s=500, c=colormap[categories])plt.show()", "e": 2266, "s": 1663, "text": null }, { "code": null, "e": 2274, "s": 2266, "text": "Output:" }, { "code": null, "e": 2286, "s": 2274, "text": "anikakapoor" }, { "code": null, "e": 2296, "s": 2286, "text": "kk9826225" }, { "code": null, "e": 2314, "s": 2296, "text": "Python-matplotlib" }, { "code": null, "e": 2338, "s": 2314, "text": "Technical Scripter 2020" }, { "code": null, "e": 2345, "s": 2338, "text": "Python" }, { "code": null, "e": 2364, "s": 2345, "text": "Technical Scripter" }, { "code": null, "e": 2462, "s": 2364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2492, "s": 2462, "text": "Iterate over a list in Python" }, { "code": null, "e": 2537, "s": 2492, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2559, "s": 2537, "text": "Python map() function" }, { "code": null, "e": 2587, "s": 2559, "text": "Read JSON file using Python" }, { "code": null, "e": 2609, "s": 2587, "text": "Enumerate() in Python" }, { "code": null, "e": 2659, "s": 2609, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2677, "s": 2659, "text": "Python Dictionary" }, { "code": null, "e": 2721, "s": 2677, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2737, "s": 2721, "text": "Deque in Python" } ]