Drawing a polygon in a Google Maps Angular component

So I’ve been reading about the updates of dependencies but couldn’t find wich are the correctly most recent. Also I’ve read the documentation of GM and Ng and still don’t know wich options should I use.

So far I was able to render the map with an initialized 4 coordenates polygon.

(Sorry but I’d wish I could understand how to copy code here with stackoverflow not crying about the format I’m using to post)

    export class MapComponent {
  title = 'Google Maps';
  polygonPoints: google.maps.LatLngLiteral[] = [
    { lat: -34.5, lng: -58.4 },
    { lat: -34.5, lng: -59.4 },
   { lat: -35.5, lng: -59.4 },
   { lat: -35.5, lng: -58.4 },
 ];
 options = {
   mapTypeId: "satellite",
   streetViewControl: false,
   fullscreenControl: false
 }
 bsAs = {
  lat: -34.6118,
  lng: -58.4173,
 }
 vic = {
   lat: -32.62014554060702,
   lng: -60.149028935272156
 }
 position = this.bsAs
 zoom = 8
 centerVic() {
  this.position = this.vic
   this.zoom = 10
 }
}

I’m thinking about adding a function with a listener of the coordinates of the clicks on the map to set them in this objetc since this is rendered fine:

 polygonPoints: google.maps.LatLngLiteral[] = [
   { lat: -34.5, lng: -58.4 },
    { lat: -34.5, lng: -59.4 },
    { lat: -35.5, lng: -59.4 },
   { lat: -35.5, lng: -58.4 },
  ];

But I’m wondering if is this the right way to do it or there is something way faster..

Thank you!

D3.js: Is there a was to delete annotations in a pie chart when switching the dataset?

So i’ve been working on a school project thats due tomorrow, and we have to make a data visualisation using the d3 chart library. i’ve found some code that allows me to add annotations to my pie chart, but i don’t know how to delete the previous annotations when switching dataset. Can anyone help me out?

HTML code:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <!DOCTYPE html>
<meta charset="utf-8">

<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Color scale -->
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>

<!-- Add buttons -->
<button onclick="update(data1)">Data 1</button>
<button onclick="update(data2)">Data 2</button>
<button onclick="update(data3)">Data 3</button>
<button onclick="update(data4)">Data 4</button>
<button onclick="update(data5)">Data 5</button>
<button onclick="update(data6)">Data 6</button>


  <!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>
</head>

<body>
  Lorem Ipsum
  <script src="script.js"></script>

 <!--
  This script places a badge on your repl's full-browser view back to your repl's cover
  page. Try various colors for the theme: dark, light, red, orange, yellow, lime, green,
  teal, blue, blurple, magenta, pink!
  -->
  <script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script> 
</body>

</html>

Javascript:


// set the dimensions and margins of the graph
var width = 450
    height = 450
    margin = 40

// The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin.
var radius = Math.min(width, height) / 2 - margin

// append the svg object to the div called 'my_dataviz'
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

// create  data_set
var data1 = {a: 1, b: 20, c:30, d:20, e:20}
var data2 = {a: 6, b: 16, c:20, d:14, e:19, f:12}
var data3 = {a: 9, b: 1}
var data4 = {a: 1, b: 2, c:3, d:4, e:5, f:6}
var data5 = {a: 2, b: 3, c:4, d:1, e:8}
var data6 = {a: 3, b: 9, c:5, d:3, e:2, f:3}

// set the color scale
var color = d3.scaleOrdinal()
  .domain(["a", "b", "c", "d", "e", "f"])
  .range(d3.schemeDark2);

// A function that create / update the plot for a given variable:
function update(data) {

  // Compute the position of each group on the pie:
  var pie = d3.pie()
    .value(function(d) {return d.value; })
    .sort(function(a, b) { console.log(a) ; return d3.ascending(a.key, b.key);} ) // This make sure that group order remains the same in the pie chart
  var data_ready = pie(d3.entries(data))


  // The arc generator
  var arc = d3.arc()
    .innerRadius(radius * 0.5)         // This is the size of the donut hole
    .outerRadius(radius * 0.8)


  // Another arc that won't be drawn. Just for labels positioning
  var outerArc = d3.arc()
    .innerRadius(radius * 0.9)
    .outerRadius(radius * 0.9)

  
  // map to data
  var u = svg.selectAll("path")
    .data(data_ready)

  // Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
  u
    .enter()
    .append('path')
    .merge(u)
    .transition()
    .duration(1000)
    .attr('d', d3.arc()
      .innerRadius(0)
      .outerRadius(radius)
    )
    .attr('fill', function(d){ return(color(d.data.key)) })
    .attr("stroke", "white")
    .style("stroke-width", "2px")
    .style("opacity", 1)

  // Add the polylines between chart and labels:
  svg
    .selectAll('allPolylines')
    .data(data_ready)
    .enter()
    .append('polyline')
      .attr("stroke", "black")
      .style("fill", "none")
      .attr("stroke-width", 1)
      .attr('points', function(d) {
        var posA = arc.centroid(d) // line insertion in the slice
        var posB = outerArc.centroid(d) // line break: we use the other arc generator that has been built only for that
        var posC = outerArc.centroid(d); // Label position = almost the same as posB
        var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2 // we need the angle to see if the X position will be at the extreme right or extreme left
        posC[0] = radius * 0.95 * (midangle < Math.PI ? 1 : -1); // multiply by 1 or -1 to put it on the right or on the left
        return [posA, posB, posC]
      })

  // Add the polylines between chart and labels:
  svg
    .selectAll('allLabels')
    .data(data_ready)
    .enter()
    .append('text')
      .text( function(d) { console.log(d.data.key) ; return d.data.key } )
      .attr('transform', function(d) {
          var pos = outerArc.centroid(d);
          var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
          pos[0] = radius * 0.99 * (midangle < Math.PI ? 1 : -1);
          return 'translate(' + pos + ')';
      })
      .style('text-anchor', function(d) {
          var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
          return (midangle < Math.PI ? 'start' : 'end')
      })
 

 
  
  
  
  // remove the group that is not present anymore
  u
    .exit()
    .remove()

  
  
}

// Initialize the plot with the first dataset
update(data1)


I’ve tried using the .exit() and .remove() functions, but i think that i’ve misused these functions, as they have not been very helpful

Azure Service Bus Sender scheduledEnqueueTimeUtc not being respected

We are currently sending batches of messages into a Azure Service Bus queue and setting scheduledEnqueueTimeUtc to schedule them in chunks of 100, one minute apart. I can see this is set in the Message properties on the Service Bus Explorer on the portal. However my Azure Functions are still processing these messages on the queue on arrival, not respecting the scheduled enqueue time. There isn’t a lot of examples of folk doing this in javascript and node, I assume I’m setting something wrong? Relevant sending of message code

const { app, output } = require('@azure/functions');
const { ServiceBusClient  } = require('@azure/service-bus');
const { DefaultAzureCredential } = require("@azure/identity");
const moment = require('moment');
const { getAllEmployeeXRefs }  = require('../util/GetAllEmployeeXRefs.js');

const credential = new DefaultAzureCredential();
const serviceBus = new ServiceBusClient(process.env["ServiceBusConnection__fullyQualifiedNamespace"],credential);
const serviceBusSender = serviceBus.createSender("cacheemployeequeue");


function chunkArrayInGroups(arr, size) {
    var myArray = [];
    for(var i = 0; i < arr.length; i += size) {
      myArray.push(arr.slice(i, i+size));
    }
    return myArray;
 }


app.http('CacheAllEmployees', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    handler: async (request, context) => {
      

        employeeXrefsToCache = await getAllEmployeeXRefs(filter);
        
        const groupsOfMessages = chunkArrayInGroups(employeeXrefsToCache.Data, 100);
        
        for (let i=0;i<groupsOfMessages.length;i++) {
            
            const batchOfMessages = groupsOfMessages[i];
            const messagesToPush = [];
            for (chunk in batchOfMessages) {
                const message = {
                    body: batchOfMessages[chunk],
                    contentType: "application/json",
                    scheduledEnqueueTimeUtc: moment().add(1*i, 'minutes').format('M/D/YYYY H:mm:ss A')
        
                };
                messagesToPush.push(message);
            }
            await serviceBusSender.sendMessages(messagesToPush);
        }
    
        return  { body: `added ${employeeXrefsToCache.Data.length} to queue` }
    }
});

in the Explorer messages look like this (which is correct):

enter image description here

But the consumption function get them before the scheduled time, as fast as we load them in.

How to create an url redirect based on the value of the input field with event handlers

I want to create a dynamic url route for an event handler function.

I have the following codebase in an index.js file.

This is the vercel deployment: https://havadurumu-7pqg.vercel.app/

export default function Home() {
    const [city, setCity] = useState('')
    const fetchWeather = async (e) => {
          e.preventDefault()
      // setLoading(true)
          const axiosRequest = require('axios');
          try {
              const url = `https://api.openweathermap.org/geo/1.0/direct?q=${city}&&appid=${process.env.NEXT_PUBLIC_WEATHER_KEY}`;
              const response = await axiosRequest.get(url);
              const url2 = `https://api.openweathermap.org/data/2.5/forecast/daily?lat=${response.data[0].lat}&lon=${response.data[0].lon}&units=metric&cnt=16&appid=${process.env.NEXT_PUBLIC_WEATHER_KEY}`;
              const response2 = await axiosRequest.get(url2);
              setWeather(response2);
              router.push(`/weather?city=${encodeURIComponent(city)}`);


    return (
       <form onSubmit={fetchWeather} className={'flex justify-between w-full items-center m-auto p-1 bg-transparent border-2 border-gray-400 text-white rounded-2xl'}>
                                    <div>
                                        <input
                                            onChange={(e) => setCity(e.target.value)}
                                               className={'bg-transparent border-none text-gray-600 focus:outline-none text-sm'}
                                               type="text"
                                               placeholder="Şehir ara"/>
                                    </div>
                                    <button type="submit" onClick={fetchWeather}>
                                        <BsSearch size={20}/>
                                    </button>
                                </form>
<div className='lg:mx-auto md:mx-auto  overflow-x-auto justify-around container'>
                    {weather.data && <Weather  data={weather} /> }
                  </div>
)

I tried the router.push() method but got an error. I was expecting to redirect to a url whatever typed in the input field(in this case city) of the return statement. e.g localhost:3000/weather/london.

React Component Rendering Error – Element Type Invalid

React Uncaught Error: Element type is invalid

I am facing an issue in my React application where I receive the following error message:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

This error is occurring in my Login component.

Here’s my application structure:

  • App.jsx is the main component that sets up routes.
  • Login.jsx is one of the components used in a route.

Here is the simplified code for Login.jsx:

`
import React, { useEffect, useState } from "react";
import { Hourglass } from 'react-loader-spinner';

const Login = () => {
  <>
            {isLoading ? (
                <Hourglass
                    visible={true}
                    height="100"
                    width="100"
                    ariaLabel="hourglass-loading"
                    wrapperStyle={{
                        position: 'absolute',
                        left: '50%',
                        top: '50%',
                        transform: 'translate(-50%, -50%)'
                    }}
                    wrapperClass=""
                    colors={['#306cce', '#72a1ed']}
                />
            ) : (
              {* html stuff *}
            )}
        </>
};`

export default Login;
In my App.jsx, I have defined a route that uses the Login component:

jsx
`import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import MainContent from './components/mainContent/MainContent';
import Login from './components/login/Login';

const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<MainContent />} />
        <Route path="/login" element={<Login />} />
      </Routes>
    </BrowserRouter>
  );
};

export default App;`

## The Issue

I was able to run my application without any errors previously. However, after doing an npm run build, I started encountering this error. I have tried the following steps to resolve it:

Checked for syntax errors.
Reviewed imports.
Verified the correct export of the Login component.
Checked the React Router configuration in App.jsx.
Cleared the build cache.
Ensured that dependencies are up to date.

## The Mystery

The most puzzling aspect is that I had previously run the application without encountering this error, and it started occurring after the build. I have also noticed that removing a specific section of code from Login.jsx, such as <Hourglass ... />, resolves the error, but I am unable to determine why this component is causing the problem.

Can anyone provide insights into what might be causing this error and how to resolve it?

Any help or guidance would be greatly appreciated. Thank you!

Tried various fixes, still errors.

Mysql2 error in NextJS13, cant find module Net

I’m trying to acquire information from a mysql database in nextjs13 using the mysql2 dependency, like this:


import mysql from 'mysql2/promise'

export const getData = async(req, res) => {
    const dbconnection = await mysql.createConnection({
        host: "hostname",
        database: "databasename",
        user: "username",
        password: "password",

      });

      try {
        const query = "SELECT productid, productname, productimage FROM products";
        const values = [];
        const [data] = await dbconnection.execute(query, values);
        dbconnection.end();
    
        res.status(200).json({ products: data });
      } catch (error) {
        // unhide to check error
        // res.status(500).json({ error: error.message });
      }

  return dbconnection
}

At first the error was that the net module was missing, which is called when mysql.createConnection is used. Then when I added the module, it said that net.connection is not a function. I have already tried it in both client side and server side components and neither work. The strings in the object are examples ofc. Does anybody know what could it be?

Player not jumping off platform

I made a simple player and platform for it to stand on, but the player won’t jump when it is standing on the platform. Here is my code:

var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
var isJumping = false
canvas.width = 1024;
canvas.height = 576;
const gravity = 0.2
class Player {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.velocityY = 0;
        this.velocityX = 0
    }
    draw() {
        c.fillStyle = 'red';
        c.fillRect(this.x, this.y, this.width, this.height);
    }
    update() {
        this.y += this.velocityY
        if(this.y + this.height + this.velocityY<= canvas.height){
            this.velocityY += gravity
            this.y += this.velocityY
        }else{
            this.velocityY = 0 
            isJumping = false
        }
        this.x += this.velocityX
        this.draw();
    }
}
class Platform{
    constructor(x,y,width,height){
        this.x = x
        this.y = y
        this.width = width
        this.height = height
    }
    draw(player){
        c.fillStyle = 'green'
        c.fillRect(this.x,this.y,this.width,this.height)

        if(player.y <= this.y && player.y+player.height>=this.y&& player.x+player.width>=this.x && player.x<=this.x+this.width){
            player.velocityY = 0
            player.y = this.y-player.height
            isJumping = false
        }
    }
}
const player = new Player(0, 0, 50, 100);
const platform = new Platform(0,300,100,50)
function update() {
    c.fillStyle = 'black'
    c.fillRect(0,0,canvas.width,canvas.height) // Clear the canvas on each frame
    platform.draw(player)
    player.update();
    requestAnimationFrame(update); // Request the next frame
}

update(); // Start the animation loop

addEventListener('keydown', (event)=>{
    if(event.code==="KeyD"){
        player.velocityX=3
    }
    if(event.code==="KeyA"){
        player.velocityX=-3
    }
    if(event.code==="Space"&& isJumping == false){
        player.velocityY = -8
        isJumping = true
    }
})

addEventListener('keyup', (event)=>{
    if(event.code==="KeyD"){
        player.velocityX=0
    }
    if(event.code==="KeyA"){
        player.velocityX=0
    }
})

I expected the player to be able to jump off the platform, but it won’t. I’ve tried everything I can, but it still won’t work. I’m assuming it has something to do with the velocity of the player, can someone tell me what’s wrong?

Updating en element in array of objects through ‘useState’ isn’t updating the value in first render, ‘useEffect’ doesn’t help (React project) [duplicate]

React project has a form of parameters with <input …/> fields. When I input value it renders a chart with trendline.
The problem is that this set of parameters updates only after second render. This does not work for the initial/first render.

Form for parameters input:

const DCAForm = ({ formParams, onChangeFormParams, title }) => {

  return (
      <div>
          <p>{title}</p>
          <ul style={{ listStyle: 'none' }}>
            {formParams.map(param => (
              <li key={param.id}>
                <label>
                  {param.label}
                <input
                  value={param.value} 
                  name ={param.label}
                  onChange={ e=> {
                  onChangeFormParams({
                    ...param,
                    value: e.target.value            
                  });
                  }}
                  />
                  </label>
              </li>
            ))}
          </ul>
      </div>
  );
};

export default DCAForm;

Parameter set:

const initialForm = [

    {id:0, label:'title', value:'P90'},
    {id:1, label:'date', value:'01.08.2023'},
    {id:2, label:'Qi', value:52},
    {id:3, label:'Di', value:0.00069289159455027},
    {id:4, label:'ti', value:'01.01.2020'},
    {id:5, label:'b', value:0.11},
  ];
  const [formParams, setFormParams] = useState(initialForm);

Event handler, which supposed to update values:

function handleChangeFormParams(fParam) {

  const newParams = formParams.map(p=>{
                    if(p.id===fParam.id) {
                      return fParam;
                    } else{
                      return p;
                    }
                });

 setFormParams(() => {return newParams});

 //here fp has OLD value, np has new value from input field.
 console.log('fp: '+ formParams[2].value);
 console.log('np: '+ newParams[2].value);

 // this function updates set of data and then the chart is updating.
 setDeclines(calculateDecline(wellData,12,formParams));
 
}

The problem can be solved by adding button, which will submit the results, than the chart is built the right way with the latest value from input field. But I would like it to be ‘dynamically’ when user types into field, the chart is updating simultaneously.
have found dozens of topics similar to that, none of them did help, sorry if I’m missing something.

thanks beforehand.

How change Checkbox body styles depeding of its input state at Mantine?

I’m using Mantine and have to implement a specific styled container for Checkbox input.

This checkbox will change its body styles depending of the input state(checked or not checked). Therefore, to change checkbox’ container body style, I need to know the checkbox’ input pseudo class state.

Inside the theme file. I have something like this:

Checkbox: {
      styles: theme => ({
        body: {
          background: "white",
        },
        "input:checked": {
          body: {
            background: "black",
          }
        },
      }),
    },

This body and input value comes from StylesAPI from Mantine:

enter image description here

Any idea how can I achieve this?

Thank you in advance!

Weird behaviour with javascript Arrays and promises [duplicate]

I’ve been experiencing some behaviour that I don’t understand to do with JavaScript arrays. As viewed from the firefox console savedMessages[channelId] displayed differently at different points.
Both of these should be the same but they are displayed and act differently

They look the similar when they are expanded

“Array[]”

“Array() [ Li, Li, …]”

The first instance skips foreach functions as if the elements inside do not exist and I see it when I run this.

getMessagesFromDB(channelId, 1, 60).then((messages) => {
    savedMessages[channelId] = messages;
    console.log(savedMessages);               //This is what produces the Array[] result
    
    console.log(savedMessages[channelId]);
    savedMessages[channelId].forEach((message)=>{       //This is completely skipped    
            messageContainer.append(message);
    });
    resolve();
})

This started appearing when I switched a section of the code producing the elements in getMessagesFromDM to include a promise as another function has to gather extra information from the database.
Please could anybody explain what this might be and how it could be fixed.

Also appologies if I haven’t explained my issue very well. I’m pretty new to JS.

Has been blocked by CORS, Redirect is not allowed for a preflight request

Thanks a lot to help me !

I try to make a connected light with a raspberry pi 0 W and a Pimoroni mood light.
the goal is to control the light (color and brightness) from a website on a web server who is not my raspberry pi.

To make this, I use :

  1. a flask web server to recieve all the requests to change the color,

  2. the unicorn package for the LEDs

  3. a web server with a web page who you can control the color (just a html page)

  4. a javascript script who fetch the raspberry pi

  5. a raspberry pi tunnel to access securely my raspberry pi from the internet

and when i use my website, the website says :

Access to fetch at 'https://link.to.my.raspberry.com/color' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

this is my flask web server :

from flask import Flask, jsonify, render_template, request, url_for, redirect
import unicornhat as unicorn
unicorn.set_layout(unicorn.AUTO)
unicorn.rotation(0)
unicorn.brightness(0.4)
width,height=unicorn.get_shape()
app = Flask(__name__)   # Flask constructor

@app.route('/')
def home():
    return render_template("home.html");

@app.route("/color", methods = ["POST"])
def setColors():
    print(request.form)
    red = request.form["red"]
    green = request.form["green"]
    blue = request.form["blue"]
    brightness = request.form["brightness"]
    print(red)
    print(green)
    print(blue)
    unicorn.set_all(int(red), int(green), int(blue))
    unicorn.brightness(float(brightness))
    unicorn.show()
    return ('', 204)

if __name__=='__main__':
    app.debug = True
    app.run()
    app.run(debug = True)

this is my local website (home.html):

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h1>Hello !</h1>
        <form action = "/color" method = "POST"> 
            <p><h3>Enter LEDs color</h3></p> 
            <p><input type="range" id="red" name="red" min="0" max="255" step="1" style="width: 200px;"></p>
            <p><input type="range" id="green" name="green" min="0" max="255" step="1" style="width: 200px;"></p>
            <p><input type="range" id="blue" name="blue" min="0" max="255" step="1" style="width: 200px;"></p>
            <p><input type="range" id="brightness" name="brightness" min="0" max="1" step="0.1"></p>
         </form>
    </body>
    <script src="./index.js"></script>
</html>

and here is the javascript file :

let pitunnel = "https://my.link.to.my.raspberry.com"
        document.addEventListener("mouseup", async function apiFetch(params) {
            let red = await document.getElementById("red").value;
            let green = await document.getElementById("green").value;
            let blue = await document.getElementById("blue").value;
            let brightness =  await document.getElementById("brightness").value;
            const response = await fetch(pitunnel + "/color", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({red : red, green : green, blue : blue, brightness : brightness})
            });
        })

It should be noted that I’ve tried to use this file home.html and it worked, bit i want a instant update, not a button to click :

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h1>Bonjour !</h1>
        <form action = "https://my.link.to.my.raspberry/color" method = "POST"> 
            <p><h3>Enter LEDs color</h3></p> 
            <p><input type="range" name="red" min="0" max="255" step="1" style="width: 200px;"></p>
            <p><input type="range" name="green" min="0" max="255" step="1" style="width: 200px;"></p>
            <p><input type="range" name="blue" min="0" max="255" step="1" style="width: 200px;"></p>
            <p><input type="range" name="brightness" min="0" max="1" step="0.1"></p>
            <p><input type = 'submit' value = 'mettre'/></p> 
         </form> 
    </body>
</html>

Thank you a lot to help me !

have a nice day.

move row to another sheet based on cell value google sheets – issue with code

I have hit the wall and can’t pass it.

I have been using a code to move and compare data in the spreadsheet.

After testing i tried to move code to spreadsheet where i want this code work but am having a problem.

I have tried to remove a trigger for script on test sheet and there i started to having issues as well. Any ideas why that might be?. Code was working fine for a about week.

function Move_new_Data(e) {
  var ss = SpreadsheetApp.getActive();
  var sh = ss.getSheetByName("Form responses 5")
  var tin = ss.getSheetByName("IN")
  var tout = ss.getSheetByName("OUT")
  var trsh = ss.getSheetByName("TRUE( Archive )")
  var mas = ss.getSheetByName("FR Check LIST")

  var vls = e.values;

  

  if (vls[2] == "IN"){
    
    
    var dt = tout.getDataRange().getValues();
    var dt2 = mas.getDataRange().getValues();
    var st = false;
    var st2 = false;
    for (var i =0;i<dt.length;i++){
      if(dt[i][2] == vls[1] && dt[i][3] == vls[3]){
        trsh.appendRow([null,vls[1],vls[3],vls[3],dt[i][0],vls[0],"TRUE"])
        tout.deleteRow(i+1)
        st = true;

        for (var j =0;j<dt2.length;j++){
          if(dt2[j][1] == vls[1]){
            mas.deleteRow(j+1);
            break;
          }
        }
        break;
      }

      else if(dt[i][2] == vls[1]){
        for (var j =0;j<dt2.length;j++){
          if(dt2[j][1] == vls[1]){
            mas.getRange(j+1,4).setValue(vls[3])
            //mas.getRange(4,j+1).setValue(vls[3])
            st2 = true;
            break;
            
          }
        }
      }
    }

    

    if (st == false){
      tin.appendRow([vls[0],vls[2],vls[1],vls[3]])
      
      if(st2 == false){
        var n = mas.getRange("B2:B").getValues().filter(String).length+2;
        mas.getRange(n,1,1,4).setValues([[null,vls[1],null,vls[3]]])
      }
      
    }

    sh.deleteRow(sh.getLastRow())
  }

   else if (vls[2] == "OUT"){
    
    
    var dt = tin.getDataRange().getValues();
    var dt2 = mas.getDataRange().getValues();
    var st = false;
    var st2 = false;
    for (var i =0;i<dt.length;i++){
      if(dt[i][2] == vls[1] && dt[i][3] == vls[3]){
        trsh.appendRow([null,vls[1],vls[3],vls[3],dt[i][0],vls[0],"TRUE"])
        tin.deleteRow(i+1)
        st = true;

        for (var j =0;j<dt2.length;j++){
          if(dt2[j][1] == vls[1]){
            mas.deleteRow(j+1);
            break;
          }
        }
        break;
      }

      else if(dt[i][2] == vls[1]){
        for (var j =0;j<dt2.length;j++){
          if(dt2[j][1] == vls[1]){
            mas.getRange(j+1,3).setValue(vls[3])
            //mas.getRange(4,j+1).setValue(vls[3])
            st2 = true;
            break;
            
          }
        }
      }
    }

    

    if (st == false){
      tout.appendRow([vls[0],vls[2],vls[1],vls[3]])
      
      if (st2 == false){
        var n = mas.getRange("B2:B").getValues().filter(String).length+2;
        mas.getRange(n,1,1,4).setValues([[null,vls[1],vls[3],null]])
      }
      
    }

    sh.deleteRow(sh.getLastRow())
  }
 
}

Scripts is being trigger when google form is submitted

Here how trigger is set: Trigger

Any ideas.

Looking at Executions history all have been completed with no issue. Not sure why is not working anymore.

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request:The browser (or proxy) sent a request that this server could not understand. KeyError: ‘video’

I’m trying to pass a live video stream from JS to python for face recognition using a HTTP request and I get the error
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'video'

After checking my terminal for the logs of the app I see the data type of the stream coming in as Bytes and I believe I need to convert it to a numpy array before passing it to a python script.

My current implementation is as follows
I have my JS code on a html template that opens a POST request to my python file which now processes the live video stream to get the frames with faces in them.

Here’s the HTML with the JS

`<button id="startBtn" onclick="openCam()">Open Webcam</button>
<br>
<!-- close button -->
<button id="closeButton" onclick="closeCam()">Close</button>
<br>
<!--video element to show the live video-->
<video id="video" autoplay></video>
<!-- javascript video stream -->
<script>
    const video = document.getElementById('video');
    const closeButton = document.getElementById('closeButton');

    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    
    let intervalID;

    function openCam(){
        navigator.mediaDevices.getUserMedia({ video: true })
        .then((stream) => {
            video.srcObject = stream;
            intervalID = setInterval(() => {
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            const dataURL = canvas.toDataURL('image/jpeg');
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/markin');
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(`video=${encodeURIComponent(dataURL)}`);
            }, 1000 / 30);
        })
        .catch((error) => {
            console.error(error);
        });
    }

    // Close the live stream by removing the interval counter
    function closeCam(){
        // const stopButton = document.getElementById('stopButton');
        closeButton.addEventListener('click', () => {
        clearInterval(intervalID);
        video.srcObject.getTracks()[0].stop();
        window.location.href = "{{ url_for('markin') }}";    
    });
    }
</script>`

Here’s the python end of the code

# get the video stream from the data request data = request.form['video'] dataURL = request.form.get('video',False) if dataURL is not null: print("DATA IS NOT EMPTY!!!") # print(dataURL) print(type(data)) print(data) else: print("DATA IS EMPTY!!!") # Decode Base64-encoded video stream data decoded_data = base64.b64decode(dataURL.split(',')[1]) img = decoded_data if img is not null: print("IMAGE IS NOT EMPTY!!!") print(type(img)) print(img)

I’ve tried applying the other options for live video streaming such as WebRTC and it’s quite an uphill journey trying to configure it to my app and would appreciate a more straight forward example on how to do so if you provide it as a solution to this question.