Firebase cloud function to send notification to multiple topics (.sendMulticast() error)

I’ve tried to make a cloud function that sends a notification to multiple topics. However when I use .sendMulticast() I receive error “Error: tokens must be a non-empty array
at Messaging.sendMulticast”.I don’t want to have any tokens since I have already specified the topics I’m sending the notification to. Here is my current cloud function:

exports.newStoreTopic = functions
    .region("europe-west2")
    .firestore
    .document("StoreDatabase/{productName}")
    .onCreate(async (snapshot, context) => {
      const newStore = snapshot.data();
      const store = newStore.StoreName;
      const message = {
        notification: {
          title: "New Store!",
          body: store+" has just been added",
        },
        topic: ["storeUpdates", newStore.StoreName],
      };
      return admin
          .messaging()
          .sendMulticast({
            tokens: [],
            topic: ["storeUpdates", store],
            message,
          })
          .then(() => {
            console.log("Notification sent successfully");
            return null;
          })
          .catch((error) => {
            console.error("Error sending notification:", error);
            return null;
          });
    });

redux store values being passed as props to another component are empty

so Im trying to access the values from the store, after updating the redux state. but the values are empty even though the store gets updated synchronously.

const {
    storeSimulationSelProd,
    storeApiProductsData,
    storeUpdatedInput,
    storeUpdatedResponse
  } = useSelector((state) => {
    return state.resultsCard
  } 

const addNewPanel = async () => {
    console.log(simulationSelProd)
    console.log(apiProductsData)
    console.log(updatedInput)
    console.log(updatedResponse)

    dispatch(updateResultsCard({simulationSelProd, apiProductsData, updatedInput, updatedResponse}))

      const newPanel = (
        <Panel header={"Simulation " + ((panels.length)+1)} key={(panels.length) + 1}>
          <ResultsCard options={dropdownProducts} selectedProduct={storeSimulationSelProd} productsData={storeApiProductsData} inputData={storeUpdatedInput} response={storeUpdatedResponse} showSendToResultTab={true} showData={true}/>
        </Panel>
      );
      const updatedPanels = [...panels, newPanel];
      setPanels(updatedPanels)
      dispatch(setSimulation({selectedProduct, updatedPanels}))
  }

I want to pass these values as props, to another component, but it is getting updated late even though the store is getting updated when i am checking synchronously. any fix for this?

How to make similar space in flex container?

Look, i have a flex menu container, in menu i have a menu_cart and menu_body, and in menu_body i have carts, where i have justify-content: space-between. I need to make flex width between menu_cart and menu_body, the same as between cards. This is how it is now:
enter image description here
And this is how it is should be:
enter image description here

How can I make a white background between two svg paths

Hi I’m trying to make a white background color between my two paths and I want to make it perfectly line-aligned and that’s why I’m stuck, I don’t know how to do it. Do I have to do a different path or what?
If someone helps I will be very happy!
Thanks a lot <3

 <section style="height: 150vh; background-color: black;">
        <div id="svg-container2">
          <svg viewBox="0 0 1440 320" style="transform: scaleX(-1)">
            <path id="my-path-2" class="path-2" d="M0,256L48,229.3C96,203,192,149,288,133.3C384,117,480,139,576,176C672,213,768,267,864,266.7C960,267,1056,213,1152,181.3C1248,149,1344,139,1392,133.3L1440,128" />
          </svg>
        </div>  
        <svg viewBox="0 0 1440 320">
          <path id="my-path" class="path-" d="M0,256L48,229.3C96,203,192,149,288,133.3C384,117,480,139,576,176C672,213,768,267,864,266.7C960,267,1056,213,1152,181.3C1248,149,1344,139,1392,133.3L1440,128" />
        </svg>
      </section>



 svg {
    width: 100%;
    height: 30%;
    z-index: -1;
}

path {
    stroke: #0099ff;
    stroke-width: 2;
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
    fill: none;
}


const path1 = document.querySelector("#my-path");
const pathLength1 = path1.getTotalLength();
path1.style.strokeDasharray = pathLength1;
path1.style.strokeDashoffset = pathLength1;

const path2 = document.querySelector("#my-path-2");
const pathLength2 = path2.getTotalLength();
path2.style.strokeDasharray = pathLength2;
path2.style.strokeDashoffset = pathLength2;

window.addEventListener("scroll", () => {
  const scrollTop = window.pageYOffset;
  const scrollHeight = document.body.scrollHeight - window.innerHeight;
  const scrollFraction = scrollTop / scrollHeight;

  const drawLength1 = pathLength1 * scrollFraction;
  path1.style.strokeDashoffset = pathLength1 - drawLength1;

  let drawLength2 = pathLength2 * scrollFraction;
  let offset2 = pathLength2 - drawLength2;
  if (scrollFraction === 1) {
    offset2 = pathLength2 - 1;
  }
  path2.style.strokeDasharray = pathLength2;
  path2.style.strokeDashoffset = offset2;

  if (drawLength2 <= 0) {
    path2.style.strokeDasharray = pathLength2;
    path2.style.strokeDashoffset = pathLength2;
  }
});

Javascript – How do I make holding blocks for a tetris game?

I’m making a tetris game using HTML and Javascript and I would like to add the feature where you can hold blocks by pressing a key on the keyboard and if you are already holding a block then it will swap the block your holding with the block that is currently falling. How would I do this?

HTML:

<html>
    <head>
        <title>Tetris Clone</title>
        <style>
            body {
                background: #202028;
                color: #fff;
                font-family: sans-serif;
                font-size: 2em;
                text-align: center;
            }
            canvas {
                border: solid .2em #fff;
                height: 90vh;
            }
        </style>
    </head>
    <body>
        <div id ="score"></div>
        <canvas id="tetris" width="240" height="400"></canvas>
        <script src=tetris.js ></script>
    </body>
</html>

Javascript:

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

context.scale(20, 20);

function arenaSweep() {
    let rowCount = 1;
    outer: for (let y = arena.length - 1; y > 0; --y) {
        for (let x = 0; x < arena[y].length; ++x) {
            if (arena[y][x] === 0) {
                continue outer;
            }
        }

        const row = arena.splice(y, 1)[0].fill(0);
        arena.unshift(row);
        ++y;
        player.score += rowCount * 10;
        rowCount *= 2;
    }
}

function collide(arena, player) {
    const [m, o] = [player.matrix, player.pos];
    for (let y = 0; y < m.length; ++y) {
        for (let x = 0; x < m[y].length; ++x) {
            if (m[y][x] !== 0 && (arena[y + o.y] && arena[y + o.y][x + o.x]) !== 0) {
                return true;
            }
        }
    }
    return false;
}

function createMatrix(w, h) {
    const matrix = [];
    while (h--) {
        matrix.push(new Array(w).fill(0));
    }

    return matrix
}

function createPiece(type) {
    if (type === 'T') {
        return [
            [0, 0, 0],
            [1, 1, 1],
            [0, 1, 0],
        ];
    } else if (type === 'O') {
        return [
            [2, 2],
            [2, 2],
        ];
    } else if (type === 'L') {
        return [
            [0, 3, 0],
            [0, 3, 0],
            [0, 3, 3],
        ];
    } else if (type === 'J') {
        return [
            [0, 4, 0],
            [0, 4, 0],
            [4, 4, 0],
        ];
    } else if (type === 'I') {
        return [
            [0, 5, 0, 0],
            [0, 5, 0, 0],
            [0, 5, 0, 0],
            [0, 5, 0, 0],
        ];
    } else if (type === 'S') {
        return [
            [0, 6, 6],
            [6, 6, 0],
            [0, 0, 0],
        ];
    } else if (type === 'Z') {
        return [
            [7, 7, 0],
            [0, 7, 7],
            [0, 0, 0],
        ];
    }
}

function draw() {
    context.fillStyle = '#000';
    context.fillRect(0, 0, canvas.width, canvas.height);

    drawMatrix(arena, {x: 0, y: 0});
    drawMatrix(player.matrix, player.pos);
}

function drawMatrix(matrix, offset) {
    matrix.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value !== 0) {
                context.fillStyle = colors[value];
                context.fillRect(x + offset.x, y + offset.y, 1, 1);
            }
        });
    });
}

function merge(arena, player) {
    player.matrix.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value !== 0) {
                arena[y + player.pos.y][x +player.pos.x] = value;
            }
        });
    });
}

function playerDrop() {
    player.pos.y++;
    if (collide(arena, player)) {
        player.pos.y--;
        merge(arena, player);
        playerReset();
        arenaSweep();
        updateScore();
    }
    dropCounter = 0;
}

function playerMove(dir) {
    player.pos.x += dir
    if (collide(arena, player)) {
        player.pos.x -= dir
    }
}

function playerReset() {
    const pieces = 'ILJOTSZ';
    player.matrix = createPiece(pieces[pieces.length * Math.random() | 0]);
    player.pos.y = 0;
    player.pos.x = (arena[0].length / 2 | 0) - (player.matrix[0].length / 2 | 0);

    if (collide(arena, player)) {
        arena.forEach(row => row.fill(0));
        player.score = 0;
        updateScore();
    }
}

function playerRotate(dir) {
    const pos = player.pos.x
    let offset = 1;
    rotate(player.matrix, dir)
    while(collide(arena, player)) {
        player.pos.x += offset;
        offset = -(offset + (offset > 0 ? 1 : -1));
        if (offset > player.matrix[0].length) {
            rotate(player.matrix, -dir);
            player.pos.x = pos;
            return;
        }
    } 
}

function rotate(matrix, dir) {
    for (let y = 0; y < matrix.length; ++y) {
        for (let x = 0; x < y; ++x) {
            [
                matrix[x][y],
                matrix[y][x]
            ] = [
                matrix[y][x],
                matrix[x][y]
            ];
        }
    }

    if (dir > 0) {
        matrix.forEach((row => row.reverse()));
    } else {
        matrix.reverse();
    }
}

let dropCounter = 0;
let dropInterval = 1000;

let lastTime = 0;
function update(time = 0) {
    const deltaTime = time - lastTime;
    lastTime = time;

    dropCounter += deltaTime;
    if (dropCounter > dropInterval) {
       playerDrop();
    }

    draw();
    requestAnimationFrame(update);
}

function updateScore() {
    document.getElementById('score').innerText = player.score;
}

const colors = [
    null,
    'purple',
    'yellow',
    'orange',
    'blue',
    'cyan',
    'green',
    'red',
];

const arena = createMatrix(12, 20)

const player = {
    pos: {x: 0, y: 0},
    matrix: null,
    score: 0,
}

document.addEventListener('keydown', event => {
    if (event.keyCode === 37) {
        playerMove(-1);
    } else if (event.keyCode === 39) {
        playerMove(1);
    } else if (event.keyCode === 40) {
        playerDrop();
    } else if (event.keyCode === 90) {
        playerRotate(-1);
    } else if (event.keyCode === 88) {
        playerRotate(1);
    }
})

playerReset();
updateScore();
update();

Unable to reflect the selected values from dropdown inside a heading or a table

Whenever I am choosing a value from the dropdown so that it at least can get reflected in the heading, it is showing, devices.map is not a function. devices is an array where the data from the API got fetched. Below is the code:

import React, { useState, useEffect, useMemo } from "react";

const Devdropdown = () => {
  const [devices, setDevices] = useState([]);
  const url = "..";

  useEffect(() => {
    async function getDevices() {
      const response = await fetch(url);
      const body = await response.json();
      setDevices(body.data);
    }
    getDevices();
  }, []);

  const handleChange = (e) => {
    e.preventDefault();
    setDevices(e.target.value);
  };

  const uniqueDeviceIds = useMemo(
    () => Array.from(new Set(devices.map((device) => device.device_id))),
    [devices]
  );

  console.log(uniqueDeviceIds);
  return (
    <div>
      <h1>Aircraft {}</h1>
      <select
        value={uniqueDeviceIds}
        onChange={handleChange}
        placeholder="select an option"
      >
        {devices
          ? uniqueDeviceIds.map((deviceId) => (
              <option key={deviceId}>{deviceId}</option>
            ))
          : null}
      </select>
    </div>
  );
};

export default Devdropdown;

So, in the Aircraft {} line, what should go inside the curly braces? uniqueDeviceIds or devices?
And when I am having the onChange inside select, whenever I am going to select the element, it is showing, device.map is not a function.

How to setState to prevState?

When I press a button

<Pressable
            onPress={() => {
              this.onPressHandler();
            }}>

I want to setState to its previous value, but it doesn’t happen

onPressHandler = () => {
    this.setState(
      prevState => (
        {
          data: prevState.data
        }
      )
    );
  };

What am I doing wrong?

Email not being sent using smtp.js

I have some javascript which i am using to send some email from my app.
I referenced both smtp.js and my javascript in my html code.
When I send the email the alert tells me the email has been sent. Recently google will not allow ‘less secure app’ function so i am now using 2 step verification and app password for my settings. regardless … the email does not get delivered. Can anyone tell me why?

const btn = document.getElementById("2")
const inputs = document.getElementById("1")

btn.addEventListener('click', ()=> {
    Email.send({
        Host: "smtp.gmail.com",
        Username: "[email protected]",
        Password: "my app password",
        To: "[email protected]",
        From: inputs.elements["email"].value,
        Subject: "Contact Us Query by the Customer",
        Body: "Test"
    }).then(msg => alert("Email Sent"))
})

Take Live webpage screenshot

I am trying to take a screenshot of remote webpage/external domain using html2canvas

My Code

var url = "https://example.com"; // Replace with the URL of the webpage you want to screenshot
var options = {
  useCORS: true,
  allowTaint: true,
  scrollX: 0,
  scrollY: 0,
  width: window.innerWidth,
  height: window.innerHeight,
};
html2canvas(document.body, options).then(canvas => {
  // `canvas` is the screenshot of the webpage, represented as a canvas element
  // You can append the canvas to the document or export it as an image:
  document.body.appendChild(canvas);
  // To export the screenshot as an image file:
  var link = document.createElement("a");
  link.download = "screenshot.png";
  link.href = canvas.toDataURL();
  link.click();
}).catch(error => {
  console.error(error);
});
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

This code successfully taking the screenshot of web page of this script instead of screenshot of external domain example.com

How do i fix this?

I am getting this error on my discord bot

enter image description here

This is my code:

require('dotenv').config();
const { Client, Intents } = require('discord.js');

const client = new Client({
  intents: [
    Intents.FLAGS.Guilds,
    Intents.FLAGS.GuildMembers,
    Intents.FLAGS.GuildMessages,
    Intents.FLAGS.MessageContent,
  ],
});

client.on('ready', (c) => {
  console.log(`✅ ${c.user.tag} is online.`);
});

client.on('messageCreate', (message) => {
  if (message.author.bot) {
    return;
  }

  if (message.content === 'hello') {
    message.reply('hello');
  }
});

I tried to make a simple test command but when i try to run it , it gives me that error.
I dont understand what i did wrong, i followed a tutorial. But it works perfectly fine with ‘node .’but with nodemon it has that error

Looking for a way to automatically signin to a windows based login using ip address in web browser

I have setup a server at 192.168.18.40. Server works fine. I am using windows profile. So every time i use this ip address, it asks for sign in which i must enter into a popup window.Sign in Screen
There is no security concern. I don’t want this window to popup. I want my html page to somehow automatically enter username and password and sign in (i guess using javascript or something). I have searched everywhere for the answer but could not find one. Username and Password is the same as one of the windows local profiles.

Next.js Types not being infered from getServerSideProps to NextPage

So the data type from getServerSideProps is not being passed to the page.

This is the model

export type TypeUser = {
  _id?: Types.ObjectId;
  name: string;
  email: string;
  image: string;
  emailVerified: null;
  profileDescription: string;
  imageDownloadFormat: string;
};

This is my getServerSideProps

export const getServerSideProps: GetServerSideProps = async (ctx: GetServerSidePropsContext) => {
  const session = await getServerSession(ctx.req, ctx.res, authOptions);

  if (!session) {
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  }

  const response = await NextAPIClient.get(`/api/users/by-email/${session.user?.email}`);
  const user: TypeUser = await response.data.data;

  return {
    props: { user },
  };
};

and this is the NextPage

const ProjectsPage: NextPage<InferGetServerSidePropsType<typeof getServerSideProps>> = ({ user }) => {
console.log(user.name);
...

So basically I’m not getting type completion when I do user. something