looking to inject a script into twitch chat but am stuck, do i need background.js or is there a way to just inject the content script

kind of lost right now have been on google for 2 hours i am new to coding and want to inject something that adds a button to each twitch chat ‘on-hover’

Manifest.json

{
    "name": "Hello Extensions",
    "description": "Base Level Extension",
    "version": "1.0",

    "manifest_version": 3,
    "action": {
        "default_popup": "popup.html",
        "default_icon": "hello.png"
      },
      "background": {
          "service_worker": "content-script.js"
      },
      "permissions": ["tabs"],
      "content_scripts": [{
          "matches": ["https://*.twitch.tv/*"],
          "exclude_globs": ["https://www.twitch.tv/directory/*",
          "https://www.twitch.tv/p/*",
          "https://www.twitch.tv/products/*",
          "https://www.twitch.tv/*/manager*",
          "https://www.twitch.tv/*/dashboard",
          "https://www.twitch.tv/broadcast",
          "https://www.twitch.tv/messages/*",
          "https://www.twitch.tv/settings"],
          "js": ["content-script.js"],
          "run_at": "document_end"
      }
    ]
  }

Content-script.js

var config = {attributes: false, childList: true, characterData: false};

var htmlBody = $("body")[0];
var chatLoadedObserver = new MutationObserver(function (mutations, observer) {
    mutations.forEach(function (mutation) {
        var chatSelector = $(".chat-line__message");
        if (chatSelector.length > 0) {
            // Select the node element.
            console.log("new chat message.")
            var target = chatSelector[0];

            // Pass in the target node, as well as the observer options
            bookmark.observe(target, config);

            // Unregister chatLoadedObserver. We don't need to check for the chat element anymore.
            observer.disconnect();
        }
    })
});

chatLoadedObserver.observe(htmlBody, config);

what else do i need to make this functional?

how would I write code so that I could read a json and check if it contains a certain word that I type into an input box with an eventlistener

const textinput2 = document.getElementById("inputbox")


fetch("wordlist copy.json").then(function(response){
    response.json().then(function(data) {
      let ex = JSON.stringify(data)

document.getElementById("submit").onclick = function(e) {
  e.preventDefault();
const test = document.getElementById("start").innerHTML
textinput2.addEventListener('input', () =>{
  console.log('changed')


   if (ex.match(textinput2) && textinput2.value.charAt(0) == test.slice(-1)) {
     

     
            document.getElementById("start").innerHTML = document.getElementById("start").innerHTML.replace(test, textinput2.value)
            document.getElementById("inputbox").value = '';
            
            console.log("worked");

     
    
  }
  

});
};
})
})

Im trying to figure out how to read my json file which is filled with just strings of words I want to make it so that the if statement doesnt trigger when I type in one letter but when I type in a whole word while having the eventlistener constantly listening for changes so that when the word eventually is found it swaps the word with some other element on my html

Check if there is no id in database node.js

so bassically, i am creating a router to update data in database, I started by checking the id in database using if function, at first it works when there is no such id I put in the path, but its come out with this error

BError [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:558:11)
at ServerResponse.header (C:Usersjansen stanlieDesktopsimple-appnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (C:Usersjansen stanlieDesktopsimple-appnode_modulesexpresslibresponse.js:174:12)
at ServerResponse.json (C:Usersjansen stanlieDesktopsimple-appnode_modulesexpresslibresponse.js:278:15)
at C:Usersjansen stanlieDesktopsimple-appcontrollerstodo.controller.js:79:21
at Array.forEach ()
at C:Usersjansen stanlieDesktopsimple-appcontrollerstodo.controller.js:60:9
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async putToDo (C:Usersjansen stanlieDesktopsimple-appcontrollerstodo.controller.js:54:2) {
code: ‘ERR_HTTP_HEADERS_SENT’
}
(node:12008) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:558:11)
at ServerResponse.header (C:Usersjansen stanlieDesktopsimple-appnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (C:Usersjansen stanlieDesktopsimple-appnode_modulesexpresslibresponse.js:174:12)
at ServerResponse.json (C:Usersjansen stanlieDesktopsimple-appnode_modulesexpresslibresponse.js:278:15)
at C:Usersjansen stanlieDesktopsimple-appcontrollerstodo.controller.js:86:20
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async putToDo (C:Usersjansen stanlieDesktopsimple-appcontrollerstodo.controller.js:54:2)
(Use node --trace-warnings ... to show where the warning was created)
(node:12008) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12008) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

and after that I cannot update any data even though there is in the database

here is my code

const putToDo = async (req, res) => {
const body = req.body;
let id = req.params.id;
console.log(id);
let data = [];
let updatedData = [];
await db
    .query("select * from suppliers")
    .then((results) => {
        data = results.rows;
    })
    .then(() => {
        data.forEach((datas) => {
            if (datas.id == id) {
                db.query(
                    `UPDATE suppliers
                SET Name = '${body.name}'
                WHERE id = ${id};`
                )
                    .then(() => {
                        db.query("select * from suppliers").then((updated) => {
                            updatedData = updated;
                            console.log(updatedData);
                        });
                    })
                    .then(() => {
                        res.status(200).json({
                            message: "Data Successfully Updated",
                        });
                    });
            }
            res.status(500).json({
                message: "No data in database",
            });
        });
    })
    .catch((e) => {
        console.log(e);
        res.status(500).json({
            message: "INTERNAL SERVER ERROR",
        });
    });};

where did I do wrong here…?

Parse error: syntax error, unexpected variable “$conn”

can anyone help me with this error?

Parse error: syntax error, unexpected variable “$conn” in C:xampphtdocsfyptemplatesupload.php on line 5

this is my php coding

connect_error){
die(‘Connection Failed: ‘ .$conn->connect_error);
} else {
$stmt = $conn->prepare(“insert into video(video) values(?)”);
$stmt -> bind_param(“s”, $video);
$stmt -> execute();
echo “Video Successfully…”;
$stmt -> close();
$conn -> close();
}
?>

how do I enable all options when user selects a date that is not the current date?

I am trying to get the datepicker to work with the select options, so if the user selects a date that’s not the current date, then the function will not be called so the user can select any time they want.

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<select id="time1">
    <option value="" disabled selected>Select delivery time</option>
    <option value="8-10">8:00 AM - 10:00 AM</option>
    <option value="13-15">1:00 PM - 3:00 PM</option>
    <option value="15-19">3:00 PM - 7:00 PM</option>
</select>

<script>
    $(function () {
        $("#datepicker").datepicker({
            dateFormat: 'dd/mm/yy',
            minDate: 0,
            maxDate: '+1y',
            onSelect: function (dateText, inst) {
                var date = $("#datepicker").datepicker('getDate'),
                    day = date.getDate();
                var d2 = new Date();
                if (day == d2) {
                    let element = document.getElementById('select-a-delivery-time');
                    let validateInterval = (element) => {
                        let currentDate = new Date();
                        let currentHour = currentDate.getHours();

                        for (let opt of element.options) {
                            let timeOpt = opt.value.split('-');
                            if (Array.isArray(timeOpt) && timeOpt.length > 1) {
                                opt.disabled = (+timeOpt[0] <= currentHour && +timeOpt[1] > currentHour) ? false : true;
                            }

                        }

                    }
                } else {
                    opt.disabled = false;
                }
                validateInterval(element);
            }
        });
    });
</script>

Array not populated with new data [duplicate]

I have a fetch request that populates an array with pokemon data. After calling on the populate function and transforming each entry to create a new div with the information and assigning it to another array it is empty?

<!DOCTYPE html>

<html> 
    <head> 
        <title>PokéSearch</title>
    </head>
    <body>
        <h1>PokéSearch</h1>
        <div class="autocomplete_container">
            <input id="search" placeholder="Search for a Pokemon..."></input>
            <div class="modal">  
            </div>
        </div>
    </body>   
    <script>
        
        const pokemonData = []
        for (let i=0;i < 151; i++) {
            fetch(`https://pokeapi.co/api/v2/pokemon-form/${i + 1}`)
                .then((response) => response.json())
                .then(({name,sprites}) => pokemonData.push({name,sprite_front: sprites.front_default,sprite_back: sprites.back_default}))
        }

        function populate() {
            let newData = []
            newData = pokemonData.map((pokemon,i) => 
                    `<div class="pokemon" key=${i}>
                        <span>${pokemon.name}</span>
                        <img src=${pokemon.sprite_front} alt="pokemon"/>
                        <img src=${pokemon.sprite_back} alt="pokemon"/>
                    </div>`     
                );
            console.log(newData)
            const htmle = newData.length ? newData.join('') : '';
            document.querySelector('.modal').innerHTML = htmle;
        }

        populate()
    </script> 

Is it possible to reference a variable that has just been previously destructed as the default value for Destructuring Assignment?

I have a question about Destructuring assignment in ECMAScript.

Is it possible to reference a variable that has just been previously destructed as the default value?

function doSomething({ requiredProp, optionalProp = requiredProp }) {
}

Is there a guarantee of evaluation order in the spec? From looking at the transpiled code to ES5 with Babel or tsc, this seems to work.

Pusher working only after refreshing page

I’m implementing pusher in a web application using nextjs. It works as expected in my development environment. But it does not work correctly when I deploy it to vercel. I can only see the results when I refresh the page in the browser.

This is the implementation for the client:

useEffect(() => {

    const pusher = new Pusher(`${process.env.PUSHER_KEY}`, {
        cluster: `${process.env.PUSHER_CLUSTER}`,
        useTLS: true
    });

    const channel = pusher.subscribe('franks-auto-spa');
    channel.bind('cancel-wash', data => {
        console.log(data.date);
        removeWash(data.date);
    });

}, []);

And this is the implementation for the API:

export default async (req, res) => {

    const connection = await mysql.createConnection(process.env.DATABASE_URL);
    console.log(req.body.date);
    const result = await connection.query('DELETE FROM ongoing WHERE date = ?', [req.body.date]);
    console.log(result);

    const pusher = new Pusher({
        appId: `${process.env.PUSHER_ID}`,
        key: `${process.env.PUSHER_KEY}`,
        secret: `${process.env.PUSHER_SECRET}`,
        cluster: `${process.env.PUSHER_CLUSTER}`,
        useTLS: true
    });

    pusher.trigger('franks-auto-spa', 'cancel-wash', req.body);
    res.json({message: 'Wash deleted deleted...'});
}

Am I missing any configuration in Vercel?

How to send mail in servlet,jsp

my code not working

       Properties properties = new Properties();
       properties.put("mail.smtp.host", "smtp.gmail.com");
       properties.put("mail.smtp.port", "587");
       properties.put("mail.smtp.auth", "true");
       properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.starttls.required", "true");
        properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
       properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
       Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
        

problem: javax.mail.MessagingException: Exception reading response;
nested exception is:

Problem sending a post graphql, nextjs react

Hello guys I have the following problem:

wherever I try to post a comment I get the following error:

ClientError: input:3: Field "post" is not defined by type CommentCreateInput.
: {"response":{"errors":[{"message":"input:3: Field "post" is not defined by type CommentCreateInput.n"}],"data":null,"extensions":{"requestId":"cl3uwxntaa8r70cll4db25q72"},"status":400,"headers":{}},"request":{"query":"n    mutation CreateComment($name: String!, $email: String!, $comment: String!, $slug: String!) {n      createComment(data: {name: $name, email: $email, comment: $comment, post: {connect: {slug: $slug}}}) { id }n    }n  ","variables":{"name":"Roberto","email":"[email protected]","comment":"a","slug":"react-testing"}}}
    at /home/xue/Documents/Programacion/blog-nodejs/node_modules/graphql-request/dist/index.js:356:31
    at step (/home/xue/Documents/Programacion/blog-nodejs/node_modules/graphql-request/dist/index.js:63:23)
    at Object.next (/home/xue/Documents/Programacion/blog-nodejs/node_modules/graphql-request/dist/index.js:44:53)
    at fulfilled (/home/xue/Documents/Programacion/blog-nodejs/node_modules/graphql-request/dist/index.js:35:58)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  response: {
    
}
API resolved without sending a response for /api/comments, this may result in stalled requests.

this is my code so far:

pages/api/comments.js
import { GraphQLClient, gql } from ‘graphql-request’;

const graphqlAPI = process.env.NEXT_PUBLIC_GRAPHCMS_ENDPOINT
const graphcmsToken = process.env.XUE_TOKEN


// export a default function for API route to work
export default async function asynchandler(req, res) {
  console.log({graphcmsToken})
  const graphQLClient = new GraphQLClient((graphqlAPI), {
    headers: {
      authorization: `Bearer ${graphcmsToken}`,
    },
  })
  const query = gql`
    mutation CreateComment($name: String!, $email: String!, $comment: String!, $slug: String!) {
      createComment(data: {name: $name, email: $email, comment: $comment, post: {connect: {slug: $slug}}}) { id }
    }
  `
    try {
      const result = await graphQLClient.request(query, req.body)
      return res.status(200).send(result)
    } catch (error) {
      console.log(error)
    }


}

— this my commentform.jsx
components/commentForm.jsx

import React, { useState, useEffect } from 'react';
import { submitComment } from '../services';

const CommentsForm = ({ slug }) => {
  const [error, setError] = useState(false);
  const [localStorage, setLocalStorage] = useState(null);
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);
  const [formData, setFormData] = useState({ name: null, email: null, comment: null, storeData: false });

  useEffect(() => {
    setLocalStorage(window.localStorage);
    const initalFormData = {
      name: window.localStorage.getItem('name'),
      email: window.localStorage.getItem('email'),
      storeData: window.localStorage.getItem('name') || window.localStorage.getItem('email'),
    };
    setFormData(initalFormData);
  }, []);

  const onInputChange = (e) => {
    const { target } = e;
    if (target.type === 'checkbox') {
      setFormData((prevState) => ({
        ...prevState,
        [target.name]: target.checked,
      }));
    } else {
      setFormData((prevState) => ({
        ...prevState,
        [target.name]: target.value,
      }));
    }
  };

  const handlePostSubmission = () => {
    setError(false);
    const { name, email, comment, storeData } = formData;
    if (!name || !email || !comment) {
      setError(true);
      return;
    }
    const commentObj = {
      name,
      email,
      comment,
      slug,
    };

    if (storeData) {
      window.localStorage.setItem('name', name);
      window.localStorage.setItem('email', email);
    } else {
      window.localStorage.removeItem('name');
      window.localStorage.removeItem('email');
    }

    submitComment(commentObj)
      .then((res) => {
        if (res.createComment) {
          if (!storeData) {
            formData.name = '';
            formData.email = '';
          }
          formData.comment = '';
          setFormData((prevState) => ({
            ...prevState,
            ...formData,
          }));
          setShowSuccessMessage(true);
          setTimeout(() => {
            setShowSuccessMessage(false);
          }, 3000);
        }
      });
  };

  return (
    
  );
};

export default CommentsForm;

I don’t know how to get this working and sorry for my bad english. Let me know if you need more info

Javascript Hangman Game Running Functions += Times After Reset

Ok this is my very first ever coding project. I’m self taught and thought creating a hangman game my 2 young kiddos could enjoy would be fun.
I have the game coded and it runs perfectly fine the first time through however, once I click on my reset button to restart the game, my lives start going down by 2 instead of one. After a third reset it goes down by three, and so on. Any console.log()s I put in to check run as many times as well.
I’ve spend hours racking my brain trying to figure it out and I’ve looked all over and I’m just not getting what’s wrong. I thought about just saying screw it and resort to refreshing the page after every play through to avoid the problem but my brain wont let me do that.

Does anyone have any idea how to fix the problem? I know my code is probably not the most efficient and can definitely use to touch ups, but like I said, this is my first ever project and I know efficiency and skill will come with time and practice (like this). Below is the main chunk of my code.

function gameStart() {
    // user writes in a word
    pickedWord = prompt('pick a word').toUpperCase();
    pickLetterHeading.innerText = 'Pick a Letter'
    numLivesSec.hidden = false;
    startBtn.disabled = true;
    gameIsGoing = true;
    resetBtn.disabled = false;
    // enables buttons to press
    for (let j = 0; j < alphabet.length; j++) {
        document.getElementsByClassName('letterBtnClass')[j].disabled = false;
    }
    numLives = 7;
    numLivesRemaining.innerText = numLives;
    // calls the main game function
    gameInProgress();
}

function reset() {
    startBtn.disabled = false;
    pickedWord = '';
    gameIsGoing = false;
    resetBtn.disabled = true;
    pickLetterHeading.hidden = true;
    numLivesSec.hidden = true;
    while (guessedSec.firstChild) {
        guessedSec.removeChild(guessedSec.firstChild);
    }
    for (let l = 0; l < alphabet.length; l++) {
        document.getElementsByClassName('letterBtnClass')[l].disabled = true;
        letters[l].classList.replace('correct', 'letterBtnClass');
        letters[l].classList.replace('incorrect', 'letterBtnClass');
    }
    numLives = 7;
}

function gameInProgress() {
    pickLetterHeading.hidden = false;
    wordInProgress = '';
    for (let i = 0; i < pickedWord.length; i++) {
        let lettersToGuess = document.createElement('span');
        lettersToGuess.innerText = '_';
        guessedSec.appendChild(lettersToGuess);
        wordInProgress += '_';
    }

    for (let btn = 0; btn < letters.length; btn++) {
        letters[btn].addEventListener('click', function (e) {
            letters[btn].disabled = true;

            if (pickedWord.indexOf(letters[btn].innerText) == -1) {
                console.log('letter not there!');
                numLives -= 1;
                numLivesRemaining.innerText = numLives;
                console.log('TESTING!')

                // checks if you have any tries left. If you have 0, then runs game over
                if (numLives == 0) {
                    console.log('GAME OVER!')
                    gameIsGoing = false;
                    pickLetterHeading.innerText = 'You lose. Try again.'
                    for (let j = 0; j < alphabet.length; j++) {
                        document.getElementsByClassName('letterBtnClass')[j].disabled = true;
                    }
                }
            }
            // checks if the letter picked matches anything in the chosen word
            for (let x = 0; x < pickedWord.length; x++) {
                if (letters[btn].innerText == pickedWord[x]) {
                    // adds class to chosen letter to show you guess correctly
                    letters[btn].classList.add('correct');
                    document.getElementsByTagName('span')[x].innerText = pickedWord[x];
                    wordInProgress[x] = pickedWord[x];

                    // if picked letter matches something in the chosen word, changes the "_" to the correct letter to show user progress
                    String.prototype.replaceAt = function (index, char) {
                        let a = this.split("");
                        a[index] = char;
                        return a.join("");
                    }
                    wordInProgress = wordInProgress.replaceAt(x, pickedWord[x]);

                    // when the word is complete. will show you win
                    if (wordInProgress == pickedWord) {
                        console.log("WINNER WINNER CHICKEN DINNER!");
                        pickLetterHeading.innerText = 'YOU WIN!'
                        for (let j = 0; j < alphabet.length; j++) {
                            document.getElementsByClassName('letterBtnClass')[j].disabled = true;
                        }
                    }
                } else {
                    // since you chose incorrectly it adds a class to the button to show a bad choice
                    letters[btn].classList.add('incorrect');
                }
            }
        })
    }
}

Possible to add a reducer that can read from multiple state slices?

I am using createSlice to create slices of state. Let’s call them sliceA and sliceB. Mostly these slices are decoupled from each other. However I would like to create one reducer in sliceA that has (read) access to both sliceA and sliceB. Is this possible?

I know I can use extraReducers to accept actions that were not defined in the slice. But I think I would still be limited (in these extra reducers) to read only sliceA, and not sliceB.

Any idea how I could create a reducer that can read from both slices?

How to merge records with similar names?

I’m trying to merge records that have similar names into one.

For example:

Lumiere Technologies,
Lumiere Tech, Inc.,
Mendes Metal SA - Central Office,
*** DO NOT USE *** Mendes Metal,
Mendes Metal, SA,
Ship to Klapisch Aerospace gmbh,
Klapisch Aero, gmbh Munich
Klapisch Aerospace tech (use Klapisch Aero, gmbh Munich acct 84719482-A)

would be combined into Lumiere, Mendes Metal, and Klapisch Aero or something similar.

I haven’t been able to come up with anything at all, any help would be GREATLY appreciated.