Discord JS command with autocomplete dont Work

the autocomplete works fine but when im trying to execute the command it stops and idk why.. even the conditional i think the problem is in the autocomplete maybe i can be on a loop but idk how to handle that
my index is fine, it gives no error it just stops when i press enter to execute the command.

const { SlashCommandBuilder } = require('discord.js');
const { joinVoiceChannel, VoiceConnectionStatus } = require('@discordjs/voice');
const SpotifyWebApi = require('spotify-web-api-node');

const spotifyApi = new SpotifyWebApi({
    clientId: process.env.CLIENT_IDP,
    clientSecret: process.env.CLIENT_SECRET
});


module.exports = {
    data: new SlashCommandBuilder()
        .setName('play')
        .setDescription('Makes the bot say the provided text.')
        .addStringOption(option =>
            option.setName('cancion')
                .setDescription('The text you want the bot to say.')
                .setRequired(true)
                .setAutocomplete(true)),

                async autocomplete(interaction) {
                    try {
                        const focusedValue = interaction.options.getFocused();
                        
                        // Verificar si el valor enfocado está vacío o no definido
                        if (!focusedValue) {
                            return;
                        }
                        
                        const credenciales = await spotifyApi.clientCredentialsGrant();
                        spotifyApi.setAccessToken(credenciales.body.access_token);
                        let choices = [];
                
                        // Buscar canciones en Spotify basadas en el texto enfocado
                        const searchResults = await spotifyApi.searchTracks(focusedValue, { limit: 15 });
                        choices = searchResults.body.tracks.items.map(track => ({ name: track.name, value: track.uri }));
                
                        await interaction.respond(choices);
                    } catch (error) {
                        console.error("Error al realizar autocompletado de Spotify:", error);
                        // Manejar el error
                    }
                },

    async execute(interaction) {
        const voiceChannel = interaction.member.voice.channel;

        if (voiceChannel) {
            await interaction.reply("name song");
            try {
                // Unirse al canal de voz
                const connection = joinVoiceChannel({
                    channelId: voiceChannel.id,
                    guildId: interaction.guild.id,
                    adapterCreator: interaction.guild.voiceAdapterCreator
                });

            
                connection.on('stateChange', (_, newState) => {
                    if (newState.status === VoiceConnectionStatus.Disconnected) {
                        // Manejar la desconexión del canal de voz
                    }
                });

                // Desconectar después de 5 segundos
                setTimeout(() => {
                    connection.destroy();
                }, 5000);
            } catch (error) {
                console.error("Error al unirse al canal de voz:", error);
                await interaction.followUp({ content: "Hubo un error al unirse al canal de voz.", ephemeral: true });
            }

        } else {
            await interaction.reply({ content: "El usuario no está en un canal de voz.", ephemeral: true });
        }
    },
};

Recording Canvas With Logo Results in Segmented Audio

I was trying to implement the Screen Recording With Video and a logo using the RecordRTC library but found out that while using the example shown in

https://www.webrtc-experiment.com/RecordRTC/simple-demos/show-logo-on-recorded-video.html

results in segmented audio in the recording.

Here is a reproducible fiddle: https://jsfiddle.net/kiran589/L34bdhu7/5/

The code is like:

var videoPreview = document.getElementById('video-preview');
var logoImage = document.getElementById('logo-image');
var waitImage = document.getElementById('wait-image');

navigator.mediaDevices.getUserMedia({video: true, audio: true}).then(function(camera) {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    canvas.style = 'position: absolute; top: 0; left: 0; opacity: 0; margin-top: -9999999999; margin-left: -9999999999; top: -9999999999; left: -9999999999; z-index: -1;';
    document.body.appendChild(canvas);

    var video = document.createElement('video');
    video.autoplay = true;
    video.playsinline = true;
    video.srcObject = camera;

    var canvasStream = canvas.captureStream(15);

    var audioPlusCanvasStream = new MediaStream();

    // "getTracks" is RecordRTC's built-in function
    getTracks(canvasStream, 'video').forEach(function(videoTrack) {
        audioPlusCanvasStream.addTrack(videoTrack);
    });

    // "getTracks" is RecordRTC's built-in function
    getTracks(camera, 'audio').forEach(function(audioTrack) {
        audioPlusCanvasStream.addTrack(audioTrack);
    });

    var recorder = RecordRTC(audioPlusCanvasStream, {
        type: 'video'
    });

    recorder.setRecordingDuration(10 * 1000).onRecordingStopped(function() {
        var blob = recorder.getBlob();
        recorder = null;
        camera.stop();

        videoPreview.srcObject = null;
        videoPreview.src = URL.createObjectURL(blob);
    });

    recorder.startRecording();

    videoPreview.srcObject = canvasStream;

    var tries = 0;
    (function looper() {
        if(!recorder) return; // ignore/skip on stop-recording

        tries += 100;

        canvas.width = 320;
        canvas.height = 240;

        // show hello.png for one second
        if(tries < 5000 || tries > 6000) {
            context.drawImage(video, 0, 0, canvas.width, canvas.height);

            // context.drawImage(logoImage, parseInt(canvas.width / 2) - parseInt(logoImage.width / 2), canvas.height - logoImage.height - 10);
            // context.drawImage(logoImage, parseInt(canvas.width / 2) - parseInt(32 / 2), canvas.height - 32 - 10, 32, 32);
            context.drawImage(logoImage, 10, 10, 32, 32);
        }
        else {
            context.drawImage(waitImage, 0, 0, canvas.width, canvas.height);
        }

        // repeat (looper)
        setTimeout(looper, 100);
    })();
}).catch(function(error) {
    alert('Unable to capture camera. Please check console logs.');
    console.error(error);
});

If you go to the link and start recording, and say aaaaaaaaaaaaaaaaaaaa, then the recording outputs the audio like aaaa aaa aaa.

Is this a bug in RecordRTC?
Is there any way to get smooth audio and video in the recording while using canvas recording?

Thanks for your help in advance.

JSONBION.IO API for update

I created three pages of createUser.js, UpdateUser.js, and readUser.js and index.html which simply collects user details of employees and store them. I used the create file, it worked and created a JSON data. I used the readUser file and it worked to read uses. I even added more user details manually so I can read the JSON file, but the updateUser is overriding the JSON data inside my bin and adding the new user details.

I have read the documentation of jsonbin and I still can’t find what I am doing wrong.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Details Form</title>
    <style>
        /* Add your CSS styles here */
    </style>
</head>
<body>
    <h1>User Details Form</h1>
    <form id="userForm">
        <label for="firstName">First Name:</label>
        <input type="text" id="firstName" name="firstName" required><br>

        <label for="lastName">Last Name:</label>
        <input type="text" id="lastName" name="lastName" required><br>

        <label for="age">Age:</label>
        <input type="number" id="age" name="age" required><br>

        <label for="yearOfEmployment">Year of Employment:</label>
        <input type="number" id="yearOfEmployment" name="yearOfEmployment" required><br>

        <label for="hobbies">Hobbies:</label><br>
        <input type="checkbox" id="reading" name="hobbies" value="Reading">
        <label for="reading">Reading</label><br>

        <input type="checkbox" id="cooking" name="hobbies" value="Cooking">
        <label for="cooking">Cooking</label><br>

        <input type="checkbox" id="hiking" name="hobbies" value="Hiking">
        <label for="hiking">Hiking</label><br><br>

        <!-- Address section -->
        <label for="street">Street:</label>
        <input type="text" id="street" name="street" required><br>

        <label for="city">City:</label>
        <input type="text" id="city" name="city" required><br>

        <label for="country">Country:</label>
        <input type="text" id="country" name="country" required><br>

        <button type="submit">Submit</button>
    </form>

    <!--<script src="jsonbin.js"></script>-->
    <script src="jsonbin2.js"></script>
</body>
</html>

document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('userForm');

    form.addEventListener('submit', async function(event) {
        event.preventDefault(); // Prevent default form submission

        // Get form values
        const firstName = document.getElementById('firstName').value;
        const lastName = document.getElementById('lastName').value;
        const age = document.getElementById('age').value;
        const yearOfEmployment = document.getElementById('yearOfEmployment').value;
        const hobbies = getHobbies();
        const street = document.getElementById('street').value;
        const city = document.getElementById('city').value;
        const country = document.getElementById('country').value;

        // Create user object
        const newUser = {
            firstName,
            lastName,
            age,
            yearOfEmployment,
            hobbies,
            address: {
                street,
                city,
                country
            }
        };

        // Call function to update user details
        await updateUserDetails(newUser);
    });

    // Function to get selected hobbies
    function getHobbies() {
        const checkboxes = document.getElementsByName('hobbies');
        const selectedHobbies = [];
        checkboxes.forEach(function(checkbox) {
            if (checkbox.checked) {
                selectedHobbies.push(checkbox.value);
            }
        });
        return selectedHobbies;
    }

    // Function to update user details
    async function updateUserDetails(newUser) {
        const binId = 'xxaaxx'; // Replace with your bin ID
        const apiUrl = `https://api.jsonbin.io/v3/b/${binId}`;

        try {
            // Fetch existing user data
            const response = await fetch(apiUrl, {
                method: 'GET',
                headers: {
                    'X-Master-Key': 'xxxxxxxx' 
                }
            });

            if (response.ok) {
                const userData = await response.json();

                let updatedUser;
                if (userData.record) {
                    const existingUser = userData.record.data;
                    // Merge existing user data with new user data
                    updatedUser = {
                        ...existingUser,
                        ...newUser
                    };
                } else {
                    updatedUser = newUser;
                }

                // Update user details
                await fetch(apiUrl, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Master-Key': 'xxxxxxx' 
                    },
                    body: JSON.stringify({ data: updatedUser })
                });

                alert('User details updated successfully now!');
                form.reset(); // Clear the form after updating details
            } else {
                throw new Error('Failed to fetch existing user data');
            }
        } catch (error) {
            console.error(error);
            alert('Failed to update user details. Please try again later.');
        }
    }
});

use externally loaded rot.js with typescript, without bundling?

I would like to use external rot-js with typescript, without bundlers.
IE load rot-js from e.g. dist/rot.js, and compile my own ts code with TSC.
This causes conflicts both for TSC, for tsconfig.json, and for type resolution during editing.

If I specify nodenext/node moduleResolution in tsconfig, editor can happily see types, but TSC will try to generate require-imports for node, which is wrong both for the externally loaded rot-js, and for our browser context.
If I don’t specify nodenext as module-resolution, I may not use

import * as ROT from "rot-js";

or

import { Display } from "rot-js"; 

Without nodeNext, I could instead do

import * as ROT from "./node_modules/rot-js/dist/rot.js";

but it doesn’t appear to work/editor can’t see types,
and also it emits an ‘import’ in the js output.

rot-jslib actually DOES contain *.d.ts files,
and even index.d.ts. But I can’t seem
to actually import declarations from them..?
Display is exported in index.d.ts,
but if I try to import it directly, I get TS2846,
which says that declaration files can only be imported with
import type.
IF I try to import Display with

import type

I get the error that values can’t be resolved through
import type, so I can’t do e.g.
new Display(…)

If I try to install typings for rot-js, I get a dummy package
which proudly claims, that it is not necessary because
rot-js already has everything and already has typescript source.

I also tried to use triple-slash /// reference path/types, but this doesn’t seem to work either.

Maddeningly, VSCode intellisense seems to ‘know’ the syntax/properties for rot-js stuff, but feigns ignorance when I try to e.g. jump to a symbol. So first it says ‘yeah, there is an object called Display, and it takes these arguments’, but next thing it says ‘a constructor for Display? I know nothing about that, who told you that?”

It feels like a labyrinth of endless combinations that invariably make something else not work.
I read through SOs suggested earlier questions on this topic, but sadly they are mostly unsatisfactorily answered variants of my question here.
Also, this is a general issue I have with typings for external modules when working with typescript tooling, so the question is broader than rot-js.

I guess I could write my own declares from scratch for rot-js, but surely the existing tooling is supposed to already work, in a way I haven’t been able to figure out yet?

To sum up the problem, I ‘just’ want the types to be resolved/enforced, without emitting weird imports or requires. And I cannot figure out if that should come from *.d.ts files, or from actual typescript files, or..

Typings tooling with javascript is really hard to wrap your head around, unless you just close your eyes and use webpack :-/

Stop notification from duplicating

I am working on a bell notification. Notifications should appear in notification pop up when clicked bell icon and when user scrolls to the bottom it should send get request to the backend and fetch older notifications.

  1. If theres global notification, it will stick as 1st notification and rest of the personal notification appear below it.
    2)The Personal notification (notification that is not global), older ones should appear in the bottom and newer ones should appear in the top (without having to refresh the page).

The problem: newer notifications appear in the top but the same notification appear in the bottom as well. Example:

current notification box :H,G,F

new notifications has been added to the database -> updated notification box: I,H,G,F,I

scrolls to the bottom and older notifications get loaded ->updated notification box :I,H,G,F,I,E,D,C

refeshes the page ->current notification box: I,H,G

scrolls to the bottom and older notifications get loaded -> current notification box: I,H,G,F,E,D

As shown in example it works fine when refreshed the page but it shows duplicated when its not. Also any advice for the code is welcomed.

 $(document).ready(function() {

        var pageNumber =1;
        var displayNotificationOnId = [];
        var newNotificationIds = [];
        var loading = false;
        var loadDelay = 4000;

        var bellClickedToOpen = true;


        function getNewNotifications() {

            $.ajax({
                type:'GET',
                url:'/notifications?page=' + pageNumber,
                success: function (data) {
                    populateNotifications(data.notifications);
                    data.notifications.forEach(function(dta){
                        if (!newNotificationIds.includes(dta.id)) {
                            newNotificationIds.push(dta.id)

                        }
                    })
                    console.log(data)
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching new notifications:', error);
                }
            })
        }

        // $(document).ready(function() {
        $('#notificationDropdown').on('scroll', function() {
            var container = $(this);
            var scrollPosition = container.scrollTop();
            var containerHeight = container.innerHeight();
            var contentHeight = container[0].scrollHeight;

            var distanceBottom = contentHeight - (scrollPosition + containerHeight);

            var threshold = 50;
            // Check if the scroll position is near the bottom of the container
            if (distanceBottom <=threshold && !loading ) {

                loading = true


                $('#loading').show();
                console.log("inside if statement" + loading)

                setTimeout(function () {
                    console.log("reached bottom of the popup")
                    pageNumber +=1;
                    getNewNotifications(pageNumber); // Fetch new notifications when near the bottom
                    loading = false;
                    $('#loading').hide;

                }, loadDelay)

            }
        });
        // });


        function fetchNotificationCount () {
            $.ajax({
                url : '/notifications',
                method: 'GET',
                success: function (data) {
                    var notifications = data.notifications;
                    if(data.newNotificationsCount>0){
                        $('#notificationBadge').text(data.newNotificationsCount).show();
                        $("#readAll").removeClass("disabled-link");
                        console.log(">0" + data.newNotificationsCount);
                    } else {
                        $('#notificationBadge').hide();
                        $("#readAll").addClass("disabled-link");
                        console.log("else" + data.newNotificationsCount);
                    }
                    // $('#notificationBell').click(function() {
                    populateNotifications(notifications);

                }, error: function (xhr, status, error) {
                    console.error(error);
                }
            })
        }

        fetchNotificationCount();
        setInterval(fetchNotificationCount, 5000);


        function markSingleNotificationAsRead(id, read){

            console.log(id, read);


            var isUnread = read ===0;


            var buttonText = isUnread ? "Unread":"Read";

            var $button = $('.mark-as-read-btn[data-notification-id="' + id + '"]');

            $.ajax({
                url:`/notificationsRead/${id}`,
                method: 'POST',
                success: function(response) {
                    console.log("Notification marked as " + buttonText + " successfully");
                    $button.text(buttonText);

                },
                error:function (xhr, status, error) {
                    console.error('Error marking notification as read:', error);
                }
            })
        }

        function populateNotifications(notifications) {
            // var $notificationList = $('#notificationList');
            // $notificationList.empty(); // Clear existing notifications
            var globalNotificationDiv = $('#global-notification');
            var hasGlobalNotification = false;

            console.log(notifications);

            var globalNotifications = notifications.find(function (notification){
                return notification.type === 'global';
            })

            if (!globalNotifications) {
                // alert("hello")
                globalNotificationDiv.empty();
            }
            if(globalNotifications && !displayNotificationOnId.includes(globalNotifications.id)) {
                console.log(globalNotifications)
                // console.log(globalNotifications.expired)

                displayNotification(globalNotifications, true)
            }

            // notifications.forEach(function(notification) {

            for (var i=0; i<notifications.length; i++) {
                var notification = notifications[i];
                var buttonText = notification.read === 0 ? "Unread" : "Read";
                var notificationClass = notification.read === 0 ? "unread-notification" : "";

                if (!displayNotificationOnId.includes(notification.id)) {
                    displayNotification(notification, false);
                    console.log(displayNotificationOnId, notification.id);
                }
            }



            // });

            $('#notificationBell').click(function (){
                $('#notificationDropdown').show();

            })


        }



        function displayNotification (notification, isGlobal) {
            var $notificationList = $('#notificationList');
            var globalNotificationDiv = $('#global-notification');
            var greaterThanLargestId= false;

            var notificationRead = notification.read ===0 ? "unread-notification" : "";
            var disableClick = isGlobal ? "disable-globalNotification" : "";

            var daNotifications = `
                    <div class="list-group-item ${notificationRead} ${disableClick}"  >


                        <a  href= "${notification.url}" class="mainNotiHeader" data-notification-global="${notification.type}"   data-notification-id="${notification.id}" data-notification-read="${notification.read}" >
                            <div class = "notificationInfo">
                                <h4  class="list-group-item-heading">${notification.tool}</h4>
                                <p >${notification.created_at}</p>
                            </div>
                            <p class="list-group-item-text" >${notification.text}</p>
                        </a>



                    </div>

`;

            if (!displayNotificationOnId.includes(notification.id)) {

                for (var i = 0; i<displayNotificationOnId.length; i++){

                    if (notification.id >displayNotificationOnId[i]){
                        greaterThanLargestId = true;
                        break;
                    }

                }
                if (greaterThanLargestId) {


                    $notificationList.prepend(daNotifications);
                    greaterThanLargestId= false;
                    displayNotificationOnId.push(notification.id);


                }
            }

            if(isGlobal) {
                globalNotificationDiv.html(daNotifications);

            } else if (greaterThanLargestId === false) {
                console.log("!greaterThanLargestId: " +greaterThanLargestId  )
                $notificationList.append(daNotifications);
                displayNotificationOnId.push(notification.id);
                
            }
            if (isGlobal) {
                globalNotificationDiv.find('.disable-globalNotification').click(function (event){
                    event.preventDefault();
                })
            }

            console.log("line 494" + displayNotificationOnId);


        }

Next.js vercel open graph image rendering

I want to share user profile to socials, I want to do that by just pasting in a link and it will render this “card” and it looks nice and have some data inside. I am using nextjs and I have component in /api folder (I use page router version) for this and Open Graph image render. The problem is that because I need to get profile data first (I cannot pass it through params to /api component) and additionally I have to fetch some external images it takes sometimes 4-5 seconds to load the image. The problem is that when I paste a profile link to twitter and wait few seconds the “card” preview does not load. I have to paste it few times to actually load the data. I’ve tried to put all the images to my project files and fetch it instead of making external requests but it does not work because edge functions have limit to 2mb. I was able to speed image loading to like 3-4 seconds but its still not enough for twitter to load it correctly.
I have no idea how to fix this
and its a very important feature to let people just copy paste user link and get his statistics

Python + JavaScript good? [closed]

I learned python and I’m good on python but is python good choice to use it with JavaScript(React + Next.js)

And I use Python(Django + FastApi) as a backend lib

Is JavaScript(React+Next.js) good with Python(Django + FastApi) as freelancer

I tried to search about that thing and every web and video say “everything is good” but I need to search it for a free lance work

Bootstrap ‘needs-validation’ not Triggering on Form Submission

I have a PHP file index.php containing a form with Bootstrap’s needs-validation class, but it seems that the validation isn’t being triggered upon form submission. Here’s my index.php file:

<!DOCTYPE html>
<html lang="de">

<head>
    <?php include_once __DIR__ . '/src/php/head.php' ?>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="src/css/login.css">
</head>

<body>
    <div class="container">
        <div id="box">
            <h1>Login</h1>
            <form method="POST" action="src/php/login.php" class="row g-4 needs-validation" id="loginForm" novalidate>
                <div class="col-sm-12">
                    <label for="username" class="form-label">Benutzername: *</label>
                    <input type="text" class="form-control" id="username" name="username" required>
                    <div class="invalid-feedback">
                        Benutzername ist erforderlich
                    </div>
                </div>
                <div class="col-sm-12">
                    <label for="password" class="form-label">Passwort: *</label>
                    <input type="text" class="form-control" name="password" id="password" required>
                    <div class="invalid-feedback">
                        Passwort ist erforderlich
                    </div>
                </div>
                <button class="btn btn-primary rounded-pill px-3" type="submit">Login</button>
            </form>
            <div id="register">
                <a href="users/create">Registrieren</a>
            </div>
        </div>
    </div>
</body>
<?php include_once 'src/php/footer.php' ?>
<script src="src/js/login.js"> </script>

</html>

Additionally, here’s my head.php file:

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href=https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css rel="stylesheet"
    integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

And footer.php:

<script src=https://code.jquery.com/jquery-3.7.1.min.js
    integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script src=https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js
    integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous">
</script>

Despite having the needs-validation class on the form, it doesn’t seem to trigger validation when I submit the form. What could be causing this issue, and how can I fix it?

mistake in using id in react in html

слушайте вы случайно не знаете, как убрать ошибку? поставил на div id- что бы по клику кнопки осуществлялся переход на данное место в странице. но id выделяется как ошибка -Тип “{ children: (“” | Element | undefined)[]; id: string; className: string; }” не может быть назначен для типа “DetailedHTMLProps<HTMLAttributes, HTMLDivElement>”.
Свойство “id” не существует в типе “DetailedHTMLProps<HTMLAttributes, HTMLDivElement>”.ts(2322). пока локально все запущено, то все работает, хоть и выделяется красным. при билде выходит ошибка с этим id. не пойму как исправить. приложение на react typescript

не нагуглил ничего что бы помогло

How to make deeplink ionic for ios correct?

I was developing a hybrid mobile application for Android/iOS using Nuxt 3, TypeScript, and Ionic. My app serves as an online store. During the payment process, the application redirects users to the epay Halyk website, and when the ‘back’ button is pressed, it should lead back to our application.

This functionality works well on Android devices and in the Xcode emulator. However, when I build it for TestFlight and the App Store, it doesn’t work. I’m not sure why this issue is occurring.

      window.halyk.pay({
            ...response.data,
            backLink:        'https://m.smartdeal.kz',
            failureBackLink: 'https://m.smartdeal.kz',
            postLink:        response.data.postLink,
        });

Why setting the state inside a fetch callback (doesn’t) cause an infinite loop?

I have the following code snippet, and I expected it to result in an infinite loop due to a state update inside a fetch callback inside the body of the component without using ‘useEffect’. However, it’s not behaving as expected. Here’s the code:

function App() {
  const [cartContent, setCartContent] = useState(null);

  fetch("https://fakestoreapi.com/carts/6")
    .then((resp) => resp.json())
    .then((data) => {
      setCartContent("test");
    });

  console.log(cartContent);

  return <div className="cartContent">{cartContent}</div>;
}

export default App;

My understanding was that console.log(cartContent) should log the initial value of cartContent, then when setCartContent(“test”) is called inside the fetch callback, it should log “test”, and this process should repeat indefinitely, creating an infinite loop.

Could someone please help me understand why this code doesn’t result in an infinite loop as expected? Any insights or explanations would be greatly appreciated. Thank you!

How to use Webpack with Github actions to deploy multiple websites

I am building a fairly simple website using Webpack for customer_A. I would like to now use a template to allow me to build the same website for customer_B, customer_C etc. What would be a good Webpack tool to do this with for a simple HTML, CSS and JS website?

The second part is how is this best achieved. Is there a way that Webpack itself can be used to build multiple websites each with its own dist folder or would it be best to call Webpack in the Github actions pipeline multiple times in a for loop and pass in each customer’s specific parameters?

I have been using Webpack and JS for a few days now so don’t have much experience in this area.

Which algorithm to downsample a 2D array of values to save space in js

I’m working with 1D and 2D arrays containing values for plotting heatmaps.
Some datasets can containing thousands of values which represent millions of values in the matrix. I’d like to try some downsampling/compression methods with some parameters to save space on disk and still be able to plot everything.

I have 3 arrays, X and Y being 1D and Z being 2D (of dimension X*Y).

I already have a downsampling method, which basically removes every k-th value, it works on huge datasets but I could lose some valuable information without any smart processing.