setInterval that changes innerHTML seems to interfere with EventListener?

I have an interesting behavior where a timer that’s changing innerHTML of a div seems to invalidate a previously added EventListener. Should I be re-adding the EventListener every time innerHTML gets updated?

If you wait 5 seconds on the JSFiddle and then try to click ‘Settings’ nothing will happen …

HTML:

<div class="header left font13" id="setup">Settings</div>
<div class="header mid font13" id="wtime"></div>

JavaScript:

document.getElementById("setup").addEventListener("click", function() {
  console.log("Settings!");
});

setInterval(function() {
  console.log("Alive!");
  document.getElementById("wtime").innerHTML = "11:45".replaceAll(":", "<span class='blink'>:</span>");
}, 5000);

https://jsfiddle.net/pog0h29t/

Node Postgres Library Error When Searching JSON Object

I am using the node-postgress package in my React project. I am trying to query my PostgreSQL database and for some reason this specific filter isn’t working with their variable substitution. Am I doing something wrong?

First, my where clause is located within:

await client.query(`QUERY HERE`, [VARIABLES])

And the specific where clause causing me issues is with my object History. History is a JSON object, and contains a record, state, which is an array that contains several states. I am trying to see if a specific state code, like OH, exists in this array.

($15::text = '' OR h.history -> 'state' @> '["' || $15::text || '"]')

While this doesn’t work, this does:

($15::text = '' OR h.history -> 'state' @> '["OH"]')

Can someone please help? I am very confused.

How to transform Source code to code tree in Visual Studio Code

I’ve got a source code which I´d like to modify and reuse. The picture shows an example (not my website). I’ve got stuck for a while with the simple task of displaying the code not as a flowing text but as an actual code tree. Excuse my lack of basic skills; everyone starts somewhere. Appreciate your responses and guidance.

enter image description here

Already tried to find the settings in VSC without results. Also, lacking the correct terminology, I couldn’t find any information through google, AIs or YouTube. Any hint is welcome.

How to click on two or more elements in the same location

I have a graphic chart that has some dots in it. These dots may locate in one place. I need to process click on two or more elements in the same spot. Is there any simple ways to do that in Vue 3?

I tried using refs and passing them to handleClick function so I can see which elements was clicked. But only higher element is responding to click.

Express JS and Mongo DB connection issues

This is the simple code of connecting the express js to mongodb, and i also install the both packages, so why i’m facing this error?

const express = require("express");
const app = express();

app.listen(300,() => {
    console.log("Server is running at port number 3000");
})

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myDatabase",{
    useNewUrlParser:true,
    useUnifiedTopology:true
})
.then(()=>{console.log("Connection is Succeed")})
.catch((e)=>{console.log("Received an Error")});

Error I’m facing, they are not connecting.

Server is running at port number 3000
(node:10828) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
(Use `node --trace-warnings ...` to show where the warning was created)
(node:10828) [MONGODB DRIVER] Warning: `useUnifiedTopology` is a deprecated option: `useUnifiedTopology` has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
Received an Error

Postman REST API Decrypt From Responses Test Script

i am trying to decrypt responses in postman using Tests Script. I use pre-request script to create headers request..

My pre-request script

const consid = pm.environment.get('consid');
const secretkey = pm.environment.get('secretkey');
const userkey = pm.environment.get('userkey');
var timestamp = String(Math.floor(Date.now() / 1000));

var pre_signature = CryptoJS.HmacSHA256(consid + "&" + timestamp, secretkey).toString(CryptoJS.enc.Base64);

var pre_auth = pm.environment.get('username') + ':' + pm.environment.get('password') + ':' + pm.environment.get('AppCode');

var auth = btoa(pre_auth);

pm.request.headers.add({
    key: "X-cons-id",
    value: consid
});
pm.request.headers.add({
    key: "X-timestamp",
    value: timestamp
});
pm.request.headers.add({
    key: "X-signature",
    value: pre_signature
});
pm.request.headers.add({
    key: "X-Authorization",
    value: 'Basic ' + auth
});
pm.request.headers.add({
    key: "user_key",
    value: userkey
});

My Tests Script

const consid = pm.request.headers.get('X-cons-id');
const secretkey = pm.environment.get('secretkey');
const tStamp = pm.request.headers.get('X-timestamp');
const pre_encryptedBody = pm.response.json();
const encryptedBody = pre_encryptedBody.response;
const key = consid + secretkey + tStamp;

if (pre_encryptedBody.response != "") {
    let iv = CryptoJS.enc.Hex.parse(CryptoJS.SHA256(key).toString().substring(0, 32));
    let key_hash = CryptoJS.enc.Hex.parse(CryptoJS.SHA256(key).toString());

    let decryptedMessage = CryptoJS.AES.decrypt(
        encryptedBody,
        key_hash,
        {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }
    );

    decryptedMessage = decryptedMessage.toString(CryptoJS.enc.Base64);

    const lzstringJS = pm.globals.get('lz_stringjs');

    pm.sendRequest(lzstringJS, (error, response) => {
        eval(response.text());
        let json = LZString.decompressFromEncodedURIComponent(decryptedMessage);
        pm.environment.set("response_decoded", json);

        let bodyResponse = pre_encryptedBody;
        bodyResponse.response = JSON.parse(json);

        var template = `
            <html>
                <body>
                    <pre id="response_decoded">
                    </pre>
                    <script>
                        pm.getData((err, data) => {
                            document.getElementById("response_decoded").innerHTML = JSON.stringify(JSON.parse(data.response), null, 4);
                        });
                    </script>
                </body>
            </html>
        `;
        pm.visualizer.set(template, {
            response: JSON.stringify(bodyResponse)
        });
    });
}

I got a blank “response_decoded” in my env. Where is the error in writing my javascript code. Thank you.

I tried to change the Test script

decryptedMessage = decryptedMessage.toString(CryptoJS.enc.Utf8);

but i got Error: Malformed UTF-8 data

How to Enable a Submit Button on a Submit Button Click from Another Page (PHP)

I need your help on a project I’m working on. So here is my scenario, I have button1 and button3 on page1 and button2 on page2. Now I need to disable button2 and button3 by default, and then enable button2 when you click button1, and then enable button3 when you click button2. I am using PHP and Java Script. Thank you so much.

I haven’t tried anything yet because I cant figure out how I’m going to code the function.

How to show a React component when a single table row is clicked

I am creating a table in React that has multiple rows. For each row there will be a React component underneath called AutoShopPricesExpanded that has more details about that row’s prices. When I click on a single row I want to show only 1 of the components underneath.

Currently, the code shows all the components for every row when the user clicks on the ‘Toggle Show’ button.

My question is, how do I only show a single component for the relevant table row.

The code below is my current progress

import { Box, Text, Table, Tbody, Td, Th, Thead, Tr} from '@chakra-ui/react';
import {AutoShopPriceExpand} from './autoShopPriceExpand';
import { useState } from 'react';

export const AutoShopPricesList = ({filteredAutoShopPricesLists}:{filteredAutoShopPricesLists: any}) => {
    const [isOpen, setIsOpen] = useState(false);
    function toggle() {
        setIsOpen((isOpen) => !isOpen);
    }

    return (
        <Box py={1}>
            <Table variant='striped'>
                <Thead>
                    <Tr>
                        <Th>Vehicle</Th>
                        <Th>Service</Th>
                        <Th isNumeric>Price</Th>
                    </Tr>
                </Thead>
                <Tbody>
                    {filteredAutoShopPricesLists.map((autoshop: any)=>{
                        return(
                            <>
                                <button onClick={toggle}>Toggle show</button>
                                <Tr key = "lol">
                                    <Td>{autoshop.car_year} {autoshop.car_make} {autoshop.car_model} <br/> <Text color='gray' fontSize='sm'> {autoshop.car_trim} </Text></Td>
                                    <Td>{autoshop.service} <br/>  <Text color='gray' fontSize='sm'>{autoshop.date_of_quote} </Text> </Td>
                                    <Td isNumeric> ${autoshop.service_price} <br/>  <Text color='gray' fontSize='sm'>{autoshop.source_of_price} </Text></Td>
                                </Tr>
                                {isOpen && <AutoShopPriceExpand details = {autoshop}/>}
                            </>
                        );
                        
                    })}
                </Tbody> 
            </Table>  
        </Box>
    );
};

Should we embed GA4 into an iframe of a page even though this page has already embedded another GA4 account?

I’m researching “Can I embed one more GA4 account into an iframe of the page even though this page has already embedded another GA4 account?”

I researched that we shouldn’t use two GA4 accounts on a page, as it will lead to tracking inaccurate metrics.

In this scenario, a GA4 account (account A) is embedded in an iframe of a page and this page is also using a different GA4 account (account B). Does it lead to influences of tracking Analytics?

problem in calculation of 2 input tag variable in JavaScript

i have 2 selector

  1. var price = parsFloat($(‘[argumentid=”Price”]’).val());

  2. var totalAmount = parsFloat($(‘[argumentid=”TotalAmount”]’).val());
    price and totalamount input tag are disabled ,
    in the price ,the value come from sql server and change dynamically everytime, the price value not set from outside ,because this input tag is disabled,and i want keep it disabled.
    i want , whenever changed price value Whenever there is a price value change. So the value of the price should be copied in the same time total amount.
    And the decimal with the price should be .000.
    And the total amount should also be rounded to a decimal
    i,m trying, whenever price value change then same time in the totalamount, price value copied

Test with Jest impossible to pass

I’m building a simple battleship game in javascript and I’m trying to test this module with Jest:

class Ship{
    constructor(length,coordinates){
        this.length=length;
        this.hits=0;
        this.coordinates=coordinates;
        this.sunk=false;
    }
    hit(){
        return this.hits+=1
    }
    isSunk(){
        if(this.hits==this.length){
            this.sunk=true
            return true
        }else{
            return false
        }
    }
}
class Gameboard{
    constructor(player,ships){
        this.player=player;
        this.shipsNumber=ships.length;
        this.ships=ships;//ships is an array of objects
        this.missingCoordinates=[]
    }
    receiveAttack(coordinates){
        let found=false
        //inserire la logica di controllo se lo shot è stato gia fatto
        //se non è stato fatto controlla se ha preso la nave
        //Se ha preso la nave nopn cambiare turno, inserisci le coordinate nell' array shots e continua a giocare
        //looks in each ship if the coordinate of the shot matches
        this.ships.forEach(object=>{
        if(object.coordinates.includes(coordinates)){  
            //if matches hit the ship and check if it s sunk         
            found=true;
            object.hit();
            if(object.isSunk()){
                this.shipsNumber-=1
            }
        }
      })
      //if doesn t match put the coordinates in missing coordinates
      // se invece non ha colpito la nave  cambia turno e insirisci le coordinate negli shot
      //later we can change the color to the cell and make it impossible to click again
      if(found==false){
        this.missingCoordinates.push(coordinates);
      }
     this.player.active=true;
    }
}
class Player{
    constructor(name,active){
        this.name=name
        this.active=active
    }
    attackOpponent(coordinates,opponentGameboard){
        opponentGameboard.receiveAttack(coordinates);
        this.active=false;
    }
}
module.exports={Gameboard,Ship,Player};

Using this tests sequence:

let {Gameboard,Ship, Player} = require("./App");

let user=new Player("Eligio",true);
let computer=new Player("Computer",false);

let userShips=[new Ship(4,["00","01","02","03"]),new Ship(4,["20","21","22","23"])];
let computerShips=[new Ship(4,["70","71","72","73"]),new Ship(4,["80","81","82","83"])];

test('hitted boat', () => {
    let gameboard1= new Gameboard(user, userShips)
    gameboard1.receiveAttack("00");
    expect(gameboard1.ships[0].hits).toBe(1);
});
test('Sunk boat', () =>{
    let gameboard1= new Gameboard(user, userShips)
    gameboard1.receiveAttack("00");
    gameboard1.receiveAttack("01");
    gameboard1.receiveAttack("02");
    gameboard1.receiveAttack("03");
    expect(gameboard1.ships[0].sunk).toBeTruthy()
})
test('missing shot', ()=>{
    let gameboard1= new Gameboard(user, userShips)
    gameboard1.receiveAttack("25")
    expect(gameboard1.missingCoordinates[0]).toBe("25")
})
test('all ships are sunk',()=>{
    let gameboard1= new Gameboard(user, userShips)
    gameboard1.receiveAttack("00");
    gameboard1.receiveAttack("01");
    gameboard1.receiveAttack("02");
    gameboard1.receiveAttack("03");
    gameboard1.receiveAttack("20");
    gameboard1.receiveAttack("21");
    gameboard1.receiveAttack("22");
    gameboard1.receiveAttack("23");
    expect( gameboard1.shipsNumber).toEqual(0);

})
test('switching players', ()=>{
    let playerGameboard= new Gameboard(user, userShips);
    let computerGameboard=new Gameboard(computer,computerShips)
    user.attackOpponent("00",computerGameboard);
    expect(user.active).toBeFalsy();
    expect(computer.active).toBeTruthy()
    computer.attackOpponent("00",playerGameboard);
    expect(computer.active).toBeFalsy()
    expect(user.active).toBeTruthy();
})

I manage to pass all tests apart for the “all ships are sunk”.

Using different console logs the App works as expected so I can’t really understand why the test doesn’t pass.
I’ve also tried different Jest Matchers like .toBe to see if there were any differences but nothing

Can anyone help me please?

Progressive Web App Notification Creation like whatsapp or skype [closed]

Developing a progressive web app, facing issues while creation of whatsapp or skype like notification at time of phone calling

I want to convert my website to progressive web app which should be compatible with mobile devices as well and behave like a mobile app. So, I am trying to add the phone call feature for that i am using the twilio and I want to make calling feature something like whatsapp or skype in which when we start to call the user then got the notification also and it also tells about the status of call like ringing ,ongoing etc.I also want to add the answer and decline call buttons at the notification..And that notification will not hide until or unless call is disconnected. At click of that notification it should render the calling page but that notification should stick shouldnt be disppear from notifications bar…
Technology stack :Javscript, nodejs(additional php)

Can anyone help me out, its really very urgent how can i implement this feature.Please provide me a solution, I will be very grateful to you.

How to run npm start automatically on page load?

I have been trying to learn npm recently to use for a website. I am wondering though how it is used in a website, like do you have to run the command “npm start”? How is this integrated in a live website? Like would I have to run “npm start” every time the user enters the main page for example? And if yes, how is this done?

On visual studio code I can easily do it by running “npm start” in the terminal, but I am basically wondering how this is done without visual studio code and in a live website?

how to fix react-app-rewired freeze when save?

Please help

When i edit something on development my app will freeze until i refresh it

however i try to use “FAST_REFRESH=false” in script start it refresh app

but in another framework it just update content and not refresh i want like that

this is my script :

“scripts”: {
“dev”: “FAST_REFRESH=false react-app-rewired start”,
“build”: “react-app-rewired build”,
“test”: “react-app-rewired –env=jsdom”,
“less”: “lessc –js src/styles/wieldy.less public/css/style.css && lessc –js src/styles/wieldy.less public/css/style.min.css –compress -x”
},

‘nz-alert’ is not a known element

‘nz-alert’ is not a known element:

  1. If ‘nz-alert’ is an Angular component, then verify that it is part of this module.
  2. If ‘nz-alert’ is a Web Component then add ‘CUSTOM_ELEMENTS_SCHEMA’ to the ‘@NgModule.schemas’ of this component to suppress this message

enter image description here

I just opened an Angular project using VSCode, and after loading the dependencies, the project runs successfully without any errors. However, I am getting error prompts in the editor. How should I handle this situation?

Some of the online solutions I found did not work after trying them. I know it’s not a code issue; it’s likely a configuration problem with VSCode regarding Angular.