React useEffect needs console log to “find” variable

I’m building a web store using magento PWA studio (React). On the privacy cms page I have a button and when the user clicks on that button a cookie message should be shown. Due to security reasons it is not allowed to run inline javascript. I therefore created a simple CookieButton component for this.

import React, { useEffect } from 'react';

const CookieButton = () => {


    function handleClick(e) {
        if (!e.target.matches('#cookieBtn')) return;

        e.preventDefault();

        eCookieBar.bar.open(); return false;
    }

    useEffect(() => {

        const pageTitle = document.querySelector('h1[class*=cms-heading]');
        console.log(pageTitle)
        if(pageTitle && pageTitle.innerText.toLocaleLowerCase().includes('privacy')) {
            document.addEventListener("click", handleClick);
        }

        return () => {
            document.removeEventListener('click', handleClick);
        };
    }, []);

    return null
};

export default CookieButton;

Notice the console.log(pageTitle). This code won’t run unless I put this console.log there. It seems like it slows down the code just enough to find the pageTitle in time. Why is this happening? I dont want to have an unnecessary console.log in my code.

Trivia assistance for an upcoming project

I have been working on a triva quiz for a class project. I have two issues: one, I can’t figure out how to implement text based questions. I could only figure out multiple choice. Two: I couldn’t figure out how to implement a function that would result in a reset after three incorrect answers. If anyone can help out it would be great. I am specifically looking for help on the chatgpt.js file.

GitHub Link: https://github.com/DodgerZ22/Trivia-Quiz

Updating score by comparing results of different strings with conditional || of strings (Rock, Paper, and Scissors Game)

I have been trying to debug this code and was wondering why the playerScore and computerScore does not increment or update correctly.

Here is the full code.


function playRound(playerSelection, computerSelection) {
  console.log("Computer chooses: " + computerSelection);
  if(computerSelection===playerSelection){
      return "It's a Tie!";
  }else if(playerSelection==="paper"){
      if(computerSelection==="rock"){
          return "You Win! Paper beats Rock."
      }else if(computerSelection==="scissors"){
          return "You Lose! Scissors beats Paper."
      }
  }else if(playerSelection==="scissors"){
      if(computerSelection==="paper"){
          return "You Win! Scissors beats Paper."
      }else if(computerSelection==="rock"){
          return "You Lose! Rock beats Scissors."
      }
  }else if(playerSelection==="rock"){
      if(computerSelection==="scissors"){
          return "You Win! Rock beats Scissors."
      }else if(computerSelection==="paper"){
          return "You Lose! Paper beats Rock."
      }
  }
}

function getComputerChoice() {
  let choice = ["rock", "paper", "scissors"];
  return choice[Math.floor(Math.random()*choice.length)]
}

function game(){
  let playerScore = 0;
  let computerScore = 0;
  let round = 1;
  console.log("Welcome to the Rock, Paper, and Scissors Game!")
  for (let i = 0; i<5; i++){
      const computerSelection = getComputerChoice();
      console.log("Round: " + round++);
      const playerSelection = prompt("Rock, Paper, or Scissors: ").toLowerCase();
      const result = playRound(playerSelection, computerSelection);
      console.log(result);
      if(result==="It's a Tie!"){
        continue;
      }
      if(result===("You Win! Paper beats Rock." || "You Win! Scissors beats Paper." || "You Win! Rock beats Scissors.")){
        playerScore++;
      }else if(result===("You Lose! Paper beats Rock." || "You Lose! Rock beats Scissors." || "You Lose! Scissors beats Paper.")){
        computerScore++;
      }
      console.log("Player Score: " + playerScore);
      console.log("Computer Score: " + computerScore);
  }
  console.log("Final Player Score: " + playerScore);
  console.log("Final Computer Score: " + computerScore);
  
  if(playerScore>computerScore){
      return "Congrats! You Win The Game.";
  }else if(playerScore===computerScore){
      return "It's a Tie! Nobody Wins."
  }else{
      return "Too Bad! You Lose The Game."
  }
}

console.log(game());

Here is a picture of the result, the program does not update the score correctly.
playerScore and computerScore does not add correctly.

Please help and explain why. I have just started to learn JavaScript.

How to properly infer nested and complex types in Typescript?

I think sometimes Typescript does not infer properly when it comes to complex and nested types.

I need to know if it’s a bug or if I’m doing wrong. And if I’m doing wrong, what is the best way to achieve inference of nested and complex types ?

I came up with this code so far:

// Storable type is the Object with an optional key prop
type Storable<O, Key extends string> = O & { [key in Key]?: string };
// Stored type is the Object with a required key prop
type Stored<S> = S extends Storable<infer O, infer Key extends string> ? O & { [key in Key]: string} : never

// MyObject is a standard object
type MyObject = { prop1: boolean; prop2: number; };
// MyStorableObject is a Storable MyObject
type MyStorableObject = Storable<MyObject, "id">;

// Transforms a Storable object to a Stored object
function store<T, B extends string>(object: Storable<T, B>, key: B): Stored<T> {
  return { ...object, [key]: 'generatedId' } as unknown as Stored<T>;
}

When I call store function, I expect stored not to be never type :

const storableObject:MyStorableObject = { prop1: true, prop2: 0 };
const stored = store(storableObject, 'id');

What is weird is that sometimes, it works, sometimes it doesn’t. For example, with this MyObject type :

type MyObject = { prop1: string };

The stored object type is what I expect:

const stored: MyObject & {
    id?: string | undefined;
} & {
    id: string;
    prop1: string;
}

How can I create a handleOpen function that opens one chakra ui modal, but closes the modal that was previously opened?

Below is the component that appears when I click on a button, and then there are two new buttons that open a second modal. I need the previous modal to close onOpen of the next modal.

function GetFundsDetails({ onClose: onClosePrevious }: Omit<ModalProps, 'children'>) {
const { isOpen, onClose, onOpen } = useDisclosure();

function handleOpen(onCloseOriginal: () => void, onOpen: () => void) {
return () => {
onCloseOriginal();
onOpen();
};
}

return (
<Box>
<Button onClick={handleOpen(onClosePrevious, onOpen)}>
Click me to open another modal
</Button>
<SecondModalToOpen isOpen={isOpen} onClose={onClose} />
</Box>
);
}

Thank you for looking into this.

I am trying to pass the first modals onClose, into the second modals component, then call that in the handleOpen function before returning the onOpen for the second modal.

Socket.io chat app sends multiple messages with different usernames

I know it sounds ridiculous but believe me guys

The chat app that I am making with socket.io has a problem that first when all the users log in it displays the log in message and also after that when anybody posts a message it displays the message but multiple times with all the usernames active in the chat room even if anyone hasn’t posted the message,

I am a newbie to node.js & socket.io btw,

I would be really grateful if somebody could help me with my problem,

Below are my codes if you want to test the app yourselves and suggest me the proper ways of doing it and fixing the problem,

Sevrer.js –

const express = require('express');
const app = express();
const { Server } = require('socket.io');
const http = require('http');
const server = http.createServer(app);
const io = new Server(server);
const port = 80;
const path = require('path');


app.use(express.static(path.join(__dirname,'public')));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

// Now let's move to the socket io part

io.on('connection', (socket) => {
    socket.on('new-user', (username) => {
        //users[socket.id] = username;
        console.log(`${username} just connected to the server!`);
        io.emit('connected-user', username)
        socket.emit('user-connected',username)
        // console.log("A new user just connected!");
    })


    socket.on('senders-name',(username) => {
        socket.broadcast.emit('name',username);
        //socket.removeAllListeners('senders-name',username);
    })

       socket.on('send message',(chat) => {
        socket.broadcast.emit('the-msg',chat);
        /*socket.on('senders-name',(username) => {
            socket.broadcast.emit('name',username);
        })*/
         console.log(`Sender sent this message : ${chat}`);
    })

    socket.on('send-time',(time) => {
        socket.broadcast.emit('time',time);
        console.log(time);
    })

    socket.on('send-date',(date) => {
        socket.broadcast.emit('date',date);
        console.log(date);
    })


    socket.on('disconnect',(username) => {
        //io.emit('disconnected-user',users[socket.id]);
    //  users[socket.id] = username;
        socket.broadcast.emit('user-disconnect',username);
        io.emit('user-disconnect',username);
        console.log(`${username} just left!`);
        //delete users[socket.id];
    })
})



server.listen(port, () => {
    //console.log(`Server is listening at the https://localhost:${port}/`);
    console.log(`Server is listening at the https://localhost/`);
});

Script.js –

const socket = io();

const sendBtn = document.getElementById("send");
const form = document.getElementById("forms");
const messageInput = document.getElementById("msgs");


const chatWindow = document.getElementById("chat-window");



const joinBtn = document.getElementById("join");
const refreshBtn = document.getElementById("ref");
const usernameInput = document.getElementById("username");
const bg = document.getElementById("bg");
const userForms = document.getElementById("user-form");

var date = new Date();
var current_date = date.getDate()+"/"+(date.getMonth() + 1)+'/'+date.getFullYear();
var current_time = date.getHours()+":"+date.getMinutes();


joinBtn.addEventListener("click",(e) => {
    e.preventDefault();
    if(usernameInput.value === ''|usernameInput.value == null){
        alert("An username is required before entering the chat!");
    }
    else{
        bg.style.opacity = '0';
        bg.style.pointerEvents = 'none';
        // Now lets obtain the user field's value
        const val = usernameInput.value;
        socket.emit('new-user',val);
        socket.emit('user-left',val)
    }
});

userForms.addEventListener('submit',(e) => {
    e.preventDefault();
})

/*usernameInput.addEventListener('keydown',(e) => {
    e.preventDefault();
    if(keyCode = 13){
        if(usernameInput.value === ''|usernameInput.value == null){
            alert("An username is required before entering the chat!");
        }
        else{
            bg.style.opacity = '0';
            bg.style.pointerEvents = 'none';
            // Now lets obtain the user field's value
            const val = usernameInput.value;
            socket.emit('new-user',val);
            socket.emit('user-left',val)
            socket.emit('senders-name',usernameInput.value);
        }
    }
})*/

document.addEventListener("close",(e) => {
    const val = usernameInput.value;
    socket.emit('user-left',val);
})

socket.on('connected-user', (username) =>{
    const parentContainer = document.createElement('div');
    parentContainer.className = 'join-info';
    chatWindow.appendChild(parentContainer);

    const user = document.createElement('p');
    user.className = 'join';
    user.innerText = `${username} joined the Chat!`;
    parentContainer.appendChild(user);
});

socket.on('user-left', (username) => {
    const parentContainer = document.createElement('div');
    parentContainer.className = 'join-info';
    chatWindow.appendChild(parentContainer);

    const user = document.createElement('p');
    user.className = 'join';
    user.innerText = `${username} left the Chat!`;
    parentContainer.appendChild(user);
})

sendBtn.addEventListener("click",(e) => {
    //e.preventDefault();
    if(messageInput.value === ''|messageInput.value == null){
        e.preventDefault();
        alert("First you need to type then click on send!");
    }
})

form.addEventListener("submit",(e) => {
    e.preventDefault();
    if(messageInput.value){
        //socket.emit('send message',messageInput.value);
        socket.emit('send-time', current_time);
       // socket.emit('senders-name',usernameInput.value);
        //socket.emit('send-date', current_date);

        const parent = document.createElement('div');
        parent.className = 'parent';
        chatWindow.appendChild(parent);
    
        const chatMsg = document.createElement('div');
        chatMsg.className = 'chat-msg';
        parent.appendChild(chatMsg);
    
        const msgInfo = document.createElement('div');
        msgInfo.className = 'info';
        chatMsg.appendChild(msgInfo);
    
        const time = document.createElement('p');
        time.className = 'time';
        time.innerText = current_time;
        msgInfo.appendChild(time);
    
        const userName = document.createElement('p');
        userName.className = 'time';
        userName.innerText = usernameInput.value;
        msgInfo.appendChild(userName);
    
        const content = document.createElement('div');
        content.className = 'content';
        chatMsg.appendChild(content);
    
        const msg = document.createElement('p');
        msg.className = 'msg';
        msg.innerText = messageInput.value;
        content.appendChild(msg);
    
        messageInput.value = '';
    }
})

socket.on('name',username =>{
    socket.on('the-msg',chat => {
        const parent = document.createElement('div');
        parent.className = 'parent1';
        chatWindow.appendChild(parent);
    
        const chatMsg = document.createElement('div');
        chatMsg.className = 'chat-msg1';
        parent.appendChild(chatMsg);
    
        const msgInfo = document.createElement('div');
        msgInfo.className = 'info1';
        chatMsg.appendChild(msgInfo);
    
        const userName = document.createElement('p');
        userName.className = 'time1';
    
        userName.innerText = username;
        msgInfo.appendChild(userName);
        const time = document.createElement('p');
        time.className = 'time1';
        time.innerText = current_time;
        msgInfo.appendChild(time);
    
        const content = document.createElement('div');
        content.className = 'content1';
        chatMsg.appendChild(content);
    
        const msg = document.createElement('p');
        msg.className = 'msg1';
        msg.innerText = chat;
        content.appendChild(msg);
    
        messageInput.value = '';
    })
})

function showUser(username){
    const parentContainer = document.createElement('div');
    parentContainer.className = 'join-info';
    chatWindow.appendChild(parentContainer);

    const user = document.createElement('p');
    user.className = 'join';
    user.innerText = `${username} joined the Chat!`;
    parentContainer.appendChild(user);
    
}

function appendMessage(message){
    const parent = document.createElement('div');
    parent.className = 'parent';
    chatWindow.appendChild(parent);

    const chatMsg = document.createElement('div');
    chatMsg.className = 'chat-msg';
    parent.appendChild(chatMsg);

    const msgInfo = document.createElement('div');
    msgInfo.className = 'info';
    chatMsg.appendChild(msgInfo);

    const time = document.createElement('p');
    time.className = 'time';
    //time.innerText = Date();
    msgInfo.appendChild(time);

    const userName = document.createElement('p');
    userName.className = 'time';
    userName.innerText = message;
    msgInfo.appendChild(userName);

    const content = document.createElement('div');
    content.className = 'content';
    chatMsg.appendChild(content);

    const msg = document.createElement('p');
    msg.className = 'msg';
    msg.innerText = message;
    content.appendChild(msg);

    messageInput.value = '';
}

styles.css –

*{
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}
html{
    scroll-behavior: smooth;
    scroll-padding-top: .5rem;
}
html,body{
    margin: 0;
    height: 100%;
}
body{
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    height: 100vh;
    background: rgb(30,30,30);
    font-family: system-ui,sans-serif;
}
button{
    outline: none;
}
.chat-container{
    border: none;
    box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
    padding: .2rem .3rem;
    border-radius: .3rem;
    height: 530px;
    position: relative;
    width: 400px;
    display: flex;
    overflow: hidden;
    align-items: center;
    justify-content: center;
    background: linear-gradient(90deg,purple,74%,rgb(0, 81, 255));
}
.msgs-input{
    position: absolute;
    bottom: 2%;
    width: 100%;
    border: none;
    display: flex;
    justify-content: space-between;
    padding: 0rem .3rem .2rem .5rem;
}
#forms{
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0px;
    width: 100%;
    border: none;
}
.msgs{
    padding: .5rem 1rem;
    border: none;
    font-size: 1.15rem;
    transition: all .3s;
    border-top-left-radius: .3rem;
    border-bottom-left-radius: .3rem;
    outline: none;
    width: 100%;
}
.msgs:hover{
    background: #dedede;
}
.msgs:focus{
    box-shadow: 0 0px 10px 0 rgba(0,0,0,.6);
}
.send{
    padding: .5rem 1rem;
    border: none;
    font-size: 1.15rem;
    border-top-right-radius: .3rem;
    border-bottom-right-radius: .3rem;
    width: 55px;
    cursor: pointer;
    transition: all .3s;
    background: hsl(160, 84%, 31%);
    color: #fff;
    position: relative;
    overflow: hidden;
    outline: none;
}
.send > span {
    position: absolute;
    background: rgba(255,255,255,.5);
    transform: translate(-50%, -50%);
    pointer-events: none;
    border-radius: 50%;
    animation: rippleffect 1s linear infinite;
  }
@keyframes rippleffect {
    0% {
      height: 0;
      width: 0;
    }
    100% {
      height: 500px;
      width: 500px;
    }
  }

.send:hover{
    background: hsl(160,84%,26%);
    box-shadow: 0 0px 10px 0 rgba(0,0,0,.6);
}
.send:active{
    scale: .98;
}
.chats{
    border: none;
    width: 100%;
    height: 80%;
    background: #2a2d2e;
    border-radius: .3rem;
    margin-bottom: 1rem;
    padding: .3rem 1rem 2rem 1rem;
    overflow: auto;
}
.default{
    display: flex;
    color: #fff;
    align-items: center;
    width: 100%;
    justify-content: center;
    height: 60vh;
}
.chat-header{
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: space-between;
    top: 0;
    padding: .3rem 1rem;
    color: #fff;
    width: 100%;
}
.icon{
    border:none;
    width: fit-content;
    font-size: 1.15rem;
    padding: 5px;
    border-radius: 50%;
}
.chat-msg1{
    background: #eee;
    padding: .3rem .5rem;
    border-radius: .3rem;
    width: 80%;
    transition: all .2s;
    cursor: default;
    box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
}
.info1{
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.content1{
    width: 100%;
    margin-top: 1rem;
}
.chat-msg{
    background: hsl(160, 93%, 36%);
    padding: .3rem .5rem;
    border-radius: .3rem;
    width: 80%;
    cursor: default;
    transition: all .2s;
    box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
}
.info{
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.content{
    margin-top: 1rem;
}
.content,.content1{
    width: 100%;
    border: none;
    padding: .5rem;
    overflow-wrap: break-word;
}
.content1{
    display: flex;
    border: none;
    align-items: flex-end;
    justify-content: right;
}
.msg{
    width: 100%;
}
.chat-msg1:hover{
    background: hsl(0, 0%, 83%);
}
.chat-msg:hover{
    background: hsl(160, 93%, 31%);
}
.parent{
    display: flex;
    flex-direction: column;
    align-items: end;
    border-radius: .3rem;
    width: 100%;
    background: transparent;
    padding: .3rem 0rem;
    margin-top: 1rem;
}
.parent1{
    display: flex;
    flex-direction: column;
    align-items: start;
    border-radius: .3rem;
    width: 100%;
    background: transparent;
    padding: .3rem 0rem;
    margin-top: 1rem;
}
.chat-msg1,.chat-msg{
    animation: pop 1s ease-in-out;
}
@keyframes pop {
    from{
        scale: 0;
        opacity: 0;
    }
    to{
        scale: 1;
        opacity: 1;
    }
}

.join-info{
    color: #fff;
    background: #4b4d4e;
    width: 100%;
    font-size: 18px;
    box-shadow: none;
    cursor: default;
    transition: all .3s;
    padding: .5rem .5rem;
    border-radius: .3rem;
    margin-top: 1rem;
    text-align: center;
}
.join-info:hover{
    background: hsl(200, 2%, 27%);
}
#forms{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.bg{
    background: linear-gradient(rgba(0,0,0,.6),rgba(0,0,0,.75));
    color: #fff;
    width: 220px;
    padding: .5rem 1rem 1.5rem 1rem;
    border-radius: .3rem;
    position: absolute;
    box-shadow: 0 10px 20px 0 rgba(0,0,0,.75);
    height: fit-content;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    transition: all .3s ease-in-out;
    z-index: 1;
}
.bg{
    height: 100vh;
    width: 100vw;
}
.prompt{
    background: #2a2d2e;
    color: #fff;
    width: 220px;
    padding: .5rem 1rem 1.5rem 1rem;
    border-radius: .3rem;

    box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
    height: fit-content;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    transition: all .5s ease-in-out;
    z-index: 1;
}
.input-field{
    width: 100%;
    transition: all .5s ease-in-out;
}
.username{
    outline: none;
    width: 100%;
    padding: .6rem 1rem .6rem .5rem;
    font-size: .9rem;
    border: none;
    border-radius: .3rem;
    transition: all .2s ease-in-out;
    color: #000;
    margin-bottom: 1rem;
}
.username:hover{
    background: #dedede;
}
.username:focus{
    box-shadow: 0 0px 20px 0 rgba(90, 106, 143, 0.6);
}
.btns{
    display: grid;
    grid-template-columns: repeat(2,1fr);
    grid-gap: 10px;
    transition: all .5s ease-in-out;
}
.done,.ref{
    padding: .5rem 1rem;
    transition: all .2s;
    font-size: .9rem;
    border: none;
    background: #0385b1;
    cursor: pointer;
    color: #fff;
    border-radius: .3rem;
}
.done:hover,.ref:hover{
    transform: scale(0.95);
    box-shadow: 0 5px 10px 0 rgba(0,0,0,.6);
}
.done:active,.ref:active{
    scale: .9;
}
#user-form{
    width: 100%;
}
@media (max-width: 400px) {
    .chat-container{
        width: 95%;
    }
}

And finally the Html code –

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node js Chat application</title>
    <link rel="stylesheet" href="css/styles.css" />
    <script src="https://kit.fontawesome.com/f3220d5256.js" crossorigin="anonymous"></script>
</head>
<body>
    <div id="bg" class="bg">
        <div class="prompt">
            <div class="txt">
                <p>
                    Please type your name here before entering the Chat
                </p>
                <br>
            </div>
            <div class="input-field">
                <form id="user-form">
                    <input type="text" id="username" class="username" placeholder="Type Your Name here..." />
                    <br>
                    <div class="btns">
                        <button class="ref" type="reset" id="ref">Refresh</button>
                        <button class="done" type="submit" id="join">Join</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="chat-container">
        <div class="chat-header">
            <div class="icon">
                <i class="fa fa-comment"></i>
            </div>
            <div class="header">
                <h3>
                    Blaze Chat Application
                </h3>
            </div>
            <div class="status">
                <p id="online">
                    Active
                </p>
            </div>
        </div>
        <div class="chats"  id="chat-window">
            <!--<div class="default">
                <p>
                    No Messages Yet
                </p>
            </div>-->
            <div class="parent1">
                <div class="chat-msg1">
                    <div class="info1">
                        <p id="name1" class="name1">
                            Inferno (Bot)
                        </p>
                        <p id="time1" class="time1">
                            17:05
                        </p>
                    </div>
                    <div class="content1">
                        <p id="msg1">
                            Hello everyone! Welcome to the node js chatting application. Please don't misuse this application
                             for anything 
                        </p>
                    </div>
                </div>
            </div>

            <!--<div class="parent">
                <div class="chat-msg">
                    <div class="info">
                        <p id="time" class="time">
                            17:07
                        </p>
                        <p id="name" class="name">
                            BlazeInferno64
                        </p>
                    </div>
                    <div class="content">
                        <p id="msg" class="msg">
                            Sure! I would keep a check on that in my server. Btw, this application is made on a pure node js based
                             server
                        </p>
                    </div>
                </div>
            </div>

            <div class="join-info">
                <p id="join" class="join">
                    BlazeInferno64 left the Chat!
                </p>
            </div>-->

        </div>
        <div class="msgs-input">
            <form id="forms">
                <input type="text" class="msgs" name="messages" id="msgs" placeholder="Type your message here..." />
                <button type="submit" id="send" class="send">
                    <i class="fa fa-send"></i> 
                </button>
            </form>
        </div>
    </div>
    <script defer src="js/script.js"></script>
    <script src="/socket.io/socket.io.js"></script>
</body>
</html>

I hope that someone could understand my problem and help me out please!

Please help me to find a fix for it

DevOPSengineer Hiring

Anyone here from San Diego CA, Currently searching a job opportunity as DevOPSengineer?

anyone from here are open to apply? you may send you cv at [email protected]

Job Title: DevOPS Engineer CT or NY
Pay Rate: 130000-150000

You will be responsible to:
Implement tools to scale applications written in various languages (Java, C++, etc.), setup
alerts and monitoring.
Help the software development teams with reviewing and collecting information related
to operational issues.
Review and document complex projects with many stakeholders.
Research and deploy new technologies to drive innovation and continuous improvement
at our client

Qualifications
Bachelor’s Degree (or higher), in Computer Science or any STEM-related discipline.
5 years of experience in Java, C/C++, Python and/or shell scripting.
Experience with Unix/Linux operating systems, especially Red Hat distributions.
Experience configuring, deploying, monitoring, and supporting Java and Python
applications
Familiarity with distributed version control systems, especially Git.
Self-starter attitude that is comfortable working both independently and collaborating
with your team.
Good to have:
Experience with virtualization technologies such as VMware, Docker, and Kubernetes.
A systematic problem-solving approach coupled with strong communication skills and a
sense of ownership and drive.
This job can be located in either Greenwich, CT or mid-town NYC
Excellent pay and benefits and the company has an unbelievable track record of
employee loyalty and retention
Must Haves!
Unix
Docker
Redhat
either Java, C++ or Bash

event.preventDefault is not working to stop refreshing the page?

I am making a search project that when you write car or library that pops up photos about them in js.
Here is the html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arama Uygulaması</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <div>
        <div class="form-wrapper">
            <form id="form">
                <input id="searchInput" type="text" placeholder="Search something."/>

                <div class="button-wrapper">
                    <button id="searchButton">Search</button>
                    <button id="clearButton">Clear</button>
                </div>
            </form> 
        </div>

        <div class="imagelist-wrapper">
            <!--Will hold the pictures-->
           
        </div>
    </div>
    
    <script src="app.js"></script>
</body>
</html>

And here is the code of app.js:

const formWrapper = document.querySelector(".form-wrapper");
const form = document.querySelector("#form");
const input = document.querySelector("#searchInput");
const buttonWrapper = document.querySelector(".button-wrapper");
const searchButton = document.querySelector("#searchButton");
const clearButton = document.querySelector("#clearButton");
const imageListWrapper = document.querySelector(".imagelist-wrapper");

function runEventListeners(){
    form.addEventListener("submit", search);
}
function search(e)
{
    console.log("example output");
    e.preventDefault();
}

So when I submit the search button the page refreshes itself even with using preventDefault. What is the problem here and how can i fix this?

I expected that preventDefault would prevent the page from refreshing.

problem with .find() function from mongoose library nodejs

it never excute task.find() function, always catch error idk the reason i’ve tried multiple ways to solve this but non worked

const Task = mongoose.model('Task', schema) //creating table for schema
//use render to load ejs view
app.get('/', (req, res) =>{
    res.render('todo') //to show certain page in this directory

    console.log("here")
    try{                                      
    const all = Task.find(); // Get All Data from schema
    console.log(all)
    res.send(all)
}
 catch(err){
        console.log("error occured")
     }
})  

i tried downloading older versions of mongoose but it seems not to be compatible with other librarys i guess, i also tried changing it from function to object but also wont work

How to access an ejs variable inside a script tag present inside an ejs file

Here I’m using Open Meteo Climate API to fetch climate data in order to plot a line graph in my node app. I want to render these variables into my chart.ejs and make them accessible inside the script tag in order to do that. I searched everywhere but didn’t find any way out. Is there any way I could achieve it?
This is my API call:
Fetching the climate data from open meteo API

How to get these variable inside this script tag to make the line graph?

I want to access var time, var temperatue_mean, var temperatue_min, var temperatue_max Inside the script tag.

This is the js code to plot a line graph which is inside the ejs file:

<div id="container" style="width:100%; height:400px;"></div>

<% var time=time %>
<%var temperatue_mean= temperature_mean; %>
<%var temperatue_min= temperature_min; %>
<%var temperatue_max= temperature_max; %>
<script>

document.addEventListener('DOMContentLoaded', function () {
var time="<%=time %>"
var temperatue_mean= "<%temperature_mean %>"
var temperatue_min= "<%temperature_min %>"
var temperatue_max= "<%=temperature_max %>"
    const chart = Highcharts.chart('container', {
        chart: {
            type: 'line'
        },
        title: {
            text: 'Climate Change'
        },
        xAxis: {
            title:{
                text:'Time'
            },
            categories: time
        },
        yAxis: {
            title: {
                text: 'Temperature'
            }
        },
        series: [{
            name: 'Mean Temperature',
            data: temperature_mean
        }, {
            name: 'Min Temperature',
            data: temperature_min
        }
        , {
            name: 'Max Temperature',
            data: temperatue_max
        }]
    });
});
</script>
<script type="text/javascript" src="/js/themes/gray.js"></script>

I tried this but failed:

<% var time=time %>
<%var temperatue_mean= temperature_mean; %>
<%var temperatue_min= temperature_min; %>
<%var temperatue_max= temperature_max; %>
<script>

document.addEventListener('DOMContentLoaded', function () {
var time="<%=time %>"
var temperatue_mean= "<%temperature_mean %>"
var temperatue_min= "<%temperature_min %>"
var temperatue_max= "<%=temperature_max %>"
...
</script>

How to copy prototype using reducer function of Array.reduce()

I have written a function to convert keys of a javascript object from lowercase to uppercase using combination of Object.keys(obj) and Array.reduce()

function doCapitalizeFeatureKeys(in_obj){
    if(in_obj.features && in_obj.features.length > 0){
        const obj2 = in_obj.features.map(item =>
            Object.keys(item).reduce((accumulator, currentValue) => {
                if(currentValue === "attributes" && item[currentValue]){
                    var cap = Object.keys(item[currentValue]).reduce((acc, curr) => {
                        acc[curr.toUpperCase()] = item[currentValue][curr];
                        return acc;
                    }, {});
                    accumulator[currentValue] = cap;
                } else {
                    accumulator[currentValue] = item[currentValue];
                }
                return accumulator; // line 14
            }, {}));
        in_obj.features = obj2;
        return in_obj;
    }
    return in_obj;
}

Below is the structure of the in_obj (for clarity) –

{
    "features": [
            {
                "attributes": {
                    "prnt_acct_id": "034037",
                    "chld_acct_id": "030614"
                },
                "geometry":"",
                "symbol":"",
                [[Prototype]]
            },
            {
                "attributes": {
                    "prnt_acct_id": "034038",
                    "chld_acct_id": "030615"
                },
                "geometry":"",
                "symbol":"",
                [[Prototype]]
            }
        ]
}

The problem is that the accumulator in reducer function is not inheriting prototype of feature object. I have tried Object.setPrototypeOf(accumulator,item) at line 14 but that inherits lowercase attributes along with the prototype so the resulting obj has both lowercase and uppercase attributes, I only want to keep uppercase attributes. I am looking for a neater way of inheriting the prototype of item into accumulator without exiting lowercase attributes. Thanks in advance.

Conditional menu items on Next.js 13.4 app directory

Everything seems different than the Next.js page directory! I have started a project using the latest Next.js such as App Directory/Routing but I am just able to work on the front end using this latest Next.js and I am just stacked into the API making and some conditional statements on JSX.

Look into my below codes:

In the RootLayout

export default async function RootLayout({ children }) {
    const user = await getCurrentUser();
    return (
        <html lang="en">
            <body suppressHydrationWarning={true}>
                <Navbar user={user} />
                {children}
                <Footer />
            </body>
        </html>
    );
}

And the user object below:

user: {
    id: 5,
    first_name: 'john',
    last_name: 'doe',
    email: '[email protected]'
}

But in the Navbar component ({ user }) when I give a conditional logic for Login & Logout like below

{user && user.id ? (
    <button
        onClick={handleLogout}
    >
        Logout
    </button>
) : (
    <Link
        href="/auth/signin"
    >
        Login
    </Link>
)}

it seems not working such as always showing the Login either user presence or not.

I really do not understand what is going on here.

Thanks

How to Add a dynamic marker on MUI slider component?

I am using MUI v4 slider component to show some labels and values. I want a dynamic label on certain value on the slider. The value will come from API.

Lets say my slider has value from 0 to 1.5, and from API i get a value of 0.9 the there should be a fixed market on the slider where value is 0.9. This marker should be fixed and not movable like the slider pointer.

In short only the slider-marker component can move right to left but this fixed marker will remain on fixed position every time.slider image

As you can see in the slider marker triangle should be movable. I need a fixed dynamic marker on the number line.

Only the slider triangle marker should be movable, Need a fixed dynamic marker on number line.

Why is computedFee too small when using function?

I tried to calculate computedFee according to this page: https://www.metacrypt.org/tools/uniswap-v3-calculator-simulator/?network=ethereum&token0=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2&token1=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&feeTier=3000 But computedFee is 1.8282539706741483e-21, which is too small.

//poolID: 0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8

const feeTier = 0.003;
const volumeUSD = 6631238.50;
const existingLiquidity = 283207208.65;
const depositAmount = 1000; // dollar

// These values depend on the token pair and the price range
const ethPrice = 1800; // dollar
const amount0 = depositAmount / 2; // amount of token0 to deposit
const amount1 = (depositAmount / 2) / ethPrice ; // amount of token1 to deposit
const sqrtRatioAX96 = 146144307145949320; // lower bound of the price range
const sqrtRatioBX96 = 156816964661737472; // upper bound of the price range
const P = 1870.596264329329820965675342457762; // current price
const Pa = 1649.0832769175609; // lower bound of the price range in terms of price
const Pb = 1974.6659682730651; // upper bound of the price range in terms of price

// Calculate user liquidity
const liquidity0 = amount0 * (sqrtRatioBX96 * sqrtRatioAX96) / (sqrtRatioBX96 - sqrtRatioAX96);
const liquidity1 = amount1 / (sqrtRatioBX96 - sqrtRatioAX96);

let userTotalLiquidity;
if (P <= Pa) {
  userTotalLiquidity = liquidity0;
} else if (Pa < P && P < Pb) {
  userTotalLiquidity = Math.min(liquidity0, liquidity1);
} else if (P >= Pb) {
  userTotalLiquidity = liquidity1;
}

// Calculate computed fee
const computedFee = feeTier * volumeUSD * (userTotalLiquidity / (existingLiquidity + userTotalLiquidity));
console.log(computedFee);

I think I set the variables amount0, amount1, sqrtRatioAX96, sqrtRatioBX96, P, Pa, Pb incorrectly, but I don’t know where the error is in the process of calculating computedFee. Please refer to https://www.metacrypt.org/tools/uniswap-v3-calculator-simulator/?network=ethereum&token0=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2&token1=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&feeTier=3000 for reference.