Firebase Deployment Error: JavaScript Cloud Functions onWorkFormCreated and onTalentFormCreated Fail Container Healthcheck on Cloud Run

I am trying to deploy a cloud function on Firebase but it gives me following error:

Error:

Could not create or update Cloud Run service onworkformcreated, Container Healthcheck failed. Revision 'onworkformcreated-00001-hab' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable.

I have am trying to deploy with custom
Code:

/* eslint-disable */

const admin = require("firebase-admin");
const sgMail = require("@sendgrid/mail");
const { onValueCreated } = require("firebase-functions/v2/database");
const functions = require("firebase-functions");

// Initialize Firebase
const serviceAccount = require("../firebase-adminsdk.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "Firebase Realtime Database URL",
});

// Initialize SendGrid
const sendgridApiKey = functions.config().sendgrid.key;
sgMail.setApiKey(sendgridApiKey);

// Sender email
const senderEmail = "[email protected]";

// Function to send confirmation email
async function sendConfirmationEmail(userType, userEmail, firstName, lastName) {
  // Email Content goes here
}

// Realtime Database trigger for 'work' node
exports.onWorkFormCreated = onValueCreated("/work/{pushId}", (event) => {
  const formData = event.data.val();
  sendConfirmationEmail(
    formData.userType,
    formData.email,
    formData.firstName,
    formData.lastName,
  );
});


// Realtime Database trigger for 'talent' node
exports.onTalentFormCreated = onValueCreated("/talent/{pushId}", (event) => {
    const formData = event.data.val();
    sendConfirmationEmail(
      formData.userType,
      formData.email,
      formData.firstName,
      formData.lastName,
    );
});

I try deploying with different versions of Node.Js like version 16, 18, and 20 nothing works.

Determining visible center of SVG as rotation origin while panning and zooming

I’m developing an SVG viewer, using svg-pan-zoom library to pan and zoom the SVG.

What I want
What I want in the end is to be able to pan/zoom to a specific point in the SVG and be able to rotate from that point (and be able to repeat this process).
The red circle (when clicking or panning) is just a visual debugging tool

SVG structure:

<svg id="svgElement" viewBox="0 0 500 500">
  <g id="svg-pan-zoom-container"> <!-- SVG-pan zoom translations are applied to this group -->
    <g id="group" transform="rotate(60 250 250)">
      <rect x="225" y="225" width="20" height="20" fill="blue" />
    </g>
  </g>
</svg>

Problem

Updating the rotation origin results in the SVG jumping.
I tried compensating by panning to the coordinates after updating the origin.
I’ve tried multiple ways of determining the pan coordinates.

In the first example (with the click point as center and origin) seems to work, so I’m kind of lost why it won’t work with panning.

Questions

  • Would another zooming/panning approach work better? I’ve considered implementing my own solution.
  • Is the a better approach to always rotating from the visual center?
  • Am i stupid? 🙁

How to show an image in react front-end, using a Node.js backend with SQL Database?

Two years ago I started studying programming at my university, so I’m pretty new.
I am struggling to achieve the following:
I’m trying to make an app for a movie-theater, the objective is to display photos (movieposters basically) from the SQL-database into my react front-end application. I successfully connected my front-end to the database but got stuck at the following part:

MovieCard.jsx

import React from "react";
import { Link, Navigate, useNavigate } from "react-router-dom";

const MovieCard = ({ title, year, cast, extract, thumbnail, id }) => {

  const navigateToMovie = useNavigate();
  return (
    <div
      onClick={() => {
        navigateToMovie(`/movies/${id}`);
      }}
      className="movie-card"
    >
      <img src={thumbnail} alt={id} />

      <div className="movie-details">
        <h2>
          {title} ({year})
        </h2>
        <p>{extract}</p>
        <p>Cast: {cast}</p>
      </div>
    </div>
  );
};

export default MovieCard;

As you see here, this is my MovieCard that I want to display on the front page, there will be around 20 movies on the homepage. movies in my database exists out of : id (auto-increment), Name(varchar 100), Description (varcharmax), Cast (varcharmax), photo (image-url from source) and year (int)

// MovieList.jsx
import React from "react";
import { Link } from "react-router-dom";
import MovieCard from "./MovieCard";

const MovieList = ({ movies }) => {
  return (
    <div className="movie-list">
      {movies.map((movie) => (
        <Link key={movie.id} to={`/movie/${movie.id}`}>
          <MovieCard {...movie} />
        </Link>
      ))}
    </div>
  );
};

export default MovieList;

The moviecards get put into a List to show on the HomePage.

import React, { useEffect, useState } from "react";
import MovieList from "./MovieList";
// import "../css/filmcss";

const FilmComponent = () => {
  const [moviesData, setMoviesData] = useState([]);

  useEffect(() => {
    
    fetch("http://localhost:5050/movies")
      .then((response) => response.json())
      .then((data) => setMoviesData(data))
      .catch((error) => console.error("Error fetching data:", error));
  }, []);

  return (
    <>
      <div>Hier worden alle films getoond</div>
      <MovieList movies={moviesData} />
    </>
  );
};

export default FilmComponent;

The class above gets shown directly to the homepage. it returns empty spaces, but the right ID gets shown, so I know that there is just a problem somewhere with the pictures itself.

I would love some feedback or solutions.

How Can I Style This Converter?

I want to make the box under Amount, From, and To to look the same. Preferrably, I want them to look like the one under Amount from size to border and background. I also want it to print the exchange rates and not just the conversion with the font-size of the Conversion bigger than others unlike it is right now where it is smaller compared to the currency acronyms. Thanks. I want to use this in a WordPress posts and Pages.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .converter-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 20px;
        }

        .label-container {
            display: flex;
            flex-direction: column;
            align-items: left;
            margin-bottom: 10px;
        }

        .labels-row {
            display: flex;
            justify-content: space-around;
            width: 100%;
            margin-bottom: 10px;
        }

        label {
            font-size: 18px;
            margin-bottom: 5px;
        }

        input, span, select {
            font-size: 16px;
            padding: 10px;
        }

        select::-ms-expand {
            display: flex;
        }

        select {
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            padding-top: 10px;
            padding-right: 80px;
            padding-bottom: 10px;
            padding-left: 10px;
        }
        select:after {
            content: '25BC'; /* Unicode character for down arrow */
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
        }

        #result {
            font-size: 20px;
            margin-top: 10px;
        }
    </style>
</head>
<body>

<!-- Combined Converter -->
<div class="converter-container" id="combined-converter">
    <div class="labels-row">
        <div class="label-container">
            <label for="amount">Amount</label>
            <input type="number" id="amount" placeholder="Enter amount" oninput="convertCurrency()" value="1" />
        </div>

        <div class="label-container">
            <label for="from">From</label>
            <select id="from" onchange="updateToCurrency()">
                <option value="usd" selected>USD</option>
                <option value="ngn">NGN</option>
            </select>
        </div>

        <div class="label-container">
            <label for="to">To</label>
            <select id="to" onchange="updateFromCurrency()">
                <option value="usd">USD</option>
                <option value="ngn" selected>NGN</option>
            </select>
        </div>
    </div>

    <p id="result">1 USD = <span id="converted">...</span> NGN</p>
</div>

<script>
    function convertCurrency() {
        var amount = document.getElementById('amount').value;
        var fromCurrency = document.getElementById('from').value;
        var toCurrency = document.getElementById('to').value;

        var exchangeRate = (fromCurrency === 'usd' && toCurrency === 'ngn') ? 410 : 0.0024;

        var result = amount * exchangeRate;

        document.getElementById('converted').innerHTML = result.toFixed(2);
    }

    function updateToCurrency() {
        var fromCurrency = document.getElementById('from').value;
        document.getElementById('to').value = (fromCurrency === 'usd') ? 'ngn' : 'usd';

        convertCurrency();
    }

    function updateFromCurrency() {
        var toCurrency = document.getElementById('to').value;
        document.getElementById('from').value = (toCurrency === 'usd') ? 'ngn' : 'usd';

        convertCurrency();
    }

    // Initial conversion
    convertCurrency();
</script>

</body>
</html>

Vercel Next.js – third-party package fetch – CACHE MISS

I have many deployed projects on Vercel.com, recently I combined many common interfaces and apis in node_modules package.

All of my FETCH api have revalidate tag on fetch, cache HIT was every second time, now I do have cache MISS all the time.

Next.js local build however caches pages correctly

Is there any configuration which I need to specify that I have fetch need to be cached in node_modules package

My node package has both cjs and esm

I built a bootstrap form and the script is not grabbing it’s data

I’m learning to use bootstraps in google script and I wanted to build a form that could change some values in a sheet.

But my script is not grabbing the data from the form when I press the submit button.

The script is supposed to grab the data from the form, compare it to other data in the sheet and depending on the result of that comparison, change some values in the sheet.

But I keep getting errors that indicate the script is not getting the data from the form.

“Error TypeError: Cannot read properties of undefined (reading ‘State’)”

This is my script

function onOpen(){
  SpreadsheetApp.getUi().createMenu('Side Bar').addItem('Actions', "CustomSideBar").addToUi();
  }

function CustomSideBar(){
  var Html = HtmlService.createTemplateFromFile('Side Bar').evaluate();
  Html.setTitle('Sheet Actions');
  SpreadsheetApp.getUi().showSidebar(Html); 
  }

function doGet() {
  var SS = SpreadsheetApp.getActive();
  var DT = SS.getSheetByName('Data Table');
  var DTLR = DT.getLastRow();

  var Mails = DT.getRange(5, 3, DTLR - 4, 1).getDisplayValues().flat();
  var Options = [...new Set(Mails)];
  Options.unshift("")

  var htmlOutput = HtmlService.createHtmlOutputFromFile('Side Bar')
    .setTitle('Mails')
    .setWidth(300);

  return htmlOutput;
}

function getOptions() {
  var SS = SpreadsheetApp.getActive();
  var DT = SS.getSheetByName('Data Table');
  var DTLR = DT.getLastRow();

  var Mails = DT.getRange(5, 3, DTLR - 4, 1).getDisplayValues().flat();
  var Options = [...new Set(Mails)];
  Options.unshift("")
  return Options;

}

function doGet2() {
  var SS = SpreadsheetApp.getActive();
  var DT = SS.getSheetByName('Data Table');
  var DTLR = DT.getLastRow();

  var Date = DT.getRange(5, 8, DTLR - 4, 1).getDisplayValues().flat();
  var Options2 = [...new Set(Date)];
  Options2.unshift("")

  var htmlOutput = HtmlService.createHtmlOutputFromFile('Side Bar')
    .setTitle('Date')
    .setWidth(300);

  return htmlOutput;
}

function getOptions2() {

  var SS = SpreadsheetApp.getActive();
  var DT = SS.getSheetByName('Data Table');
  var DTLR = DT.getLastRow();

  var Date = DT.getRange(5, 8, DTLR - 4, 1).getDisplayValues().flat();
  var Options2 = [...new Set(Date)];
  Options2.unshift("")
  return Options2;

}

function ChangeState(Data){
  var SS = SpreadsheetApp.getActive();
  var DT = SS.getSheetByName('Data Table');
  var DTLR = DT.getLastRow();
  var Mails = DT.getRange(5, 3, DTLR - 4, 1).getDisplayValues().flat();
  var Date = DT.getRange(5, 8, DTLR - 4, 1).getDisplayValues().flat();

  Logger.log(Data.State)
  
  for (I = 0; I<Mails.length; I++){
    if (Data.State != "" && Data.Reason != "" && Data.Mail == Mails[I] && Data.Date == Date[I]){
      var StateRange = DT.getRange(I+5, 15);
      StateRange.setValue(Data.State);
      var ReasonRange = DT.getRange(I+5, 16);
      ReasonRange.setValue(Data.Reason);
    }
  }
}

and this my html

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>

<body>

  <form>
    <fieldset>
      <legend class='Review Requests'>Review Requests</legend>

      <div> <label for="Mails">Select Agent's Mail:</label>
        <select id="Mails" name="Mails">
        <? var options = getOptions(); ?>
        <? for (var i = 0; i < options.length; i++) { ?>
          <option value="<?= options[i] ?>"><?= options[i] ?></option>
        <? } ?>
      </select>
      </div><br>

      <div><label for="Date">Select Date:</label>
        <select id="Date" name="Date">
        <? var options = getOptions2(); ?>
        <? for (var i = 0; i < options.length; i++) { ?>
          <option value="<?= options[i] ?>"><?= options[i] ?></option>
        <? } ?>
      </select>
      </div><br>

      <div><label for="State">Select State:</label>
        <select name="State" id="State">
        <option value=""></option>
        <option value="APPROVED">APPROVED</option>
        <option value="DENIED">DENIED</option>
        <option value="PENDING">PENDING</option>
        </select>
      </div><br>

      <div><label for="Reason">Select State:</label>
        <select name="Reason" id="Reason">
        <option value=""></option>
        <option value="Hours Requested">Hours Requested</option>
        <option value="Hours Available">Hours Available</option>
        <option value="Hours Unavailable">Hours Unavailable</option>
        <option value="Country Laws">Country Laws</option>
        <option value="Other">Other</option>
        </select>
      </div><br>

      <div class="Submit"><input id="Submit" type="Submit" value="Submit"></div>

    </fieldset>
  </form>

  <script>
    MailBox = document.getElementById("Mails");
  DateBox = document.getElementById("Date");
  StateBox = document.getElementById("State");
  ReasonBox = document.getElementById("Reason");

  document.getElementById("Submit").addEventListener("click", function(event) {
    event.preventDefault(); // Prevent the default form submission behavior

    AddData();
  });

  function AddData() {
    // Log values to console for debugging
    console.log("Mail:", MailBox.value);
    console.log("Date:", DateBox.value);
    console.log("State:", StateBox.value);
    console.log("Reason:", ReasonBox.value);

    Data = {
      Mail: MailBox.value,
      Date: DateBox.value,
      State: StateBox.value,
      Reason: ReasonBox.value
    };

    // Log the entire Data object
    console.log("Data:", Data);

    google.script.run.ChangeState(Data);
  }
  </script>


  <fieldset>

    <legend class='Other Actions'>Other Actions</legend>

    <input type="button" value="Move Requests"><br><br>
    <input type="button" value="Check Data">

  </fieldset>

</body>

</html>

why does react only invoke state change after the second time I unfocus the input?

in this code I want react to start validating only after I leave the field for the first time, yet it only does after the second time (focus => blur => focus => blur). why is this happening ?

const BasicForm = (props) => {
    const [email, setEmail] = useState("");
    const [emailError, setEmailError] = useState("");
    const [emailEntered, setEmailEntered] = useState(false);

    function validateEmail() {
        const formatCheck = /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/.test(
            email
        );
        const emptyCheck = email.trim() !== "";

        if (emailEntered) {
            if (!formatCheck) {
                setEmailError(
                    `email can only contain letters, numbers, . , _ also it must end with a @ + domain`
                );
            }
            if (!emptyCheck) {
                setEmailError("email can't be empty");
            }
            if (formatCheck && emptyCheck) {
                setEmailError("");
            }
        }
    }

    function handleEmailChange(event) {
        const emailInput = event.target.value;
        setEmail(emailInput);
        validateEmail();
    }

    function handleEmailBlur() {
        setEmailEntered(true);
        validateEmail();
    }

    return (
        <form onSubmit={}>
            <div className="control-group">
            <div className="form-control">
                <label htmlFor="email">E-Mail Address</label>
                <input
                    type="text"
                    id="email"
                    value={email}
                    onChange={handleEmailChange}
                    onBlur={handleEmailBlur}
                />
                {emailError && <small>{emailError}</small>}
            </div>
        </form>
    );
}

I inspected the component state in the browser and on first blur it does change the emailEntered to true but the emailError is still empty. it only changes after the second time.

Append textarea if span have data-action with name “custom-new-field”

I am trying to append a new textarea if the field have “data action”, with “new field name”. If we uncheck the field the textarea should remove. I want it on multi field if any field have this data action it should add the new text area with name. I am adding the script on codepen.

https://codepen.io/hnpiocyj-the-encoder/pen/vYPYpWz?editors=1111

<style>.active {
  border: 1px solid;
}
</style>
<div class="customize">
<span onclick="select(this);">text 1</span>
<span onclick="select(this);" data-action="new-field-1">text 2</span>
<span onclick="select(this);" data-action="new-field-2">other</span>
</div>
function select(currObj) {
  const allActiveSpans = document.querySelectorAll('span.active');
  allActiveSpans.forEach(span => {
    if(span !== currObj){
      span.classList.remove('active');
    }
    
  });
  currObj.classList.toggle('active');
  data_action = $(currObj).data('action');
  if(!data_action)
  {
    $('.append').remove();
  }
  if(data_action) {
  $('.customize').append('<textarea class="append" id="'+data_action+'" name="'+data_action+'" rows="3" cols="5"></textarea>');
   }
}

The issue is when i am appending text area it is appending but when i clicking that field again it is adding it multi time. For this field if the textarea is appended it should not append it again. If i uncheck the field it should remove it. and if the other fields are check then textarea should be there.

Stable Diffusion API with React issue

I’m new here and would appreciate your help.
I am currently experiencing an issue with the stablediffusion API.
Here’s my code.

const request_body = {
    key: process.env.REACT_APP_STABLE_DIFFUSION_API,
    prompt: "ultra realistic close up portrait ((beautiful pale cyberpunk female with heavy black eyeliner))",
    negative_prompt: null,
    width: "512",
    height: "512",
    samples: 1,
    num_inference_steps: "20",
    seed: null,
    guidance_scale: 7.5,
    safety_checker: "yes",
    multi_lingual: "no",
    panorama: "no",
    self_attention: "no",
    upscale: "no",
    embeddings_model: null,
    webhook: null,
    track_id: null,
};

const generateImage = async () => {
  const generateResponse = await axios.post(
    "https://stablediffusionapi.com/api/v5/text2video",
    request_body
  );
  console.log(generateResponse.data);
};

It’s not just an issue with the API key. The result is an error.
The status shows an error and the error message needs a seconds value.

Force DevTools to Focus on an Particular Element in an iframe on Element Inspection

If I have an iframe in my page and I do Google Chrome Development Tools, Element Inspection, it selects the html by default via #document.

There is no way to auto launch the DevTools by default on click.

Can I programmatically open the devtools from a Google Chrome extension?

Is there a way to set focus (as in the element is selected in DevTools) given that if I have

<iframe srcdoc="<h1></h1>"></iframe>

So basically when the user clicks on the element, the Devtools is launched (not possible) but atleast the element in question, h1 is selected.

What code do I add to a .js file to define “start”, to fix the Invalid Block Definition?

I’m new to Blockly. To learn how to create a Custom Block, I used https://developers.google.com/blockly/guides/configure/web/toolbox#json. I copied portions of this text to an HTML file:

'''
<body>
<div id="blocklyDiv"></div>
<script>
  var toolbox = 
  {
    "kind": "categoryToolbox",
    "contents": [
      {
        "kind": "category",
        "name": "Core",
        "contents": [
          {
            "kind": "block",
            "type": "controls_if"
          },
          {
            "kind": "block",
            "type": "logic_compare"
          },
        ]
      },
      {
        "kind": "category",
        "name": "Custom",
        "contents": [
          {
            "kind": "block",
            "type": "start"
          },
          {
            "kind": "category",
            "name": "Move",
            "contents": [
              {
                "kind": "block",
                "type": "move_forward"
              }
            ]
          },
          {
            "kind": "category",
            "name": "Turn",
            "contents": [
              {
                "kind": "block",
                "type": "turn_left"
              }
            ]
          }
        ]
      }
    ]
  }
  var workspace = Blockly.inject('blocklyDiv', {toolbox: toolbox});
</script>
'''

Using VSCode -> F5 — results in this on a Chrome browser -> https://snipboard.io/ToY9UW.jpg

Selecting the “Custom” icon -> https://snipboard.io/X9WIFH.jpg, the VSCode “Debug Console” shows -> https://snipboard.io/qkpXCi.jpg.

What code do I add to a .js file to define “start”, to fix the Invalid Block Definition?

I can’t switch between table-view and grid-view with script

<section class="section table-section">
<div class="table-container">
    <div class="table-header">
        <div
            class="d-flex align-items-center justify-content-between py-3 px-3"
        >
            <div class="d-flex align-items-center">
                <i class="fa-solid fa-list-ul p-2"></i>
                <i class="iconsax p-2" icon-name="grid-apps"></i>
            </div>
            <div>
                <i class="iconsax p-2" icon-name="arrow-up-down"></i>
            </div>
        </div>
    </div>

    <table class="table"> ...

I have a table view here. There are 2 icons in the header on the table. One of them is the list icon and the other is the grid icon.

<section class="section grid-section">
<div class="table-container">
    <div class="table-header">
        <div
            class="d-flex align-items-center justify-content-between py-3 px-3"
        >
            <div class="d-flex align-items-center">
                <i class="fa-solid fa-list-ul p-2"></i>
                <i class="iconsax p-2" icon-name="grid-apps"></i>
            </div>
            <div>
                <i class="iconsax p-2" icon-name="arrow-up-down"></i>
            </div>
        </div>
    </div>
    <div class="d-flex">
        <div class="col-4 card-grid"> ...

Here, I have a grid-shaped layout, there are three grid elements side by side that I called with col-4. The same header as above is here too.

    .grid-section {
    padding: 1rem 3rem 1rem 3rem;
    display: none;
}

grid-section’s css.

.table-section {
    padding: 1rem 3rem 1rem 3rem;
    display: block;
}

table-section’s css.

Here, when the page is first opened, I say show only the table, not the Grid-view.

    <script>
    document.addEventListener("DOMContentLoaded", function () {
        // Get the list icon and grid icon elements
        var listIcon = document.querySelector(".fa-solid.fa-list-ul");
        var gridIcon = document.querySelector(
            ".iconsax[icon-name='grid-apps']"
        );

        // Add a click event listener to the list icon
        listIcon.addEventListener("click", function () {
            // Show the table view and hide the grid view
            document.querySelector(".table-section").style.display = "block";
            document.querySelector(".grid-section").style.display = "none";
        });

        // Add a click event listener to the grid icon
        gridIcon.addEventListener("click", function () {
            // Show the grid view and hide the table view
            document.querySelector(".table-section").style.display = "none";
            document.querySelector(".grid-section").style.display = "block";
        });
    });
</script>

Finally, in the script, if the first icon is clicked, i.e. the icon with class .fa-solid.fa-list-ul, I say show the grid view. If the second icon is clicked, i.e. the class .iconsax[icon-name=’grid-apps’], I say show the grid view. . When I click on the grid icon, I can get grid view. But it doesn’t click on the list icon again. I can’t switch back to list view.

how to create an animated changing number

how to make the numbers change until the User stop on the page it stops
using html – css -js .

when we scroll the page the number of the visits starts to change until the User stop on the page
tell me : if it’s better with another freamwork like react

A formula to calculate a combined weight of a similarity search results

I am looking a way to sort the results of a similarity (fuzzy) search based on scores(?), number of matches(?), etc. So need some advice

The flow is like this: i have a list of articles and a search input. User inputs a string, which gets split into words, and then all the search words are used to search among the tokens, which belong to each of the articles. I am using a below formula:

var distance = levenshtein_distance(a, b);
var longest_word = Math.max(a.length, b.length);

return (longest_word - distance) / longest_word;

the results are [0,1] and the bigger is better.

So calculating the combined weight of an article, using just an arithmetical mean is not that good, as it does not respect the number of matches, only the mean, obviously.

Any best practices for such a cases?

tried the arithmetical mean formula, doesn’t look good