Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Friday, January 10, 2025

Custom JavaScript Plugin

 

1. Introduction

Plugins are a powerful mechanism for avoiding repetitive tasks. Once you develop a plugin, you can reuse it in multiple projects. That’s why learning how to build custom plugins is a valuable skill for developers. It enables you to extend the functionality of existing software, tailor solutions to specific requirements, and optimize your workflow.

In this article, we’ll walk you through the fundamental steps of developing and using a custom plugin in JavaScript. We will explain an example of a custom plugin that creates a tooltip that displays the data of the attached element. The tooltip opens and closes if you click on the corresponding element. The full example of this custom tooltip and a demo of its usage is on GitHub:

https://github.com/noura-github/custom-plugin-tooltip-blog


For more examples, including another custom tooltip implementation, you can explore our repository on GitHub:

https://github.com/noura-github/custom-plugin-translate-blog


This custom plugin enables a tooltip that displays the translation of a word when hovered over. The translation is rendered in the language selected from a dropdown menu.


2. JavaScript Plugin

A jQuery plugin is a reusable code which adds new functionalities to jQuery. Plugins are a kind of pre-built solution for common tasks. They help reduce repetitive codes. They utilize existing libraries and frameworks to streamline development and reduce redundant code. 


Technically, a plugin is code written in a JavaScript file and consists of one or multiple functions that extend the jQuery object. To use the plugin’s functionality, you can call a custom method on a jQuery object.


2.2. Use Cases for jQuery Plugins

jQuery plugins can be used for a variety of purposes, including:

UI Components and Widgets: Modals, tables, date pickers, etc.

Form Enhancements: Form validation, processing, auto-complete, etc.

DOM manipulation and traversal

Effects and Animations: Fade effects, etc.

Ajax Enhancements: Simplified data loading and displaying.


2.3. Plugin Definition

We usually start by creating a new JavaScript file to create a new plugin. This file defines the plugin code, including its properties and functions. Then, we attach these functions to the jQuery object using the $.fn property.


Here’s a simple example of a jQuery plugin that adds a ‘myPlugin()’ method:


(function($) {

  $.fn.myPlugin = function(options) {

    this.css('background-color', options.bgColor);

    this.css('border', options.border);

    this.css('font-size', options.fontSize);

    return this;

  };

})(jQuery);


Now we can attach the plugin ‘myPlugin()’ to an element (paragraph) like this:


$("p").myPlugin({

     bgColor: "red",

     fontSize: "18px",

     border: "2px solid blue"

});


3. Example of Custom Plugin

The plugin we want to suggest to you in this section is useful for creating visually rich and interactive tooltips. The tooltip opens and closes when you click on the corresponding element.


Note. Here, we focus exclusively on the key aspects of defining and using a custom plugin. For the complete example, visit the GitHub repository:

https://github.com/noura-github/custom-plugin-tooltip-blog


3.1. Tooltip Plugin Code

The tooltip plugin code is developed in jQuery. But for the demonstration, we need a back-end and front-end code. The back-end code is written in Python to send dummy data from a database to the front-end code. We also need HTML and CSS code to display and style the data respectively. Finally, the JavaScript code is used to create the tooltip plugin and demonstrate how to use it.


Python Code

For this example, we need some data. So, we created a Python SQLite database named ‘custom_plugin.db’ with two tables: ‘employee’ and ‘files’. The table ‘employee’ stores the data about an employee such as their first name, last name, email, and so on. 

The ‘files’ table stores a file with a file name and description. A file can be associated with an employee using the foreign key ‘file_id’ which corresponds to a primary key ‘id’ in the ‘files’ table. Here is the code for the ‘create_database()’ function:


# Function to create the database and tables

def create_database():

    # Connect to SQLite database (or create it if it doesn't exist)

    conn = sqlite3.connect('custom_plugin.db')

    cursor = conn.cursor()


    # Create the files table

    cursor.execute('''

    CREATE TABLE IF NOT EXISTS files (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        filename TEXT NOT NULL,

        description TEXT,

        file BLOB

    )

    ''')

    print("Table 'files' created successfully.")


    # Create the employee table

    cursor.execute('''

    CREATE TABLE IF NOT EXISTS employee (

        id INTEGER PRIMARY KEY,

        firstname TEXT NOT NULL,

        lastname TEXT NOT NULL,

        email TEXT NOT NULL,

        phone TEXT NOT NULL,

        departmentId INTEGER NOT NULL,

        departmentName TEXT NOT NULL,

        companyName TEXT NOT NULL,

        file_id INTEGER,

        FOREIGN KEY (file_id) REFERENCES files (id)

    )

    ''')

    print("Table 'employee' created successfully.")


    # Commit changes and close the connection

    conn.commit()

    conn.close()


We need then to insert some dummy data. Thus, to add some data to the ‘files’ table, we suggest the following functions:


# Function to insert a file into the database

def insert_file(filename, description, filepath):

    # Connect to SQLite database

    conn = sqlite3.connect('custom_plugin.db')

    cursor = conn.cursor()


    # Read the file as binary data

    with open(filepath, 'rb') as file:

        file_data = file.read()


    # Insert the file into the table

    cursor.execute('''

        INSERT INTO files (filename, description, file)

        VALUES (?, ?, ?)

    ''', (filename, description, file_data))


    print(f"File '{filename}' inserted successfully.")


    # Commit changes and close the connection

    conn.commit()

    conn.close()


# Function to populate the files table

def populate_files():

    # Example: Insert a file into the table

    insert_file('Dock.jpg', 'A dock over a lake at night.', 'static/images/Dock.jpg')

    insert_file('Fields.jpg', 'A road in the fields of flowers leading to the mountains.', 'static/images/Fields.jpg')

    insert_file('Waterfall.jpg', 'A Cascading Waterfall under pink trees.', 'static/images/Waterfall.jpg')

    insert_file('Lake.jpg', 'A a blue water lake.', 'static/images/Lake.jpg')


The ‘insert_file()’ Function: This function inserts a file into the SQLite database. It reads the file as binary data, then executes an SQL INSERT statement to store the file’s name, description, and contents in the ‘files’ table.


The ‘populate_files()’ Function: This function inserts four image files into the database using the ‘insert_file()’ function, with their respective names, descriptions, and file paths.


In this Python code, we need a ‘get_data()’ function as a Flask route that handles GET requests to the ‘/data’ endpoint by returning the employee data dictionary as a JSON object.


@app.route('/data', methods=['GET'])

def get_data():

    # Sample data to send to the frontend

    return jsonify(get_employee_data())


Moreover, we need another Flask API endpoint that handles a POST request to the ‘/imagedata’ route. The endpoint expects a JSON payload with an ‘id’ field, which is used to retrieve a file’s binary data.


@app.route('/imagedata', methods=['POST'])

def get_image_data():

    # Ensure request contains JSON data

    data = request.get_json()


    if not data or 'id' not in data:

        return Response("Missing 'id' in request body", status=400)


    file_id = data.get('id')


    # Your logic to retrieve the file data

    file_row = find_image_file(file_id)

    if not file_row or not file_row[0]:

        return Response("File not found", status=404)


    blob_data = file_row[0]


    # Return binary data with appropriate headers

    response = Response(blob_data, mimetype='application/octet-stream')

    response.headers['Content-Disposition'] = 'attachment; filename="output_file.bin"'

    return response


The ‘get_image_data()’ Function: This function handles POST requests to the ‘/imagedata’ route, validates the request for a file ‘id’, retrieves the corresponding binary file data from the database, and returns it as a downloadable response.


The ‘find_image_file()’ Function: This function connects to the ‘custom_plugin.db’ SQLite database and retrieves the file associated with the given ‘file_id’ from the files table.


def find_image_file(file_id):

    # Connect to SQLite database

    conn = sqlite3.connect('custom_plugin.db')

    cursor = conn.cursor()


    # Query the table for the file

    cursor.execute('''

        SELECT file FROM files WHERE id = ?

    ''', (file_id,))


    # Fetch the file data

    file_data = cursor.fetchone()


    # Close the connection

    conn.close()


    return file_data


HTML Code

In HTML code, we need a table to display the data:

<table id="dataTable">

    <thead>

        <tr>

            <th>First Name</th>

            <th>Last Name</th>

            <th>Department Name</th>

            <th>Company Name</th>

        </tr>

    </thead>

    <tbody class="containment">

    </tbody>

</table>


JavaScript Code

We have crafted two files in JavaScript. The first one, tooltipdata.js, houses our custom plugin, while the other file, main.js, is designed to populate the data and activate the ‘tooltipdata’ plugin. Let’s dive into the details of the custom plugin and how to utilize it.


Custom Tooltip Plugin. An overview of the code for this plugin is as follows:


(function($) {


    function __tooltipdata(elem, options) {

        var that = this;

        this.id = options.id;

        this.title = options.title;

        this.customClass = options.customClass;

        this.containerClass = options.containerClass;

        this.tooltipImgClass = options.tooltipImgClass;

        this.headerClass = options.headerClass;

        this.menuClass = options.menuClass;

        this.contentClass = options.contentClass;

        this.footerClass = options.footerClass;


// Rest of the code (properties, methods, or events handler)

...

    }

    // Plugin function

    $.fn.tooltipData = function(data) {

        return this.each(function() {

            // Check if the element already has tooltip data initialized

            if (!$.data(this, "tooltipdata")) {

                // Initialize the tooltip data and store it in the element's data

                $.data(this, "tooltipdata", new __tooltipdata($(this), data));

            }

        });

    };

}(jQuery));


Plugin Properties. The code defines a function named ‘__tooltipdata’ that takes two arguments: ‘elem’ and ‘options’. This function creates and manages tooltip data for a given element. The ‘__tooltipdata’ function sets up several properties for the tooltip data, including:

id: an identifier for image file of the tooltip.

title: the title of the tooltip

customClass: a custom CSS class for the tooltip.

containerClass: a CSS class for the tooltip container.

tooltipImgClass: a CSS class for the tooltip image.

headerClass: a CSS class for the tooltip header.

menuClass: a CSS class for the tooltip menu.

contentClass: a CSS class for the tooltip content.

footerClass: a CSS class for the tooltip footer.

image: the URL of the tooltip image.

info_head, info_foot, and info_menu: HTML content for the tooltip header, footer, and menu, respectively.


Tooltip Creation. The code creates a tooltip element using jQuery and appends it to the elem element. It also sets up event listeners for the tooltip, including a click event handler that toggles the tooltip’s visibility.


elem.tooltip({

  content: this.content,

  position: this.position,

  show: this.show,

  hide: this.hide,

  track: this.track,

  classes: this.classes,

  open: function(event, ui) {

    // code here

  }

});


In the event handler of the click event, if the title property is set, the code checks the ‘isOpened’ property of that object. This property is used to keep track of whether the tooltip is currently open or not. If the ‘isOpened’ property is true, the code sets it to false and hides the tooltip using the tooltip("disable") method. This method is part of the tooltip plugin and is used to disable the tooltip.


$(elem).click(function () {

   if (that.title) {

       if (that.isOpened) {

           that.isOpened = false;

           // Hide the tooltip using the API

           $(elem).tooltip("disable");

       } else {

           that.isOpened = true;

           // Temporarily update the title and enable the tooltip

           $(elem).attr("title", that.title).tooltip("enable");

           // Show the tooltip programmatically

           $(elem).tooltip("open");

       }

   }

});


The function ‘onOpen()’: If the image is not cached, the code makes an AJAX request to the URL specified in the ‘imageurl’ property of the ‘tooltipdata’ plugin. The request is made using the $.ajax method and has the following properties:

type: The request method is set to POST.

url: The request URL is set to the value of the ‘imageurl’ property.

dataType: The expected data type of the response is set to binary.

processData: This property is set to false. This means that the data sent in the request body will not be processed by jQuery.

contentType: This property is set to ‘application/json’, which means that the request body will be sent as JSON data.

xhrFields: This property is set to an object with a single property ‘responseType’ set to blob. This means that the response will be treated as a binary blob.

data: The request body is set to a JSON object with a single property ‘id’ set to the value of the ‘id’ property of the plugin.

When the response is received, the code checks if the response was successful. If it was, the code creates a URL for the response blob using the ‘URL.createObjectURL’ method and sets the image property to the created URL. The code also caches the image URL in the ‘imageCache’ object using the ‘id’ property as the key. Finally, the code updates the ‘src’ attribute of the ‘tooltipImg’ element with the created image URL.


this.onOpen = function() {

   if (that.image) return;

   if (that.imageCache[that.id]) {

       that.image = that.imageCache[that.id];

       that.tooltipImg.attr("src", that.image);

   } else {

       $.ajax({

          type: 'POST',

          url: that.imageurl,

          dataType: 'binary',

          processData: false,

          contentType: 'application/json',

          xhrFields: { responseType: 'blob' },

          data: JSON.stringify({ 'id': that.id }),

          success: function(blob) {

              // Create a URL for the blob

              var imageUrl = URL.createObjectURL(blob);

              that.image = imageUrl;

             // Cache the image

             that.imageCache[that.id] = imageUrl;

             // Set the src attribute of the img element

             that.tooltipImg.attr("src", imageUrl);

           },

           error: function(xhr, status, error) {

              console.error("Error: ", error, "Status: ", status);

           }

        });

    }

}


Plugin Function. The code defines a plugin function named ‘tooltipData’ that can be used to create and manage tooltips for a given element.


To work with this plugin, we first need to load some data. For this, we create a function called ‘getEmployeeData()’ that we call once the document is ready as follows:


$(document).ready(function () {

    getEmployeeData();

});


The ‘getEmployeeData()’ Function: This function makes a GET request to the ‘/data’ endpoint to retrieve employee data in JSON format. Upon successful retrieval, it calls two other functions: ‘displayEmployeeData()’ to display the received data and ‘initializeTooltipData()’ to set up tooltip data.


function getEmployeeData() {

    $.ajax({

        type: 'GET',

        url: '/data',

        dataType: 'json',

        success: function(data) {

            displayEmployeeData(data);

            initializeTooltipData();

        },

        error: function(xhr, status, error) {

            console.error("Error: ", error, "Status: ", status);

        }

    });

}


The ‘displayEmployeeData()’ Function: This function takes an array of employee data and populates the table with the data. It loops through each employee object in the data array. For each employee, it appends a new table row (tr) to the table body. Within the table row, it creates four table cells (td) containing the employee’s: First name (with a tooltip trigger), Last name (with a tooltip trigger), Department name, and Company name. The tooltip triggers (span elements with class ‘tooltip_trigger’) contain additional data attributes (e.g. data-firstname, data-lastname, etc.) that will be used to display more information about the employee when the tooltip is triggered.

function displayEmployeeData(data) {

    const $tableBody = $("#dataTable tbody");

    $tableBody.empty();


    $.each(data, function(index, employee) {

        $tableBody.append(`

            <tr>

                <td><span class="tooltip_trigger" data-firstname="${employee.firstname}" data-lastname="${employee.lastname}" data-id="${employee.file_id}" data-filename="${employee.filename}" data-description="${employee.description}" data-email="${employee.email}" data-phone="${employee.phone}">${employee.firstname}</span></td>

                <td><span class="tooltip_trigger" data-firstname="${employee.firstname}" data-lastname="${employee.lastname}" data-id="${employee.file_id}" data-filename="${employee.filename}" data-description="${employee.description}" data-email="${employee.email}" data-phone="${employee.phone}">${employee.lastname}</span></td>

                <td><span>${employee.departmentName}</span></td>

                <td><span>${employee.companyName}</span></td>

            </tr>

        `);

    });

}


The ‘initializeTooltipData()’ Function: This function initializes tooltips for each employee data row in the table. It selects all span elements within the table body that contain employee data. For each span element, it extracts various data attributes (e.g. firstname, lastname, email, phone, etc.). If the firstname or lastname attribute is present, it creates a tooltip with the following content:

- Header with employee name.

- Footer with file title and description.

- Menu with email and phone number.

The function then initializes a tooltip for each span element using the ‘tooltipData’ method, passing in various options for the tooltip’s behavior, appearance, and content.

function initializeTooltipData() {

    const $tableBody = $("#dataTable tbody");

    let $spanElem = $tableBody

                .children("tr")

                .find("td")

                .find("span");


    $spanElem.each(function () {

        const $span = $(this);

        let firstname = $span.data("firstname");

        let lastname = $span.data("lastname");

        if (firstname || lastname) {

            let email = $span.data("email");

            let phone = $span.data("phone");

            let fileName = $span.data("filename");

            let description = $span.data("description");

            let file_id = $span.data("id");

            let info_head = "<span class='menu-head'>" + firstname + " " + lastname + "</span>";

            let info_foot = "<span class='menu-head'>" + "Title: " + "</span>"

                            + "<span class='menu-body'>" + getFileBaseName(fileName) + "</span>"

                            + "<br>"

                            + "<span class='menu-head'>" +  "Description: " + "</span>"

                            + "<span class='menu-body'>" + description + "</span>";

            let info_menu = "<span class='menu-head'>" + "Email: " + "</span>"

                            + "<span class='menu-body'>" + email + "</span>"

                            + "<br>"

                            + "<span class='menu-head'>" + "Phone: " + "</span>"

                            + "<span class='menu-body'>" + phone + "</span>";

            $span.tooltipData({

                id: file_id,

                title: $span.text(),

                contentClass: "content-tooltip",

                containerClass: "tooltip-container",

                tooltipImgClass: "tooltip_img",

                headerClass: "header",

                menuClass: "menu",

                contentClass: "content",

                footerClass: "footer",

                image: "",

                info_head: info_head,

                info_foot: info_foot,

                info_menu: info_menu,

                imageurl: "/imagedata",

                position: { my: "left+10 center", at: "right center" },

                show: {

                    effect: "fadeIn", 

                    duration: 400   

                },

                hide: {

                    effect: "fadeOut",

                    duration: 400   

                },

                track: true,

                classes: {

                    "ui-tooltip": "highlight"

                },

            });

        }

    });

}


3.2. Example Running

When you run the example, and you click on the last name (‘Smith’), you get its tooltip as shown in the following figure:










Monday, November 11, 2024

Cache in JavaScript: Service Workers

 

Caching is a technique for storing data in a temporary storage area called a cache. It aims to retrieve data quickly and avoid costly processes such as recalculating or searching it in the database, especially for frequently asked resources. In the first article, I introduced the different possibilities for caching data in JavaScript and how to choose the appropriate caching possibility according to your needs. In a previous article, I introduced an example of using the Web Storage API (localStorage and sessionStorage) to cache data. Then, I dedicated another article to using objects and data-* attributes to temporarily cache data in JavaScript. In this article, I will elucidate the use of service workers to cache static resources like HTML, CSS, and JavaScript files or API responses.


1. Service Workers API

This technique is used especially to cache static resources (HTML, CSS, etc.) or API responses. It helps enhance the responsiveness and performance of the web application. Please note that ‘service worker’ is a complex topic and it is impossible to cover all its features in this article. That’s why we focus only on the basic features to show how they cache resources and API responses.


The Service Worker API is a script that runs asynchronously and independently of the main browser thread.

- It is a kind of interface between the browser and the network.

- It is executed in the background.

- It handles tasks such as intercepting network requests and caching assets to allow the application to continue working even offline.


2. Tasks of Service Worker API

Let’s summarize the main tasks that service workers can perform when are ready to operate.


Interception of Network Requests: Service workers can intercept network requests and decide to handle them. Service workers can respond with cached resources or search data from the network according to some conditions like the network connection. If it is a poor connection, it responds to the client from cached resources, allowing fast loading and enhancing offline working. 


Background Sync: Service workers can synchronize data in the background, sending data to the server even if the app is not open. For example, they save user input while the connection is unavailable and send the data when the connection is back.


Caching: Service workers cache resources like HTML, CSS, JavaScript, and images. Thus the web app can be loaded faster and even continue working offline.


Push Notifications: Service workers handle push notifications so the web app sends messages to users even if the corresponding web page is closed.


3. Security Considerations

- Since service workers intercept network requests to make decisions, they must operate in a secure environment, which means they can only operate over HTTPS.

- Service workers run in a thread independent of the main thread, so they do not block the normal execution of the user interface.


4. Benefits of Service Workers

- Service workers improve the performance of web applications. Since they cache resources, they significantly reduce server calls, which reduces load times and strain on the server.

- Worker services allow offline access. In other words, users can interact with the application without an internet connection.

- Through push notifications, service workers keep users informed with regular updates.


5. Service Worker Lifecycle

The Service Worker lifecycle is event-driven and consists of several phases that describe how a Service Worker is installed, activated, and managed. The following table summarizes the key phases of a Service Worker's lifecycle. Note that a step can only be executed if the previous step has been completed successfully.

Service Worker Lifecycle

Phase

Definition

Code

Registration

A service worker must be registered by a page before it starts to work.

Method: ServiceWorkerContainer.register()

Download

A service worker is downloaded to the client.


Installation

- The browser installs the Service Worker.

- The install event is triggered.

- You can handle the install event to cache resources or complete an initial setup.

Event: install

Activation

- Once installed, the service worker is activated.

- Old caches are cleaned.

- The service worker gets ready to take control of the application.

Event: activate

Fetch

The service worker can intercept network requests using the fetch event and respond to them from the network or the cache.

Event: fetch


6. Example of Registering a Service Worker

Let’s take an example of how you can cache resources and API responses using the service worker API. For this, we need some back-end code to return data. A straightforward way to do this is using Python’s Flask framework. Additionally, we develop HTML, CSS, and JavaScript code for the front-end.


Note. We only write the relevant part here to explain how to use service workers to cache resources and intercept network requests. If you want the full example, you can find it on GitHub here:

https://github.com/noura-github/serviceworker-app-blog


Python Code

In the back-end code, we first define ‘employees_datas’ as a list containing a collection of employees, where each dictionary represents data about an employee and includes details such as its ID, first name, last name, and email.


We define some routes to enable the user to access web pages. For instance, to access the root URL of the application, the index function is called, and it renders the ‘index.html’ template file to display the content on the web page. 


We have also a route for ‘employee.html’ file and another one for ‘about.html’ file. Note that in the ‘employee’ function, the ‘render_template’ function renders the specified template file and passes the ‘employees_data’ variable to the template.


@app.route('/')

def index():

    # Render the index.html file

    return render_template('index.html')


@app.route('/employee')

def employee():

    return render_template('employee.html', employees_data=employees_data)


HTML Code

In the front-end code, we define a few HTML files, ‘index.html’ as the main web page, ‘employee.html’ to display some content sent from the back-end, and ‘about.html’. An additional file called ‘layout.html’ will be defined as a common template that will be extended by the other files.


This HTML template provides the structure for a basic web page that uses the Bootstrap library for styling, jQuery for JavaScript functionality, and placeholders for dynamic content through a template engine ‘Jinja’ of the Flask framework.


The {% block swjs %}{% endblock %} block is a placeholder for a service worker script that can be inserted by the template engine only in the ‘index.html’ template.


Inside the ‘navbar’, there are different navigation links to different parts of the website:

- ‘Home’ links to ‘/’, which consists of loading the ‘index.html’ template.

- ‘Employee’ links to ‘/employee’, which consists of loading the ‘employee.html’ template.

- ‘About’ links to ‘/about’, which consists of loading the ‘about.html’ template.


<div class="container"> holds the page’s main content and uses Bootstrap’s container class for responsive layout.

{% block content %}{% endblock %} serves as a placeholder for page-specific content that other templates can insert.


<head>

    ...

    {% block swjs %}{% endblock %}

</head>

<body>

    <nav class="navbar navbar-expand-lg navbar-light bg-primary">

        <a class="navbar-brand" href="/">SW Demo</a>

        <div class="collapse navbar-collapse">

            <ul class="navbar-nav mr-auto">

                <li class="nav-item">

                    <a class="nav-link" href="/">Home</a>

                </li>

                <li class="nav-item">

                    <a class="nav-link" href="/employee">Employee</a>

                </li>

                <li class="nav-item">

                    <a class="nav-link" href="/about">About</a>

                </li>

            </ul>

        </div>

    </nav>


    <div class="container">

        {% block content %}{% endblock %}

    </div>

</body>

</html>


Within the ‘index.html’ file, we have the following code:


{% extends "layout.html" %}


{% block swjs %}

    <script type="text/javascript" src="/static/js/main.js"></script>

{% endblock %}


{% block content %}

    <h1>Welcome to the Home Page</h1>

    <p>This is the home page of the Service Worker API Demo</p>

{% endblock %}


Let’s explain the main parts of this code:


{% extends "layout.html" %} indicates that this template file extends the ‘layout.html’ file,  meaning it inherits the structure and styling defined in ‘layout.html’.


{% block swjs %} and {% endblock %} define a block named ‘swjs’ where you can insert content specific to JavaScript files. In this case, it includes a script tag that links to the ‘main.js’ file located in the /static/js/ directory.


{% block content %} and {% endblock %}: This defines a block named content where you can insert the main content of the page. In this case, there is an <h1> heading and a <p> paragraph welcoming users to the Home Page of the Service Worker API Demo.


The content of the employee template in the file ‘employee.html’ is suggested as follows:


{% extends "layout.html" %}


{% block content %}

    <h1>Employee List</h1>

    <p>This is the employee List</p>

    <table>

        <thead>

            <tr>

                <th>Firstname</th>

                <th>Lastname</th>

                <th>Email</th>

            </tr>

        </thead>

        <tbody id="myTable">

            {% for item in employees_data %}

                <tr>

                    <td>{{ item.first_name }}</td>

                    <td>{{ item.last_name }}</td>

                    <td>{{ item.email }}</td>

                </tr>

            {% endfor %}

        </tbody>

    </table>

{% endblock %}


The above code is a Jinja template that extends a layout defined in ‘layout.html’. Within the {% block content %}, it creates an Employee List page with a table displaying employee data. The table has columns for Firstname, Lastname, and Email. It then loops through the ‘employees_data’ list and populates the table rows with the corresponding data for each employee’s first name, last name, and email address.


JavaScript Code

In the JavaScript code, we show how to register and use a service worker to cache data. Two JavaScript files are defined. The ‘main.js’ file is defined to register a service worker and the ‘sw.js’ file is used to encapsulate the service worker's behavior.


In the ‘main.js’ file, the code waits for the document to be fully loaded. Once the document is ready, it calls the ‘registerServiceWorker()’ function.


$(document).ready(function(){

    registerServiceWorker();

});


function registerServiceWorker() {

    console.log('Register Service Worker ...')

    if ('serviceWorker' in navigator) {

        navigator.serviceWorker.register(href = 'sw.js')

        .then(function(registration) {

            console.log('Service Worker registered with scope:', registration.scope);

        })

        .catch(function(error) {

            console.log('Service Worker registration failed:', error);

        });

    }

}


Function ‘registerServiceWorker()’: This function checks if the browser supports service workers by checking if ‘serviceWorker’ is in ‘navigator’. If service workers are supported, it attempts to register a service worker by calling ‘navigator.serviceWorker.register('sw.js')’. If the registration is successful, it logs a message to the console with the service worker’s scope. Note that the scope is the URL path that determines which pages the service worker will control. If the registration fails, it logs an error message to the console.


In the ‘sw.js’ file, we define the main behaviors of the service worker. This consists of handling the ‘install’, ‘activate’, and ‘fetch’ events. Thus we can install and activate the service workers. The ‘fetch’ event handler will intercept network requests to respond to the client from the cache.


First, we need a few global variables like the cache name (‘cache_name’) and the URLs we want to cache (‘urls_to_cache’).


// Cache name

const cache_name = 'sw-1';


// Urls to cache

const urls_to_cache = [

    '/',

    '/employee',

    '/about',

    '/static/css/styles.css',

    '/static/js/main.js',

    '/static/js/employee.js',

];


We add an event listener for the install event in the service worker as follows:


self.addEventListener('install', function(event) {

    console.log('Installing ...');

    event.waitUntil(

        caches.open(cache_name).then(function(cache) {

            console.log('Caching data ...');

            return cache.addAll(urls_to_cache);

        })

    );

}); 


When the service worker is installed, it performs some actions.  It uses ‘event.waitUntil()’ to extend the installation process until the provided promise resolves successfully. This means the service worker will only be considered installed if everything within ‘waitUntil’ (in this case, the caching process) completes without errors. 


It opens a cache (or creates one if it doesn’t exist) with the name specified by ‘cache_name’. Once the cache is opened, it adds all the URLs listed in the ‘urls_to_cache’ array to the cache for offline access. Note that the ‘Self’ word inside the service worker script refers to the Service Worker itself.


The activate event listener triggers when the service worker becomes active. This usually happens after installation and when there are no more active clients using the previous version of the service worker. The following code snippet is a listener for the ‘activate’ event:


// Activate event: Clean up old caches

self.addEventListener('activate', event => {

    console.log('Activating ...');

    const cacheList = [cache_name];

    event.waitUntil(

        caches.keys().then(cacheNames => {

            return Promise.all(

                cacheNames.map(cName => {

                    if (!cacheList.includes(cName)) {

                        console.log('Deleting old cache:', cName);

                        return caches.delete(cName);

                    }

                })

            );

        })

    );

});


When a service worker is activated, it means it is ready to take control of the page and handle caching and other tasks. Let’s explain what the code does. This code defines an array ‘cacheList’ containing the value of ‘cache_name’. This array specifies the caches to keep. Only the caches in this array will be kept, the others will be deleted.


It uses ‘event.waitUntil(...)’ to delay the activation until all old caches are deleted. This ensures a clean start with only the necessary caches.  Inside ‘event.waitUntil(...)’, it calls caches.keys() to get a list of all the cache names. It then uses ‘Promise.all(...)’ to map over each cache name and check if it's in the ‘cacheList’. If a cache name is not in the ‘cacheList’, it logs the cache to be deleted to the console and deletes that cache using ‘caches.delete(cName)’.


We now develop a common event listener that intercepts the ‘fetch’ event, which is triggered whenever a network request is made.


self.addEventListener("fetch", (event) => {

    console.log('Fetching data ...');

    // Intercept the network request to handle it

    event.respondWith(

        (async () => {

        // Search the response first in a cache

        let cache = await caches.open(cache_name);

        let cachedResponse = await cache.match(event.request);

        console.log("cachedResponse:", cachedResponse)


        // Return a response if it is found in the cache

        if (cachedResponse) return cachedResponse;


        // If no response is already cached, use the network

        return fetch(event.request);

    })(),

    );

});


After logging 'Fetching data ...' to the console, we call the ‘event.respondWith()’ method to intercept the network request and handle it. Within the ‘respondWith()’ method, we first try to find a response in a cache by opening a cache with the name ‘cache_name’ and attempting to match the request with the cached response. If a cached response is found, we return the cached response. If no cached response is found, we make a network request using fetch (‘event.request’).


7. Execution of the Example

When you run this example on the server, you get the following UI:

Visit all the pages and then stop the server. You will see that the application continues to work offline and the pages are showing normally.

Wednesday, October 16, 2024

Cache in JavaScript: In-memory Caching

 


Caching is a technique for storing data in a temporary storage area called a cache. It aims to retrieve data quickly and avoid costly processes such as recalculating or searching it in the database, especially for frequently asked resources. In the first article, I introduced the different possibilities for caching data in JavaScript and how to choose the appropriate caching possibility according to your needs. I also introduced an example of using the Web Storage API (localStorage and sessionStorage) to cache data. So, I will dedicate this article to using objects and data-* attributes to temporarily cache data in JavaScript.


1. In-memory Caching

This technique is used to retain data for a short period of time, such as the result of API calls during a single session. The data will be removed from the cache after the page refreshes. Even though it only caches data for short-term caching while a user is on a page, this technique is still an efficient way to use resources and retrieve data quickly, instead of repeatedly searching for it on the server.


In this section, we will see through examples two approaches to temporarily caching data:

- JavaScript objects or variables

- data-* attributes


1.1. Using Objects or Variables for In-Memory Caching

JavaScript objects or variables to store data in memory are mechanisms suitable for short-term or temporary caching while a user is on a page. Let’s take an example of how you can cache the result of an API call using objects. For this, we need a back-end code to return data. An easy way to do this is to use Python’s Flask framework. Moreover, we develop HTML, CSS, and JavaScript code for the front-end.


Note. We only write the relevant part here to explain how to use the objects to cache data. If you want the full example, you can find it on GitHub here:

https://github.com/noura-github/inmemory-caching-app-blog


Python Code

In the back-end code, we first define ‘james_bond_films’ as a list containing a collection of dictionaries, where each dictionary represents a James Bond film and includes details such as its ID, title, release year, star, and director.


james_bond_films = [

    {"id": 10, "title": "No Time to Die", "year": 2021, "starring": "Daniel Craig", "directedBy": "Cary Joji Fukunaga"},

    {"id": 20, "title": "Die Another Day", "year": 2002, "starring": "Pierce Brosnan", "directedBy": "Lee Tamahori"},

    {"id": 30, "title": "The Living Daylights", "year": 1987, "starring": "Timothy Dalton", "directedBy": "John Glen"},

    {"id": 40, "title": "A View to a Kill", "year": 1985, "starring": " Roger Moore", "directedBy": "John Glen"},

    {"id": 50, "title": "Never Say Never Again", "year": 1983, "starring": "Sean Connery", "directedBy": "Irvin Kershner"},

]


In this Python code, we define two methods that we explain as follows:


Method ‘get_film_data’: To return these details in response to an AJAX POST request, we define a Flask route in ‘/load_film_data’. It fetches the JSON data from the request, extracts the film ID, and searches for the corresponding film data in the predefined ‘james_bond_films’ list using the ‘search’ method. Finally, it returns the film data as a JSON response.


Method ‘search’: The search method takes two parameters, ‘id’ and ‘ls’. It searches for a film in the ‘ls’ list whose ID matches the provided ‘id’. If a match is found, it returns the corresponding data of that film as a dictionary. If no match is found, it returns None.


# Helper function to search for an item in a list

def search(id, ls):

    result = [element for element in ls if element["id"] == id]

    if len(result) > 0:

        return result[0]

    return None



# Route to handle AJAX POST request

@app.route('/load_film_data', methods=['POST'])

def get_film_data():

    # Get JSON data from request

    data = request.get_json()


    film_id = data.get('filmId')

    film_data = search(int(film_id), james_bond_films)

    print("Found film data: ", film_data)


    # Send a JSON response back to the client

    return jsonify({

        'status': 'success',

        'film_data': film_data

    })


HTML Code

In the front-end code, we define an HTML file with some elements like a drop-down list containing the list of some James Bond movies and a table to display the details of each movie when the user selects it.


<body>

    <div class="container">

        <h1>List of James Bond Films</h1>

        <select id="selectFilm" class="select-jb-film" onchange="onChangeJBFilm()" size="1">

            <option value="10">No Time to Die (2021)</option>

            <option value="20">Die Another Day (2002)</option>

            <option value="30">The Living Daylights (1987)</option>

            <option value="40">A View to a Kill (1985)</option>

            <option value="50">Never Say Never Again (1983)</option>

        </select>


        <br><br><br><br>

        <div id="film_detail">

            <table id="film_table">

                <thead>

                    <tr>

                        <th>Film Title</th>

                        <th>Year</th>

                        <th>Starring</th>

                        <th>Directed By</th>

                    </tr>

                </thead>

                <tbody>

                </tbody>

            </table>

        </div>

    </div>

</body>


JavaScript Code

In the JavaScript code, we implement the code for ‘onChangeJBFilm()’ and other behaviors to demonstrate the use of JavaScript objects to cache data. The code handles loading, storing, and displaying some data from the James Bond movie. In this section, we explain the main functions of the code.


We add a handler to the ‘DOMContentLoaded’ event to ensure that the JavaScript program starts once the HTML page is fully loaded and the elements are created. In this handler, we call the ‘onChangeJBFilm()’ function.


We define two global variables, the ‘cache’ object which we need to cache the data, and ‘apiUrl’ to get the data from the back-end.


// An object to store cached data

const cache = {};


// Url to get data from back-end

const apiUrl = "/load_film_data";


document.addEventListener('DOMContentLoaded', function() {

    onChangeJBFilm();

}, false);


Function ‘onChangeJBFilm()’: This function is called when the selected film is changed. This function is declared as ‘async’, meaning it will return a promise and can use the await keyword inside it. In the first line, it retrieves the current value of the drop-down, which is the selected movie’s ID.


The second statement line calls the ‘fetchFilmDataFromUrl()’ function with ‘apiUrl’ and ‘filmId’ as arguments. It waits for the function to complete and assigns the returned movie data to the ‘film_data’ variable. After logging the fetched film data into the console, the function called the ‘showMovieData()’ creates a new row in the ‘film_table’ table and displays the movie data.


async function onChangeJBFilm(){

    let filmId = document.getElementById("selectFilm").value;

    let film_data = await fetchFilmDataFromUrl(apiUrl, filmId);


    // Log the found data

    console.log("Film data: ", film_data);


    // Call the function with the URL and Id

    showMovieData(film_data);

}


Function ‘fetchFilmDataInMemCache()’: This function is defined to retrieve movie data from the cache. Otherwise, it fetches movie data from the back-end. The first statements of the function allow to retrieve the currently selected option from the select element. 


The function takes two arguments, ‘url’ as the endpoint where the data will be fetched from, and ‘filmId’, which is the ID of the specific film for which data is requested. The function creates a cache key by concatenating the ‘url’ and ‘filmId’. This uniquely identifies the cached data for that particular movie request.


The function checks if the data for the given ‘cacheKey’ is already stored in the cache. If so, the data will be returned immediately.


If the data is not cached, we need to make an API call. For that, the function creates a ‘dataToSend’ object containing the ‘filmId’ ID. It sends a POST request to the specified ‘url’ with ‘dataToSend’ as the request body and waits for a response. 


The function throws an error if the response is not OK. Otherwise, the response is parsed in JSON format. The retrieved data is stored in the ‘cache’ object using its ‘cacheKey’ key. Finally, the function returns the retrieved data.


// An async function that fetches data from a URL or in memory cache

async function fetchFilmDataInMemCache(url, filmId) {


    //Define cache key as the combination of url and the film ID

    let cacheKey = url+filmId;


    // Check if data is already in the cache to return it

    if (cache[cacheKey]) {

        console.log('Returning cached data');

        return cache[cacheKey];

    }


    console.log("Fetching data...");

    let dataToSend = {filmId: filmId}

    const response = await fetch(url,

        {

            method: 'POST',

            headers: {

                'Content-Type': 'application/json'

            },

            body: JSON.stringify(dataToSend)

        }

    );


    // Await the fetch request & throw an error if status is not ok

    if (!response.ok) {

        throw new Error(`HTTP error! status: ${response.status}`);

    }


    // Await the parsing of the response as JSON

    const data = await response.json();


    // Store the fetched data in cache

    cache[cacheKey] = data.film_data;

    return data.film_data;

}


Function ‘showMovieData(film_data)’: This function dynamically creates a row in the movie details table with data such as the movie title, release year, lead role, and director. Let’s note that we create only one row every time we insert movie data. So, we clear the table’s body before adding the new row. 


function showMovieData(film_data){

    let table = document.getElementById("film_table");

    let tBody = table.getElementsByTagName('tbody')[0];

    // Clear the tbody contents to create a new row

    tBody.innerHTML = "";

    let film_title = film_data["title"];


    //Add a new row

    let tr = document.createElement('tr');

    addCell(tr, film_title);

    addCell(tr, film_data["year"]);

    addCell(tr, film_data["starring"]);

    addCell(tr, film_data["directedBy"]);

    tBody.appendChild(tr);

}


Function ‘addCell(tr, item)’: This function adds a cell with a given content to a table row.


function addCell(tr, item){

    var td = document.createElement('td');

    var content = document.createTextNode(item);

    td.appendChild(content);

    tr.appendChild(td);

}


If you execute this code and open the browser, you find the following page:



1.2. Using Element Data Attributes for In-Memory Caching

In JavaScript, you can use data-* attributes to cache data on DOM elements. The role of data-* attributes is to store any additional information you need it in your code. The content of data-* attributes must be valid HTML5.

You can add data-* attributes to HTML elements directly, or you can add and access them in JavaScript. We briefly discuss the two mechanisms for using the defined data-* attributes. We then present an example of caching data using data-* attributes in JavaScript.


Adding data-* attributes to HTML elements

In your HTML, you can add use data-* attribute like that:

<div id="myFilm" data-film-id="10" data-film-title="Die another day"></div>


Accessing data-* attributes in JavaScript

In JavaScript, you can access data-* attributes using the dataset property of the DOM element. The dataset property is a read-write object that contains all the data-* attributes of an element.


// Select the element

let element = document.getElementById('myFilm');


// Read data attributes using the dataset property

let filmId = element.dataset.filmId;


// Write data in the element's data attributes

element.dataset.filmId = "Never Say Never Again";


We can also cache JavaScript objects using data-* attributes, but we must to convert them first to a string.


Example of Using Attribute Data of an Element

We keep the same example above, except we remove the ‘fetchFilmDataInMemCache()’ function and define a new function called ‘fetchFilmDataElemCache()’ to cache the data using the data-* attribute.


Function ‘fetchFilmDataInMemCache()’: This function is defined as an asynchronous function that takes a ‘url’ and a ‘filmId’ as parameters. In the first two statements, it selects an HTML element using its ‘selectFilm’ ID and retrieves the currently selected option from this element.

It checks if the selected option already has movie data stored in its data-* attribute. If so, it logs a message and returns the cached data. Here, we use ‘JSON.parse’ to convert the cached data, which is a string, into a JavaScript object.

If the data is not cached, it sends a POST request to the specified URL with the ‘filmId’ in the request body. It then waits for the response, checks for errors parses the response as JSON, and stores the fetched data in the option’s data-* attribute for future use. Here we need to convert the ‘data.film_data’ object to a string that we can store in the data-* attribute.


// An async function that fetches data from a URL or an element cache

async function fetchFilmDataElemCache(url, filmId) {


    // Select the element

    let element = document.getElementById('selectFilm');


    //Get the selected option

    var option = element.options[element.selectedIndex];


    // Access data attributes using the dataset property

    let filmData = option.dataset.filmData;


    // Check if data is already in cache to return it

    if (filmData) {

        console.log('Returning cached data');

        return JSON.parse(filmData);

    }


    console.log("Fetching data...");

    let dataToSend = {filmId: filmId}

    const response = await fetch(url,

        {

            method: 'POST',

            headers: {

                'Content-Type': 'application/json'

            },

            body: JSON.stringify(dataToSend)

        }

    );


    // Await the fetch request & throw an error if status is not ok

    if (!response.ok) {

        throw new Error(`HTTP error! status: ${response.status}`);

    }


    // Await the parsing of the response as JSON

    const data = await response.json();


    // Store the fetched data in the cache

    option.dataset.filmData = JSON.stringify(data.film_data);

    return data.film_data;

}




Sunday, September 22, 2024

Filtering Default Dictionaries using Decorators and Regex



1. Introduction

In Python, decorators can be used effectively with default dictionaries to customize their

behavior. You can enhance their functionality by logging them, modifying their values, or applying constraints. 


You can also use decorators with regular expressions (regex) to apply operations to default dictionary entries based on pattern matching. This implementation makes it easy to apply filtering logic automatically when new data is added to keep only the relevant data. 


In this article, I introduce the ‘defaultdict’ class with some examples in Python. Then, I present some examples of using decorators with ‘defaultdict’. Finally, I present an example of using decorators with regular expressions (regex) to filter objects of the ‘defaultdict’ class.


2. Defaultdict

In Python, ‘defaultdict’ is a dictionary (subclass of the ‘dict’ class) with a specific functionality. If you try to access a key that does not exist in ‘defaultdict’, no exception is thrown but a default value is automatically assigned to that key. The key-value pair belongs to the dictionary.


To create a ‘defaultdict,’ you should provide a function to generate the default value when a missing key is accessed. This function is known as ‘default factory,’ and it is a callable that returns a value like an int, list, set, or custom function.


2.1. Example 1: Defaultdict with Int as Default Factory

To use ‘defaultdict’ in Python, import it from the ‘collections’ module. Then, create an instance of ‘defaultdict’ class with a callable as a parameter, which is ‘int’ in our example. In other words, the ‘int’ type is the default factory, which returns 0 for any non-existing key.


from collections import defaultdict


# Create a defaultdict with int as default factory

defdict = defaultdict(int)


# Access a missing key

print(defdict["k1"])  # Output: 0


# Add 10 to the value of the missing key

defdict["k1"] += 10

print(defdict["k1"])  # Output: 10


2.2. Example 2: Defaultdict with List as Default Factory

When you specify a list as the default factory for ‘defaultdict’, any missing key is assigned an empty list.


from collections import defaultdict


# Create a defaultdict with a list as default factory

defdict = defaultdict(list)


# Access a non-existing key

print(defdict["k1"])  # Output: []


2.3. Example 3: Defaultdict with a Custom Function as Default Factory

You can also define a custom function as the default factory to call whenever a missing key is accessed. In the example below, the ‘custom_def_val’ function returns a string ‘def_val’ as the value for any key that does not exist in the dictionary.


from collections import defaultdict


# Define a custom default factory

def custom_def_val():

    return "def_val"


# Create a defaultdict with the custom factory

defdict = defaultdict(custom_def_val)


3. Filtering Defaultdict with Decorator

In Python, you can use decorators to improve a default dictionary functionality such as automatically logging access, changing their values, or imposing constraints.


You can also use decorators with regular expressions (regex) to apply operations to dictionary entries based on pattern matching. You can control the dictionary's contents so that you can modify it. When accessing a non-existent key, you can intercept such an assignment by automating certain operations like:

- Logging access: Log any value added to the default dictionary.

- Enforcing constraints: Such as accepting only positive values and raising an exception otherwise.

- Modifying values: If the added value can be changed to another.


In the first and second examples, we show how to use decorators to automate the logging access to ‘defaultdict’ and enforce constraints. In the last example, we show how to use a decorator with regular expressions (regex) to filter the default dictionary.


3.1. Example 1: Logging Access to Defaultdict

Imagine we want to log a key from ‘defaultdict’ every time we access it. This is possible if we decorate the default dictionary's ‘__getitem__’ method.

We first define the ‘log_access’ decorator to log the key being accessed before calling the ‘__getitem__’ method of the ‘defaultdict’ superclass.


We declare a class ‘LoggedDefaultDict’ as a subclass of the built-in class ‘defaultdict’, in which we override the ‘__getitem__’ and decorate it with the ‘log_access’ decorator. 


In the code, we define ‘def_dict’ as an instance of the ‘LoggedDefaultDict’ class and the ‘default_factory’ function as its default factory, which returns 0 as the default value for missing keys.


from collections import defaultdict

from functools import wraps



def log_access(func):

    @wraps(func)

    def wrapper(self, key):

        print(f"Accessing key: {key}")

        return func(self, key)


    return wrapper



class LoggedDefaultDict(defaultdict):

    @log_access

    def __getitem__(self, key):

        return super().__getitem__(key)



def default_factory():

    return 0



def_dict = LoggedDefaultDict(default_factory)



def_dict['Q1']

def_dict['Q2'] += 1

def_dict['Q3'] += 2



Executing the above code produces the following result:


Accessing key: Q1

Accessing key: Q2

Accessing key: Q3


3.2. Example 2: Enforcing Constraints on Defaultdict Values

Here we show how we can use a decorator to ensure that a value added to ‘defaultdict’ obeys a specific constraint.

The ‘constraint_positive’ decorator checks that the value being set is non-negative. If the value is negative, it throws a ‘ValueError’ exception.

The ‘PositiveDefaultDict’ class inherits from the ‘defaultdict’ class and applies the ‘constraint_positive’ decorator to its ‘__setitem__’ method.


from collections import defaultdict

from functools import wraps


def constraint_positive(func):

    @wraps(func)

    def wrapper(self, key, value):

        if value < 0:

            raise ValueError(f"Value for key '{key}' should not be negative")

        return func(self, key, value)


    return wrapper



class PositiveDefaultDict(defaultdict):

    @constraint_positive

    def __setitem__(self, key, value):

        super().__setitem__(key, value)



def default_factory():

    return 0



defdict_positive = PositiveDefaultDict(default_factory)


defdict_positive['m'] = 10

print(defdict_positive['m'])  # Outputs: 10

defdict_positive['k'] = -5  # Raises an exception


3.3. Example 3: Filtering Defaultdict with Decorator and Regex

Suppose you manage sales data for some product categories in a store, and your data is stored in a dictionary where the keys are product IDs and the values are lists of sales figures. Sales figures include both positive numbers for sales and negative numbers for returns.


We want to write some code to keep only positive sales numbers and only for certain product categories based on specific patterns in their IDs. We create an ID as a string followed by a number. Product IDs starting with ‘ELEC’ are defined to represent electronics. Those starting with ‘SCHO’ represent school supplies and so on.


We create a decorator that filters sales figures based on whether the product ID matches a particular regex pattern. If the key matches one of the patterns, it filters the values to keep only positive sales figures. Otherwise, it returns the original values. The original function is then called with the filtered or original values based on the matching condition. 


from collections import defaultdict

import re

from functools import wraps


def filter_sales_figures(patterns):


    def decorator(func):

        @wraps(func)

        def wrapper(self, key, values):

            if any(re.match(pattern, key) for pattern in patterns):

                filtered_values = [value for value in values if value > 0]

                return func(self, key, filtered_values)

            else:

                return func(self, key, values)


        return wrapper


    return decorator



class ProductFigureSaleData(defaultdict):

    @filter_sales_figures([r'^ELEC', r'^CLOT'])  # Filter only electronics and clothes

    def __setitem__(self, key, values):

        super().__setitem__(key, values)


# Initialize the defaultdict

figures_sales_data = ProductFigureSaleData(list)


# Add some lists to the defaultdict

figures_sales_data['ELEC3457'] = [400, 250, -300, 20, -43]

figures_sales_data['SHOO1409'] = [55, -10, 70, -30, -60]

figures_sales_data['CLOT7890'] = [-178, -345, 300, 208, 100]


print(figures_sales_data)


Running this code gives us the following result:

ProductFigureSaleData(<class 'list'>, {'ELEC3457': [400, 250, 20], 'SHOO1409': [55, -10, 70, -30, -60], 'CLOT7890': [300, 208, 100]})


Sales of electronics (‘ELEC’) and clothing (‘CLOT’) are filtered by eliminating negative numbers. On the other hand, school supplies (‘SHOO’) are not filtered.

Saturday, September 21, 2024

The Most Powerful Concepts in Programming Languages: Machine Learning



In this blog, I would like to introduce the concepts that I believe are the most powerful in programming languages, and mastering them will give you solid programming thinking. I will explain them one by one with examples in Java and Python. After introducing the concepts of object-oriented, recursion, concurrency, functional programming, data structure, and design patterns, and annotations in earlier articles, I will elucidate the concept of machine learning in this article.



1. Object-oriented
2. Recursion
3. Concurrency
4. Functional Programming and Lambda Expressions
5. Data Structure
6. Software Design Patterns
7. Annotations and Decorators

8. Machine Learning



1. Machine Learning

Machine learning (ML) has become essential as a software development model. Machine learning is a branch of artificial intelligence (AI) that promotes the development of algorithms and models that allow a computer to learn from provided data to make predictions or decisions.


The computer in this case is not explicitly programmed. In other words, it didn’t receive a program composed of statements to execute to provide a result. Moreover, an ML system can repeatedly improve the accuracy of the results delivered through experience. In other words, every time new data is fed to an ML system, that makes it learns and optimizes its performance.


Machine learning is a new reasoning and computational model. It is a new way of thinking about and writing programs, different from simply giving instructions to the computer to execute them and produce results. We give a summary of key concepts related to machine learning in the following paragraphs.


Data: This is the backbone of ML. ML algorithms need a large amount of data to learn patterns and make decisions and predictions. More data can help ML algorithms achieve better results. The data used by ML algorithms is structured as datasets. A dataset is a collection of rows, where each row is composed of multiple variables. For example, for a dataset composed of students at a university, a row might represent data about a specific student such as name, date of birth, degree, etc.


The data can be labeled or unlabeled. Each row in labeled data is tagged with a known output. On the other hand, unlabeled data means that outcomes are not associated with data.


A dataset is generally divided into three categories: training dataset, validation dataset, and testing dataset. A possible split of the dataset could be 70% of the data for training, 20% for validation, and 10% for testing. This division may vary depending on the size and specifics of the dataset.


Training: ML algorithms analyze input data and learn from it to train ML models. During a training process, the model optimizes its internal parameters to reduce errors and maximize its performance.


Parameter: It is an internal variable of an ML model that is learned during training. The ML model makes adjustments while training the data until the optimization goals are reached. If you take the linear regression model as an example, the parameters are the coefficients of the linear equation.


Hyperparameter: This is a parameter set before the training process and not learned by the model. It is a configuration parameter that determines the behavior of the learning algorithm. Hyperparameters cannot be updated during the training process. The number of hidden layers in a neural network is an example of hyperparameters.


Parameter vs Hyperparameter: The main difference between parameters and hyperparameters can be summarized in the following table based on the three criteria of learning, control, and optimization:



Parameter

Hyperparameter

Learning

It is learned from data during the training phase

It is set before the training phase

Control

It defines the internal behavior of the ML model

It defines the learning process and impacts model performance

Optimization

It is optimized during the training phase

It is tuned to improve the performance of the ML model


ML Model: An ML model is a computer representation that finds patterns or relationships in data. It is the result of training an algorithm on labeled or unlabeled data. Many types of ML models are defined. The choice of model depends on certain factors such as the nature of the problem, the desired result, and the type of data. The most popular category of ML models is regression models, including its simplest form, the linear regression model. The latter is used to predict the value of a dependent variable in terms of one or more independent variables.


Validation and Test: Better training ML models requires validating and testing them on distinct datasets to ensure they can be applied effectively to new data. Validation helps during the training process to improve the trained ML model and tune its hyperparameters. However, the test dataset is used after the model has been fully trained to evaluate the performance and accuracy of the ML model on completely unseen data. In other words, data that the ML model has never seen before.


Deployment: Once ML models are trained and validated, they can be deployed in the production environment to make predictions on unknown data. They can be integrated into applications and used to make decisions and predictions or automate recurring tasks.


Feature: It is a measurable property of data that is used as input to train ML models. It is also called an independent variable or predictor and helps capture relevant information that enables the model to detect patterns and make decisions or predictions. The choice of features has a considerable effect on the performance and accuracy of the outcomes delivered by the model. Features can be, for instance, numeric, text, or image. 


Label: It is a value associated with each row of a dataset or output returned by a model. Labels are also called dependent variables or target variables. Let’s say you want to generate a model to predict the weather. In this case, you need features like temperature, wind speed, etc. The label in this case is the predicted weather value like sunny, cloudy, etc.


Algorithm: ML algorithms are computational techniques that can extract hidden patterns from data to make decisions or predictions. They gain experience by learning on their own. They can thus improve their performance and the accuracy of their predictions or the results obtained. ML algorithms are classified into four common types, namely supervised learning, unsupervised learning, semi-supervised learning, and reinforcement learning.


2. Types of Machine Learning Algorithms

The types of ML algorithms are defined according to their purpose and the commonly defined ones are:


1. Supervised learning

Supervised learning algorithms require external supervision to be trained. It requires labeled datasets to attempt to find patterns and make accurate data predictions or classifications.


As a basic example, we feed an ML model with labeled data, which is images of apples with labels. After training the model with data, we want to apply the model by feeding it with unseen data, i.e. the unlabeled image of an apple. If the model predicts correctly, it will give us the word ‘apple’ as the response.


2. Unsupervised Learning

In this type of ML, a model is trained with unlabeled data. The model will determine correlations and identify patterns in the fed data. These algorithms are useful in cases where even humans don’t know what they are looking for. The outcome of a model after unsupervised training could be grouping data into clusters. 


As a basic example, you feed the ML model with unlabeled data, say with mixed images containing images of apples, bananas, and pears. The model will determine patterns and extract three different categories of fruits based on their similarities.


3. Semi-supervised Learning

In semi-supervised learning, the ML model is fed with labeled and unlabeled data. This combination allows the model to use the labeled data to understand the data to find missing elements by labeling the unlabeled data.


4. Reinforcement Learning

In this type of ML, the model, which is an agent, interacts with its dynamic environment. As it performs actions, it receives feedback in the form of reward or punishment, depending on whether the action taken was good or bad.


So it can add this new learning to its dataset. In reinforcement learning, part of the data is fed into the model externally and part is generated by the model itself during its training phase.


A simple example of reinforcement learning is a walking robot that has to reach a certain point as a goal. If it moves in the right direction and gets close to the target, it will be rewarded. Otherwise, it will be punished.


Application Domains

ML is increasingly being used in various areas such as image recognition, robotics, autonomous cars, medical diagnosis of diseases, cybersecurity, fraud detection, and much more.


Programming

Many ML libraries and frameworks are now available in various programming languages such as Java and Python. Java has libraries such as JavaML, MOA, and Weka. Python has libraries such as TensorFlow, PyTorch, scikit-learn, and Keras that provide the necessary tools to develop ML models.


Linear Regression

To put you in the picture and better understand ML technically, we would like to introduce you to the simplest and best-known model, the linear regression model. Linear regression is a statistical modeling technique used to find the correlation between a dependent variable and one or more independent variables. This model assumes that the dependent variable changes proportionally as the independent variable changes. The general formula of the linear model is represented as follows:


y = m0*x0 + m1*x1 + .. mn*xn + c


Where:

- y is the dependent variable we want to predict.

- x0, x1, ..., xn are the independent variables or features that effect the dependent variable.

- m0, m1, ..., mn are the regression coefficients or model parameters.

- c is the error or bias, which accounts for variability not explained by the model.


The linear regression equation is usually represented graphically. We will get a line where x0, .., xn are represented on the x-axis and y is represented on the y-axis. The coefficients m0, .., mn are the slope of the regression line which tells us how much we expect the y value to change when we change the x value by one unit. The constant c, also called the y-intercept, is the point where the regression line crosses the vertical y-axis.


Linear regression finds the best-fit line where the difference between the observed values and those predicted by the model is the smallest. Once the best-fitting line is found, the slope and intercept coefficients are determined and the linear regression equation is known, and ready to be used to make predictions.


2. Example in Java

Java has many libraries and frameworks to perform ML programming. We can use the ‘Apache Commons Math’ library to program the ML linear regression algorithm.

For this, we need a dataset. The dataset we will use is an example containing data on the baby’s growth. This dataset is composed of two tables representing the baby’s weight as the independent variable (X) and the baby’s length as the dependent variable (Y).


import org.apache.commons.math3.stat.regression.SimpleRegression;


public class LinearRegressionExample {


public static void main(String[] args) {

     childGrowthRegRegression();

}


public static void childGrowthRegRegression() {

     double[] weightX = {2.6, 3.5, 4.5, 5.2, 5.8}; //Kg

     double[] lengthY = {46.4, 50.9, 55.1, 57.9, 60.2}; //Cm


     //Create a SimpleRegression instance

     SimpleRegression childGrowthReg = new SimpleRegression();


     //Add the data points to the regression model

     for (int i = 0; i < weightX.length; i++) {

          childGrowthReg.addData(weightX[i], lengthY[i]);

     }


     //Get the regression intercept and slope

     double intercept = childGrowthReg.getIntercept();

     double slope = childGrowthReg.getSlope();


     //Display the regression equation

     System.out.println("Regression equation is: y = " + slope + " * x + " + intercept);


     //Use the obtained equation to make prediction

     double newWeightX = 8.0;


     //Calculate the predicted length for a new weight using the regression model

     double predictedLengthY = childGrowthReg.predict(newWeightX);

    

     System.out.println("Predicted Length for X=" + newWeightX + " is Y=" + predictedLengthY);

    }

}


In this example, we import the ‘Apache Commons Math’ library to perform the linear regression. As commented in this code, we can use this library to create an instance of a simple regression model, which we named ‘childGrowthReg’. 


Next, we fed the model with the dataset consisting of two arrays (‘weightX’ and ‘lengthY’). The model is now ready to generate the equation by determining the slope and the intercept coefficients. In the same code, we provide the model with a new weight value and ask the model to make a prediction, which we will print later. 


The result of the execution of this code is: 


Regression equation is: y = 4.287869643934824 * x + 35.576403138201556

Predicted Length for X=8.0 is Y=69.87936028968015

Now we want to visualize the data points and regression line in Java. For that, certain libraries are available to developers. For instance, we can use the ‘JFreeChart’ library in Java to plot the regression line. So, in a separate example, we show how to do this.


This code of the main method of the code below creates a graphical user interface (GUI) application using the ‘JFreeChart’ library. It creates an object called ‘frame’ as an instance of the ‘JFrame’ class and sets its properties. 


Next, it creates a dataset containing the points to plot on the graph (data points and regression line) using the ‘createDataset’ method. It then called the ‘createChart’ method to create a chart using the dataset. The next statement creates a chart panel to display the chart. We can customize the chart panel to have a specific size. After that, we add the chart panel to the frame, pack the frame to adjust its size to fit the content, and display the frame.


import org.apache.commons.math3.stat.regression.SimpleRegression;

import org.jfree.chart.ChartFactory;

import org.jfree.chart.ChartPanel;

import org.jfree.chart.JFreeChart;

import org.jfree.chart.plot.PlotOrientation;

import org.jfree.chart.plot.XYPlot;

import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;

import org.jfree.data.xy.XYDataset;

import org.jfree.data.xy.XYSeries;

import org.jfree.data.xy.XYSeriesCollection;


import javax.swing.*;

import java.awt.*;


public class LinearRegressionPlot {


    private static XYDataset createDataset() {


        double[] weightX = {2.6, 3.5, 4.5, 5.2, 5.8}; //Kg

        double[] lengthY = {46.4, 50.9, 55.1, 57.9, 60.2}; //Cm


        //Create a SimpleRegression instance

        SimpleRegression childGrowthReg = new SimpleRegression();


        //Add the data points to the regression model

        for (int i = 0; i < weightX.length; i++) {

            childGrowthReg.addData(weightX[i], lengthY[i]);

        }


        //Get the regression intercept and slope

        double intercept = childGrowthReg.getIntercept(); // intercept

        double slope = childGrowthReg.getSlope(); // slope


        //Create a series of data items in the form (x, y)

        XYSeries series = new XYSeries("Babies Growth");

        for (int i = 0; i < weightX.length; i++) {

            series.add(weightX[i], lengthY[i]);

        }

        //Create a collection of series to be used as a dataset

        //Add the data points to the dataset

        XYSeriesCollection xyData = new XYSeriesCollection(series);


        //Create a series that contains the regression line

        XYSeries babyWeight = new XYSeries("Weight and Length");

        //Get the regression line using the intercept and slope to calculate the first and last x pairs (x, y)


        //Get the first point of the line pair of (x, y)

        double x = series.getDataItem(0).getXValue();

        babyWeight.add(x, slope * x + intercept);


        //Get the last point of the line pair of (x, y)

        x = series.getDataItem(series.getItemCount() - 1).getXValue();

        babyWeight.add(x, slope * x + intercept);


        //Add the regression line to the collection

        xyData.addSeries(babyWeight);


        //xyData contains now the data items and the regression line

        return xyData;

    }


    private static JFreeChart createChart(final XYDataset dataset) {


        //Create an instance of JFreeChart

        JFreeChart chart = ChartFactory.createScatterPlot("Babies Growth", "Weight (Kg)", "Length (cm)",

                dataset, PlotOrientation.VERTICAL, true, false, false);


        //Get the XYPlot object

        XYPlot plot = chart.getXYPlot();

        //Create the renderer that creates the line

        XYLineAndShapeRenderer render = (XYLineAndShapeRenderer) plot.getRenderer();


        //Make the regression line visible

        render.setSeriesLinesVisible(1, Boolean.TRUE);

        return chart;

    }


    public static void main(String[] args) {

        //Create new frame

        JFrame frame = new JFrame();

        //Set frame properties

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Get the dataset that contains the points to be plotted

        XYDataset dataset = createDataset();


        //Create the chart

        JFreeChart chart = createChart(dataset);

        //Create the chart panel with the inside and set the size

        ChartPanel chartPanel = new ChartPanel(chart) {

            @Override

            public Dimension getPreferredSize() {

                return new Dimension(600, 450);

            }

        };

        

        //Add the chart panel to the frame

        frame.add(chartPanel);


        //Display the frame

        frame.pack();

        frame.setLocationRelativeTo(null);

        frame.setVisible(true);

    }

}


In the ‘createDataset’ method, we create a dataset for a linear regression model. It defines two arrays of data points, ‘weightX’ and ‘lengthY’ (the babies’ weight and length measurements), and uses them to fit a linear regression model. It then creates a series of data items in the form of (x, y) pairs from ‘weightX’ and ‘lengthY’ and adds them to the ‘xyData’ collection. It adds a regression line using the regression equation to the ‘xyData’ collection and returns it as the dataset.


In the ‘createChart’ method, we create a scatter plot using the ‘JFreeChart’ library as an instance of the ‘JfreeChart’ class. The ‘chart’ object takes as input a ‘dataset’ object of the ‘XYDataset’ class, which contains the data points and the regression line. We specify the title and the axis labels when creating ‘chart’. We get the plot of ‘chart’ and its render to make the line regression visible. Finally, we return the chart as a result.


Executing this code gives us the following frame:





3. Example in Python

Python is one of the most popular programming languages with several powerful libraries for implementing machine learning algorithms. Let’s look at three of these libraries, namely ‘numpy’,  ‘scikit-learn’, and ‘ matplotlib’ to show how easy it is to implement regression models in Python.


Note that ‘numpy’ is a library that helps and simplifies working with numerical data in Python. The ‘scikit-learn’ library implements machine learning algorithms including linear regression. Finally, the ‘matplotlib’ library is used to create graphic representations of data. 


The following example is about looking for the relationship as a linear regression between the weight of babies and their lengths. Let’s explain in detail this code. First, we import ‘LinearRegression’ from ‘sklearn’, and ‘pyplot’ from ‘matplotlib’ to visualize the model.


We prepare now the data that are two arrays ‘weight’ and ‘length’ by converting them to ‘numpy’ arrays ‘X’ and ‘y’. But, ‘X’ should be reshaped to a matrix with 1 row and ‘n’ columns, where ‘n’ is the size of ‘X’. This is necessary to apply the linear regression. After printing ‘X’ and ‘y’, we create an instance ‘child_growth_model’ of the ‘LinearRegression’ class. Then, we fit the linear regression model to the data using the ‘fit’ method. So we get the intercept and slope of the regression line with the help of the ‘intercept_’ and ‘coef_’ attributes of ‘child_growth_model’.


import numpy as np

from sklearn.linear_model import LinearRegression

import matplotlib.pyplot as plt



weight = [.6, 3.5, 4.5, 5.2, 5.8]

length = [46.4, 50.9, 55.1, 57.9, 60.2]


# Sample data, babies weight in Kg

X = np.array(weight).reshape(-1, 1)


# Sample data, babies height in Cm

y = np.array(length)


# Print the sample data

print('X: ', X)

print('y: ', y)


# Create a linear regression model

child_growth_model = LinearRegression()


# Fit the model to the data

child_growth_model.fit(X, y)


# Get the regression coefficients

intercept = child_growth_model.intercept_

slope = child_growth_model.coef_[0]


# Print the regression equation

print(f"Regression equation is: y = {slope:.2f} * x + {intercept:.2f}")


# Predict a new value using the regression model

newX = np.array([8.0]).reshape(-1, 1)

predictedY = child_growth_model.predict(newX)


# Print the predicted value Y

print(f"Predicted Y for X = {newX[0, 0]}: {predictedY[0]:.2f}")


# Plot the data points and the regression line using a scatter plot

plt.scatter(X, y, label='Babies Weight and Height')


# Draw the regression line

plt.plot(X, child_growth_model.predict(X), color='red', label='Regression Line of Babies Growth')


# Add axis labels

plt.xlabel('Weight (Kg)')

plt.ylabel('Height (Cm)')


# Add a legend

plt.legend()


# Show the plot

plt.show()


We use the obtained attributes to display the regression equation. As our model is ready to predict values, we run it for a new value ‘8.0’ using the ‘predict’ method of ‘child_growth_model’ and print the result in the next statement. Finally, we draw the data points and the regression line using a scatter plot of the ‘matplotlib’ library.


Running the example above gives us the following result:


X:  [[0.6]

 [3.5]

 [4.5]

 [5.2]

 [5.8]]

y:  [46.4 50.9 55.1 57.9 60.2]

Regression equation is: y = 2.62 * x + 43.82

Predicted Y for X = 8.0: 64.80








Blog Posts

Enhancing Performance of Java-Web Applications

Applications built with a Java back-end, a relational database (such as Oracle or MySQL), and a JavaScript-based front-end form a common and...