Why won’t drag event trigger on first attempt?

I have a javascript application in which I’m trying to handle a drag event but it requires two attempts to drag:

enter image description here

I want the user to be able to drag the handle on the track position bar so that they can skip ahead or go back anywhere in the track. But for some reason, the user has to attempt it twice. The first time they attempt to drag, the handle doesn’t move (and the drag handler doesn’t fire). On the second attempt it does.

Here is the code:

<div class="track-position-container">
    <div class="position-bar">
        <div class="completed-bar"></div>
        <div class="position-nob" ondrag="positionNobDragged(event)" ondragend="positionNobDragEnded(event)"></div>
    </div>
</div>
function positionNobDragged(event) {
    const positionBar = document.querySelector('.position-bar');
    const positionNob = document.querySelector('.position-nob');
    const completedBar = document.querySelector('.completed-bar');

    const x = event.x - positionBar.offsetLeft;

    positionNob.style.left = x;
    completedBar.style.width = completedBar.style.left + x;
}

function positionNobDragEnded(event) {
    positionNobDragged(event);
}

You can go here to try it: http://planetshah.com/mixes/mix.html?mix=65

Does anyone know why the drag handler won’t respond on the first attempt to drag the handle?

remove blue background from markers

how to remove the blue background from the markers?
this happen using default icon and a custom one (png with transparent background)

am I doing something wrong?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@1/css/pico.min.css">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <title>Map with OpenStreetMap</title>
    <style>
        #map {
            height: 400px;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <script>
        var map = L.map('map').setView([45.418393, 10.969487], 13); // Replace with your default map center

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);

        var marker = L.marker([45.410051797705904, 10.90330758434609]).addTo(map);

    </script>
</body>
</html>

enter image description here

tried with a custom icon but still got the same problem

var LogoPin = L.icon({
    backgroundColor: 'transparent',
    iconUrl: './pin.png',
    shadowUrl: './shad.png',
    iconSize:     [30, 47], // size of the icon [38,95]
    shadowSize:   [50, 64], // size of the shadow*/
    iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
    shadowAnchor: [4, 62],  // the same for the shadow*/
    popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
    
});

L.marker([place.lat, place.lng], {icon: LogoPin}).addTo(map);

Drawing SVG line upon div entry

I have a div element with a nested SVG div where I’m trying to animate the svg. I’ve done this before with scrolling from the top of the page, but this seems to be animating earlier than expected or not at all. I have debug statements in the code as well.

I want it to start drawing the SVG only once the user has scrolled into the team-svg-line div. When that div appears at the bottom of the viewport there should be a slight delay and then the line should draw, but something is happening where it looks like it should and I just don’t see it happening.

  let svgPathDrawn = false;
function drawSVGPath() {
  if (!svgPathDrawn) {
    console.log("Drawing the SVG path...");

    var path = document.querySelector("#teamPath");
    var pathLength = path.getTotalLength();

    // Set initial styles for the SVG path
    path.style.strokeDasharray = pathLength + " " + pathLength;
    path.style.strokeDashoffset = pathLength;

    // Animate the SVG path
    path.style.transition = "stroke-dashoffset 4s ease"; // Adjust the duration (2s) and easing (ease) as needed
    path.style.strokeDashoffset = 0;
    path.style.strokeDasharray = "none"; // Reset stroke dash array after animation completes

    svgPathDrawn = true; // Set the flag to true after drawing the SVG path
  }
}


  // Define the scroll event handler
  // Define the scroll event handler
// Define the scroll event handler
function scrollHandler() {
  var elementTarget = document.getElementById("team-svg-line");
  var elementTop = elementTarget.getBoundingClientRect().top - 100; // Adjust the offset as needed
  var elementHeight = elementTarget.offsetHeight;
  var scrollPosition = window.scrollY;
  var windowHeight = window.innerHeight;

  // Calculate if the target div is in the viewport
  var isInViewport = (elementTop <= windowHeight && elementTop + elementHeight >= 0);

  if (isInViewport) {
    drawSVGPath();
    window.removeEventListener("scroll", scrollHandler); // Remove the scroll event listener after drawing the SVG path
  }
}

// Add the scroll event listener only if the SVG path hasn't been drawn yet
if (!svgPathDrawn) {
  window.addEventListener("scroll", scrollHandler);
}

  // Add the scroll event listener only if the SVG path hasn't been drawn yet
  if (!svgPathDrawn) {
    window.addEventListener("scroll", scrollHandler);
  }
<div style="height: 110vh;">

</div>
<div id="team-svg-line">


<svg
          id="Layer_1"
          data-name="Layer 1"
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 693.08 2238.36"
        >
          <defs>
            <style>
              .teamclssss1 {
                fill: none;
                stroke: rgb(55, 157, 80);
                stroke-miterlimit: 10;
                stroke-width: 50px;
              }
            </style>
          </defs>
          <polyline
            id="teamPath"
            class="teamclssss1"
            points="342.83 1.82 344.13 19.65 347.34 37.48 345.89 55.3 343.33 73.13 343.85 90.96 345.03 108.79 347.09 126.62 344.45 144.44 346.41 162.27 343.96 180.1 343.2 197.93 345.92 215.76 345.9 233.59 343.27 251.42 344.04 269.25 344.72 287.07 342.87 304.9 345.91 322.73 346.47 340.56 343.31 358.39 342.84 376.22 346.05 394.05 347.09 411.88 344.31 429.72 344.18 447.55 345.36 465.39 346.38 483.23 349.02 501.39 356.64 517.96 365.48 534.55 382.07 543.39 398.47 551.62 416.8 555.01 434.47 553.01 452.14 555.47 469.81 555.28 487.48 554.78 505.15 557.22 522.82 553.21 540.49 556.4 558.17 553.08 575.84 554.72 593.52 555.81 612.38 556.55 629.48 564.64 643.34 577.11 654.07 591.98 664.41 607.94 664.85 626.93 667.68 644.21 664.2 661.5 665.75 678.79 665.8 696.09 663.49 713.38 664.57 732.42 655.48 749.15 643.69 763.55 629.93 776.44 611.8 781.61 593.52 783.13 575.22 786.3 556.93 786.81 538.63 782.92 520.33 785.01 502.04 787.05 483.74 784.69 465.44 786.81 447.14 787.1 428.85 786.72 410.55 787.47 392.25 784.29 373.95 786.59 355.65 783.57 337.35 786.04 319.06 785.03 300.76 783.54 282.46 783.19 264.16 786.56 245.86 784.34 227.56 784.26 209.26 782.96 190.96 783.35 172.66 787.45 154.36 785.96 136.06 783.88 117.75 784.03 99.44 786.87 80.85 787.7 63.01 793.98 49.09 806.73 35.65 820.25 30.65 838.65 29.43 857.08 27.11 874.39 26.95 891.71 25.24 909.02 28.55 926.33 27.89 943.65 27.72 960.96 26.32 978.28 29.84 995.6 30.23 1014.15 37.55 1031.34 48.64 1046.4 63.54 1057.79 80.56 1066.06 99.44 1068.51 117.74 1065.99 136.03 1066.93 154.33 1065.5 172.63 1069.57 190.92 1067.69 209.22 1065.98 227.52 1066.37 245.82 1069.58 264.12 1068.85 282.41 1066.61 300.71 1069.11 319.01 1069.69 337.31 1068.27 355.61 1069.21 373.91 1069.95 392.2 1068.24 410.5 1066.38 428.8 1065.83 447.1 1068.21 465.4 1067.81 483.7 1066.48 502 1068.88 520.3 1068.24 538.6 1068.14 556.91 1067.8 575.21 1068.07 593.52 1067.28 612.32 1069.13 629.3 1077.33 645.19 1087.63 657.66 1102.27 664.46 1120.3 664.54 1139.31 666.07 1157.02 667.74 1174.73 663.62 1192.44 664.23 1210.15 664.43 1227.86 663.14 1245.57 663.1 1263.29 663.75 1281.01 663.05 1269.06 661.36 1287.24 655.03 1304.57 643.3 1318.84 629.79 1331.89 611.73 1337.01 593.52 1342.99 575.22 1341.37 556.93 1340.28 538.63 1339.25 520.33 1339.98 502.04 1339.63 483.74 1341.2 465.44 1340.65 447.14 1339.87 428.85 1340.01 410.55 1342.64 392.25 1342.85 373.95 1339.37 355.65 1339.09 337.35 1341.39 319.06 1342.93 300.76 1339.27 282.46 1341.18 264.16 1339.37 245.86 1341.75 227.56 1343.29 209.26 1340.01 190.96 1339.28 172.66 1339.59 154.36 1340.43 136.06 1340.49 117.75 1341.34 99.44 1342.78 80.37 1341.59 64.61 1352.42 48.44 1361.76 36.69 1376.53 27.92 1393.6 27.81 1412.76 28.66 1430.08 28.39 1447.39 29.04 1464.7 30.08 1482.01 28.82 1499.33 26.9 1516.65 27.3 1533.97 29.25 1551.29 30.16 1569.85 38.69 1586.36 48.58 1602.15 63.94 1612.78 81.09 1619.79 99.44 1624.46 117.74 1622.41 136.03 1624.35 154.33 1622.35 172.63 1621.07 190.92 1622.43 209.22 1622.22 227.52 1621.34 245.82 1624.94 264.12 1621.38 282.41 1621.26 300.71 1623.57 319.01 1624.87 337.31 1622.66 355.61 1621.3 373.91 1624.89 392.2 1623.12 410.5 1624.83 428.8 1621.17 447.1 1623.41 465.4 1621.13 483.7 1624.28 502 1621.57 520.3 1622.05 538.6 1623.85 556.91 1625.18 575.21 1621.05 593.52 1625.61 612.67 1623.52 629.43 1632.79 644.87 1643.64 656.05 1658.89 664.25 1676.03 666.28 1694.99 664.26 1713.76 667.09 1732.53 667.51 1751.3 667.34 1770.08 667.78 1788.86 666.68 1807.64 665 1826.42 661.72 1844.69 655.85 1862.4 645.12 1878.02 628.63 1887.24 612.11 1895.79 593.52 1900.16 575.47 1896.99 557.41 1897.26 539.36 1899.4 521.3 1900.72 503.25 1898.66 485.19 1897.02 467.13 1899.93 449.08 1896.12 431.02 1897.31 412.96 1898.19 394.9 1899.14 376.83 1898.57 361.29 1901.24 352.82 1914.31 348.55 1928.17 345.58 1946.37 347.77 1964.57 345.12 1982.77 348.85 2000.97 346.85 2019.17 349.25 2037.36 345.49 2055.56 345.1 2073.76 346.27 2091.96 345.28 2110.16 347.12 2128.36 347.47 2146.56 346.2 2164.76 345.49 2182.97 346.36 2201.17 345.75 2219.38 346.31 2237.59"
          ></polyline>
        </svg>
</div>

Fiddle: https://jsfiddle.net/5unmbLzv/7/

How can I break the foor loop within the then block? [duplicate]

I’m new to Cypress and Javascript. I want to create a loop that executes a request with different values until I get a certain response.

let continue_loop = 1

loginLoop : for (let i = 1; i < 100; i++){
                cy.request({
                    // url: Cypress.env("web_api")+"/1.0/user/login",
                    url: Cypress.env("api").staging+"/1.0/user/login",
                    method: "POST",
                    failOnStatusCode: false,
                    body: {
                        email: "email"+i+"@email.com",
                        password: "Helloworld10"
                    } 
                }).then((response) => {                
                    if (response.status == 403) {
                        continue_loop = 2
                    }
                })

                if (continue_loop == 2){
                    break loginLoop;
                }
        }

It seems that continue_loop only gets the value 2 within the then block, because after it always returns to 1 so the loop never breaks. I also tried to use Cypress aliases but it’s the same result. How can I achieve this?

WebDriverError: Error forwarding the new session Error forwarding the request Operation timed out

I’m encountering the following error when trying to run my selenium testcase using selenium grid. It’s really just a modified selenium example from their docs.
ChromeDriver is 123.0.6312.58
Chrome is 123.0.6312.59 (Although I don’t know if selenium is using this chrome)

const {By, Builder, Browser, until} = require('selenium-webdriver');
const assert = require("assert");

const chrome = require('selenium-webdriver/chrome');

const chromeDriverPath = '/usr/local/bin/chromedriver';
const options = new chrome.Options();
options.addArguments("--remote-allow-origins=*");
options.setChromeBinaryPath(chromeDriverPath);

(async function firstTest() {
  let driver;
  
  try {
    driver = await new Builder().forBrowser(Browser.CHROME).setChromeOptions(options).usingServer('http://localhost:4444/wd/hub').build();

    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
    let title = await driver.getTitle();
    assert.equal("Web form", title);
  
    await driver.manage().setTimeouts({implicit: 500});
  
    let textBox = await driver.findElement(By.name('my-text'));
    let submitButton = await driver.findElement(By.css('button'));
  
    await textBox.sendKeys('Selenium');
    await submitButton.click();
  
    let message = await driver.findElement(By.id('message'));
    let value = await message.getText();
    assert.equal("Received!", value);
  } catch (e) {
    console.log(e)
  } finally {
    await driver.quit();
  }
}())

I’m using selenium-webdriver 3.6.0. I’m trying to run this with selenium grid. I ran the command java -jar selenium-server-standalone-3.6.0.jar -role hub to start the hub and java -Dwebdriver.chrome.driver=/usr/local/bin/chromedriver -jar selenium-server-standalone-3.6.0.jar -role node -hub http://localhost:4444 to start the node.

The hub and node started successfully and logged as follows:
hub:

19:26:01.508 INFO - Selenium build info: version: '3.6.0', revision: '6fbf3ec767'
19:26:01.508 INFO - Launching Selenium Grid hub
2024-03-27 19:26:01.924:INFO::main: Logging initialized @551ms to org.seleniumhq.jetty9.util.log.StdErrLog
19:26:01.929 INFO - Will listen on 4444
2024-03-27 19:26:01.958:INFO:osjs.Server:main: jetty-9.4.5.v20170502
2024-03-27 19:26:01.970:INFO:osjs.session:main: DefaultSessionIdManager workerName=node0
2024-03-27 19:26:01.970:INFO:osjs.session:main: No SessionScavenger set, using defaults
2024-03-27 19:26:01.971:INFO:osjs.session:main: Scavenging every 660000ms
2024-03-27 19:26:01.975:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@5e3f861{/,null,AVAILABLE}
2024-03-27 19:26:01.985:INFO:osjs.AbstractConnector:main: Started ServerConnector@4c5ae43b{HTTP/1.1,[http/1.1]}{0.0.0.0:4444}
2024-03-27 19:26:01.985:INFO:osjs.Server:main: Started @613ms
19:26:01.986 INFO - Nodes should register to http://10.32.40.97:4444/grid/register/
19:26:01.986 INFO - Selenium Grid hub is up and running
19:26:03.717 INFO - Registered a node http://10.32.40.97:5555
19:26:23.738 INFO - Marking the node http://10.32.40.97:5555 as down: cannot reach the node for 2 tries
19:27:23.770 INFO - Unregistering the node http://10.32.40.97:5555 because it's been down for 60032 milliseconds
19:27:23.770 WARN - Cleaning up stale test sessions on the unregistered node http://10.32.40.97:5555

node:

19:22:38.069 INFO - Selenium build info: version: '3.6.0', revision: '6fbf3ec767'
19:22:38.070 INFO - Launching a Selenium Grid node
2024-03-27 19:22:38.275:INFO::main: Logging initialized @343ms to org.seleniumhq.jetty9.util.log.StdErrLog
19:22:38.292 INFO - Driver class not found: com.opera.core.systems.OperaDriver
19:22:38.301 INFO - Driver provider class org.openqa.selenium.ie.InternetExplorerDriver registration is skipped:
 registration capabilities Capabilities [{ensureCleanSession=true, browserName=internet explorer, version=, platform=WINDOWS}] does not match the current platform MAC
19:22:38.301 INFO - Driver provider class org.openqa.selenium.edge.EdgeDriver registration is skipped:
 registration capabilities Capabilities [{browserName=MicrosoftEdge, version=, platform=WINDOWS}] does not match the current platform MAC
19:22:38.311 INFO - Using the passthrough mode handler
2024-03-27 19:22:38.320:INFO:osjs.Server:main: jetty-9.4.5.v20170502
2024-03-27 19:22:38.331:WARN:osjs.SecurityHandler:main: [email protected]@687ef2e0{/,null,STARTING} has uncovered http methods for path: /
2024-03-27 19:22:38.333:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@687ef2e0{/,null,AVAILABLE}
2024-03-27 19:22:38.341:INFO:osjs.AbstractConnector:main: Started ServerConnector@6ad59d92{HTTP/1.1,[http/1.1]}{0.0.0.0:5555}
2024-03-27 19:22:38.341:INFO:osjs.Server:main: Started @409ms
19:22:38.341 INFO - Selenium Grid node is up and ready to register to the hub
19:22:38.347 INFO - Starting auto registration thread. Will try to register every 5000 ms.
19:22:38.347 INFO - Registering the node to the hub: http://localhost:4444/grid/register
19:22:38.354 INFO - The node is registered to the hub and ready to use

And then the output from my selenium script

node test.js
WebDriverError: Error forwarding the new session Error forwarding the request Connect to 10.32.40.97:5555 [/10.32.40.97] failed: Operation timed out
    at Object.checkLegacyResponse (/Users/zakjonat/seleniumStackOverflow/node_modules/selenium-webdriver/lib/error.js:546:15)
    at parseHttpResponse (/Users/zakjonat/seleniumStackOverflow/node_modules/selenium-webdriver/lib/http.js:509:13)
    at /Users/zakjonat/seleniumStackOverflow/node_modules/selenium-webdriver/lib/http.js:441:30
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
From: Task: WebDriver.createSession()
    at thenableWebDriverProxy.createSession (/Users/zakjonat/seleniumStackOverflow/node_modules/selenium-webdriver/lib/webdriver.js:769:24)
    at thenableWebDriverProxy.createSession (/Users/zakjonat/seleniumStackOverflow/node_modules/selenium-webdriver/chrome.js:761:15)
    at createDriver (/Users/zakjonat/seleniumStackOverflow/node_modules/selenium-webdriver/index.js:170:33)
    at Builder.build (/Users/zakjonat/seleniumStackOverflow/node_modules/selenium-webdriver/index.js:626:16)
    at firstTest (/Users/zakjonat/seleniumStackOverflow/test.js:21:131)
    at Object.<anonymous> (/Users/zakjonat/seleniumStackOverflow/test.js:54:2)
    at Module._compile (node:internal/modules/cjs/loader:1267:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1321:10)
    at Module.load (node:internal/modules/cjs/loader:1125:32)
    at Module._load (node:internal/modules/cjs/loader:965:12) {
  remoteStacktrace: ''
}
/Users/zakjonat/seleniumStackOverflow/test.js:52
    await driver.quit();
                 ^

TypeError: Cannot read properties of undefined (reading 'quit')
    at firstTest (/Users/zakjonat/seleniumStackOverflow/test.js:52:18)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v20.0.0

Any help is appreciated!

NextJS – not typing after fetching from Route Handler

I have a Route Handler like below.

app/api/auth/me

import { NextRequest, NextResponse } from "next/server";
import axios from "../../axios";


export interface DefaultResponse<T> {
  success: boolean;
  message?: string;
  data?: T;
}

export async function GET(): Promise<NextResponse<DefaultResponse<User>>> {
    const user = await axios.get(`/auth/me`);
    return NextResponse.json(
      { success: true, data: user.data },
      { status: 200 }
    );
}

Right now, when I fetch from the route handler

  useEffect(() => {
    async function fetchUserProfile() {
      try {
        const userProfileRaw = await fetch(`/api/auth/me`);
        const userRes = await userProfileRaw.json();
        ...
      } catch (err) {...}
    }
    fetchUserProfile();
  }, []);

There is no typing for userRes, which I expect should be DefaultResponse<User>.
enter image description here

Of course I am add the type manually like

 const userRes: DefaultResponse<User> = await userProfileRaw.json();

but it would be a lot of work if I have to do it every time.

Just wondering if it’s fixable?

React Link to same component, has subcomponent using the wrong version of passed state

Below I have a SubComponent and a MainComponent. This is meant to be a page that displays an image collection. In the Subcomponent using the onclick() event you can swap between pictures in that collection. The MainComponent will also display links to other collections, but these are links to the same component itself.

The problem is that when I click the link to go to a new collection, my SubComponent will often use the outdated mainImage to set the imageList state. It will fetch the correct response (data) however and also currentImage will still use the correct version of mainPicture and be set correctly. So in other words only the first image of the “image chooser” will use the outdated mainImage and be set incorrectly.

SubComponent.js

import React, { useState, useEffect } from 'react'
import my_client
import stockimage

const Subcomponent = ({ mainPicture, my_url, identifier }) => {

    const [ imagesList, setImageList ] = useState([])

    const baseImageUrl = `${my_url}`

    const [ currentImage, setCurrentImage ] = useState(`main/${mainPicture}`)

    useEffect(() => {
        const fetchList = async () => {
            const { data, error } = await my_client
              .fetch(`${identifier}`)
            if (data) {
              setImageList([`main/${mainPicture}`, ...(data.map(obj => `sub/${obj.name}`))])
            }
            if (error) {
              console.log(error)
              setImageList([])
            }
        }

        fetchList()
        console.log("fetched")

        setCurrentImage(`main/${mainPicture}`)
    }, [identifier, mainPicture])

    return (
        <div>
            {mainPicture ? <img src={`${baseImageUrl}/${currentImage}`} /> : <img src={stockimage} />}
            { imagesList && imagesList.length > 1 &&
            <div>
                { imagesList.map((item, item_index) => (
                    <div key={item_index}>
                        <img src={`${baseImageUrl}/${item}`} onClick={() => setCurrentImage(item)}/>
                    </div>
                ))}
            </div>
            }
        </div>
    )
}

export default SubComponent

MainComponent.js (simplified)

import React, { useState, useEffect, useContext } from 'react'
import SubComponent from './SubComponent'
import Context from './Context'
import my_client
import fetchLinks from './Functions.js'

const MainComponent = () => {

  const [ mainPicture, setMainPicture ] = useState(location.state?.paramPicture || null)
  const { identifier } = useParams()
  const my_url = useContext(Context)

  const [ links, setLinks ] = useState(null)

  useEffect(() => {
      const my_fetch = async () => {
          const { data, error } = await my_client
            .fetch(`${identifier}/main`)
          if (data) {
            setMainImage(data.mainImage)
            setLinks(data.otherImagesData)
          }
          if (error) {
            console.log(error)
          }
      }
      my_fetch()

      if (location.state.paramPicture) {
          setMainPicture(location.state.paramPicture)
          fetchLinks(setLinks)
      } else {
          my_fetch()
      }
  }, [identifier])

  return (
    <div>
        <SubComponent mainPicture={mainPicture} my_url={my_url} identifier={identifier} />
        {links.map(item => (<Link to={`/view/${item.link}`} state={{ paramPicture: item.picture }}>))}
    </div>
  )
}

export default MainComponent

Changing image in script with a transition effect

I am using this code:

<script>
    const body = document.querySelector("grayallbg");
    const li = document.querySelectorAll("span");
    

    li.forEach(el => {
        el.addEventListener("mouseover", () => {
            let bg = el.getAttribute("data-bg");
            grayallbg.style.background = `url(${bg})no-repeat center /cover`;
        });
    });
</script>

And it swaps fine, but I want it to ease in or fade.

I have tried to add a class, surround it with css selectors and I cannot target the images that swap.

using redis timeseries in aredes error =>Error handling publish event: [ErrorReply: ERR TSDB: invalid value]

i am using redis timeseries in aedes i want when ever someone publis something is topic that data should store in redis in form of object value : [{status,timestamp},{status,timestamp]

i try this code but giving error
CODE =>

const { createClient } = require(‘redis’);
const { TimeSeriesDuplicatePolicies, TimeSeriesEncoding, TimeSeriesAggregationType } = require(‘@redis/time-series’);

const clt = createClient();

(async () => {

try {
    // Connect to Redis before creating the time series
    await clt.connect();

    const created = await clt.ts.create('random', {
        RETENTION: 86400000, // 1 day in milliseconds
        ENCODING: TimeSeriesEncoding.UNCOMPRESSED, // No compression
        DUPLICATE_POLICY: TimeSeriesDuplicatePolicies.BLOCK, // No duplicates
    });

    if (created === 'OK') {
        console.log('Created timeseries.');
    } else {
        console.error('Error creating timeseries:', created);
    }
} catch (error) {
    console.error('Error connecting to Redis or creating timeseries:', error);
}

})();

aedes.on(‘publish’, async function (packet, client) {
if (client) {
console.log(MESSAGE_PUBLISHED : MQTT Client ${(client ? client.id : 'AEDES BROKER_' + aedes.id)} has published message "${packet.payload}" on ${packet.topic} to aedes broker ${aedes.id});

    try {
        // Convert buffer payload to string
        const payloadString = packet.payload.toString('utf8');
        
        // Parse the payload string as JSON
        const data = JSON.parse(payloadString);
        const timestamp = Date.now();
        // Extract data from the JSON payload
        const deviceId = data.deviceID;
        const nodeId = data.NodeID;
        const status = data.status;

    

      
            const value = {
                status: status,
                timestamp: timestamp
            };
               
           
                const serializedValue = JSON.stringify(value);
            console.log("Data:", data);
            console.log("DID:", deviceId);
            console.log("NODEID:", nodeId);
            console.log("Status:", status);
            console.log("Value to be stored in Redis time series:", value);

            // Add the data to the Redis time series
            const result = await clt.ts.add(`${deviceId}:${nodeId}`, timestamp, serializedValue);
            console.log("Result from Redis:", result)
            console.log(`Added timestamp ${currentTimestamp}, value ${value}.`);
            // console.log("Result from Redis:", result);

            console.log("Data saved to Redis time series.");
    } catch (error) {
        console.error("Error handling publish event:", error);
    }
}

});

and sending data in postman =>
{
“deviceID”: “23423432”,
“NodeID”: “34534”,
“status”:”1″
}

ERROR =>
Data: { deviceID: ‘23423432’, NodeID: ‘34534’, status: ‘1’ }
DID: 23423432
NODEID: 34534
Status: 1
Value to be stored in Redis time series: { status: ‘1’, timestamp: 1711579778262 }
Error handling publish event: [ErrorReply: ERR TSDB: invalid value]

I’m prevented from pasting into a form input field and the methods to circumvent this on Stack Overflow don’t work

There’s a form on a website that I fill in regularly but it’s quite time consuming so I wanted to write some code to enter some of the data automatically via JavaScript. I’ve hit a problem with the first form input because the developer has somehow disabled pasting but I’m not sure how. Here is the HTML of the form.

<form method="post" id="entry_form" action="/enter-casual-record" enctype="multipart/form-data" novalidate="novalidate">
  <input id="auth_token" name="auth_token" type="hidden" class="hidden" value="">
  <input id="nonce" name="nonce" type="hidden" class="hidden" value="">
  <input type="hidden" id="website_id" name="website_id" value="23">
  <input type="hidden" id="survey_id" name="survey_id" value="42">
  <input type="hidden" id="occurrence:record_status" name="occurrence:record_status" value="C">
  <input type="hidden" name="smpAttr:36" value="">
  <input type="hidden" name="smpAttr:58" value="">
  <input type="hidden" name="smpAttr:8" value="">
  <input type="hidden" name="smpAttr:21" value="">
  <input type="hidden" name="smpAttr:22" value="">
  <div id="controls">
    <div id="tab-misc">
      <div class="row">
        <div class="col-md-6">
          <div id="ctrl-wrap-sample-date" class="form-group ctrl-wrap not-full-width-sm">
            <label for="sample:date">Date:</label>
            <div class="input-group">
              <input type="text" placeholder="dd/mm/yyyy" class="control-width-4 date-text form-control {required:true, indiciaDate:true}" id="sample:date" name="sample:date" value="" style="display: none">
              <input type="date" placeholder="dd/mm/yyyy" max="2024-03-27" class="precise-date-picker form-control" id="sample:date:date" style="animation-name: none !important;">
              <div class="input-group-addon ctrl-addons">
                <span id="sample:date_lock" class="unlocked-icon" title="Click here to lock the control's current value so that it is reused the next time you input data using this form." alt="Click here to lock the control's current value so that it is reused the next time you input data using this form.">&nbsp;</span>
                <span class="deh-required">*</span>
              </div>
            </div>
            <p class="helpText">Select the date of the record.</p>
          </div>
        </div>
      </div>
    </div>
  </div>

The input is a date picker but you can type directly into it if you prefer. Here’s a shot of the page code from the browser console (Firefox).

enter image description here

It has an ID and two classes and the console shows some JavaScript attached to it, three scripts in fact. I’ve searched through the JavaScript on the page separately and can’t find any attached to the ID. I think the hook for the scripts is the class precise-date-picker as form control is the class of another input that I can paste into.

context menu - date picker
context menu - quantity

The three scripts are:

script 1
script 2
script 3

I’m sure it must be JavaScript causing this but I can’t see anything obvious in the scripts and I’ve not been able to confirm it. I’m sure you used to be able to disable JavaScript in the web developer’s toolbar but that doesn’t seem possible anymore.

I really don’t know why developers do this as it’s a pain and I’m sure it doesn’t help accessibility.

OK so, I’ve tried pasting directly, typing the value into another input and then dragging it into the date picker, I’ve installed the “don’t fuck with paste” extension, I’ve even tried adding contenteditable=”true” to the input in the console but nothing worked. How do I get around this? Is there a way, in jQuery or something, to fool the input into thinking the text is coming from the keyboard instead of the clipboard? The only thing I’ve found that works so far is creating an entry in “KeePass” password manager to auto-fill the input but that’s not much use.

I really don’t know what this page is doing behind the scenes as records are entered so I want to use as light a hand as possible, as if the user were just typing in the values, I don’t want to use “brute force”.

I should add that I’m just a hobbyist so my JavaScript is fairly basic. I can usually cobble together a script that works… eventually but I haven’t done much coding lately so I’m a bit rusty.

Oh the website in question is built using Drupal and Bootstrap if that helps.

when sending file contents to console SyntaxError: missing ) after argument list [duplicate]

ultimately I am trying to compare a string to the contents of the file but i dont seeb to be able to compare it in php however I was able to compare it in js for a different function but I still had the same problem with printing to consol with the echo statement php.
error:

Uncaught SyntaxError: missing ) after argument list (at search.php:1:21)

code:

<?php
$file = explode('n',file_get_contents("mapPoints.txt"));
if (!$file) {
    echo "<p>Unable to open remote file.n";
    exit;
}
echo "<script>console.log('Debug Objects: " . $file[0] . "' );</script>";
?>

I first tryed file(“mapPoints”) but I had the same result.
I have also tryed printing the file without spliting it.
I am able to compare the file contents to other strings in js but not in php.

ios maui.net custom webview default BaseUrl path

i have this custom web-view as follow in :
MainPage.xaml

                   ```
       <controls:HybridWebView
x:Name="MyWebView"
HeightRequest="140"
HorizontalOptions="Fill"
Source="{Binding Source}"
VerticalOptions="FillAndExpand"
WidthRequest="512" />

and the custoum webview code is:

    HybridWebView.cs



 public class SourceChangedEventArgs : EventArgs
 {
     public WebViewSource Source
     {
         get;
         private set;
     }

     public SourceChangedEventArgs(WebViewSource source)
     {
         Source = source;
     }
 }

 public class JavaScriptActionEventArgs : EventArgs
 {
     public string Payload { get; private set; }

     public JavaScriptActionEventArgs(string payload)
     {
         Payload = payload;
     }
 }

 public interface IHybridWebView : IView
 {
     event EventHandler<SourceChangedEventArgs> SourceChanged;
     event EventHandler<JavaScriptActionEventArgs> JavaScriptAction;
     event EventHandler<EvaluateJavaScriptAsyncRequest> RequestEvaluateJavaScript;

     void Refresh();

     Task EvaluateJavaScriptAsync(EvaluateJavaScriptAsyncRequest request);

     WebViewSource Source { get; set; }

     void Cleanup();

     void InvokeAction(string data);

 }
     

 public class HybridWebView : View, IHybridWebView
 {
     public event EventHandler<SourceChangedEventArgs> SourceChanged;
     public event EventHandler<JavaScriptActionEventArgs> JavaScriptAction;
     public event EventHandler<EvaluateJavaScriptAsyncRequest> RequestEvaluateJavaScript;

     public HybridWebView()
     {

     }

     public async Task EvaluateJavaScriptAsync(EvaluateJavaScriptAsyncRequest request)
     {
         await Task.Run(() =>
         {
             RequestEvaluateJavaScript?.Invoke(this, request);
         });
     }

     public void Refresh()
     {
         if (Source == null) return;
         var s = Source;
         Source = null;
         Source = s;
     }

     public WebViewSource Source
     {
         get { return (WebViewSource)GetValue(SourceProperty); }
         set { SetValue(SourceProperty, value); }
     }

     public static readonly BindableProperty SourceProperty = BindableProperty.Create(
       propertyName: "Source",
       returnType: typeof(WebViewSource),
       declaringType: typeof(HybridWebView),
       defaultValue: new UrlWebViewSource() { Url = "about:blank" },
       propertyChanged: OnSourceChanged);

     private static void OnSourceChanged(BindableObject bindable, object oldValue, object newValue)
     {
         var view = bindable as HybridWebView;

         bindable.Dispatcher.Dispatch(() =>
         {
             view.SourceChanged?.Invoke(view, new SourceChangedEventArgs(newValue as WebViewSource));

         });
     }

     public void Cleanup()
     {
         JavaScriptAction = null;
     }

     public void InvokeAction(string data)
     {
         JavaScriptAction?.Invoke(this, new JavaScriptActionEventArgs(data));
     }
 }

and ios

using CoreGraphics;

using Foundation;

using Microsoft.Maui.Handlers; using Microsoft.Maui.Platform;

using WebKit;

using WebViewHostExample.Controls;



 namespace WebViewHostExample.Platforms.iOS.Renderers { 

public class HybridWebViewHandler : ViewHandler<IHybridWebView, WKWebView> { public static PropertyMapper<IHybridWebView, HybridWebViewHandler> HybridWebViewMapper = new PropertyMapper<IHybridWebView, HybridWebViewHandler>(ViewHandler.ViewMapper);

const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";

    private WKUserContentController userController;
    private JSBridge jsBridgeHandler;
    static SynchronizationContext sync;


    public HybridWebViewHandler() : base(HybridWebViewMapper)
    {
        sync = SynchronizationContext.Current;
    }

    private void VirtualView_SourceChanged(object sender, SourceChangedEventArgs e)
    {
        LoadSource(e.Source, PlatformView);
    }

    protected override WKWebView CreatePlatformView()
    {
        sync = sync ?? SynchronizationContext.Current;
        jsBridgeHandler = new JSBridge(this);
        userController = new WKUserContentController();

        var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);

        userController.AddUserScript(script);
        userController.AddScriptMessageHandler(jsBridgeHandler, "invokeAction");

        var config = new WKWebViewConfiguration { UserContentController = userController };
        var webView = new WKWebView(CGRect.Empty, config);

        return webView;            
    }

    protected override void ConnectHandler(WKWebView platformView)
    {
        base.ConnectHandler(platformView);

        if (VirtualView.Source != null)
        {
            LoadSource(VirtualView.Source, PlatformView);
        }

        VirtualView.SourceChanged += VirtualView_SourceChanged;
        VirtualView.RequestEvaluateJavaScript += VirtualView_RequestEvaluateJavaScript;
    }

    private void VirtualView_RequestEvaluateJavaScript(object sender, EvaluateJavaScriptAsyncRequest e)
    {
        sync.Post((o) =>
        {
            PlatformView.EvaluateJavaScript(e);
        }, null);
    }

    protected override void DisconnectHandler(WKWebView platformView)
    {
        base.DisconnectHandler(platformView);

        VirtualView.SourceChanged -= VirtualView_SourceChanged;

        userController.RemoveAllUserScripts();
        userController.RemoveScriptMessageHandler("invokeAction");
    
        jsBridgeHandler?.Dispose();
        jsBridgeHandler = null;
    }


    private static void LoadSource(WebViewSource source, WKWebView control)
    {
        if (source is HtmlWebViewSource html)
        {
            control.LoadHtmlString(html.Html, new NSUrl(html.BaseUrl ?? "http://localhost", true));

        }
        else if (source is UrlWebViewSource url)
        {
            control.LoadRequest(new NSUrlRequest(new NSUrl(url.Url)));
        }

    }

}

public class JSBridge : NSObject, IWKScriptMessageHandler
{
    readonly WeakReference<HybridWebViewHandler> hybridWebViewRenderer;

    internal JSBridge(HybridWebViewHandler hybridRenderer)
    {
        hybridWebViewRenderer = new WeakReference<HybridWebViewHandler>(hybridRenderer);
    }

    public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
    {
        HybridWebViewHandler hybridRenderer;

        if (hybridWebViewRenderer.TryGetTarget(out hybridRenderer))
        {
            hybridRenderer.VirtualView?.InvokeAction(message.Body.ToString());
        }
    }
}}

if i use the code like this:

    
 MainPageViewModel vm;

 public MainPage()
 {
     InitializeComponent();

     vm = new MainPageViewModel();
     MyWebView.BindingContext = vm;

     MyWebView.JavaScriptAction += MyWebView_JavaScriptAction;
 }

  protected override void OnParentSet()
    {
        base.OnParentSet();
        vm.Source = new HtmlWebViewSource()
        {


,            Html = htmlSource
             BaseUrl = "ios path i want????"
  
        };

   }

if i did this in android: and add the path: “file:///android_asset/” it will work on android web-view

  protected override void OnParentSet()
    {
        base.OnParentSet();
        vm.Source = new HtmlWebViewSource()
        {


,            Html = htmlSource
             BaseUrl = "file:///android_asset/"
  
        };

   }

it will work but i want the same thing in ios ???

what is the default path that will go to “Resources/Raw/” in ios code of maui.net

Postman receiving cookie but my browser isn’t receiving it when I try

I am making a website with flask and react. The user inputs an email and password on a form, axios.post to the backend, backend checks if email and password is correct with database, if so, backend returns a cookie. In postman the cookie is set, not in my browser. Apparently the frontend is receiving nothing from the backend in my browser, because it doesnt even print the console.log that I put in the axios.post. In postman the cookie is set, not in my browser

Axios post:

  const handleLogin = function(){
    axios.post("http://127.0.0.1:5000/login", {email:email, password:password}, {withCredentials:true, headers : {'Content-Type' : 'multipart/form-data'}}).then(response => {

      if(response.data["message"] == "Logado com sucesso"){
        history.push('/');
      }

    }).catch(error => {alert(error.response.data); console.error("Error occurred in login request:", error);});

flask return:

if(check_password_hash(data[19],password)):
            resposta = make_response(jsonify({"message": "Logado com sucesso"}))
            resposta.set_cookie('id', str(data[0]), httponly=True, samesite='None')
            return resposta

Apparently the frontend is receiving nothing from the backend in my browser, because it doesnt even print the console.log that I put in the axios.post. I set the CORS to support credentials and axios.post withCredentials:true.

Multiple polylines not displaying in React

I am trying to create an application to practice drawing Kanji. I am using svg to draw the lines. I can draw one polyline but it is all connected. I need to draw multiple separate lines. I am using a 2d array of points for each line. When I create the array of lines it does not render anything. It does not render any lines or basic shapes I even tried

tags just to see if what rendering and nothing.

I have tried rendering in box svg directly and in separate function. Separate function is shown here. I am not sure why the single line renders but I cannot get the 2d array to render anything. The data does seem to be transferring properly (ie. I am getting x and y points from array).

code:

    import { useState, useEffect } from "react";

export default DrawKanji = ({ advance, randomSet }) => {
  const [stroke, setStroke] = useState([]);
  const [kanji, setKanji] = useState([]);
  const [draw, setDraw] = useState(false);

  useEffect(() => {
    console.log("run");
  }, [kanji, stroke]);

  const clearPractice = () => {
    setKanji([]);
  };

  const handleMouseDown = (event) => {
    const { clientX, clientY } = event;
    //let offset = document.getElementById("svg").getBoundingClientRect();
    setDraw(true);
    /*
    setPoints([
      ...points,
      { x: clientX - offset.left, y: clientY - offset.top },
    ]);*/
  };

  const handleMouseMove = (event) => {
    const { clientX, clientY } = event;
    let offset = document.getElementById("svg").getBoundingClientRect();
    if (draw) {
      setStroke([
        ...stroke,
        { x: clientX - offset.left, y: clientY - offset.top },
      ]);
    }
  };

  const handleMouseUp = () => {
    //setPoints([]);
    let newKanji = kanji;
    newKanji.push(stroke);
    setKanji(newKanji);
    setStroke([]);
    console.log(`kanji: ${JSON.stringify(kanji)}`);
    setDraw(false);
  };

  const drawLine = (
    <>
      {kanji.forEach((line) => {
        <polyline
          point={line.map((point) => `${point.x},${point.y}`).join(" ")}
        />;
      })}
    </>
  );
 
  return (
    <>
      <p>{`${JSON.stringify(stroke[1])}`}</p>
      <button onClick={advance} name="previous" disabled={randomSet}>
        Previous
      </button>
      <svg
        id="svg"
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        width="109px"
        hanging="100px"
        style={{ border: "1px solid black" }}
      >
        {drawLine}
      </svg>
      <button onClick={advance} name="next">
        Next
      </button>
      <p>
        <button onClick={clearPractice}>Clear</button>
      </p>
    </>
  );
};

Thanks in advance for any help or advice you can give.

angular project ( html , css & js codes )

so in my angular project , i have 4 components (comp1,comp2,comp3,comp4) , i found a code of form (html , css & js ) and i wanna put it in comp1 , so tell me if i’m right or not : do i put the html form code in comp1.component.html ? and do i put the css and js codes in app.component.html or comp1.component.css & comp1.component.ts in order ?

i put the html code in comp1.component.html , the css code in comp1.component.css and js code in comp1.component.ts but there are some errors