Why does the Promise executor *specification* need it to call `resolve` and `reject`, rather than return or throw an error like “then” callbacks?

According to MDN’s documentation on Promise.prototype.then, this is how then callback functions return values are processed:

The behavior of the returned promise (call it p) depends on the handler’s execution result, following a specific set of rules. If the handler function:

  • returns a value: p gets fulfilled with the returned value as its value.
  • doesn’t return anything: p gets fulfilled with undefined as its value.
  • throws an error: p gets rejected with the thrown error as its value.
  • returns an already fulfilled promise: p gets fulfilled with that promise’s value as its value.
  • returns an already rejected promise: p gets rejected with that promise’s value as its value.
  • returns another pending promise: p is pending and becomes fulfilled/rejected with that promise’s value as its value immediately after that promise becomes fulfilled/rejected.

If then callbacks (onFulfilled and onRejected) work like that, why does the Promise constructor callback (executor) not?

Suppose the Promise constructor were to take an executor that works just like then callbacks do. The constructor itself would return a promise, while the executor would return a promise or throw an error that’d be captured and assimilated by the constructor, just like an error thrown inside a then callback is captured and assimilated by the then method. The only difference would be that the executor would’ve had to be parameterless, since it’d be the first time resolving the Promise, while then callbacks take the previous result as their parameter.

I feel like there’s more cognitive load when using functions that end in the same place (return a new promise object to be settled, which the Promise constructor and then do) but get there through different paths (the executor takes and calls resolve or error, while onFulfilled and onRejected have to return the resolved value or throw an error). Why couldn’t the executor function use keywords like return and throw that were already there and are used by then callbacks?


I found a question that I thought would answer this (Why does the Promise constructor require a function that calls ‘resolve’ when complete, but ‘then’ does not – it returns a value instead?), but the answers boil down to explanations that they are different instead of why they are different. I wish I could comment there to ask for more, but I don’t have enough reputation.

Another question that could’ve answered this: Why functions as arguments (resolve, reject) are used in the Promise syntax rather than a simple return and throw?. There’s no answer, but there’s misunderstandings and discussion in the comments. The conclusion is that you’re able to delay the resolving of a promise with setTimeout. When is that ever useful besides demonstrating how promises work? It’s also said to be a duplicate, but the previous questions provided have nothing to do with what was asked. The first one just asserts that I can’t use throw in the executor. I know that already, but not why it was made like that! The second one answer why variables declared outside but defined inside promises remain undefined.

Je vous demande comment je peux recevoir du rémunération [closed]

Pondant 4 ans je gagne aucune rémunération

Bonjour, tout le monde
J’aimerais bien savoir plus et nous sommes déjà en train de travailler ensemble mais il me faut un salaire pour vivre comment trouver l’ audace, dynamique sur notre domaine de l’informatique, compétences,et Éducation, nationale de commerce, culture du monde, médecine générale

Security Middleware Issues

I am trying to provision for X-Content-Type-Options and X-Frame-Options in js, i.e.


    const upload = multer();
    app.use(bodyParser.json());
    app.use(upload.any());
    app.use(cors({ origin: "*" }));
    app.use(helmet());

    app.use((req, res, next) => {
      res.setHeader('X-Content-Type-Options', 'nosniff');
      next();
     });

app.use(
  helmet({
    xFrameOptions: { action: "sameorigin" },
  }),
);
app.use((req, res, next) => {
  req.clientIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
  next();
});

They don’t get executed until my app.post(“/subscribe … request is triggered (confirmed by temporarily putting console.log inside the ap.use. I also do not see the headers being added using the Network . Headers tab in the Chrome Dev tools.

I’ve read the mdn content and went down the ChatGPT rabbithole. Any help would be appreciated.

I tried putting console.log inside the app.use. They don’t get executed until the app.post and even then I do not see the headers in the Network > Header tabe in the Chrome Dev tools. I’ve tried adding a get request as suggested by ChatGPT, but that did not work either.

I also looked for Stackover and Reddit posts but did not find anything useful.

Add carousel to ASP.NET MVC project using javascript and Glide.js

I want to add a carousel to my .cshtml page. I’m trying to do it by using javascript withe the Glide.js library. This tutorial does exactly what I’m trying to achieve, except I’m trying to replicate it in an ASP.NET project.

I installed node.js using nuget, then I installed the Glide.js library in my wwwroot directory using LibMan (as described here).
Next I added the following code to my .cshtml file:

<div class="container" style="width:300px">
    <div class="glide">
        <div class="glide__track" data-glide-el="track">
            <ul class="glide__slides">
                <li class="glide__slide">0</li>
                <li class="glide__slide">1</li>
                <li class="glide__slide">2</li>
            </ul>
        </div>
        <div class="glide__arrows" data-glide-el="controls">
            <button class="glide__arrow glide__arrow--left" data-glide-dir="<">prev</button>
            <button class="glide__arrow glide__arrow--right" data-glide-dir=">">next</button>
        </div>
    </div>
</div>

<script src="@Url.Content("~/Glide.js/glide.min.js")"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const config = {
            type: 'carousel',
            perView: 3,
        };
        new Glide('.glide', config).mount();
    });
</script>

I also linked the css stylesheet in _Layout.cshtml using this line:
<link rel="stylesheet" href="~Glide.js/css/glide.core.min.css"/>
I’m trying to achieve a carousel that alternates between 3 elements but the result is as shown in the picture below and the buttons only move the column to the left and right.
enter image description here
What do I need to change to get the same result in ASP.NET as in javascript?

How is property order determined when using a spread operator on a JS object [duplicate]

I am using the spread operator and with the below code get expected results as far as element order in the resulting object

const morning = {
    breakfast: "oatmeal",
    lunch: "Peanut butter and jelly"
}

const dinner = "mac and cheese";

const backPackingMeals = {
    ...morning, 
    dinner
};

console.log(backPackingMeals);

//output:
/*{
    breakfast: 'oatmeal',
    lunch: 'Peanut butter and jelly',
    dinner: 'mac and cheese'
  }*/

The above is expected, it outputs the properties in the order they were added.
In the below though the output order is unexpected:

const backPackingMeals = {
    ...morning, 
    ...dinner
};

//result
/*{
  '0': 'm',
  '1': 'a',
  '2': 'c',
  '3': ' ',
  '4': 'a',
  '5': 'n',
  '6': 'd',
  '7': ' ',
  '8': 'c',
  '9': 'h',
  '10': 'e',
  '11': 'e',
  '12': 's',
  '13': 'e',
  breakfast: 'oatmeal',
  lunch: 'Peanut butter and jelly'
}*/

Not asking why dinner is broken into an array of letters but why that array prints before the ‘breakfast’ and ‘lunch’ properties

EventListener in Web Worker is blocked by while(true) loop

So I’m writing an emulator using html/javascript.

I have an index.html handling the gui, and a Web Worker where the emulator runs.

The Emulator works with a while(true) emulating the cpu cycles, started by pressing the “start” button in index.html

But when the while(true) starts, the EventListener is blocked and I cant send PostMessages anymore.

Before the while(true) starts, the postMessages are sent correctly.

Here is a working example:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web Worker Example</title>
</head>
<body>
  <button id="sendMessageButton">Start Worker</button>
  <button id="sendMessageButton1">Send Message to Worker</button>

  <script>
    const worker = new Worker('worker.js');

    document.getElementById('sendMessageButton').addEventListener('click', () => {
      // Send a message to the worker
      worker.postMessage('start');
    });

    document.getElementById('sendMessageButton1').addEventListener('click', () => {
      // Send a message to the worker
      worker.postMessage('mex');
    });

    // Listen for messages from the worker
    worker.addEventListener('message', (event) => {
      if(event.data === "MEX")
      {
        console.log("MEX...")
      }
    });
  </script>
</body>
</html>

worker.js

// Listen for messages from the main page
self.addEventListener('message', function(event) {
    
    console.log("EVENT: "+event)
    
    if(event.data === "mex")
    {
        self.postMessage("MEX");
    }
    if(event.data === "start")
    {
        console.log("start")
        while(true);
    }
});

How can I avoid the while(true) blocking the postMessages? I would prefer to not use setInterval or setTimeout, because the emulator would be too slow.

I keep getting this 404 error when trying to update my password. Even though my endpoint exists. Anyone might have an idea why this is happening?

I have multiple routes that are used to change details of a users account. One is specifically made to change the password for the user. However, no matter what I do, I always get a 404 error telling me the route doesnt exist even though it does. I’ll provide the 3 files that I think are related to this issue.

Note: I use the same button to update the user’s info whether it’s name, email or password. But the button changes its function depending on the tab that is active.

comptepersonnel.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/styles.css">
    <title>Mon Compte</title>
    <style>
        /* Add styles specific to comptepersonnel page here */
        #comptepersonnel .input-field {
            border: 1px solid #cccccc; /* Ensure border is visible */
            background-color: #ffffff; /* Ensure background is white */
            color: #333333; /* Text color for input */
        }

        #comptepersonnel .input-field::placeholder {
            color: #aaaaaa; /* Placeholder text color */
        }

        /* Additional specific styles */
        #comptepersonnel .input-wrapper {
            display: block; /* Ensure wrappers are visible */
        }

        #comptepersonnel .warning-message {
            display: none; /* Hide warning messages by default */
            color: #d9534f; /* Style for warning messages */
            font-size: 0.8em;
            margin-top: 4px;
        }
    </style>
</head>
<body id="comptepersonnel">
 <div class="wrapper">
    <video id="video1" src="/Background_Video_Connection.mp4" autoplay muted loop plays-inline class="back-video"></video>
    <nav class="nav">
        <div class="nav-logo">
            <p>Clipper Link MTL .</p>
        </div>
        <div class="nav-menu" id="navMenu" style="right : 20%;">
            <ul>
                <li><a href="acceuil.html" class="link">Acceuil</a></li>
                <li><a href="Salons.html" class="link">Services</a></li>
                <li><a href="Apropos.html" class="link">À propos</a></li>
                <li><a href="contact.html" class="link">Contact</a></li>
                <li><a href="inscription.html" class="link">Connexion/Inscription</a></li>
            </ul>
        </div>
        <div class="nav-button" style="visibility: hidden" disabled>
            <button class="btn white-btn" id="loginBtn" onclick="login()">Connexion</button>
            <button class="btn" id="registerBtn" onclick="register()">Inscription</button>
        </div>
        <div class="nav-menu-btn" style="visibility: hidden" disabled>
            <i class="bx bx-menu" onclick="myMenuFunction()"></i>
        </div>
    </nav>

    <body>  
        <div class="container light-style flex-grow-1 container-p-y">
            <div class="card overflow-hidden">
                <div class="row no-gutters row-bordered row-border-light">
                    <div class="col-md-3 pt-0">
                        <div class="list-group list-group-flush account-settings-links">
                            <a class="list-group-item list-group-item-action active" data-toggle="list"
                            href="#account-compte">Mon Compte</a>
                            <a class="list-group-item list-group-item-action" data-toggle="list"
                                href="#account-mdp">Changer Mot de Passe</a>
                            <a class="list-group-item list-group-item-action" data-toggle="list"
                                href="#account-reservation">Réservation</a>
                            <a class="list-group-item list-group-item-action" data-toggle="list"
                                href="#account-favoris">Favoris</a>
                            <a class="list-group-item list-group-item-action" id="deconnecter" 
                            href="javascript:void(0);">Déconnecter</a>

                        </div>
                    </div>
                    <div class="col-md-9">
                        <div class="tab-content">
                            <div class="tab-pane fade active show" id="account-compte">
                                <div id="messageContainerAccount" class="message-container"></div>
                                <hr class="border-light m-0">
                                <div class="card-body">
                                    <div class="form-group">
                                        <label class="form-label">Prénom</label>
                                        <div class="input-wrapper">
                                            <input type="text" id="inputFirstName" class="form-control mb-1 input-field" value="" required pattern="[a-zA-Z-]+">
                                            <span class="warning-message"></span>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Nom</label>
                                        <div class="input-wrapper">
                                            <input type="text" id="inputLastName" class="form-control input-field" value="" required pattern="[a-zA-Z-]+">
                                            <span class="warning-message"></span>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Courriel</label>
                                        <div class="input-wrapper">
                                            <input type="email" id="inputEmail" class="form-control mb-1 input-field" value="" required pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$">
                                            <span class="warning-message"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="account-mdp">
                                <div id="messageContainerPassword" class="message-container"></div>
                                <div class="card-body pb-2">
                                    <div class="form-group">
                                        <label class="form-label">Mot de passe actuel</label>
                                        <div class="input-wrapper">
                                            <input type="password" id="currentPasswordInput" class="form-control input-field" required pattern="(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
                                            <span class="warning-message"></span>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Nouveau mot de passe</label>
                                        <div class="input-wrapper">
                                            <input type="password" id="newPasswordInput" class="form-control input-field" required pattern="(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
                                            <span class="warning-message"></span>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Répétez le nouveau mot de passe</label>
                                        <div class="input-wrapper">
                                            <input type="password" id="repeatNewPasswordInput" class="form-control input-field" required pattern="(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
                                            <span class="warning-message"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="account-reservation">
                            </div>
                            <div class="tab-pane fade" id="account-favoris">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="text-right mt-3">
                <button type="submit" id="saveButton" class="btn btn-primary">Sauvegarder</button>
                <button type="button" class="btn btn-default">Annulé</button>
            </div>
        </div>
        <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
        <script src="/comptepersonnel.js"></script>
    </body>
    </html>

comptepersonnel.js:

document.addEventListener("DOMContentLoaded", function() {
    var token = sessionStorage.getItem("token");

    // Gestion des changements de navigation
    if (token) {
        var button = document.querySelector(".nav-menu .link[href='inscription.html']");
        if (button) {
            button.textContent = "Mon Compte";
            button.href = "comptepersonnel.html";
            button.classList.add("active");
        }
    }

    // Récupération et affichage des données utilisateur
    fetchUserData();

    // Définition d'un moment aléatoire pour la vidéo
    setRandomVideoTime();

    // Validation des champs de saisie lors de la saisie
    document.querySelectorAll('.input-field').forEach(input => {
        input.addEventListener('input', validateInput);
    });

    // Écouteur d'événement pour le bouton de sauvegarde
    document.getElementById('saveButton').addEventListener('click', function(event) {
        event.preventDefault();
        // Vérification de l'onglet actif
        if (document.getElementById('account-mdp').classList.contains('active')) {
            // L'onglet Changer le mot de passe est actif
            if (validatePasswordChangeForm()) {
                submitPasswordChange();
            }
        } else {
            // L'onglet Mon Compte est actif
            if (validateForm()) {
                updateAccount();
            }
        }
    });

    // Fonctionnalité de déconnexion
    const deconnecterBtn = document.getElementById('deconnecter');
    if (deconnecterBtn) {
        deconnecterBtn.addEventListener('click', () => {
            sessionStorage.removeItem('token');
            window.location.href = 'acceuil.html';
        });
    }
});

function setRandomVideoTime() {
    const video = document.getElementById('video1');
    if (video && video.duration) {
        video.currentTime = Math.random() * video.duration;
    }
}

function fetchUserData() {
    const token = sessionStorage.getItem('token');
    fetch('/api/account', {
        method: 'GET',
        headers: { 'Authorization': `Bearer ${token}` }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('La réponse du réseau n'était pas correcte: ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        document.querySelector('#inputFirstName').value = data.firstName;
        document.querySelector('#inputLastName').value = data.lastName;
        document.querySelector('#inputEmail').value = data.email;
    })
    .catch(error => {
        console.error('Erreur lors de la récupération des données du compte:', error);
    });
}

function updateAccount() {
    const userData = {
        firstName: document.querySelector('#inputFirstName').value,
        lastName: document.querySelector('#inputLastName').value,
        email: document.querySelector('#inputEmail').value,
        token: sessionStorage.getItem('token')
    };

    fetch('/api/account/update', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(userData)
    })
    .then(response => response.json())
    .then(data => {
        if(data.success) {
            displayMessage('Compte mis à jour avec succès', 'success');
        } else {
            throw new Error(data.message);
        }
    })
    .catch(error => {
        console.error('Erreur lors de la mise à jour du compte:', error);
        displayMessage('Échec de la mise à jour du compte', 'error');
    });
}

function validatePasswordChangeForm() {
    let isValid = true;
    const currentPassword = document.querySelector('#currentPasswordInput').value;
    const newPassword = document.querySelector('#newPasswordInput').value;
    const repeatNewPassword = document.querySelector('#repeatNewPasswordInput').value;

    // Validation du mot de passe actuel
    if (!currentPassword || !currentPassword.match(/(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)) {
        displayWarning('currentPasswordInput', 'Le mot de passe actuel est invalide.');
        isValid = false;
    }
    // Validation du nouveau mot de passe
    if (!newPassword || !newPassword.match(/(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)) {
        displayWarning('newPasswordInput', 'Le nouveau mot de passe doit contenir au moins 8 caractères, dont un chiffre, une lettre minuscule et une lettre majuscule.');
        isValid = false;
    }
    // Vérification de la correspondance des nouveaux mots de passe
    if (newPassword !== repeatNewPassword) {
        displayWarning('repeatNewPasswordInput', 'Le nouveau mot de passe ne correspond pas.');
        isValid = false;
    }

    return isValid;
}

function submitPasswordChange() {
    const currentPassword = document.querySelector('#currentPasswordInput').value;
    const newPassword = document.querySelector('#newPasswordInput').value;
    const token = sessionStorage.getItem('token');

    const passwordData = { currentPassword, newPassword, token };

    fetch('/api/account/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(passwordData)
    })
    .then(handleResponse)
    .then(handleData)
    .catch(handleError);
}

function handleResponse(response) {
    if (!response.ok) {
        throw new Error(`Erreur HTTP! status: ${response.status}`);
    }
    return response.json();
}

function handleData(data) {
    if (data.success) {
        displayMessage('Mot de passe changé avec succès.', 'success');
    } else {
        displayMessage(data.message, 'error');
    }
}

function handleError(error) {
    console.error('Erreur lors du changement de mot de passe:', error);
    displayMessage('Échec du changement de mot de passe', 'error');
}

function validateInput(event) {
    const input = event.target;
    const inputWrapper = input.closest('.input-wrapper');
    const warningMessage = inputWrapper.querySelector('.warning-message');
    const pattern = input.getAttribute('pattern');

    if (pattern) {
        const regex = new RegExp(pattern);
        if (!regex.test(input.value)) {
            warningMessage.textContent = getMessageAvertissement(input.id, input.value);
            warningMessage.style.display = 'block';
        } else {
            warningMessage.style.display = 'none';
        }
    }
}

function validateForm() {
    let isValid = true;
    const firstName = document.querySelector('#inputFirstName').value;
    if (firstName.length < 2) {
        displayWarning('inputFirstName', 'Le prénom doit contenir au moins 2 caractères.');
        isValid = false;
    }

    const lastName = document.querySelector('#inputLastName').value;
    if (lastName.length < 2) {
        displayWarning('inputLastName', 'Le nom doit contenir au moins 2 caractères.');
        isValid = false;
    }

    const email = document.querySelector('#inputEmail').value;
    if (!email.includes('@')) {
        displayWarning('inputEmail', 'L'adresse email n'est pas valide.');
        isValid = false;
    }

    return isValid;
}

function displayWarning(inputId, message) {
    const warningElement = document.querySelector('#' + inputId + ' + .warning-message');
    warningElement.textContent = message;
    warningElement.style.display = 'block';
}

function getMessageAvertissement(inputId, inputValue) {
    switch(inputId) {
        case 'inputFirstName':
            return 'Prénom invalide.';
        case 'inputLastName':
            return 'Nom invalide.';
        case 'inputEmail':
            return 'Format de l'email invalide.';
    }
}

function displayMessage(message, type) {
    const messageContainerId = document.getElementById('account-mdp').classList.contains('active') ? 'messageContainerPassword' : 'messageContainerAccount';
    const messageElement = document.getElementById(messageContainerId);
    if (messageElement) {
        messageElement.textContent = message;
        messageElement.className = type;
        messageElement.style.display = 'block';
    } else {
        console.error('Message container not found');
    }
}

serveur.js:

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const knex = require('knex')({
    client: 'sqlite3',
    connection: {
        filename: './mydatabase.db'
    },
    useNullAsDefault: true
});

const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'PageHTML')));

// Home page route
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'PageHTML', 'acceuil.html'));
});

// Salon information route
app.get('/salons', (req, res) => {
    knex.select().from('UtilisateurEntreprise')
        .then(salons => res.json(salons))
        .catch(err => res.status(500).json({ error: 'Error retrieving salons: ' + err }));
});

// Static page for salons
app.get('/salons-html', (req, res) => {
    res.sendFile(path.join(__dirname, 'PageHTML', 'Salons.html'));
});

// User registration
app.post('/register', (req, res) => {
    const { firstName, lastName, email, password } = req.body;
    if (!validatePassword(password)) {
        return res.status(400).json({ success: false, message: "Password does not meet criteria." });
    }

    const uniqueToken = require('crypto').randomBytes(50).toString('hex');

    knex('UtilisateurClient').insert({
        Nom: lastName,
        Prenom: firstName,
        Courriel: email,
        MotDePasse: password,  // Store password as plain text
        UniqueToken: uniqueToken
    })
    .then(() => res.json({ success: true, message: "User successfully registered." }))
    .catch(err => {
        if (err.message.includes('UNIQUE constraint failed')) {
            res.status(409).json({ success: false, message: "Email already in use." });
        } else {
            res.status(500).json({ success: false, message: "An error occurred: " + err });
        }
    });
});

// Password validation
function validatePassword(password) {
    const regex = /(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*W).{8,}/;
    return regex.test(password);
}

// User login
app.post('/login', (req, res) => {
    const { email, password } = req.body;
    knex('UtilisateurClient')
        .select('MotDePasse', 'UniqueToken')
        .where({ Courriel: email })
        .first()
        .then(user => {
            if (!user) {
                return res.status(401).json({ success: false, message: 'Email not registered.' });
            }
            if (user.MotDePasse !== password) {
                return res.status(401).json({ success: false, message: 'Incorrect password.' });
            }
            res.json({ success: true, message: 'Login successful.', token: user.UniqueToken });
        })
        .catch(err => res.status(500).json({ success: false, message: 'Error during login: ' + err }));
});

// Fetch user account data
app.get('/api/account', (req, res) => {
    const token = req.headers['authorization']?.split(' ')[1];
    if (!token) {
        return res.status(401).send('No token provided');
    }

    knex('UtilisateurClient')
        .where({ UniqueToken: token })
        .first()
        .then(user => {
            if (!user) {
                return res.status(404).send('User not found');
            }
            res.json({
                firstName: user.Prenom,
                lastName: user.Nom,
                email: user.Courriel
            });
        })
        .catch(error => res.status(500).send('Internal server error: ' + error));
});

// Update user account
app.post('/api/account/update', (req, res) => {
    const { firstName, lastName, email, token } = req.body;
    knex('UtilisateurClient')
        .where({ UniqueToken: token })
        .first()
        .then(user => {
            if (!user) {
                return res.status(404).json({ success: false, message: "User not found" });
            }
            knex('UtilisateurClient')
                .where({ IdClient: user.IdClient })
                .update({
                    Prenom: firstName || user.Prenom,
                    Nom: lastName || user.Nom,
                    Courriel: email || user.Courriel
                })
                .then(() => res.json({ success: true }))
                .catch(err => res.status(500).json({ success: false, message: 'Failed to update user: ' + err }));
        })
        .catch(err => res.status(500).json({ success: false, message: 'User retrieval failed: ' + err }));
});

// Route pour changer le mot de passe
app.post('/api/account/change-password', (req, res) => {
    const { token, currentPassword, newPassword } = req.body;

    if (!token) {
        return res.status(401).json({ success: false, message: 'Token non fourni.' });
    }

    // Trouver l'utilisateur par token
    knex('UtilisateurClient')
        .where({ UniqueToken: token })
        .first()
        .then(user => {
            if (!user) {
                return res.status(404).json({ success: false, message: 'Utilisateur non trouvé.' });
            }

            // Comparer le mot de passe actuel (ici sans hachage)
            if (user.MotDePasse !== currentPassword) {
                return res.status(401).json({ success: false, message: 'Mot de passe actuel incorrect.' });
            }

            // Mettre à jour le mot de passe avec le nouveau mot de passe en clair
            knex('UtilisateurClient')
                .where({ UniqueToken: token })
                .update({ MotDePasse: newPassword })
                .then(() => {
                    res.json({ success: true, message: "Mot de passe mis à jour avec succès." });
                })
                .catch(err => {
                    console.error('Erreur lors de la mise à jour du mot de passe:', err);
                    res.status(500).json({ success: false, message: "Une erreur s'est produite lors de la mise à jour du mot de passe." });
                });
        })
        .catch(err => {
            console.error('Erreur lors de la récupération de l’utilisateur:', err);
            res.status(500).json({ success: false, message: 'Erreur interne du serveur.' });
        });
});


app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

The console log error:

If anything else is needed let me know!

I have tried changing the names of the route. Changing the methods used to change the password and even completely reset the database so that it doesn’t use a hashed password.

I’m just trying to make it so that the Current password and changed to the new password that the user submits.

StackOverflowError null springboot

I want to build a page that makes a request to the backend to get some data, but i have a problem fetching those results. I will attach the error and all the code that is involved:

java.lang.StackOverflowError: null
    at java.base/java.lang.ClassLoader.defineClass1(Native Method) ~[na:na]
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017) ~[na:na]
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150) ~[na:na]
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:862) ~[na:na]
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:760) ~[na:na]
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:681) ~[na:na]
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:639) ~[na:na]
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:525) ~[na:na]
    at com.fasterxml.jackson.databind.JsonMappingException.prependPath(JsonMappingException.java:455) ~[jackson-databind-2.15.3.jar:2.15.3]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:790) ~[jackson-databind-2.15.3.jar:2.15.3]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.15.3.jar:2.15.3]

JS function:

function getAppointments(button) {
        const day = button.getAttribute('data-day');
        const month = button.getAttribute('data-month');
        const year = button.getAttribute('data-year');

        fetch(`/getAppointments?day=${day}&currentMonth=${month}&currentYear=${year}`)
            .then(response => response.json())
            .then(data => {

                // Afiseaza rezultatul in div-ul 'appointments'
                const appointmentsDiv = document.getElementById('appointments');
                appointmentsDiv.innerHTML = ''; // Sterge continutul anterior

                // Construiește div-uri pentru fiecare programare
                data.forEach(appointment => {

                    const appointmentDiv = document.createElement('div');
                    appointmentDiv.classList.add('appointment');

                    // Adaugă numele și prenumele, bolduite
                    const nameDiv = document.createElement('div');
                    nameDiv.innerHTML = `<strong>${appointment.patientProfile.lastName}, ${appointment.patientProfile.firstName}</strong>`;
                    appointmentDiv.appendChild(nameDiv);

                    // Adaugă data și ora
                    const dateTimeDiv = document.createElement('div');
                    dateTimeDiv.textContent = `Date & Time: ${appointment.appointmentDate}, ${appointment.appointmentHour}`;
                    appointmentDiv.appendChild(dateTimeDiv);

                    // Adaugă detalii
                    const detailsDiv = document.createElement('div');
                    detailsDiv.textContent = `Details: ${appointment.details}`;
                    appointmentDiv.appendChild(detailsDiv);

                    // Verifică valoarea lui fulfilled și adaugă butonul corespunzător
                    const fulfilledDiv = document.createElement('div');
                    fulfilledDiv.classList.add('fulfilled');
                    if (appointment.fulfilled) {
                        fulfilledDiv.textContent = "Fulfilled";
                    } else {
                        const button = document.createElement('button');
                        button.textContent = "Fulfill";
                        button.addEventListener('click', () => markAsFulfilled(appointment.id));
                        fulfilledDiv.appendChild(button);

                        const prescriptionButton = document.createElement('button');
                        prescriptionButton.textContent = "Create Prescription";
                        prescriptionButton.addEventListener('click', () => redirectToPrescriptionCreation(appointment.id));
                        appointmentDiv.appendChild(prescriptionButton);
                    }
                    appointmentDiv.appendChild(fulfilledDiv);

                    // Adaugă div-ul cu programarea în div-ul principal
                    appointmentsDiv.appendChild(appointmentDiv);
                });
            })
            .catch(error => console.log('Error fetching appointments:', error));
    }

backend code:

@GetMapping("/getAppointments")
    @ResponseBody
    public List<Appointment> getAppointments(@RequestParam int day, @RequestParam int currentMonth, @RequestParam int currentYear){
        return calendarService.getAppointments(day, currentMonth, currentYear);
    }


@Override
    public List<Appointment> getAppointments(int day, int currentMonth, int currentYear) {
        DoctorProfile doctorProfile = doctorProfileRepository.findByUserId(userService.getAuthenticationUser().getId());
        LocalDate localDate = LocalDate.of(currentYear, currentMonth, day);
        return appointmentRepository.findAllByDoctorProfileIdAndAppointmentDate(doctorProfile.getId(), localDate);
    }

The getAppointments function retur if alright, so it is not a problem coming from database. I have to mention that i have overrided the hashCode function.

@Table
@Entity
@Data
public class Appointment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(columnDefinition = "boolean default false")
    private boolean fulfilled;

    @Column(name = "appointment_date")
    private LocalDate appointmentDate;

    @Column(name = "appointment_hour")
    private LocalTime appointmentHour;

    private String details;

    @ManyToOne
    @JoinColumn(name ="doctor_id")
    private DoctorProfile doctorProfile;

    @ManyToOne
    @JoinColumn(name="patient_id")
    private PatientProfile patientProfile;

    @OneToOne(mappedBy = "appointment", cascade = CascadeType.ALL)
    private Prescription prescription;

    public Appointment(DoctorProfile doctorProfile, PatientProfile patientProfile){
        this.doctorProfile = doctorProfile;
        this.patientProfile = patientProfile;
    }

    public Appointment(){}

    // Pentru clasa Appointment
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + (fulfilled ? 1231 : 1237);
        result = prime * result + ((appointmentDate == null) ? 0 : appointmentDate.hashCode());
        result = prime * result + ((appointmentHour == null) ? 0 : appointmentHour.hashCode());
        result = prime * result + ((details == null) ? 0 : details.hashCode());
        result = prime * result + ((doctorProfile == null || doctorProfile.getId() == 0) ? 0 : doctorProfile.getId());
        result = prime * result + ((patientProfile == null || patientProfile.getId() == 0) ? 0 : patientProfile.getId());
        return result;
    }

    @Override
    public String toString() {
        return "Appointment{" +
                "id=" + id +
                ", fulfilled=" + fulfilled +
                ", appointmentDate=" + appointmentDate +
                ", appointmentHour=" + appointmentHour +
                ", details='" + details + ''' +
                '}';
    }
}```



----------------------

How can I add a dropdown menu to select which file you want to play with ruffle flash player?

So I have a website and I have a folder called “swf” with a bunch of .swf files.

What I want to do is make a webpage where you can select a file from a drop down menu and ruffle will play it.

the code to play a file using ruffle is:

<div id="container"> </div>
<script src="ruffle/ruffle.js"></script>
<script>
    window.RufflePlayer = window.RufflePlayer || {};
        window.addEventListener("load", (event) => {
            const ruffle = window.RufflePlayer.newest();
            const player = ruffle.createPlayer();
            const container = document.getElementById("container"); 
            container.appendChild(player);
            player.load({
                url: "filename.swf", 
                backgroundColor: "#000", 
             });
            player.style.width = "450px"; 
            player.style.height = "450px";
        });
</script>

Sorry if my question is a bit vague.

‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎

Unexpected Vertical Scroll Before Horizontal Scrolling in a React Component

I’m developing a React application and encountering an issue with scrolling behavior. Despite setting up conditional scrolling logic based on the component’s state, I’m observing an unwanted small vertical scroll before the horizontal scrolling starts. This occurs when transitioning between vertical and horizontal scrolling modes. I really don’t understand what it’s causing it.

What I want:

enter image description here

What is happening:

enter image description here

My App.tsx where the state is handled.

import "./App.css";
import CurrentLocation from "./components/CurrentLocation";
import Footer from "./components/Footer.js";
import Landing from "./components/Landing";
import { debounce } from "./utils/debounce.js";

function App() {
  const [indexScroll, setIndexScroll] = useState(0);
  const [indexHoriz, setIndexHoriz] = useState(0);

  useEffect(() => {
    console.log("Current vertical index: ", indexScroll);

    // handle vertical scroll
    const handleScrolling = debounce((e: any) => {
      // get main element
      const main = document.querySelector("main");
      e.preventDefault();
      // if scrolling up
      if (e.wheelDelta <= 0) {
        // if we are not at the last div, scroll to next one
        if (indexScroll < main?.children.length!! - 1) {
          console.log("Scrolling up");
          setIndexScroll(indexScroll + 1);
          main?.children[indexScroll + 1].scrollIntoView({
            behavior: "smooth",
          });
        } else {
          // if last div, go back to the first one
          setIndexScroll(0);
          main?.children[0].scrollIntoView({
            behavior: "smooth",
          });
        }
      } else {
        // if scrolling down
        // if we are not in the first div, scroll back
        if (indexScroll > 0) {
          setIndexScroll(indexScroll - 1);
          main?.children[indexScroll - 1].scrollIntoView({
            behavior: "smooth",
          });
        } else {
          // if we are at the first div, do nothing
          console.log("You are at the first div, can't scroll back.");
        }
      }
    }, 50);

    // handle horiz scroll
    const handleScrollingHoriz = debounce((e: any) => {
      // get main element
      const main = document.querySelector("#current-location");
      e.preventDefault();
      // if scrolling up
      if (e.wheelDelta <= 0) {
        // if we are not at the last div, scroll to next one
        if (indexHoriz < main?.children.length!! - 1) {
          console.log("Scrolling up");
          setIndexHoriz(indexHoriz + 1);
          main?.children[indexHoriz + 1].scrollIntoView({
            behavior: "smooth",
          });
        } else {
          // if last div, go back to the first one
          setIndexHoriz(0);
          main?.children[0].scrollIntoView({
            behavior: "smooth",
          });
        }
      } else {
        // if scrolling down
        // if we are not in the first div, scroll back
        if (indexHoriz > 0) {
          setIndexHoriz(indexHoriz - 1);
          main?.children[indexHoriz - 1].scrollIntoView({
            behavior: "smooth",
          });
        } else {
          // if we are at the first div, do nothing
          console.log("You are at the first div, can't scroll back.");
        }
      }
    }, 50);

    // if user is in div n°1 (current location) activate horizontal scrolling
    if (indexScroll === 1) {
      window.removeEventListener("mousewheel", handleScrolling);
      window.addEventListener("mousewheel", handleScrollingHoriz);
    } else {
      window.addEventListener("mousewheel", handleScrolling);
    }
  }, [indexScroll, indexHoriz]);

  return (
    <main>
      <Landing />
      <CurrentLocation />
      <Footer />
    </main>
  );
}

export default App;

My CurrentLocation component where the divs resides.

import useGeo from "../hooks/useGeo";

const CurrentLocation = () => {
  const { geoData, weatherData, geoLoading, weatherLoading } = useGeo();

  if (geoLoading || weatherLoading)
    return (
      <div id="current-location" className="grid">
        <p>Loading data</p>
      </div>
    );

  return (
    <div id="current-location" className="grid">
      <div className="grid-child">
        <h1>
          It looks like you're in {geoData.city}, {geoData.state_prov}.
          <br /> The current weather is{" "}
          {weatherData.list[0].weather[0].description} with a temperature of{" "}
          {weatherData.list[0].main.temp.toFixed(0)}°F.
        </h1>
      </div>
      <div className="grid-child">FORECAST 5 DAYS</div>
      <div className="grid-child">SEARCH LOCATION</div>
    </div>
  );
};

export default CurrentLocation;

My App.css and index.css

.full-page > div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 90%;
  width: 90%;
}

.full-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100dvh;
}

#current-location,
.grid-child {
  overflow-x: hidden;
}

.grid {
  display: grid;
  height: 100dvh;
  align-items: center;
  grid-template-columns: 100vw 100vw 100vw;
}

.grid-child {
  display: flex;
  justify-content: center;
  width: 100vw;
}

body {
  box-sizing: border-box;
  background-color: black;
  color: white;
  overflow: hidden;
  font-family: "DM Sans", sans-serif;
}

h1 {
  padding: 30px;
  font-size: 2.5em;
  font-weight: 400;
}

Flask server CORS issue when accessing from mobile network

I’ve developed a Flask server that serves content perfectly when accessed from my laptop connected to a WiFi network. However, when I connect my laptop to my mobile network and try to access the server, I encounter a CORS (Cross-Origin Resource Sharing) issue.

The error message I receive in the browser console is:

search.html:1

Access to fetch at ‘http://127.0.0.1:5000/recommended_movies’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

search.js:49

POST http://127.0.0.1:5000/recommended_movies net::ERR_FAILED 500 (INTERNAL SERVER ERROR)

search.js:101

Error during recommendation request: TypeError: Failed to fetch
at HTMLButtonElement. (search.js:49:7)

Here’s how my Flask server is set up for handling CORS:

server.py

from flask import Flask, request, jsonify
from flask_cors import CORS
from util import moviesList, recommend, fetch_id, movie_details

app = Flask(__name__)
CORS(app)


@app.route('/recommended_movies', methods=['POST','GET'])
def recommended_movies():
    if request.method == 'POST':
        data = request.json
        selected_movie = data.get('selectedMovie') 
        names,posters,movie_id = recommend(selected_movie)
        movie_id = [int(id) for id in movie_id] 
        response = jsonify({'names': names,'posters':posters,"movie_id":movie_id})

        return response
    else:
        return 'Invalid Request Method'
        
@app.route('/movies_list')
def movies_list():
    response = jsonify(moviesList().tolist())
    return response

@app.route('/get_id',methods=['POST','GET'])
def get_id():
    if request.method == 'POST':
        data = request.json
        movie_id = data.get('movie_id')
        id = fetch_id(movie_id) 
        response = jsonify({'id':id})

        return response
    else:
        return 'Invalid Request Method'

@app.route('/movieDetails',methods=['POST','GET'])
def movieDetails():
    if request.method == 'POST':
        data = request.json
        movie_id = data.get('movie_id')
        response = movie_details(movie_id) 

        return jsonify({'movie_details':response})
    else:
        return 'Invalid Request Method'

if __name__ == "__main__":
    app.run(debug=True)

I had used JavaScript for handing API Request

search.js

// HTML ELEMENT

const dropdownButton = document.getElementById('dropdown-button');
const searchInput = document.getElementById('search-input');
const dropdownMenu = document.getElementById('dropdown-menu');
const dropdownItem = document.getElementById('dropdown-item');
const recommendationButtonContainer = document.getElementById('recommend-btn-container')
const moviesContainer = document.getElementById('movies-container')

// Variables
let hidden = true; 
let itemValue = null;

window.onload = function() {
  fetch("http://127.0.0.1:5000/movies_list")
    .then(function(res) {
      return res.json()
    })
    .then(function(data) {
      data.forEach(item => {
        const div = document.createElement('div');
        div.className = 'block px-4 py-2 text-gray-700 hover:bg-gray-100 active:bg-blue-100 cursor-pointer rounded-md';
        div.id = 'dropdown-item'
        div.textContent = item; 
        dropdownMenu.appendChild(div);
        div.addEventListener('click', () => {
          searchInput.value = item; 
          toggleDropdown(); 
          displayRecommendationButton()
        });
      });
    })
    .catch(function(err) {
      console.log(err)
    });
};

// Recommend Button
function displayRecommendationButton() {
  const recommendationButton = document.createElement('button');
  recommendationButton.type = 'button';
  recommendationButton.className = 'text-white mt-10 bg-red-700 hover:bg-red-800 focus:outline-none focus:ring-4 focus:ring-red-300 font-medium rounded-full text-sm px-5 py-2.5 text-center me-2 mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900';
  recommendationButton.textContent = 'Recommend Movies';
  clearRecommendationButton(); 
  recommendationButtonContainer.appendChild(recommendationButton); 
  recommendationButton.addEventListener('click', () => {
    const selectedMovie = searchInput.value;
    if (selectedMovie) {
      fetch('http://127.0.0.1:5000/recommended_movies', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ selectedMovie })
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        console.log(data)
        moviesContainer.innerHTML = ''; 
        moviesContainer.classList.toggle('hidden', false);
        data.names.forEach((name, index) => {
          console.log(data) // {movie_id: Array(5), names: Array(5), posters: Array(5)}
          const movieContainer = document.createElement('div');
          movieContainer.className = 'movie-container';
          movieContainer.style.display = 'flex'
          movieContainer.style.flexDirection = 'column'
          movieContainer.style.alignItems = 'center'
          movieContainer.style.width = '266px'
          movieContainer.style.cursor = 'pointer'
          movieContainer.addEventListener('click', () => {
            const movieId = data.movie_id[index]
            window.location.href = `movie_details.html?movie_id=${movieId}`;
          });

          const movieName = document.createElement('h1');
          movieName.textContent = name;

          movieName.style.color = 'white'
          movieName.style.fontWeight = 'bold'
          movieName.style.fontSize = '20px'

          const moviePoster = document.createElement('img');
          moviePoster.src = data.posters[index]; 
          moviePoster.alt = name;

          moviePoster.style.height = '400px';

          movieContainer.appendChild(moviePoster);
          movieContainer.appendChild(movieName);

          moviesContainer.appendChild(movieContainer);
        });
        clearRecommendationButton();
      })
        .catch(error => {
          console.error('Error during recommendation request:', error);
        });
      } else {
        console.log('No movie selected');
      }
  });
}

function clearRecommendationButton() {
  recommendationButtonContainer.innerHTML = ''; 
}

function clearMoviesContainer() {
  moviesContainer.innerHTML = ''; 
  moviesContainer.classList.add('hidden'); 
}

// Dropdown Button 
 
function toggleDropdown() {
  dropdownMenu.classList.toggle('hidden', !hidden);
  hidden = !hidden
  clearMoviesContainer();
}

dropdownButton.addEventListener('click', (event) => {
  toggleDropdown();
  searchInput.focus()
});

document.addEventListener('click', (event) => {
  if (!dropdownButton.contains(event.target) && !dropdownMenu.contains(event.target)) {
    dropdownMenu.classList.add('hidden');
    hidden = true;
  }
});

// Search Input

searchInput.addEventListener('input', () => {
  const searchTerm = searchInput.value.toLowerCase();
  const items = dropdownMenu.querySelectorAll('div');
  items.forEach((item) => {
    const text = item.textContent.toLowerCase();
    if (text.includes(searchTerm)) {
      item.style.display = 'block';
    } else {
      item.style.display = 'none';
    }
  });
  clearMoviesContainer();
});

Despite this configuration, the issue persists when accessing the server from a different network. I suspect there might be some network configuration or firewall issue causing this problem.

I tried using different mobile networks, including one from my friend, but the issue persists. The Flask server only seems to work when connected to my home WiFi network.

How can I troubleshoot and resolve this CORS issue to allow access to my Flask server from a mobile network?

Any insights or suggestions would be greatly appreciated. Thank you!

AirDatepicker Highlighting cells

I am trying to highlight date cells which contain data using the AirDatepicker library. I do this by comparing the date of each cell using the onRenderCell function to a list of dates. availableDates.includes(_date) will be true on the 12th of April 2024 but for some reason the css class: highlight-date-cell is applying to the date cell corresponding to the 13th of April 2024

// Get Events as a prop
export let events: Array<any>;

// Create list of each start_date present in events
let availableDates: Array<string> = []
events.forEach(element => {
    availableDates.push(element.start_date.split(' ')[0])
});

// Create calendar and highlight date cell if said date is present in my availableDates array
new AirDatepicker('#input', {
    onRenderCell({date}) {
        const _date = new Date(date).toISOString().split('T')[0];
        const highlight = availableDates.includes(_date)

        return {
            classes: highlight ? 'highlight-date-cell' : undefined,
        }
    },
});

How to load a URDF file using urdf-loader

I am trying to render/load a urdf file as a web component but failed to do it. I haven’t find any solution on internet. I am uploading my urdf file on firebase and then store that link in mongoDB and trying to load/render that file from fileUrl on Robot Page using a npm package urdf-loader. anyone can help in doing this? i’m stuck on this thing from previous 15 days and could not find any solution.

I want a solution to render/load a urdf file from firebase url using urdf-loader.

converting old JavaScript version to new [closed]

I have codes written in old JavaScript codes. I am trying to develop it, but the new codes do not work because they are written with old codes. I need your help in converting it to the new version. thank you in advance

It doesn’t work when I replace it with:

  • old version: “1.4.0/jquery.min.js”
  • new version: “jquery-3.7.1.min.js”
$(document).ready(function(){
    /* This code is executed after the DOM has been completely loaded */

    var tmp;
    
    $('.note').each(function(){
        /* Finding the biggest z-index value of the notes */
        tmp = $(this).css('z-index');
        if(tmp>zIndex) zIndex = tmp;
    })

    /* A helper function for converting a set of elements to draggables: */
    make_draggable($('.note'));
    
    /* Configuring the fancybox plugin for the "Add a note" button: */
    $("#addButton").fancybox({
        'zoomSpeedIn'       : 600,
        'zoomSpeedOut'      : 500,
        'easingIn'          : 'easeOutBack',
        'easingOut'         : 'easeInBack',
        'hideOnContentClick': false,
        'padding'           : 15
    });
    
    /* Listening for keyup events on fields of the "Add a note" form: */
    $('.pr-body,.pr-author').live('keyup',function(e){
        if(!this.preview)
            this.preview=$('#fancy_ajax .note');
        
        /* Setting the text of the preview to the contents of the input field, and stripping all the HTML tags: */
        this.preview.find($(this).attr('class').replace('pr-','.')).html($(this).val().replace(/<[^>]+>/ig,''));
    });
    
    /* Changing the color of the preview note: */
    $('.color').live('click',function(){
        $('#fancy_ajax .note').removeClass('yellow green blue red').addClass($(this).attr('class').replace('color',''));
    });
    
    
    /* delete */
    $('.sil').live('click',function(){
        alert("delete")
    });
    
    /* The submit button: */
    $('#note-submit').live('click',function(e){
        
        if($('.pr-body').val().length<1)
        {
            alert("Not metni çok kısa!")
            return false;
        }
        
        if($('.pr-author').val().length<1)
        {
            alert("Başlık girmediniz!")
            return false;
        }
        
        $(this).replaceWith('<img src="img/ajax_load.gif" style="margin:30px auto;display:block" />');
        
        var data = {
            'zindex'    : ++zIndex,
            'body'      : $('.pr-body').val(),
            'author'    : $('.pr-author').val(),
            'color'     : $.trim($('#fancy_ajax .note').attr('class').replace('note',''))
        };
        
        
        /* Sending an AJAX POST request: */
        $.post('ajax/post.php',data,function(msg){
                         
            if(parseInt(msg))
            {
                /* msg contains the ID of the note, assigned by MySQL's auto increment: */
                
                var tmp = $('#fancy_ajax .note').clone();
                
                tmp.find('span.data').text(msg).end().css({'z-index':zIndex,top:0,left:0});
                tmp.appendTo($('#main'));
                
                make_draggable(tmp)
            }
            
            $("#addButton").fancybox.close();
            window.location.reload(false);
        });
        
        e.preventDefault();
    })
    
    $('.note-form').live('submit',function(e){e.preventDefault();});
    

});



var zIndex = 0;

function make_draggable(elements)
{
    /* Elements is a jquery object: */
    
    elements.draggable({
        containment:'parent',
        start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
        stop:function(e,ui){
            
            /* Sending the z-index and positon of the note to update_position.php via AJAX GET: */

            $.get('ajax/update_position.php',{
                  x     : ui.position.left,
                  y     : ui.position.top,
                  z     : zIndex,
                  id    : parseInt(ui.helper.find('span.data').html())
            });
        }
    });
}

Link to the entire project

I will drag and drop, delete, add, instant update etc. I got some of them working but for some I need to use new code

Hello guys i need help for discord.js

how to make the bot read another bot embed and print specific things in the embed as example if i did the cmd read my bot tell me to show inventory embed from epic rpg bot so i do Rpg i then epic rpg bot will show an embed with my items,i want from the bot to print specific things like wooden log…etc this is an example how my inventory embed looks like in epic rpg

<:_:697940429999439872> normie fish: 324

<:_:697940429500317727> golden fish: 121

<:_:543182761431793715> EPIC fish: 95

<:_:930928062860787734> SUPER fish: 1

<:_:770880739926999070> wooden log: 600

<:_:541056003517710348> EPIC log: 202

<:_:541384398503673866> SUPER log: 828

<:_:545396411316043776> MEGA log: 101

<:_:697940429668089867> apple: 741,042,216

<:_:603304907650629653> ruby: 791

<:_:818712007539818517> potato: 2,788

<:_:818712920820285450> carrot: 5,353

<:_:818716266457071626> bread: 2,304

<:_:1066950238004330536> flask: 6

<:_:541384010690199552> wolf skin: 241

<:_:542483215122694166> zombie eye: 248

<:_:545329267425149112> unicorn horn: 47

<:_:545721882805272596> mermaid hair: 15

<:_:798691812520886282> dragon essence: 19

i want from my bot to print the specific things with their amount if there’s an item not in the embed the bot doesn’t print it, please help me guys 5 days and im looking for a way to do it but i couldn’t