How do I add a plus symbol to a JS Counter-up?

I want to add a plus symbol(+) that will appear after each counter-up results; for example currently I am having 150 as a result of the counter-up but I need the result to be 150+ and this should apply to all my elements

This is the current html code

<section id="skill" class="skills">
 <div class="container">
  <div class="row counters">

<div class="col-lg-3 col-6 text-center">
        <h2 data-toggle="counter-up">65</h2>
        <p>Our Staffs</p>
      </div>

<div class="col-lg-3 col-6 text-center">
        <h2 data-toggle="counter-up">190</h2>
        <p>Our Clients</p>
      </div>

<div class="col-lg-3 col-6 text-center">
        <h2 data-toggle="counter-up">150</h2>
        <p>Completed Projects</p>
      </div>

<div class="col-lg-3 col-6 text-center">
        <h2 data-toggle="counter-up">125</h2>
        <p>Running Projects</p>
      </div>
    </div>
  </div>

`

This is the current CSS code

.skills .counters h2 {
margin: 30px 0 0 0;
font-size: 60px;
display: block;
color: #eeaa0b;
}

.skills .counters p {
padding: 0;
margin: 0;
font-size: 18px;
color: #353535;
}

This is the JS code

// jQuery counterUp
$('[data-toggle="counter-up"]').counterUp({
delay: 10,
time: 1000,
});

Current results

65 190 150 125

Expected Result

65+ 190+ 150+ 125+

Old react state is persisting when calling a function

How come the updateUser() function is getting the old users even though I have used useCallback and put users in the dependency

Ideally the output when clicking update button should be like this

{"id":1,"name":"John","age":10,"gender":"male"}

{"id":2,"name":"Stacy","age":15,"gender":"male"}

{"id":3,"name":"Kevin","age":30,"gender":"male"}

{"id":4,"name":"Jessi","age":13,"gender":"male"}

but in current output only the last user is getting updated

{"id":1,"name":"John","age":10}

{"id":2,"name":"Stacy","age":15}

{"id":3,"name":"Kevin","age":30}

{"id":4,"name":"Jessi","age":13,"gender":"male"}
import { useCallback, useState } from "react";
import "./styles.css";

export default function App() {
  const data = [
    { id: 1, name: "John", age: 10 },
    { id: 2, name: "Stacy", age: 15 },
    { id: 3, name: "Kevin", age: 30 },
    { id: 4, name: "Jessi", age: 13 }
  ];
  const [users, setUsers] = useState(data);

  const updateUser = useCallback(
    (newUser) => {
      console.log(users);
      const newState = users.map((user) =>
        user.id === newUser.id ? newUser : user
      );
      setUsers(newState);
    },
    [users]
  );

  const startUpdate = () => {
    for (const user of users) {
      updateUser({ ...user, gender: "male" });
    }
  };
  return (
    <div className="App">
      {users.map((user) => {
        return <p key={user.id}>{JSON.stringify(user)}</p>;
      })}

      <button onClick={startUpdate}>update</button>
    </div>
  );
}

I am unable to connect MongoDB properly to my server (node.js and express), would appreciate some guidance

When I send an API request using Hoppscotch, I get an error in my terminal and status code: 500 on hoppscotch. I am not able to rectify the problem. I am attaching my code below.

var mongodb = require('mongodb');
var ObjectID = mongodb.ObjectId;
var crypto = require('crypto');
var express = require('express');
var bodyParser = require('body-parser');
const exp = require('constants');

var genRandomString = function (length) {
    return crypto.randomBytes(Math.ceil(length / 2))
        .toString('hex')
        .slice(0, length);
};

var sha512 = function (password, salt) {
    var hash = crypto.createHmac('sha512', salt);
    hash.update(password);
    var value = hash.digest('hex');
    return {
        salt: salt,
        passwordHash: value
    };
};

function saltHashPassword(userPassword) {
    var salt = genRandomString(16);
    var passwordData = sha512(userPassword, salt);
    return passwordData;
}

function checkHashPassword(userPassword, salt) {
    var passwordData = sha512(userPassword, salt);
    return passwordData;
}

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/hwmDatabase')
    .then(() => {
        app.post('/register', (request, response, next) => {
            var post_data = request.body;

            var plaint_password = post_data.password;
            var hash_data = saltHashPassword(plaint_password);

            var password = hash_data.passwordHash;
            var salt = hash_data.salt;

            var name = post_data.name;
            var email = post_data.email;

            var insertJson = {
                'email': email,
                'password': password,
                'salt': salt,
                'name': name
            };

            var db = client.db('hwmDatabase');

            db.collection('user')
                .find({ 'email': email }).count(function (err, number) {
                    if (number != 0) {
                        response.json('Email already exists');
                        console.log('Email already exists');
                    }
                    else {
                        db.collection('user')
                            .insertOne(insertJson, function (error, res) {
                                response.json('Registration successful');
                                console.log('Registration successful');
                            })
                    }
                })
        });

        app.post('/login', (request, response, next) => {
            var post_data = request.body;

            var email = post_data.email;
            var userPassword = post_data.password;

            var db = client.db('hwmDatabase');

            db.collection('user')
                .find({ 'email': email }).count(function (err, number) {
                    if (number == 0) {
                        response.json('Email not exists');
                        console.log('Email not exists');
                    }
                    else {
                        db.collection('user')
                            .findOne({ 'email': email }, function (err, user) {
                                var salt = user.salt;
                                var hashed_password = checkHashPassword(userPassword, salt).passwordHash;
                                var encrypted_password = user.password;

                                if (hashed_password == encrypted_password) {
                                    response.json('Login success');
                                    console.log('Login success');
                                }
                                else {
                                    response.json('Wrong password');
                                    console.log('Wrong password');
                                }
                            })
                    }
                })
        });

        console.log("Connection Open!")

        app.listen(3000, () => {
            console.log("APP IS LISTENING ON PORT 3000")
        })
    })
    .catch(err => {
        console.log("Error lmao")

        console.log(err)
    })

The package.json file is attached below:

{
  "name": "hwm_nodejs_mongodb",
  "version": "1.0.0",
  "description": "hwm backend",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Underdogs_United",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "crypto": "^1.0.1",
    "express": "^4.18.2",
    "mongodb": "^6.3.0",
    "mongoose": "^8.0.1"
  }
}

This code is part of a task which was given to us (I am part of a team). I have to create a database using MongoDB using node.js as server. I used express as I am comfortable with it.
When I used an API testing tool to see if i can send data to my database, I was unable to do so. It showed status code:500 and rather than getting a JSON file, it got an HTML file, which is an error.
The error it showed on the terminal is as follows:
Connection Open!
APP IS LISTENING ON PORT 3000
TypeError [ERR_INVALID_ARG_TYPE]: The “data” argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at new NodeError (node:internal/errors:406:5)
at Hmac.update (node:internal/crypto/hash:104:11)
at sha512 (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBindex.js:16:10)
at saltHashPassword (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBindex.js:26:24)
at C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBindex.js:46:29
at Layer.handle [as handle_request] (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterroute.js:144:13)
at Route.dispatch (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterroute.js:114:3)
at Layer.handle [as handle_request] (C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterlayer.js:95:5)
at C:UsersBS JaglanDocumentshwm_nodeJS_mongoDBnode_modulesexpresslibrouterindex.js:284:15

Need to modify matrix rain in javascript

I’ve tried to modify this script so that instead of having the rain composed of random chars it display a name, let’s say, just for the pourpose of this exercise, “John Smith”. What I want is that on every column the name ‘John Smith’ is falling down from top to bottom with the same ghost effect of the original script.
Just for info I found this script on “https://github.com/javascriptacademy-stash/digital-rain”.
On every column I should see the name written like this:

enter image description here

So from the top border I can see John coming out first followed by Smith. That’s what I want to change but it seems so difficult to just change the string.

const canvas = document.getElementById('Matrix');
const context = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const katakana = 'アァカサタナハマヤャラワガザダバパイィキシチニヒミリヰギジヂビピウゥクスツヌフムユュルグズブヅプエェケセテネヘメレヱゲゼデベペオォコソトノホモヨョロヲゴゾドボポヴッン';
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';

const alphabet = katakana + latin + nums;

const fontSize = 16;
const columns = canvas.width/fontSize;

const rainDrops = [];

for( let x = 0; x < columns; x++ ) {
    rainDrops[x] = 1;
}

const draw = () => {
    context.fillStyle = 'rgba(0, 0, 0, 0.05)';
    context.fillRect(0, 0, canvas.width, canvas.height);
    
    context.fillStyle = '#0F0';
    context.font = fontSize + 'px monospace';

    for(let i = 0; i < rainDrops.length; i++)
    {
        const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length));
        context.fillText(text, i*fontSize, rainDrops[i]*fontSize);
        
        if(rainDrops[i]*fontSize > canvas.height && Math.random() > 0.975){
            rainDrops[i] = 0;
        }
        rainDrops[i]++;
    }
};

setInterval(draw, 30);

provisional headers are shown. disable cache to see full headers for google auth login

Subdomain working fine with google login but main domain not working, only header error but no error on console log. I would like to inform that my main domain html php prefix removed but subdomain with php prefix.

    function handleCredentialResponse(response){
      
    // Post JWT token to server-side
    fetch("log", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ request_type:'user_auth', credential: response.credential }),
    });
 
}```
This code with database insert code working working fine with google login in subdomain where is php prefix but my main domain without prefix not working.

I had try below this code:

` <script>
     function handleCredentialResponse(response) {
        decodeJwtResponse(response.credential);
    }

    function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
}

function decodeJwtResponse(data){
    console.log(parseJwt(data))
 
}
</script>`

This code working on console log in main domain without prefix and get JSON but its bot working when I create another JS file and put in. Its only working on html body or header.

I want to work on first code which working on subdomain but I want to do without html php prefix. Please help me get out. 

nodejs connector to mariadb keeps timeouting

Hi this is my first stackoverflow post, I am currently working on a project for school, but unfortunately I can’t get this bug fixed.

I have a node.js script which should process a JSON file and insert it into a MariaDB database. However, when I execute the script, the following error message appears after 10 seconds (timeout). I suspect that it is not due to the processing function of the script, but already timeouted before.

The database and the script are both on my Raspberry PI 4 with Rasbian

Regards
Alex from Frankfurt, Germany

error message:

Error:  SqlError: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10002ms
    (pool connections: active=0 idle=0 limit=5)
    at module.exports.createError (/home/alexpi/node_modules/mariadb/lib/misc/errors.js:64:10)
    at Pool._requestTimeoutHandler (/home/alexpi/node_modules/mariadb/lib/pool.js:349:26)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  sqlMessage: 'retrieve connection from pool timeout after 10002msn' +
    '    (pool connections: active=0 idle=0 limit=5)',
  sql: null,
  fatal: false,
  errno: 45028,
  sqlState: 'HY000',
  code: 'ER_GET_CONNECTION_TIMEOUT'
}

node.js script:

const mariadb = require('mariadb');
const moment = require('moment-timezone');
const fs = require('fs');

// Read the JSON file
const rawData = fs.readFileSync('weather.json');
const weatherData = JSON.parse(rawData);

// Database connection configuration
const pool = mariadb.createPool({
  host: 'localhost',
  user: 'querry',
  password: 'querry_pw',
  database: 'weather',
  connectionLimit: 5,
});

async function processData() {
  // Create a connection
  let conn;
  try {
    conn = await pool.getConnection();

    // Delete existing entries in the database
    await conn.query('DELETE FROM allData');

    // Iterate over each weather entry
    for (const entry of weatherData.weather) {
      // Parse and convert timestamp to CET
      const timestampCET = moment(entry.timestamp).tz('Europe/Berlin');

      // Round values
      const temperature = Math.round(entry.temperature);
      const windSpeed = Math.round(entry.wind_speed);
      const precipitation = Math.round(entry.precipitation);
      const precipitationProbability = Math.round(entry.precipitation_probability);

      // Insert data into the database
      await conn.query(
        'INSERT INTO allData (date, time, temperature, wind_speed, precipitation, precipitation_probability, icon) VALUES (?, ?, ?, ?, ?, ?, ?)',
        [
          timestampCET.format('YYYY-MM-DD'),
          timestampCET.format('HH:mm:ss'),
          temperature,
          windSpeed,
          precipitation,
          precipitationProbability,
          entry.icon,
        ]
      );
    }

    console.log('Data inserted successfully.');
  } catch (err) {
    console.error('Error: ', err);
  } finally {
    if (conn) conn.release(); // release connection
  }
}

// Process the data
processData();

I have read through every Google entry on the error message and asked AI, but unfortunately no approach has worked so far.

Is using `aes-gcm-256` encoding with web crypto api like this secure?

Just wanted to make sure if there are any holes in my implementation 🙂

Because i’m running my app in edge environment most of the node apis are unavailable. i’m using web crypto api

Encoding

const generateToken = async ({ userId }: { userId: number }): Promise<string> => {
    const iv = crypto.getRandomValues(new Uint8Array(12));
    const aesGcmParams: AesGcmParams = { name: 'AES-GCM', iv };
    const serverBaseUrl = new URL(process.env.BASE_URL);
    const clientBaseUrl = new URL(process.env.BASE_URL);
    const key = await crypto.subtle.importKey(
        'raw',
        Buffer.from(process.env.TOKEN_SECRET, 'base64url'),
        { name: 'AES-GCM', length: 256 },
        false,
        ['encrypt', 'decrypt'],
    );

    const payload: AuthTokenPayload = {
        iat: dayjs().valueOf(),
        exp: dayjs().add(28, 'days').valueOf(),
        iss: serverBaseUrl.hostname,
        aud: clientBaseUrl.hostname,
        user_id: userId,
    };

    const utf8EncodedPayload = Buffer.from(JSON.stringify(payload), 'utf8');
    const encryptedArrayBuffer = await crypto.subtle.encrypt(aesGcmParams, key, utf8EncodedPayload);

    return Buffer.concat([iv, Buffer.from(encryptedArrayBuffer)]).toString('base64url');
};

Decoding

const decryptToken = async (token: string): Promise<AuthTokenPayload> => {
    const tokenBuffer = Buffer.from(token, 'base64url');
    const iv = tokenBuffer.subarray(0, 12);
    const cipher = tokenBuffer.subarray(12);
    const aesGcmParams: AesGcmParams = { name: 'AES-GCM', iv };
    const key = await crypto.subtle.importKey(
        'raw',
        Buffer.from(process.env.TOKEN_SECRET, 'base64url'),
        { name: 'AES-GCM', length: 256 },
        false,
        ['encrypt', 'decrypt'],
    );

    const decryptedArrayBuffer = await crypto.subtle.decrypt(aesGcmParams, key, cipher);
    const decryptedUtf8String = Buffer.from(decryptedArrayBuffer).toString('utf8');

    const payload = AuthTokenPayloadSchema.parse(JSON.parse(decryptedUtf8String));

    return payload;
};

and this is how i generated my TOKEN_SECRET

const generateKey = async (): Promise<string> => {
    const generatedKey = await crypto.subtle.generateKey(
        {
            name: 'AES-GCM',
            length: 256,
        },
        true,
        ['encrypt', 'decrypt'],
    );
    const exportedKey = await crypto.subtle.exportKey('raw', generatedKey);

    return Buffer.from(exportedKey).toString('base64url');
};

i’m kinda using it as jwt as i’m allowing access to resources based on user_id in the decrypted token (not checking the database), but i didn’t go with jwt because i don’t want anyone to read the contents inside of the token and also just for the sake of learning how to do this without it lol

is this more secure than jwt with RS256 algorithm?

Set map.setHeading() transition speed in google maps javascript API

I use google maps API on a mobile device (web application, javascript) and would like to update the map’s heading so the map’s north is always pointing to the real worlds north:

map.setHeading(-alpha);

So far so good, but there seems to be a rotation transition for some milliseconds causing a laggy rotation experience. You can try it:

map.setHeading(90);

My Question: I was wondering if the transition can be removed or if the duaration can be set to 0s?

Thanks & best regards,
Andreas

Why my Luhn’s algorithm implementation is not working? (JS)

I’m currently implementing a Luhn algorithm on javascript:

const validateCred = arr => {
  let sum = 0, cardNum = [...arr]
  const lastCardNum = cardNum.pop()
  cardNum.reverse()

  cardNum.forEach((element, index)=> index % 2 === 0 ? sum+=element: element*2 > 9 ? sum+=element*2-9: sum+=element*2)
  
  return sum % 10 === lastCardNum ? true: false
}

The Luhn Formula:

  • Drop the last digit from the number. The last digit is what we want to check against
    Reverse the numbers
  • Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and subtract 9 to all any result higher than 9
  • Add all the numbers together
  • The check digit (the last number of the card) is the amount that you would need to add to get a multiple of 10 (Modulo 10)

I’m trying to test the following code but it returns true instead of false:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; // actually a valid card number
console.log(validateCred(valid1)) // returns false :/

For some reason the sum of all numbers is 66 and obviously the modulo 10 of it is 6 and not 8

Gerar Codigo hierárquico Plano Contas [closed]

Estou tentando gerar uma sugestão do proximo codigo do plano de contas mas a minha função não esta fazendo corretamente e não estou conseguindo ter o codigo correto, no caso abaixo quando eu clicar em uma conta 2.1 ele deve me sugerir 2.1.1 se ja tiver ele sugere o proximo disponivel naquela hierarquia e assim para os de mais , alguem ja vez isso ou e tem uma dica vou disponibilizar meu codigo ele faz uma coisa semelhamente mas ele incrementa mais um depois e não ta fazendo correto

2 Passivo
2.1 Passivo Circulante
2.1.1 Impostos
2.1.1.1 FUNRURAL
2.1.1.2 ICMS ST
2.1.2 Contas a Pagar
2.1.2.1 Fornecedores
2.1.2.2 Produtores
2.1.2.3 Compradores
2.1.2.4 Motoristas
2.2 Passivo Não Circulante
2.2.1 Empréstimo bancário (longo prazo)
2.2.1.1 Empréstimo banco


<script>
  // Obtém a lista de contas
  const contas = document.querySelectorAll('.conta');

  // Adiciona um ouvinte de evento para cada conta
  contas.forEach(conta => {
    conta.addEventListener('click', () => {
      // Obtém o código da conta clicada
      const codigoAtual = conta.getAttribute('data-codigo');

      // Calcula o próximo código considerando o nível
      const proximoCodigo = calcularProximoCodigo(codigoAtual);

      // Verifica se o próximo código já existe no mesmo nível
      const proximoCodigoExiste = verificarExistenciaCodigo(proximoCodigo);

      if (proximoCodigoExiste) {
        alert(`O próximo código ${proximoCodigo} já existe no mesmo nível.`);
      } else {
        // Exibe o próximo código
        //document.getElementById('proximo-codigo').innerText = `Próximo código: ${proximoCodigo}`;
        $('#codestrutural').val(proximoCodigo);
        $('#cadcontasmodal').modal('show');
        var set = setInterval(function(){
                $('#desc').focus();
                clearInterval(set);
            },600);
      }
    });
  });

  // Função para calcular o próximo código com base no código atual e nível
  function calcularProximoCodigo(codigoAtual) {
    // Quebra o código atual em partes
    const partes = codigoAtual.split('.');

    if(partes.length == 1){
       // Se for o primeiro nível, adiciona '.1'
        const proximoCodigo = partes[0]+'.1';
        return proximoCodigo;
    }else{
        const ultimoNumero = parseInt(partes.pop(), 10) + 1;

        // Adiciona o novo número à lista
        partes.push(ultimoNumero);

        // Junta as partes para formar o novo código
        const proximoCodigo = partes.join('.');

        return proximoCodigo;
    }
    // Incrementa o último número

  }

  // Função para verificar se um código já existe no mesmo nível
  function verificarExistenciaCodigo(proximoCodigo) {
    // Obtém todos os elementos da tabela com a classe 'conta'
    const contas = document.querySelectorAll('.conta');

    // Extrai o nível do próximo código
    const nivelProximoCodigo = proximoCodigo.split('.').length;

    // Verifica se o código já existe no mesmo nível
    for (const conta of contas) {
      const codigoExistente = conta.getAttribute('data-codigo');
      const nivelCodigoExistente = codigoExistente.split('.').length;

      if (nivelProximoCodigo === nivelCodigoExistente && codigoExistente.startsWith(proximoCodigo)) {
        return true;
      }
    }

    return false;
  }
</script>

jest – Extend call stack of failed test outside of helper function, up to the test case

While writing unit tests for my codebase, I’ve noticed that I’m duplicating the code that does the http request and adds expectations for the response. So I ended up with some helper functions, one of those is called: expectedResponseForGET, which I made static inside a TestUtils class, in a file called: utils.ts.

In some tests I call that method multiple times to check multiple things after a POST. But when that expectation fails(the response is not what I expected to be), the test fails and the call stack shows that it failed the expectation from the expectedResponseForGET function, without the call stack to the test which called that helper function.

The call stack I receive for the failed expectation looks like this:

src/tests/sites/add.test.ts
  Add site route
    ✓  User4 - Add site, not company manager (238 ms)
    ✕  User1 - Add site, company manager (269 ms)

  ● Add site route ›  User1 - Add site, company manager

    expect(received).toEqual(expected) // deep equality

    - Expected  -  1
    + Received  +  1

    @@ -1,63 +1,10 @@
    -       "location": "Location2",
    +       "location": "Location",

      92 |       .set('Authorization', user.token);
      93 |     expect(res.status).toBe(200);
    > 94 |     expect(res.body).toEqual(response);
         |                      ^
      95 |     return res;
      96 |   };
      97 |

      at src/tests/utils.ts:94:22
      at fulfilled (src/tests/utils.ts:5:58)

This part:

at src/tests/utils.ts:94:22            -> This is for the line containing the expectation
at fulfilled (src/tests/utils.ts:5:58) -> This is for the import of request from supertest

Which doesn’t contain the line from src/tests/sites/add.test.ts test file which called expectedResponseForGET.

Here is the test:

test(' User1 - Add site, company manager', async () => {
    await TestUtils.expectedResponseForPOST(
      server,
      C1.users.U1,
      route,
      C1.sites.S5.requests.addSite,
      C1.sites.S5.responses.fullSite,
    );

    await TestUtils.expectedResponseForGET(
      server,
      C1.users.U1,
      routeSites,
      C1.sites.responses.allAfterS5,
    );

   await TestUtils.expectedResponseForGET(
      server,
      C1.users.U1,
      routeWork,
      C1.work.responses.allAfterS5,
    );
  });

Here are the helper functions:

import request from 'supertest';

class TestUtils{
  static expectedResponseForGET = async (
    server: Express,
    user: UserTest,
    route: string,
    response: GenericResponse,
  ) => {
    const res = await request(server)
      .get(route)
      .set('Authorization', user.token);
    expect(res.status).toBe(200);
    expect(res.body).toEqual(response);
    return res;
  };

  static expectedResponseForPOST = async (
    server: Express,
    user: UserTest,
    route: string,
    // eslint-disable-next-line @typescript-eslint/ban-types
    req: Object,
    response: GenericResponse,
  ) => {
    const res = await request(server)
      .post(route)
      .send(req)
      .set('Authorization', user.token);
    expect(res.status).toBe(200);
    expect(res.body).toEqual(response);
    return res;
  };
}

Has anyone encountered this problem and knows a fix for this or a workaround to display the line from the test which called the helper method?

buffering in lottieFiles lottie animation at first go

const Animation = () => {
    const lottieRef = useRef();
    const {
        gameLottieSrc,
        isLose
    } = useGameContext();

    useEffect(() => {
        if (isLose) {
            if (lottieRef.current) {
                lottieRef.current.load(gameLottieSrc);
            }
        } else {
            if (lottieRef.current) {
                lottieRef.current.load(gameLottieSrc);
            }
        }
    }, [gameLottieSrc]);

    if (isLose) {
        return ( <
            div >
            <
            lottie - player ref = {
                lottieRef
            }
            autoplay loop count = {
                2
            }
            src = {
                gameLottieSrc
            }
            path = {
                gameLottieSrc
            }
            speed = {
                0.6
            }
            background = "transparent"
            className = "dragon raw"
            id = "dragon" >
            <
            /lottie-player> < /
            div >
        );
    }
    export default Animation;

i try to make a game for which i have used lottie-player in which i fetch the json and i pass the json in src but it has buffering animation at first time is there anything in LottieFiles/lottie-player to smoothen the animation

The content of scraped div is empty (Dynamic JS script)

Could someone please help me scraping information from transfermarkt?

This is an example url: https://www.transfermarkt.com/georginio-wijnaldum/transfers/spieler/49499

This is how it looks in DevTools:
TransferHistoryScript

For this question I would like to know if I could scrape the text value ‘Paris SG’ in this case.

I tried this:

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
url = https://www.transfermarkt.com/georginio-wijnaldum/transfers/spieler/49499

temp_player = requests.get(url, headers=headers, timeout=5)
temp_player = BeautifulSoup(temp_player.text, 'html.parser')
test = etree.HTML(str(temp_player))
temp_player_name = test.xpath('//*[@id="main"]/main/div[2]/div[1]/tm-transfer-history/div/div[2]/div[3]/a[2]')
print(temp_player_name) 

which returns an empty list.

I have tried multiple xpaths, but none of it returns anything. Also, looking at the html text when read in Python, the value cannot be found manually.

Any help would be appreciated!
Thanks in advance

Any questions or unclarities, please let me know.

how to properly export functions to JS

I have a 2 functions in userController.js file and i wanna export functions and import in another file but i have an error:

import selectPersonData from “./controllers/userController.js”
^^^^^^^^^^^^^^^^
SyntaxError: The requested module ‘./controllers/userController.js’ does not provide an export named ‘default’

This is code of functions and export

async function selectAllData (config) {
    const selectQuery = 'SELECT * FROM YourTableName';
  
    try {
      const pool = await sql.connect(config);
      const result = await pool.request().query(selectQuery);
      return result.recordset;
    } catch (err) {
      console.error('Request execution error:', err);
      throw err;
    } finally {
      await sql.close();
    }
  };

 async function selectPersonData (config, id) {
  const selectQuery = `SELECT id, name FROM YourTableName WHERE id = @id`;
  
  try {
    const pool = await sql.connect(config);
    const result = await pool.request()
      .input('id', sql.Int, id)
      .query(selectQuery);
    await sql.close();
    return result.recordset;
  } catch (err) {
    console.error('Request execution error:', err);
    throw err;
  }
}

export { selectPersonData, selectAllData };

And this is import code:

import {selectPersonData, selectAllData} from "../controllers/userController.js";

I tried a lot of variants which i found in some articles and other questions in stackoverflow and asked chatGPT but nothing and i have no idea what to do
P.S I have nodejs version 18.16 and i have “type”: “module”, in my package json file

Percentage Loading Animation using max time

I saw a solution loading animmation on this forum on how to display a loading bar before the entire page is loaded. However, the solution doesn’t really solve my problem, I want to animation progress to be determined by a time that I set, say 60 secs and not determined by document.images.length as implemented in the solution below.

;(function(){
  function id(v){ return document.getElementById(v); }
  function loadbar() {
    var ovrl = id("overlay"),
        prog = id("progress"),
        stat = id("progstat"),
        img = document.images,
        c = 0,
        tot = img.length;
    if(tot == 0) return doneLoading();

    function imgLoaded(){
      c += 1;
      var perc = ((100/tot*c) << 0) +"%";
      prog.style.width = perc;
      stat.innerHTML = "Loading "+ perc;
      if(c===tot) return doneLoading();
    }
    function doneLoading(){
      ovrl.style.opacity = 0;
      setTimeout(function(){ 
        ovrl.style.display = "none";
      }, 1200);
    }
    for(var i=0; i<tot; i++) {
      var tImg     = new Image();
      tImg.onload  = imgLoaded;
      tImg.onerror = imgLoaded;
      tImg.src     = img[i].src;
    }    
  }
  document.addEventListener('DOMContentLoaded', loadbar, false);
}());
*{margin:0;}

Thank you.

I tried to rewrite the code to use a max time to display the percentage progress bar without success.
I would want the % to increment with the number of times I set.