cutting a square out of a mesh in THREE.js

In essence what I want to do is project a square onto an arbitrary mesh.
Basically the DecalGeometry that is already in three.js and not far from what is here https://threejs.org/examples/?q=decal#webgl_decals

The issue that I am having is that I want to make sure that if I where to flatten the square the dimensions would end up at exactly a,b.

This also means that I can’t just set the projection plane to a,b as the mesh will warp. For instance if I project onto a cylinder and the size of the square is large enough it should wrap to the oposite side of the cylinder.

Are there any known algorithms for doing this?

Cannot update an input field to an empty value

Hello I try when I update an object to delete the value of an input and the update it. (I want it to be empty)

this is an example:

        <input
          name="video"
          value={videoUrl}
          onChange={(e) => {
            setVideoUrl(e.target.value);
          }}
          type="text"
          className="border border-primary rounded w-full bg-slate-100 px-2 py-1"
        />

what should I change?

Feedback for a beginner JS project much appreciated

Basically any constructive criticism for a beginner rock paper scissors project via The Odin Project would be much appreciated.

I was following TOP’s instructions and tailored my code accordingly. TOP’s instructions for the project

function getComputerChoice() {
    let computerChoice = Math.floor(Math.random() * 3);
    return computerChoice === 0 ? 'rock' :
        computerChoice === 1 ? 'paper' :
        'scissors';
}

function playRound (playerSelection, computerSelection) {
    playerSelection = prompt("What's your choice: rock, paper or scissors?").toLowerCase();
    if (playerSelection === computerSelection) {
        return message = "It's a tie!";
    } else if ((playerSelection === 'rock' && computerSelection === 'paper') || (playerSelection === 'paper' && computerSelection === 'scissors') || (playerSelection === 'scissors' && computerSelection === 'rock')) {
        computerScore++;
        return message = "Computer won!";
    } else if ((playerSelection === 'rock' && computerSelection === 'scissors') || (playerSelection === 'paper' && computerSelection === 'rock') || (playerSelection === 'scissors' && computerSelection === 'paper')) {
        playerScore++;
        return message = "You won!";
    }
}

let playerSelection;
const computerSelection = getComputerChoice();
let message, playerScore, computerScore;
playerScore = computerScore = tiedGames = 0;

function game() {
    for (let i = 0; i < 5; i++) {
        playRound (playerSelection, computerSelection);
        console.log(message);
    }
    if (playerScore === computerScore) {
        console.log("It's a tie; try again!");
    } else if (playerScore > computerScore) {
        console.log("Congratulations! You won!");
    } else if (playerScore < computerScore){
        console.log("Awww, you lost! Better luck next time!");
    }
}

Feedback highly appreciated.

Separate Array into multiple objects in Javascript

How to separate the Array to objects,

Need to convert the following
arr = [
    { name: 'abc', age: 15, roll_no: 25 },
    { name: 'def', age: 10, roll_no: 20 },
    { name: 'xyz', age: 16, roll_no: 18 },
  ];

Expected Output :

arr = [ abc : { name: 'abc', age: 15, roll_no: 25 },
        def : { name: 'def', age: 10, roll_no: 20 },
        xyz : { name: 'xyz', age: 16, roll_no: 18 }]

Kindly help me in this. Thanks in Advance

ripple effect with transition

i’m trying to create simple ripple effect. When i add classes to element newClick i expected ripple effect. Got troblued because appending class is instantly and i dont see the effect. Could you help me?

const button = document.querySelector('.button');

const handleClick = (e) => {
    const newClick = document.createElement('div');
    newClick.classList.add('point');

    newClick.style.top = `${e.offsetY}px`;
    newClick.style.left = `${e.offsetX}px`;

    newClick.classList.add('active');
    button.appendChild(newClick);
};

button.addEventListener('click', handleClick);
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: flex;
    align-items: center;
    justify-content: center;

    height: 100vh;
    background-color: #000;
}

.button {
    position: relative;
    background-color: #7c1a76;
    border: none;
    padding: 1em 2em;
    color: #fff;
    letter-spacing: 1px;
    text-transform: uppercase;
    cursor: pointer;
    overflow: hidden;
}

.point {
    position: absolute;
    width: 5px;
    height: 5px;
    border-radius: 50%;
    opacity: 1;
    background-color: #fff;
    transform: scale(1);
    transition: transform 0.5s, opacity 0.5s;
}

.active {
    transform: scale(10);
    background-color: #fff;
    opacity: 0;
    transition: transform 0.5s, opacity 0.5s;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Button Ripple Effect</title>
        <link rel="stylesheet" href="css/style.css" />
    </head>
    <body>
        <button class="button">click me</button>

        <script src="script.js"></script>
    </body>
</html>

I spend few hours on this trouble. Why i dont see effect of transition? This is project from tutorial but i want do it on my way.

Clickaway gets triggered twice on one click

I want to create a filter component where i can pass filter options down to my child component. I put on every filter an click event to open the filter so the user can chosse the options and an v-on-clickaway when the user clicks away so the options closes
This is how my child component looks like:

        <div
          v-for="filter in filters"
          id="desktop-menu-0"
          class="relative inline-block text-left"
          @click="toggle(filter.id, true)"
          v-on-clickaway="toggle(filter.id, false)"
        >...</div>

Here the script:

<script lang="ts">
import { mixin as clickaway } from 'vue-clickaway'

export type FilterOptionT = {
  text: string
  value: unknown
  selected: boolean
}
export type FilterT = {
  id: any
  text: string
  open: boolean
  values: FilterOptionT[]
}
export default {
  mixins: [clickaway],
  props: {
    filters: {
      default: () => [] as FilterT[],
    },
  },
  setup(props, { emit }) {
    function toggle(id: any, state: boolean) {
      emit('toggleFilter', id, state)
    }

    return { toggle }
  },
}
</script>

Here my parent component:

<filterVue @toggleFilter="toggleFilter" :filters="filters"></filterVue>

let filters = ref<FilterT[]>([
  {
    open: false,
    text: paths.members_table.status,
    id: 'status',
    values: [
      {
        selected: false,
        text: paths.statustexts.accepted,
        value: Userstatus.ACCEPTED,
      },
      {
        selected: false,
        text: paths.statustexts.asked,
        value: Userstatus.WAIT,
      },
      {
        selected: false,
        text: paths.statustexts.activated_eda,
        value: Userstatus.MC_ACTIVATED,
      },
    ],
  },
])

function toggleFilter(filterId: any, state: boolean) {
  console.log(state, filterId)
  let filterIndex = filters.value.findIndex((f) => f.id === filterId)
  if (filterIndex !== -1) {
    filters.value[filterIndex].open = state
  }
}

When i click now on my element it shows me 3 logs in my console:

enter image description here

It instantly closes it, what am i doing wrong here?

Which library would you choose – axios, got or node-fetch? [closed]

Which library would you choose to simply fetch the html code of pages – axios, got or node-fetch?

I did some small speed measurements and got these average results

Axios: 2.238s
Got: 2.389s
Node-fetch: 2.010s

What other parameters besides speed affect your choice?

Ease of Use?
Error Handling?
Additional Features?
Popularity and Adoption?
Size and Dependencies?

The problem with window transparency in Three.js / Three Fiber

I’m adding a window object, which is a GLTF model. Depending on the window’s size, I place a mesh object behind it to simulate glass (to make the interior of the hall visible). This works correctly on one side of the hall (image #1), but on the other sides of the hall, it doesn’t work as intended (image #2).

enter image description here
enter image description here

import { useState, useEffect } from 'react';
import * as THREE from 'three';
import { Shape, ShapeGeometry, MeshBasicMaterial } from 'three';
import { useSpring, animated } from '@react-spring/web'
import { useDrag } from 'react-use-gesture';
import { useThree } from "@react-three/fiber";
const _ = require("lodash");  

function DraggableWindow(props) {
    const { size, viewport } = useThree();
    const aspect = size.width / viewport.width;
    let sub;
    if(props.direction === 'back' || props.direction === 'front'){
        sub = props.elementPositionToSub;
    }else if(props.direction === 'left' || props.direction === 'right' ){
        sub = props.elementPositionToSubSides;
    }
    let glassRotation;
    if(props.direction === 'front'){

    }else if(props.direction === 'back'){

    }else if(props.direction === 'left'){
        glassRotation = [0, 0, Math.PI];
    }else if(props.direction === 'right'){
        glassRotation = [0, Math.PI, 0];
    }
    const [position, setPosition] = useState((props.direction === 'back' || props.direction === 'front' ? [props.newposition.x, props.newposition.y, props.ModelPos] : [props.ModelPos, props.newposition.y, props.newposition.z]));
    const [rotation, setRotation] = useState([props.newrotation.x, props.newrotation.y, props.newrotation.z]);
    const [scale, setScale] = useState(props.scaleX !== undefined ? [props.scaleX, props.scaleY, 25] : props.scale);
    const [show, setShow] = useState(false);
    const [draggable, setDraggable] = useState(true);
    let circlePosition, circleRotation, xRotation;
    if(props.direction === 'front' || props.direction === 'back'){
        if(props.obj === '1_window'){
            circlePosition = [0, 1.7, -0.09];
            circleRotation = [0, 3.2, 0];
            xRotation = [0, 0, 0];
        }else if(props.obj === '2_window'){
            circlePosition = [1.9, 2.2, 0.07];
            circleRotation = [0, 0, 0];
            xRotation = [0, 0, 0];
        }else if(props.obj === '3_window'){
            circlePosition = [2.21, -0.02, -0.05];
            circleRotation = [0, -Math.PI / 2, 0];
            xRotation = [0, -Math.PI / 2, Math.PI / 4];
        }else if(props.obj === '4_window'){
            circlePosition = [3.95, 1.65, 0.02];
            circleRotation = [0, 0, 0];
            xRotation = [0, 0, 0];
        }
    }else{
        if(props.obj === '1_window'){
            circlePosition = [1.2, 1.7, 0.02];
            circleRotation = [0, 0, 0];
            xRotation = [0, 0, 0];
        }else if(props.obj === '2_window'){
            circlePosition = [0, 2.2, -0.14];
            circleRotation = [0, Math.PI, 0];
            xRotation = [0, 0, 0];
        }else if(props.obj === '3_window'){
            circlePosition = [0.05, 0.09, -0.05];
            circleRotation = [0, Math.PI / 2, 0];
            xRotation = [0, -Math.PI / 2, Math.PI / 4];
        }else if(props.obj === '4_window'){
            circlePosition = [0.65, 1.65, -0.09];
            circleRotation = [0, Math.PI, 0];
            xRotation = [0, 0, 0];
        }
    }

    const bind = useDrag(
        ({ active, offset: [x, y] }) => {
            if(draggable){
                if(props.direction === 'front'){
                    const [, , z] = position;
                    setPosition([x / aspect, -y / aspect, props.ModelPos - sub]);
                    props.setCameraMovement(!active);
                }else if (props.direction === 'back'){
                    const [, , z] = position;
                    setPosition([-x / aspect, -y / aspect, props.ModelPos + sub]);
                    props.setCameraMovement(!active);
                }else if (props.direction === 'left'){
                    const [z, , ] = position;
                    if(props.obj === '4_window'){
                        setPosition([props.ModelPos - (sub + 3.5), -y / aspect, x / aspect]);
                    }else{
                        setPosition([props.ModelPos - sub, -y / aspect, x / aspect]);
                    }
                    props.setCameraMovement(!active);
                }else if (props.direction === 'right'){
                    const [z, , ] = position;
                    if(props.obj === '4_window'){
                        setPosition([props.ModelPos + (sub + 3.5), -y / aspect, -x / aspect]);
                    }else{
                        setPosition([props.ModelPos + sub, -y / aspect, -x / aspect]);
                    }
                    props.setCameraMovement(!active);
                }
            }
        },
        { pointerEvents: true }
    );

    
    useEffect(() => {
        if(props.direction === 'front'){
            setPosition([position[0], position[1], props.ModelPos - sub]);
        }else if(props.direction === 'back'){
            setPosition([position[0], position[1], props.ModelPos + sub]);
        }else if(props.direction === 'left'){
            if(props.obj === '4_window'){
                setPosition([props.ModelPos - (sub + 3.5), position[1], position[2]]);
            }else{
                setPosition([props.ModelPos - sub, position[1], position[2]]);
            }
        }else if(props.direction === 'right'){
            if(props.obj === '4_window'){
                setPosition([props.ModelPos + (sub + 3.5), position[1], position[2]]);
            }else{
                setPosition([props.ModelPos + sub, position[1], position[2]]);
            }
        }
    }, [props.ModelPos]);

    const changeYScale = (e) => {
        // Store the initial position of the mouse
        setDraggable(false)
        const initialY = e.clientY;
        const onPointerMove = (e) => {
            const deltaY = e.clientY - initialY;
            setScale([scale[0], scale[1] - deltaY, scale[2]])
            setPosition(position)
        };

        const onPointerUp = () => {
          document.removeEventListener('pointermove', onPointerMove);
          document.removeEventListener('pointerup', onPointerUp);
        };

        document.addEventListener('pointermove', onPointerMove);
        document.addEventListener('pointerup', onPointerUp);
    }

    const changeXScale = (e) => {
        // Store the initial position of the mouse
        setDraggable(false)
        const initialX = e.clientX;
        const onPointerMove = (e) => {
            const deltaX = e.clientX - initialX;
            setScale([scale[0] + deltaX, scale[1], scale[2]])
            if(props.direction === 'front' || props.direction === 'back'){
                setPosition(position)
            }else if(props.direction === 'left'){
                setPosition([position[0] - 3.5, position[1], position[2]])
            }else if(props.direction === 'right'){
                setPosition([position[0] + 3.5, position[1], position[2]])
            }
        };

        const onPointerUp = () => {
          document.removeEventListener('pointermove', onPointerMove);
          document.removeEventListener('pointerup', onPointerUp);
        };

        document.addEventListener('pointermove', onPointerMove);
        document.addEventListener('pointerup', onPointerUp);
    }

    const Rectangle = () => {
        const rectangleShape = new THREE.Shape();
        rectangleShape.moveTo(0, 0);
        rectangleShape.lineTo(0, 1);
        rectangleShape.lineTo(1, 1);
        rectangleShape.lineTo(1, 0);
        rectangleShape.lineTo(0, 0);
      
        const geometry = new THREE.ShapeGeometry(rectangleShape);
      
        return (
          <mesh>
            <geometry attach="geometry" args={[geometry]} />
            <material attach="material" color="blue" />
          </mesh>
        );
      };

    return (
        <mesh
            onPointerEnter={(e) => { 
                const canvas = document.querySelector('canvas'); 
                if(e.object.parent.type === 'Group'){
                    canvas.style.cursor = 'pointer';
                }else{
                    canvas.style.cursor = 'grab';
                }
            }}
            onPointerLeave={() => { const canvas = document.querySelector('canvas'); canvas.style.cursor = null }}
            onClick={() => setShow(true)}
            onPointerMissed={() => setShow(false)}
            position={position}
            rotation={rotation}
            {...bind()}
        >
            <primitive object={props.window} scale={scale}>
                {(show ? <group position={circlePosition} rotation={(props.obj === '3_window' ? [0, 0, 1.6] : [0, 0, 0.8])} onClick={() => props.handleDeleteWindow(props.index)}>
                <mesh rotation={circleRotation}>
                    <circleBufferGeometry args={[0.15, 32]} /> {/* Ustaw odpowiednią średnicę i ilość segmentów */}
                    <meshStandardMaterial color="red" />
                </mesh>
                <mesh rotation={xRotation}>
                    <boxBufferGeometry args={[0.03, 0.2, 0.01]} />
                    <meshStandardMaterial color="white" />
                </mesh>
                <mesh rotation={xRotation}>
                    <boxBufferGeometry args={[0.2, 0.03, 0.01]} />
                    <meshStandardMaterial color="white" />
                </mesh>
            </group> : '')}
            {/* transparent element */}
            <mesh position={[2.3, 0.8, 0]} rotation={glassRotation}>
                <planeBufferGeometry attach="geometry" args={[3.2, 1.6]} />
                <meshPhongMaterial side={THREE.FrontSide} color="#999999" transparent={true} opacity={0.5} premultipliedAlpha={true}/>
            </mesh>
            {(show && props.obj === '4_window' ? 
                <mesh 
                    onPointerDown={(e) => {changeYScale(e)}}
                    onPointerLeave={() => {setDraggable(true); props.setCameraMovement(!props.cameraMovement);}}
                    scale={[0.6, 0.3, 0.5]} rotation={(props.direction === 'front' || props.direction === 'back' ? [0, 0, 0] : (props.direction === 'left' ? [Math.PI, 0, Math.PI] : [Math.PI, 0, Math.PI]))} position={[2.26, 1.9, 0]}
                >
                    <shapeGeometry/>
                    <meshStandardMaterial color="rgba(0, 0, 0, 0.2)"/>
                </mesh> 
            : '')}
            {(show && props.obj === '4_window' ? 
                <mesh  onPointerDown={(e) => {changeXScale(e)}} onPointerLeave={() => {setDraggable(true); props.setCameraMovement(!props.cameraMovement);}} scale={[0.6, 0.3, 0.5]} rotation={(props.direction === 'front' || props.direction === 'back' ? [0, 0, -Math.PI / 2] : (props.direction === 'left' ? [Math.PI, 0, Math.PI / 2] : [Math.PI, 0, Math.PI / 2]))} position={(props.direction === 'front' || props.direction === 'back' ? [4.195, 0.9, -0.1] : [0.4, 0.9, -0.1])}>
                    <shapeGeometry/>
                    <meshStandardMaterial color="rgba(0, 0, 0, 0.2)"/>
                </mesh> 
            : '')}
            </primitive>
        </mesh>
    )
}

Why does the object work correctly when added to one side of the hall, but not for the other sides?

App react-native: Generated a random token, but impossible to retrieve it

(Question posted using a translator).

My problem is quite simple: I generate a random token upon the user’s login, but it’s impossible for me to retrieve it (I should specify that the token expires after about an hour and that with each login, a unique and random token is generated to increase the security of the application).

Therefore, the login works quite well; I retrieve the user ID obtained at registration with the username. Once registered, it is possible to log in with the email and password.

I will present my code to you.

The jwt file that allows me to generate my token:

const jwt = require("jsonwebtoken");
require("dotenv").config();

module.exports = {
  //
  generateTokenForUser: function (userData) {
    // génération du token
    return jwt.sign(
      {
        // données encodées dans le token
        userId: userData.id,
        isAdmin: userData.isAdmin,
      },
      // clé secrète pour l'encodage
      process.env.JWT_SIGN_SECRET,
      {
        // durée de validité du token
        expiresIn: "1h",
      },
    );
  },
  parseAuthorization: function (authorization) {
    // récupération du token
    return authorization != null ? authorization.replace("Bearer ", "") : null;
  },
  getUserid: function (authorization) {
    // récupération de l'ID utilisateur
    const jwttoken = module.exports.parseAuthorization(authorization);
    console.log(jwttoken);
    if (jwttoken != null) {
      try {
        // vérification du token
        const jwtToken = jwt.verify(jwttoken, process.env.JWT_SIGN_SECRET);
        if (jwtToken && jwtToken.userId) {
          // si le token est valide, on retourne l'ID utilisateur
          return jwtToken.userId;
        } else {
          // Sinon, renvoyez une erreur
          throw new Error("ID d'utilisateur manquant dans le jeton JWT");
        }
      } catch (err) {
        // Sinon, renvoyez une erreur
        throw new Error("Erreur de vérification du jeton utilisateur");
      }
    } else {
      throw new Error("Jetons identification non valides");
    }
  },
  generateTemporaryToken: function (userId) {
    return jwt.sign(
      {
        userId: userId,
        // Autres données éventuelles
      },
      process.env.TEMPORARY_TOKEN_SECRET, // Clé secrète spécifique pour les tokens temporaires
      {
        expiresIn: "15m", // Durée de validité du token temporaire (30 minutes)
      },
    );
  },
  parseTemporaryToken: function (temporaryToken) {
    // récupération du token
    return temporaryToken != null
      ? temporaryToken.replace("Bearer ", "")
      : null;
  },
};

The AuthContext file where I store the information:

// src/context/AuthContext.js

// Importation des dépendances nécessaires
import React, { createContext, useState } from 'react';

// Création du contexte d'authentification
export const AuthContext = createContext();

// Composant fournisseur du contexte d'authentification
export const AuthProvider = ({ children }) => {
  // État pour suivre si l'utilisateur est connecté ou non
  const [isUserLoggedIn, setUserLoggedIn] = useState(false);
  const [userId, setUserId] = useState(null);
  const [userPseudo, setUserPseudo] = useState(null);
  const [userData, setUserData] = useState(null);
  const [userToken, setUserToken] = useState(null);

  // Fonction pour connecter l'utilisateur
  const login = async (user) => {
    const userToken = await generateTokenForUser(user);
    localStorage.setItem('userToken', userToken);

    setUserLoggedIn(true);
    setUserId(user.id);
    setUserPseudo(user.pseudo);
    setUserToken(userToken);
  };

  // Fonction pour déconnecter l'utilisateur
  const logOut = () => {
    //localStorage.removeItem('userToken');

    setUserLoggedIn(false);
    setUserId(null);
    setUserPseudo(null);
    setUserData(null);
    setUserToken(null);
  };

  // Fonction pour mettre à jour le pseudo de l'utilisateur
  const updateUserPseudo = (pseudo) => {
    setUserPseudo(pseudo);
  };

  // Fonction pour définir l'ID de l'utilisateur dans le contexte d'authentification
  const setAuthContextUserId = (id) => {
    setUserId(id);
  };

  // Fournir l'état et les fonctions associées aux composants enfants via le contexte
  return (
    <AuthContext.Provider value={{
      isUserLoggedIn, userId, userPseudo, userData, userToken, setUserToken,
      updateUserPseudo, setUserLoggedIn, setUserId, setAuthContextUserId, setUserPseudo, setUserData,
      login, logOut }}>
      {children}
    </AuthContext.Provider>
  );
};

Here are the files that require a token: homeLocationctrl:

// importation des modules
const { homelocation } = require("../Models");
const jwt = require("../utils/jwt");

module.exports = {
  newlocations: async (req, res) => {
    // récupération du header d'authentification
    try {
      console.log("Nouvelle requête de création de lieu.");

      const headerAuth = req.headers["authorization"];
      const userId = jwt.getUserid(headerAuth);

      console.log("ID de l'utilisateur extrait du token :", userId);

      /**
       * Finds a user's home location by their user ID.
       * @async
       * @function
       * @param {number} userId - The user ID to search for.
       * @returns {Promise<object>} - A Promise that resolves with the user's home location object if found, or null if not found.
       */
      const userFound = await homelocation.findOne({
        where: { homeID: userId },
      });

      const { namelocation, infolocation, adresslocation } = req.body;

      console.log("Données reçues de la requête :", req.body);

      if (!namelocation || !infolocation || !adresslocation) {
        console.log("Paramètres manquants.");
        return res.status(400).json({ error: "Paramètres manquants" });
      }

      if (namelocation.length < 5 || namelocation.length > 20) {
        console.log("Le nom du lieu ne respecte pas la longueur requise.");
        return res.status(400).json({
          error: "Le nom du lieu doit être compris entre 5 et 20 caractères",
        });
      }

      if (infolocation.length < 5 || infolocation.length > 350) {
        console.log("Les informations ne respectent pas la longueur requise.");
        return res.status(400).json({
          error:
            "Les informations doivent être comprises entre 5 et 350 caractères",
        });
      }

      if (adresslocation.length < 5 || adresslocation.length > 100) {
        console.log("L'adresse ne respecte pas la longueur requise.");
        return res.status(400).json({
          error: "L'adresse doit être comprise entre 5 et 100 caractères",
        });
      }

      homelocation
        .create({
          homeID: userId,
          namelocation,
          infolocation,
          adresslocation,
        })
        .then(function (newLocation) {
          console.log("Nouvelle location créée :", newLocation);
          return res.status(201).json({
            locationID: newLocation.homeID,
            message: "Nouvelle location créée",
          });
        })
        .catch(function (err) {
          console.error("Erreur lors de la création de la location :", err);
          return res
            .status(500)
            .json({ error: "Erreur inattendue : merci de recommencer" });
        });
    } catch (error) {
      console.error("Erreur inattendue :", error);
    }
  },

  // route getlocations
  getlocations: async (req, res) => {
    console.log("Requête GET reçue pour /api/homelocation/getloc");
    try {
      console.log("Nouvelle requête pour obtenir les lieux de l'utilisateur.");

      const headerAuth = req.headers["authorization"];
      console.log("Token reçu depuis le client :", headerAuth);
      const userId = jwt.getUserid(headerAuth);

      console.log("ID de l'utilisateur extrait du token :", userId);

      homelocation
        .findAll({
          where: { homeID: userId },
        })
        .then(function (userFound) {
          // retour si l'utilisateur existe déjà
          if (userFound && userFound.length > 0) {
            console.log("Voici les résultats");
            return res.status(200).json(userFound);
          } else {
            console.log("L'utilisateur n'a pas de lieu enregistrer");
            return res
              .status(404)
              .json({ error: "L'utilisateur n'a pas de lieu enregistrer pour le moment" });
          }
        })
        .catch(function (err) {
          console.error("Erreur lors de la récupération des lieux :", err);
          return res
            .status(500)
            .json({ error: "Impossible de récupérer les lieux" });
        });
    } catch (error) {
      console.error("Erreur inattendue :", error);
    }
  },

  // route updatelocations
  updatelocations: async (req, res) => {
    try {
      console.log("Nouvelle requête de modification de lieu.");

      const headerAuth = req.headers["authorization"];
      const userId = jwt.getUserid(headerAuth);

      console.log("ID de l'utilisateur extrait du token :", userId);

      homelocation
        .findOne({
          where: { homeID: userId },
        })
        .then(function (userFound) {
          if (userFound) {
            userFound
              .update({
                namelocation: req.body.namelocation,
                infolocation: req.body.infolocation,
                adresslocation: req.body.adresslocation,
              })
              .then(function () {
                console.log("Location modifié avec succès.");
                return res.status(201).json({ message: "Lieu modifié" });
              })
              .catch((err) => {
                console.error("Erreur lors de la modification du lieu :", err);
                return res
                  .status(500)
                  .json({ error: "Impossible de modifier le lieu" });
              });
          } else {
            return res.status(404).json({ error: "Le lieu n'existe pas" });
          }
        })
        .catch(function (err) {
          console.error("Erreur lors de la modification du lieu :", err);
          return res
            .status(500)
            .json({ error: "Impossible de modifier le lieu" });
        });
    } catch (error) {
      console.error("Erreur inattendue :", error);
    }
  },

  // route deletelocations
  deletelocations: async (req, res) => {
    try {
      console.log("Nouvelle requête de suppression de lieu.");

      const headerAuth = req.headers["authorization"];
      const userId = jwt.getUserid(headerAuth);

      console.log("ID de l'utilisateur extrait du token :", userId);

      const userFound = await homelocation.findOne({
        where: { homeID: userId },
      });

      if (!userFound) {
        console.log("Le lieu n'existe pas.");
        return res.status(404).json({ error: "Le lieu n'existe pas" });
      }

      userFound
        .destroy()
        .then(function () {
          console.log("Lieu supprimé avec succès.");
          return res.status(201).json({ message: "Lieu supprimé" });
        })
        .catch(function (err) {
          console.error("Erreur lors de la suppression du lieu :", err);
          return res
            .status(500)
            .json({ error: "Impossible de supprimer le lieu" });
        });
    } catch (error) {
      console.error("Erreur inattendue :", error);
    }
  },
};

Location:

// src/navigation/location.js

// Importations nécessaires
import { useState, useEffect, useContext } from 'react';
import { View, Text, TouchableOpacity, FlatList, Button } from 'react-native';
import locationStyle from '../styles/locationStyle';
import { AuthContext } from '../contexts/AuthContext';
import { get } from 'react-native/Libraries/TurboModule/TurboModuleRegistry';

function LocationScreen({ route, navigation }) {
  const { userId, userToken, userPseudo } = useContext(AuthContext);
  const [locations, setLocations] = useState([]);
  const [showDeleteButton, setShowDeleteButton] = useState(true);

  useEffect(() => {
    console.log("Token mis à jour :", userToken);
    if (!userId) return;
    // Charger les locations depuis l'API
    const loadUserLocations = async () => {
      console.log("Page Mes Location ID:", userId, "- Username:", userPseudo, "- Token:", userToken)

        // Vérifier si le userToken est vide
  if (!userToken || userToken.trim() === '') {
    console.log("Le token de l'utilisateur est absent ou vide.");
    // Ici, tu pourrais renvoyer une erreur ou demander à l'utilisateur de se reconnecter
    return; // Arrêter l'exécution si le token n'est pas valide
  }

      try {
        const response = await fetch(`http://192.168.1.17:3000/api/homelocation/getloc?userId=${userId}`, {
          headers: {
            'Authorization': `Bearer ${userToken}`, // userToken provient de ton AuthContext
            'Content-Type': 'application/json'
          }
        });

        console.log('Réponse brute:', response);

        // Vérifiez le statut HTTP de la réponse
        if (response.ok) {
          const data = await response.json();
          setLocations(data);
        } else {
          console.error('Erreur de statut:', response.status);

          // Log de la réponse pour le debug
          const text = await response.text();
          console.log('Réponse brute:', text);
        }
      } catch (error) {
        console.error('Erreur lors du chargement des emplacements', error.message);
      }
    };

    loadUserLocations();
  }, [userId]);

  useEffect(() => {
    if (route.params?.locationTitle && !locations.includes(route.params?.locationTitle)) {
      setLocations(prev => [...prev, route.params?.locationTitle]);
    }
  }, [route.params?.locationTitle]);

  // Fonction pour gérer la suppression d'une location
  const handleDeleteLocation = async (item) => {
    try {
      await fetch(`http://192.168.1.17:3000/homelocation/deleteloc`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${userToken}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: item.id }),
      });
      setLocations((prevLocations) => prevLocations.filter((location) => location.id !== item.id));
    }  catch (error) {
      console.error('Erreur lors de la suppression de l'emplacement', error);
    }
  };

  return (
    <View style={locationStyle.container}>
      <Button
        title="Ajouter une nouvelle location"
        onPress={() => {
          navigation.navigate('CreateLocation');
        }}
      />
      <FlatList
        data={locations}
        renderItem={({ item }) => (
          <View style={locationStyle.listItem}>
            <TouchableOpacity
              onPress={() => {
                navigation.navigate('UiInterface');
              }}
            >
              <Text style={locationStyle.text}>{item.title}</Text>
            </TouchableOpacity>
            <View style={locationStyle.buttonsContainer}>
              <TouchableOpacity
                style={locationStyle.button}
                onPress={() => {
                  // Mettre en place la logique de modification ici
                }}
              >
                <Text style={locationStyle.buttonText}>Modifier</Text>
              </TouchableOpacity>

              {showDeleteButton && (
                <TouchableOpacity
                  style={locationStyle.button}
                  onPress={() => {
                    handleDeleteLocation(item);
                  }}
                >
                  <Text style={{ ...locationStyle.buttonText, color: 'red' }}>Supprimer</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        )}
        keyExtractor={(item) => (item.id ? item.id.toString() : Math.random().toString())}
      />
    </View>
  );
}

export default LocationScreen;

Here are the logs at login:

 LOG  Code de statut: 200
 LOG  Données envoyées: {"email": "[email protected]", "password": "Bisous5910*", "username": ""}     
 LOG  Mot de passe envoyé: Bisous5910*
 LOG  Réponse du serveur: {"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImlzQWRtaW4iOmZhbHNlLCJpYXQiOjE2OTkwMDcxNjksImV4cCI6MTY5OTAxMDc2OX0.wQC54F4SkJEIPO4h1ZOtUhuHCBT3Lbf1gAzzliIeED0", "userId": 1, "username": "Zana-S"}

When I click on a button named “My Rentals,” I need to retrieve the rentals created by the user, but to do that, I must retrieve the token that is associated with the ID in the database.

LOG  Bouton Mes Location
LOG  Token mis à jour : null
LOG  Page Mes Location ID: 1 - Username: Zana-S - Token: null
LOG  Le token de l'utilisateur est absent ou vide.

Error: Incompatible versions detected, cypress-grep 3.0.0+ requires Cypress 10.0.0+

Desired behavior:
I’m trying to filter tests using the ‘@cypress/grep’ plugin but getting incomaptible error

Command:**
npm run test:dev2 –env grep=”Regression”

Cypress Version:
10.0.0

TestScript
it(‘Validate Default signature is being populated Reply to all email task (Regression,Sanity)’,{tags: [‘@Regression,@Sanity’]}, () => {
getWorkTab();
waitUntilPageLoad();

//open an email task
filterWorkTypeAsEmail();
cy.waitUntil(() => cy.get(Locators.taskColumn).should('contain.text', 'Email'));
cy.get(Locator.taskCheckBox).eq(0).click();
cy.get(Locator.taskContainer).last().dblclick({ force: true });

//validate Default signature populating for ReplyAll
cy.contains('Reply All').scrollIntoView().click();
cy.get(Locators.subject).contains('RE:');
cy.get(Locators.signatureEditor).its('0.contentDocument').its('body').contains('sh-etfswaps-settlements');

});
**

Error:
Error: Incompatible versions detected, cypress-grep 3.0.0+ requires Cypress 10.0.0+

Try:
i upgraded cypress version to 10.0.0 but still same Error: Incompatible versions detected, cypress-grep 3.0.0+ requires Cypress 10.0.0+ i am getting.

Create a constructor class Multiply that has public integer variables num1 and num2 [closed]

Create a constructor class Multiply that has public integer variables num1 and num2. Include a default constructor and a method Product that accepts the two integer parameters,calculates and outputs the multiplication.
In your main class Calculate_Product include a main method that prompts the user to enter 2 integer values and create a reference called total for the constructor Multiply. Output the values entered by the user and the product of the values in the command line window.

Explanation and a picture

vue-scrollto scrollTo(‘#id’) scrolls more than expected on windows 11 and some mac devices

I’m using vue-scrollto in my component to scroll to an element with specific ‘id’.
For windows 10 it scrolls to proper location of the element in the page, but for Chrome on Windows 11 and for some mac devices (Safari) it scrolls some additional pixels than expected.

I’ve used it as below:

import VueScrollTo from 'vue-scrollto';
...
this.$scrollTo('#ratings')

next build fails because of webpack errors

Also in: https://github.com/vercel/next.js/discussions/57939?fbclid=IwAR0nh0p08-CqH9EWpYiB-18cbIUC1jo5z_2wAT9wFpX6tzFd-Zoi4BulIPI

What version of Next.js are you using?
14

What version of Node.js are you using?
18.18.0

What browser are you using?
Google Chrome

What operating system are you using?
Windows 10

How are you deploying your application?
Vercel

Describe the Bug
Attempting to npm run build this is what it shows:

   FetchError: request to https://fonts.gstatic.com/s/inter/v13/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa2ZL7W0Q5n-wU.woff2 failed, reason: connect ETIMEDOUT 2404:6800:4017:801::2003:443
    at ClientRequest.<anonymous> (C:file herenode_modulesnextdistcompilednode-fetchindex.js:1:65756)
    at ClientRequest.emit (node:events:517:28)
    at ClientRequest.emit (node:domain:489:12)
    at TLSSocket.socketErrorListener (node:_http_client:501:9)
    at TLSSocket.emit (node:events:517:28)
    at TLSSocket.emit (node:domain:489:12)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT'
}
FetchError: request to https://fonts.gstatic.com/s/inter/v13/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa2JL7W0Q5n-wU.woff2 failed, reason: connect ETIMEDOUT 2404:6800:4017:801::2003:443
    at ClientRequest.<anonymous> (C:file herenode_modulesnextdistcompilednode-fetchindex.js:1:65756)
    at ClientRequest.emit (node:events:517:28)
    at ClientRequest.emit (node:domain:489:12)
    at TLSSocket.socketErrorListener (node:_http_client:501:9)
    at TLSSocket.emit (node:events:517:28)
    at TLSSocket.emit (node:domain:489:12)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT'
}
FetchError: request to https://fonts.gstatic.com/s/inter/v13/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa1pL7W0Q5n-wU.woff2 failed, reason: connect ETIMEDOUT 2404:6800:4017:801::2003:443
    at ClientRequest.<anonymous> (Cfile herenode_modulesnextdistcompilednode-fetchindex.js:1:65756)
    at ClientRequest.emit (node:events:517:28)
    at ClientRequest.emit (node:domain:489:12)
    at TLSSocket.socketErrorListener (node:_http_client:501:9)
    at TLSSocket.emit (node:events:517:28)
    at TLSSocket.emit (node:domain:489:12)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT'
}
Failed to compile.

applayout.tsx
`next/font` error:
Failed to fetch `Inter` from Google Fonts.


> Build failed because of webpack errors
   Creating an optimized production build  .

Expected behavior
Clean build

Github repo: https://github.com/Jennelle186/NextJS-Supabase
I am using Supabase as well for the database.

Example

https://github.com/Jennelle186/NextJS-Supabase

Why it logs all the elements after “if statement” instead of eception of one element?

I try to build Tic Tac Toe by javascript without looking at someone’s code and i want to log all the Elements who has not got url yet but it logs all the elements including the one which has already got the url and why it happens ?

const cells = document.querySelectorAll("img");
let boxs = [];
cells.forEach(function (cell) {
  cell.addEventListener("click", manChoice, false);
});
function manChoice() {
  this.src = "Small_uppercase_letter_X.svg.png";

  setTimeout(1000, computerChoice());
}
function computerChoice() {
  for (let cell of cells) {
    if (cell.src != "Small_uppercase_letter_X.svg.png") {
      console.log(cell);
    }
  }
}