How can I optimize the load speed of an embedded survey with multiple API calls and server-side validations?

I’m working on a system where a survey is embedded into third-party customer websites. We embed the survey as HTML .The survey is triggered based on user interactions such as clicks or scroll events. Currently, the loading time is around 4-5 seconds, which is longer than the desired 1-2 seconds. One of the key factors causing the delay is that we need to make 2-3 API calls to perform server-side validations before rendering the survey. Despite keeping the bundle size small, these API calls are necessary for the functionality and are leading to the slower load time.

I’ve taken several steps to reduce the load time, including:

  • Minimizing the JavaScript bundle size
  • Implementing lazy loading for certain assets
  • Optimizing client-side rendering

However, these changes haven’t been enough to meet the desired performance. The expectation is for the survey to load within 1-2 seconds, but I am still seeing 4-5 seconds due to the API call delays. I’m looking for strategies to reduce the loading time without compromising the server-side validations.

Why do async spawn blocks event loop in NodeJS?

The following code when ran I notice 1-2 seconds event loop block with execSH which use spawn async version. According to NodeJS docs, spawn shouldn’t block event loop unless spawnSync used.

// From https://github.com/tsertkov/exec-sh/blob/master/lib/exec-sh.js
const execSH = require("exec-sh").promise;
const blocked = require('blocked-at')

blocked((time, stack) => {
    console.log(`Event Blocked for ${time}ms, operation started here:`, stack)
  })

async function c(eName, port) {
    await execSH(`avdmanager create avd --name ${eName} --package "system-images;android-34;google_apis;arm64-v8a"`, true);
}

await Promise.all([c("test1", 5412), c("test2", 5413)]);

What cause the blocking?

jQuery script for Next> button executes only once

So I have a page, that has

search results…
next >

The next button code is below.

<a href="?re=browse,nearby,mainmenu#page2" id="__page_next" class="nav-next">
  <span>Next</span>
  <span class="ifc ico-nav-right"></span>
</a>

It has a “Next” text, and an “>” arrow.
I added this script, so that arrow gets replaced with spinner/loader, while results are loaded

$(function () {
  $( "#__page_next" ).on( "click", function() {
    $('#__page_next .ico-nav-right').removeClass('ico-nav-right').addClass('animate-spin ico-spin5');
  });
});

So the script works fine, but only on page 1

After “Next >” is clicked the page doesn’t refresh, it only replaces results and the button is also replaced.
Script remains there the whole time, the newly loaded button(s) have same ID’s and classes, but it doesn’t replace the arrow anymore.

It seems that jquery is executed only once, doesnt continuously watch for next button being clicked but rather first time its clicked script is done.
If thats the case, how do I make the script continiously active insted of executing just once?

My appologies if question is stupid, I am not very good in javascript.

The script works only on page 1
I would like the script to continue to be active on page 2, 3, 4…

how to add methods to javascript class with super keyword dynamically

class bcomp {
 some(){
    console.log("bcomp");
 }
}
class acomp extends bcomp {
 some(){
    super.some();
    console.log("acomp");
 }
}
var ins = new acomp();
ins.some()

so output will be
“bcomp
acomp”

i need to override some method of acomp with super keyword

acomp.prototype.some = function (params) {
    super.some();
    console.log("new acomp");
}

SyntaxError: ‘super’ keyword unexpected here
how to achieve the above ?

Uncaught ReferenceError: iziToast is not defined

{{define "scripts"}}

<script src="/admin/assets/js/iziToast.min.js"></script> 
<script> iziToast.show({ title: 'Hey', message: 'What would you like to add?' }); </script>

{{end}}

Although I define it as a script, I cannot get the message on the site when I run it.

I was expecting ‘What would you like to add?’ but I get ‘Uncaught ReferenceError: iziToast is not defined’ error in the console.

How to send variables data to a react app using electron

HI I’m trying to repurpose a old app that I found interesting and I also want to migrate from a web based react application to an electron GUI and still use react

At first the app used express to emit the data and the data was received on the web app with io.on but ive switched to electron I’m using a preload and renderer file

old way to transmit data
server.js

// Server part
var app = express();

app.use('/', express.static(path.join(__dirname, 'public')));
var port = 8090
var server = app.listen(port);
console.log('Server listening on port ' + port);

// Socket.IO part
var io = require('socket.io')(server);

io.on('connection', function (socket) {
    console.log('New client connected!');

    //send data to client
    setInterval(function () {

        // Change values so you can see it go up when developing
        if (process.env.NODE_ENV === "development") {
            //do something with the data
        }
        socket.emit('ecuData', { send the data });
    }, 100);
});

dash.jsx

componentDidMount: function () {
    this.socket = io();
    this.socket.on('ecuData', function (data) {
        this.setState({ rpm: data.rpm });
        this.setState({ coolantTemp: data.coolantTemp });
        this.setState({ fuelLevel: data.fuelLevel })
        this.setState({ odo: data.odo })
        this.setState({ drive: data.drive })
        this.setState({ amp: data.amp })
        this.setState({ dte: data.dte })
    });
},

new way to transmit data
render.js first when the window finishes loading a setIntervale sends request every 100ms

document.addEventListener('DOMContentLoaded', () => {
    setInterval(async () => {    
        const data = await electronAPI.getDashData();
    }, 100);
})

preload.js relay the request to the main process

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
    getDashData: (data) => ipcRenderer.invoke('getData', data)
})

gui.js (main process) receive the request and send back an object containing all the updated data

const createWindows = (win, page) => {
    win = new BrowserWindow({
        width: 1024,
        height: 600,
        resizable: false,
        fullscreen: true,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
        },
    });
    if(page == "dash.html"){
        ipcMain.handle('getData', (req, data) => {
            var dashData = {
                rpm: rpm,
                carSpeed: carSpeed,
                coolantTemp: coolantTemp,
                fuelLevel: fuelLevel,
                odo: odo,
                drive: drive,
                amp: amp,
                dte: dte,
                onoffLights: onoffLights
            }
            return (dashData);
        })
    }
    win.loadFile(page)
};

function updateData() {
    // Change values so you can see it go up when developing
    if (process.env.NODE_ENV === "development") {
        setInterval(() => {
            //do something with the data
        }, 100)
    }
}
app.whenReady().then(() => {
    createWindows(leftWindow, "dash.html");
    //createWindows(rightWindow, "controls.html");
    updateData()
});

when the data is sent back to the render.js i can add alert(data.rpm) and it displays the updated rpm but I dont know how to actually send the data directly to the dash.jsx to upadte my gui i can only go to the consoleand look at the data

Service Worker isn’t called for video sources in Firefox

I have a rather quirky Firefox behavior, I can’t explain. Imagine those two very simple HTML tags:

<img src="http://localhost:1234/api/getBlob/1">...
<video src="http://localhost:1234/api/getBlob/2">...

I wrote a service worker that adds the JWT to the Authorization Header as my backend isn’t public.

self.addEventListener('fetch', function (event) {
  const url = event.request.url.toLowerCase();
  if (!url.includes('api/getblob')) {
    return;
  }

  if (event.request.headers.has('Authorization')) {
    return;
  }

  event.respondWith(
    (async function () {
      const token = await requestTokenFromMainThread();
      const headers = new Headers(event.request.headers);
      headers.set('Authorization', 'Bearer ' + token);
      const modifiedRequestInit = {
        headers: headers,
        mode: 'cors',
        credentials: 'omit',
      };

      const modifiedRequest = new Request(event.request, modifiedRequestInit);

      try {
        return fetch(modifiedRequest);
      } catch (error) {
        console.error('Error fetching resource:', error);
        return new Response('Error fetching resource', { status: 500 });
      }
    })(),
  );
});

function requestTokenFromMainThread() {
  return new Promise((resolve) => {
    const channel = new MessageChannel();
    channel.port1.onmessage = (event) => {
      resolve(event.data);
    };
    self.clients.matchAll().then((clients) => {
      if (clients && clients.length) {
        clients[0].postMessage('requestToken', [channel.port2]);
      }
    });
  });
}

This works great with Safari and Chromium-based browsers (like Edge or Chrome itself). But it starts to get quirky with Firefox. While <img src is handled by the service worker, <video src isn’t and I never ever land inside the fetch function. So I put a debug point at const url = event.request.url.toLowerCase(); this will never be hit with a <video src but will be hit with <img src, and I am not sure why.

EDIT 1:
In Firefox, if I go to the request in question and click “Use as fetch in console” – then, as almost expected, it works like a charm.

Most resource efficient way to create a beach umbrella in Three.js

I’m new to Three.js, I find it great because with very low effort I’ve been able to create a simple scene.
I’m working on a beach scene and I’d like to add 10 thousands of beach umbrella to the scene. I’ve been able to do so easily using cones to represent canopy and cylinders for poles. Now to make the scene more realistic, I’d like to make the canopy of my umbrella with stripes, as you see in very common beach umbrellas.
I understand there are multiple ways I can do that:

  • Using a texture
  • changing material for each face
  • creating each slide as a separate mesh

Since each of these options require some work, I’d like to understand which one is the best to keep the scene lightweight considering I’m planning to add around 10 thousands of umbrellas to my scene.

Thanks for your help

Chrome starts showing some code of the website when I reopen a closed tab

When I open this website, it opens perfectly
Screenshot of website

When I reopen a closed tab using cmd+shift+t , chrome browser starts showing some code.
Screenshot of website error

When I reload this site using cmd+r, it works fine again.

We are using Next.js

One of the points I believe is leading to this issue is Cache. But when I disable the cache in network tag and perform the same activity, it remains the same.

I have spent a lot of time on this issue understanding how chrome handles cache. There exists two types of memories, disk and memory that chrome uses.

It is possible that the error is related to something else and not cache.

Node.js – Hosting to Digital Ocean web App [closed]

I have the problem local the app work correctly

but when i try to host it says not found – Error: ENOENT: no such file or directory, stat ‘/workspace/project-root/public/index.html’

here it is how i organize

can someone explain how to fix it ?

i try every solution from chat gpt also hahah

How do I remove old routes that are rendered on map using DirectionsRenderer?

When route is displayed for one mode of transport and i select another mode of transport, the old route stays and i end up with 2 routes displayed.

import './App.css';
import React, { useState, useEffect } from 'react';
import SearchBar from './components/SearchBar';
import {
  APIProvider,
  Map,
  useMapsLibrary,
  useMap,
} from "@vis.gl/react-google-maps";

const App = () => {
  const [mapVisible, setMapVisible] = useState(false);
  const [destinationPlaceID, setDestinationPlaceID] = useState(null);
  const [originPlaceID, setOriginPlaceID] = useState(null);
  const [modeOfTravel, setModeOfTravel] = useState('DRIVING');
  const position = { lat: 1.3397443, lng: 103.7067297 };
  
  // Function to start routing with the selected destination
  const startRouting = (placeID) => {
    setDestinationPlaceID(placeID);
    setMapVisible(true); // Show the map when routing starts
  };

  // Function to get Place ID from user's coordinates (Returns a Promise)
  const getPlaceIdFromCoordinates = (latitude, longitude) => {
    return new Promise((resolve, reject) => {
      const geocoder = new google.maps.Geocoder();
      geocoder.geocode(
        { location: { lat: latitude, lng: longitude } },
        (results, status) => {
          if (status === google.maps.GeocoderStatus.OK) {
            if (results[0]) {
              const placeId = results[0].place_id;
              resolve(placeId); // Resolve with Place ID
            } else {
              reject('No results found');
            }
          } else {
            reject('Geocoder failed: ' + status);
          }
        }
      );
    });
  };

  function Directions() {
    const map = useMap();
    const routesLibrary = useMapsLibrary('routes');
    const [directionsService, setDirectionsService] = useState(null);
    const [directionsRenderer, setDirectionsRenderer] = useState(null);
    const [routes, setRoutes] = useState([]);
    const [routeIndex, setRouteIndex] = useState(0);
    const selected = routes[routeIndex];
    const leg = selected?.legs[0];

    useEffect(() => {
      console.log("Map Loaded with Zoom:", map.getZoom()); // This will log the initial zoom level
    }, [map]);
    

    useEffect(() => {
      if (!routesLibrary || !map) return;
      setDirectionsService(new routesLibrary.DirectionsService());
      setDirectionsRenderer(new routesLibrary.DirectionsRenderer({ map }));
    }, [routesLibrary, map]);

    // Fetch directions once `originPlaceID` is set
    useEffect(() => {
      if (!directionsService || !directionsRenderer || !originPlaceID) return;

      (async () => {
        try {
          
          const response = await directionsService.route({
            origin: { placeId: originPlaceID },
            destination: { placeId: destinationPlaceID },
            travelMode: google.maps.TravelMode[modeOfTravel],
            provideRouteAlternatives: true,
          });
          directionsRenderer.setDirections(response);
          setRoutes(response.routes);
          setRouteIndex(0);
        } catch (error) {
          console.error('Error fetching directions:', error);
        }
      })();
    }, [directionsService, directionsRenderer, destinationPlaceID, originPlaceID, modeOfTravel]);

    useEffect(() => {
      if (!directionsRenderer) return;
      directionsRenderer.setRouteIndex(routeIndex);
    }, [routeIndex, directionsRenderer]);

    if (!leg) return null;

    return (
      <div className="directions">
        <h2 className="mapTitle">{selected.summary}</h2>
        <p>{leg.start_address.split(',')[0]} to {leg.end_address.split(',')[0]}</p>
        <p>Distance: {leg.distance?.text}</p>
        <p>Duration: {leg.duration?.text}</p>

        <br></br>
        <h2 className="mapTitle">Other Routes</h2>
        <ul class="otherRoute">
          {routes.map((route, index) => (
            <li key={route.summary}>
              <button id="listText" onClick={() => setRouteIndex(index)}>{route.summary}</button>
            </li>
          ))}
        </ul>
      </div>
    );
  }

  // Geolocation effect to get the origin Place ID
  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(async (position) => {
        const { latitude, longitude } = position.coords;
        try {
          const placeId = await getPlaceIdFromCoordinates(latitude, longitude);
          setOriginPlaceID(placeId); // Set the origin Place ID
        } catch (error) {
          console.error('Geocoding error:', error);
        }
      }, () => {
        alert('Geolocation is not supported by this browser.');
      });
    } else {
      alert('Geolocation is not supported by this browser.');
    }
  }, []);

  return (
    <div>
      <h1>Find and Route</h1>
      <SearchBar startRouting={startRouting} />

      <label htmlFor="modeOfTravel">Select Mode of Travel:</label>
      <select
        id="modeOfTravel"
        value={modeOfTravel}
        onChange={(e) => setModeOfTravel(e.target.value)}
      >
        <option value="DRIVING">Driving</option>
        <option value="WALKING">Walking</option>
        <option value="BICYCLING">Bicycling</option>
        <option value="TRANSIT">Transit</option>
      </select>

      {mapVisible && (
        <div style={{ height: "100vh", width: "100%" }} id="map">
        <APIProvider apiKey={import.meta.env.VITE_GOOGLE_API_KEY}>
          <Map
            defaultCenter={position}
            defaultZoom={15}
            options={{
              zoomControl: true,
              gestureHandling: "auto",
              scrollwheel: true,
              mapTypeControl:true,
              scaleControl:false,
              streetViewControl:false,
              overviewMapControl:false,
              rotateControl:false, 
            }}
          >
            {destinationPlaceID && <Directions />}
          </Map>
        </APIProvider>
      </div>
      
      )}
    </div>
  );
};

export default App;

I have seen lots of solutions suggesting to initialise directionsRenderer as a global variable and using setMap(null) however I cant find a successful way to do it in my code without getting lots of errors.

I also tried setting the route array to an empty array.

The routes for the other transport modes is queried successfully and displays properly but i just cant get rid of the old routes.

How to install jsdom for all Node.js projects in Eclipse?

I’m currently using Eclipse 2020-06 with Node.js 14 and created a “General” project with a single .js file to test some Javascript code. I opened a command prompt and ran npm install [email protected] to install jsdom but this code:

const jsdom = require("jsdom");

… caused the following error when I ran the .js file:

Error: Cannot find module ‘jsdom’

I cd-ed to the project folder and ran the install command again, now the code runs without any errors.

How do I install this specific version of jsdom in a way that all current and future Eclipse projects are going to find it too, without having to install it (= run the command) for every single project? There’s no option to access the build path for this project (“no actions available”) and so far I haven’t been able to find any information about how to link to it with an environment variable or if there’s a global setting for it in Eclipse.

Why can’t I get the websocket message

I’m trying to make a component to render an order. I’m using MVVN architecture on React. The connection with backend is based on websocket connections. When I test the backend webscoket connection I am able to get the response. But on my frontend side, I only see the message sent, but no answer back. I think that the way that I am handling the useEffect is wrong. But I’m no sure where.

This is the frontend code:

import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import useWebSocket, { ReadyState } from 'react-use-websocket'

import { UseCase } from '@/domain/model/types'
import { Epc, Order } from '@/domain/model/OrderTagging'
import { PrinterPoint, Terminal } from '@/domain/model/PrinterPoint'

import { ROUTES } from '@/utils/common/constant'
import { toaster } from '@/utils/common/toaster'
import { StorageKeys } from '@/utils/common/constant/storage'

import useStoreDataInLocalStorage from '@/hooks/useStoreDataInLocalStorage'

import { closeCodeMessages, WebSocketCloseCode } from './webSocketCloseCodes'

import { FormDataSchema } from '@/presenter/components/OrderForm/view-models/types'

type Dependencies = {
  readonly getOrderUseCase: UseCase<Order>
}

export type UseOrderViewModelResponse = {
  order: Order | null
  queue: Epc[] | null
  isLoading: boolean
  sendMessageOnSubmit: (formData: FormDataSchema) => void
}

export const useOrderViewModel = ({ getOrderUseCase }: Dependencies): UseOrderViewModelResponse => {
  const [order, setOrder] = useState<Order | null>(null)
  const [queue] = useState<Epc[] | null>(null)
  const [socketUrl, setSocketUrl] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const navigate = useNavigate()

  const { value: locality } = useStoreDataInLocalStorage<PrinterPoint>(StorageKeys.User.Locality)
  const { value: terminal } = useStoreDataInLocalStorage<Terminal>(StorageKeys.User.Terminal)

  const { sendJsonMessage, lastJsonMessage, readyState } = useWebSocket(socketUrl, {
    onOpen: () => {
      // eslint-disable-next-line no-console
      console.log('Open connection')
    },
    onMessage: (evt) => {
      // eslint-disable-next-line no-console
      console.log('Message received:', evt.data)
    },
    onClose: () => {
      // eslint-disable-next-line no-console
      console.log('Close connection')
    },
    onError: () => {
      // eslint-disable-next-line no-console
      console.log('Close onError')
    },
    shouldReconnect: (evt) => {
      try {
        const { message, isError } = handleWebSocketCloseCode(evt.code as WebSocketCloseCode)
        toaster('error', message)
        return isError
      } catch (e) {
        // eslint-disable-next-line no-console
        console.log(e)
        return false
      }
    },
    reconnectInterval: 1500,
    reconnectAttempts: 3
  })

  function handleWebSocketCloseCode(code: WebSocketCloseCode) {
    const message = closeCodeMessages[code] || `Código de fechamento desconhecido: ${code}`
    const isError = code !== 1000

    return { message, isError }
  }

  const sendMessageOnSubmit = (formData: FormDataSchema) => {
    sendJsonMessage({
      action: 'start_print',
      data: {
        storeNumber: order?.storeNumber,
        ean: formData.product,
        quantity: formData.quantity,
        expiryDate: formData.expiryDate,
        productSession: formData.product
      }
    })
  }

  const getOrderData = useCallback(async () => {
    try {
      setIsLoading(true)
      sendJsonMessage({
        action: 'open_order',
        data: {
          boxBarcode: '00002919802331',
          bureauIdentifier: 'cd_x',
          storeNumber: '21955',
          owner: 'user1',
          terminalIdentifier: 'Bancada 01'
        }
      })
    } catch (error) {
      toaster('error', 'Erro ao carregar os dados do pedido. Por favor, tente novamente.')
      navigate(`/${ROUTES.TABS}`)
    } finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => {
    const controller = new AbortController()

    if (locality?.identifier && terminal?.name) {
      setSocketUrl(`${import.meta.env.VITE_SOCKET_CONNECT}/${locality.identifier}/${terminal.name}`)
    }

    ;(async () => await getOrderData())()

    return () => {
      controller.abort()
    }
  }, [])

  return { order, queue, isLoading, sendMessageOnSubmit }
}

This is the console view:
enter image description here

org.apache.kafka.common.network.InvalidReceiveException: Invalid receive (size = 1195725856 larger than 104857600)

Steps I have followed-

  1. Installed docker
  2. Installed Zookeeper
    using cmd docker run -d --name zookeeper -p 2181:2181 zookeeper:3.5
  3. Started Kafka
    using cmd docker run -d --name kafka -p 9092:9092 -e KAFKA_ZOOKEEPER_CONNECT=<ip_addr>:2181 -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://<ip_addr>:9092 -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 confluentinc/cp-kafka

getting this error
enter image description here

I’m using **kafkajs **on my server to connect and produce messages.
I want to run kafka locally and publish to a topic which will be subcribed on another server

Project 3D coordinates on 2D plane [closed]

I need to project 3D coordinates (the player’s position X Y Z (see red axis and red points)) on the 2D X’ and Y’ axis in order to represent, on the 2D image, the player’s location based on his 3D position.

I already try multiple solutions (based on sin/cos), but i can’t figure out how to project it correctly.
And I think I need an offset and scale to adjust the projection properly but i don’t know how to determine it.

When working on this projection:

  • does Y axis is 40° or 140° ?
  • does X axis is -30° or 150° ?

Additional detail: the arrow indicate the increase direction and the angle relative to horizontal

Image caption:

  • red axis: 3D coordinates (player position in game)

  • red points 1,2,3,4: are real 3D coordinates in game

  • green axis: 2D coordinates (player position on the image)

  • green coordinates: correspond to the image position (in 2D ref) of the corresponding red point (3D)

PS: code response (JS, lua, PHP) is preferable over math notation

Thank’s

Tony Hawk's pro skater Hall map view