web development – Solution to notify users Single Page Application (SPA) static resources have updated if users don’t refresh their browsers

Basically you want to trigger an event when the version changes to inform the user that their UI is outdated and they should refresh. If you want to keep it simple this can be done file-based. You basically need these components:

  • A JavaScript file (currentversion.js) that dispatches a event about the current version
  • Logic in the SPA that periodically reloads currentversion.js file and defines listeners for the “currentversion” event.

The generation of that currentversion.js and currentVersion can be automatically generated to contain the correct version on every build.

The idea is to (re)load the currentversion.js as needed to dispatch the current version of the UI. The logic can listen for that event and act when the version has deviated from last known version.

In theory you can have something like:

currentversion.js

window.dispatchEvent(new CustomEvent('currentversion', { detail: '1.1' }));

index.html

<html>
    <body>
        <script>
            const currentVersion = '1.1';
            
            function startVersionCheck() {
                const versionJs = document.getElementById('version-js');
                const versionJsUrl = versionJs.src;
                let versionJsReloadCount = 0;
                const versionCheck = function () {
                    versionJs.src = (versionJsUrl, '?rc=', ++versionJsReloadCount).join('');
                };
                setInterval(versionCheck, 60000);
            }

            window.addEventListener('currentversion', function (e) {
                const version = e.detail;
                if (currentVersion !== version) {
                    window.dispatchEvent(new CustomEvent('versionchanged', { detail: version }));
                }
            });

            window.addEventListener('versionchanged', function (e) {
                alert('New UI version available!');
            });

            window.addEventListener('load', startVersionCheck);
        </script>
        <script id="version-js" src="./currentversion.js"></script>
    </body>
</html>

Both the UI and currentversion.js expose the same version initially. When the value changes in currentversion.js it should eventually trigger the versionchanged event on the next reload.

Once the user reloads both version are in sync again.

time complexity – Why is the maximum single sell profit by divide and conquer O(n log n)

The single sell profit problem is:

Given a list of prices on each day, find the maximum profit that could have been made by buying on one of the days and selling on a later day.

There is a solution with a single scan that is easy to implement and runs in $O(n)$. This question is not about that. It’s about the divide-and-conquer solution. Here’s my Python implementation:

def best_trade(prices: List(int)) -> int:
    def f(prices: List(int)) -> Tuple(int, int, int):
        if len(prices) < 2:
            return 0, min(prices), max(prices)
        else:
            best_left, min_left, max_left = f(prices(: len(prices) // 2))
            best_right, min_right, max_right = f(prices(len(prices) // 2 :))
            return (
                max(best_left, best_right, max_right - min_left),
                min(min_left, min_right),
                max(max_left, max_right),
            )

    return f(prices)(0) if prices else 0  # else 0 for the corner case where prices = ()

The inner recursive function returns the maximum profit, the minimum price, and the maximum price.

This recurses by breaking the problem into two subproblems, each half the size of the original problem. As far as I can tell the combination step outside the recursion is $O(1)$. I’m using max and min builtins for readability, but it just compares 3 numbers, 2 numbers and 2 numbers.

If that’s correct, the running time is $T(n) < 2 T(n/2) + O(1)$. By the master method, this implies the algorithm has time complexity $O(n)$. That’s because $a = 2$, $b = 2$ and $d = 0$, so we’re in the case where $a > b^d$, so $O(n^{log_b a}) = O(n)$.

I can’t see any flaw in the above, but I’ve read twice that this algorithm is $O(n log n)$: once when this problem is discussed in Elements of Programming Interviews in Python by Aziz, Lee and Prakash (it’s problem 5.6), and once in these PDF lecture notes by Kevin Zatloukal of UW (page 23). Both these sources say the divide and conquer solution is slower than a simple scan.

Reading between the lines in both cases, they appear to be describing a divide-and-conquer implementation without an inner function that returns the best trade directly, which requires them to call min and max on the subarrays, i.e.

def best_trade_2(prices: List(int)) -> int:
    if len(prices) < 2:
        return 0
    else:
        best_left = best_trade_2(prices(: len(prices) // 2))
        best_right = best_trade_2(prices(len(prices) // 2 :))
        return max(
            best_left,
            best_right,
            max(prices(len(prices) // 2 :)) - min(prices(: len(prices) // 2)),
        )

I can see here that the work done outside the recursion is $O(n)$ because of the max/min calls on the sublist, which implies the algorithm is $O(n log n)$.

My implementation seems fundamentally the same algorithm but it has different complexity. I feel like I’m getting work for free. What am I missing? Is my implementation actually different (and better)? Or is my analysis of my implementation wrong?

mathematical philosophy – How can make one single function of 2 connected functions?

I have 2 functions that both working for making one single value for Width which they are like this:

First Function (For Zone 1 and 3):

Width = Sin(90 + thetaDegree)

Seconde Function (For Zone 2 and 4):

Width = Sin(270 - thetaDegree)

the value of thetaDegree would declare which function should be used for calculation.

For example if the value of thetaDegree would be 45 degree then we should use first Function because thetaDegree is inside Zone 1.

My Goal is making a Single function, that I be free to observing the value of thetaDegree, in this way that we just gave some value to thetaDegree and using just one function instead using that 2 function.

How can I do this? thanks.

enter image description here

amazon web services – Do I need 1 RDS Cluster for each DB or a single RDS Cluster for all my DBs?

Let’s suppose I have 5 databases I’m going to use in my application. The application will be used by +100k users. I’m planning to use RDS Cluster with Aurora PostgreSQL. What would be best?

Create 1 cluster for each DB, I’ll end up with 5 clusters, which I think is good for performance but with a higher cost.

OR

Create a single cluster with enough resources(CPU, RAM, etc.) that will contain the 5 databases in it.

java – Should I create two synchronous or a single asynchronous rest APIs?

Here is the situation. System A sends the notification as it completes the work items to System B. System A does not know how many items the project consists of. It’s just a pass-through system. System B knows the number of items. Once sys B receives the notification for the last item, it has to wait for the final authorization and the send the close-project notice to system A.

My question is should I try to implement it as one asynchronous REST API for all transactions, or two synchronous APIs, one for items completion (from A to B) and the other one for the final approval transaction (B to A)?
system A system B

item 1 done ——- >

<———- got it —

item 2 done ————->

<———- got it —

. . .

item n done ——- >

<———- got it waiting for manager’s approval. may take weeks.

…. make take days/weeks

< —————Manager signed. Project closed. Here is the details.

web development – Options to notify users Single Page Application (SPA) static resources have updated if users don’t refresh their browsers

I need to design a way to notify my user the SPA has updated if they don’t refresh their browsers, i.e. if no requests to get index.html is made after the initial load, how do I notify users the javascript or css files have updated on the server? Note, it is not the REST api that my SPA communicate with updates but the SPA’s static resources.

I think the options are limited:

  1. Start a time to keep querying the latest version number
  2. Add a customer header field about the latest version in responses for most if not all XHR requests SPA send
  3. using websocket to notify SPA
  4. I am not familiar with service worker but I read articles about it may work too.

There is another problem I need to deal with, my SPA is deployed on its own server, which is separated from the REST server it communicates with(although I suspect it is common) and there are cases that the SPA has new versions while REST server doesn’t. The version number I design should be able to tell these 2 cases.

I notice folks asked this kind of questions on stackoverflow many times. I can find more 10 questions, with the earliest one I found in 2013 and the latest one in 2019. I list some here.

  1. How to handle expired files without refreshing the browser when using Single Page Application (SPA)?
  2. How to force update Single Page Application (SPA) pages?
  3. How can I force SPA clients to hard refresh if there is a new build?
  4. Refreshing a cached Angular SPA
  5. Proper way to refresh Single Page Application

The reasons I asked here are:

  1. I like to design a build process to update the SPA version automatically. Manually update the version number is error prone. None of answers seem to address this.
  2. All those Q&A on SO seemed to failed to mention the case that the SPA server and REST server is separated and what I need here is an update for SPA files. For example if I use the option 2, adding a customer header field in response I need to differentiate the SPA version and REST api version. None of the answers I saw address this. Some answers just focus on REST api version update.
  3. I believe this question should be address by a build process, a communication process and maybe a deploy model. So this is a question about SPA architecture.
  4. The mere facts that this question has been asked so many times for 8 years probably has said it clearly that there is no easy answer for it, probably even without some best practices. Some answers failed to realize is the core issue here is to retrieve index.html so focus on cache busting, file naming or setting Cache-Control, like this one How to force the browser to reload cached CSS and JavaScript files

cookie – How do tracking pixels identify a single user?

From: https://www.adquadrant.com/blog/what-is-a-tracking-pixel

Tracking pixels sent information directly to servers, so they do not rely on the user’s individual browser. Pixels are able to follow users across all of their devices, linking marketing efforts across your website and mobile ads. Also, users cannot disable pixels like they can disable cookies.

I know regular analytics cookies will store a cookie with an ID for a single browser/user. Therefore, it’s able to track the user’s activity across multiple websites.

But if a tracking pixel does not store a cookie, how does it identify a single user? Is it via IP? A single IP can be shared by many users over a single network. Is it IP + some other information?

For a custom module’s composer.json how to fetch a single file from an third-party repository

From the APCu repository, the custom module needs to get a single apc.php file. This repository does not have any release.

Is there a way to specify composer.json to only fetch a single file instead of entire repository?

Is it a bad idea to have a single event bus service for the whole organization?

Assumed that the whole organization is doing the related product,

Is it a bad idea to have a single event bus service for the whole organization?

Are we going to have any scaling issues for that?