How to connect the node extension

I am trying to use this code to connect directly to a gradient node (extension by mqtt). After trying to connect I always receive same message:

< Received: WSMessage(type=<WSMsgType.CLOSE: 8>, data=1000, extra=”) >

It is necessary to know whether I am connected to websocket in order to do next moves in my project. So, I suppose to use different approaches to get useful message for example ({“error”: “invalid token”}) but always get same result.

import json
import time
import uuid
import asyncio
import aiohttp
from aiohttp import WSMsgType

class GrassWs:
    def __init__(self, user_agent: str = None, proxy: str = None):
        self.user_agent = user_agent or 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
        self.proxy = proxy
        self.session = None
        self.websocket = None
        self.user_id = 'z6QU3Kfs1HfDfyUOHSCbjX5Ic4l1'
        self.browser_id = str(uuid.uuid3(uuid.NAMESPACE_DNS, self.proxy or ""))

    async def connect(self):
        uri = "wss://wss.gradient.network/mqtt"
        headers = {
            'Pragma': 'no-cache',
            'Origin': 'chrome-extension://caacbgbklghmpodbdafajbgdnegacfmo',
            'Accept-Language': 'en-US,en;q=0.9,uk;q=0.8,ru-RU;q=0.7,ru;q=0.6,en-GB;q=0.5,pl;q=0.4',
            'Sec-WebSocket-Key': 'LrA0qPyzg/9bGVBSQYZGdg==',
            'User-Agent': self.user_agent,
            'Upgrade': 'websocket',
            'Cache-Control': 'no-cache',
            'Connection': 'Upgrade',
            'Sec-WebSocket-Version': '13',
            'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
            'Sec-WebSocket-Protocol': 'mqtt'
        }
        self.websocket = await self.session.ws_connect(uri, headers=headers, proxy=self.proxy)

    async def send_message(self, message):
        await self.websocket.send_str(message)

    async def receive_message(self):
        msg = await self.websocket.receive()
        if msg.type == WSMsgType.CLOSED:
            print("WebSocket connection closed.")
            return None
        elif msg.type == WSMsgType.TEXT:
            return msg.data  # Текстовое сообщение от WebSocket
        else:
            print(f"Received non-text message: {msg.type}")
            return None

    async def get_connection_id(self):
        msg = await self.receive_message()
        if msg:  # Проверяем, что msg не None
            try:
                data = json.loads(msg)
                return data.get('id')
            except json.JSONDecodeError:
                print("Received message is not valid JSON:", msg)
                return None
        else:
            print("No message received.")
            return None

    async def auth_to_extension(self, browser_id: str, user_id: str):
        connection_id = await self.get_connection_id()
        if not connection_id:
            return False
        message = json.dumps({
            "id": connection_id,
            "origin_action": "AUTH",
            "result": {
                "browser_id": browser_id,
                "user_id": user_id,
                "user_agent": self.user_agent,
                "timestamp": int(time.time()),
                "device_type": "extension",
                "version": "4.26.2",
                "extension_id": "caacbgbklghmpodbdafajbgdnegacfmo"
            }
        })
        await self.send_message(message)
        return True

    async def send_ping(self):
        message = json.dumps({
            "id": str(uuid.uuid4()),
            "version": "1.0.0",
            "action": "PING",
            "data": {}
        })
        await self.send_message(message)

    async def keep_alive(self):
        while True:
            try:
                await self.send_ping()
                print("Sent: PING message")
                response = await self.receive_message()
                print(f"Received: {response}")
                await asyncio.sleep(30)  # Send PING every 30 seconds
            except Exception as e:
                print(f"Error: {e}")
                print("Reconnecting...")
                await self.connect()
                await self.auth_to_extension(self.browser_id, self.user_id)

async def main():
    ws_client = GrassWs()
    async with aiohttp.ClientSession() as session:
        ws_client.session = session
        await ws_client.connect()
        print("Connected to WebSocket server.")
        await ws_client.auth_to_extension(ws_client.browser_id, ws_client.user_id)
        print("Sent authentication message.")
        await ws_client.keep_alive()  # Maintain connection for farming points

# Запуск асинхронного кода
asyncio.run(main())

Launch kubernetes-dashboard in a logged-in state by pressing button in web app

I have a web app that provides links to all system’s dashboards for user’s convenience.
It has a button for kubernetes-dashboard too.
When a user clicks on a button, i would like to open a new page with Kubernetes dashboard and i would like to automatically authenticate user. ServiceAccount token would be generated every time.

When I test this with Requestly it works. When I add generated token to haproxy it works. But I want the token to be dynamic.
I tried using the following format https://k8s-dashboard/dashboard/?token=
dashboard didn’t like it. haproxy had issues extracting the token with urlp(token). couldn’t get it to work.
I tried to pass request header in my app’s backend but that didn’t work either.

Any suggestions would be appreciated.

Thanks

Set min value for End time using datetime-local input type depending on Start Time

I have a start date/time and end date/time field on a form, using type="datetime-local"

I’d like the End Date/Time MIN value to be set to the start Date/Time value.

I can set the min date value with the following script, but the time portion does not work. Looking at the page code once the first value is set, I do see the full value being set (For example: min=”2024-11-13T18:55″). However, the date picker is not limiting the time.

           
                          
let fDate = document.querySelector('#start');
let tDate = document.querySelector('#end');

fDate.addEventListener('change', function() {
  tDate.min = this.value;
});
                            $(document).ready(function(){
  $('.first').keyup(function(){
    var a = $(this).val();
    $('.second').attr('min',a);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form>
<label>Start Date</label><br>
<input type="datetime-local" class="" name="startDate" id="start" value="">
<br>
<label>End Date</label><br>
<input type="datetime-local" class="" name="issueDate" id="end" value="">
</form>

MERN stack cookies only working in the page which set the cookies

I am having trouble getting a cookie to operate across an entire website. I haven’t worked in JS for a couple of years and cant seem to configure this properly.

I am working in a domain <client_name>.dev.domain, with a http server and the cookies are working properly for the page they are set on.

My code for setting cookies is the following:

app.use(cookie-parser("secret"));

app.use((req, res, next) => {
  if (!("cookie" in req.signedCookies) ||
      ("cookie" in req.signedCookies && req.signedCookies["cookie"] == undefined)) {
          console.log("cookie should be assigned");
          res.cookie(
            "cookie",
            "value",
            { 
              domain: '.dev.domain',
              maxAge: 3000,
              signed: true, 
              httpOnly: true,
              secure: false,
              sameSite: 'lax',
              path: '/',
            }
          );
  } else {
    console.log("cookie is already assigned");
  }
  next();
});

app.use((req, res, next) => {
  cors({
    origin: ".dev.domain:3000",
    credentials: true
  })
  next();
});

Like I said this works for the home page where the cookies are initally set.
All subsequent fetches from the front end are using the fetch api and use the following function.

const getData = async (api_url, setData, setLoading) => {
  return await fetch(
    api_url,
    {
      method: "GET",
      credentials: "include",
    })
    .then(res => res.json())
    .then(res => setData(res))
    .then(res => setLoading(res))
    .catch(err => {
      console.log("Error fetching data from: ");
      console.log(api_url);
      console.log(err);
    });
});

From everything I was reading, I figured it was an issue with the localhost domain name not meeting the subdomain.subdomain.domain requirements for I configured my /etc/hosts file to have 127.0.0.1 => <client_name>.dev.domain but this did not solve the issue.

I have tried specifying no domain name and that does not work.

I have tried using sameSite=None and that does not work.

The header for the setting of the cookie is

‘set-cookie’: ‘cookie=; Max-Age=3; Domain=.dev.domain; Path=/; Expires=; HttpOnly; SameSite=Lax;’

I have gone through a bunch of stackoverflow posts with similar problems but none of the solutions have helped.

Does anyone have any ideas on what I am misconfiguring that prevents this cookie from being used across multiple pages of the same website?

Thanks.

How to test custom hook with useEffect in React 18?

Hook:

import { useEffect, useState } from "react";

const useIsClient = () => {
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);
  }, []);

  return isClient;
};

export default useIsClient;

Tests:

import { renderHook } from "@testing-library/react";

import useIsClient from "./useIsClient";

describe("useIsClient", () => {
  it("returns false initially", () => {
    const { result } = renderHook(() => useIsClient());
    expect(result.current).toBe(false);
  });

  it("returns true after useEffect runs", async () => {
    const { result } = renderHook(() => useIsClient());
    expect(result.current).toBe(true);
  });
});

Result:

 ❯ src/hooks/useIsClient.spec.ts (2)
   ❯ useIsClient (2)
     × returns false initially
     ✓ returns true after useEffect runs

Why does it fail to return false when I don’t call any waitFor functions? Is this intended? How could I properly test this hook?

How do you use a Japanese voice with speechSynthesis in Safari/iOS 18?

In Safari, it is necessary to set a voice on an utterance as well as the lang property to get it to use the correct language.

On other platforms, speechSynthesis.getVoices() returns all available voices on the device. You can then filter to the language you need and pick one.

However, although I have a Japanese voice downloaded onto my iPhone 16 (simulator, iOS 18.0), it isn’t included in the array returned from getVoices.

I’ve tried setting Japanese as a preferred language. I’ve tried changing to another Japanese voice under Speak Selection in the accessibility settings. I’ve tried setting the html lang property to ‘ja’. There is still no Japanese voice present in the array.

Here’s the array:

0
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ar-001.Maged", name: "Majed", lang: "ar-001", localService: true, default: true}
1
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.bg-BG.Daria", name: "Daria", lang: "bg-BG", localService: true, default: true}
2
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ca-ES.Montserrat", name: "Montse", lang: "ca-ES", localService: true, default: true}
3
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.cs-CZ.Zuzana", name: "Zuzana", lang: "cs-CZ", localService: true, default: true}
4
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.da-DK.Sara", name: "Sara", lang: "da-DK", localService: true, default: true}
5
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.de-DE.Anna", name: "Anna", lang: "de-DE", localService: true, default: true}
6
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.el-GR.Melina", name: "Melina", lang: "el-GR", localService: true, default: true}
7
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-AU.Karen", name: "Karen", lang: "en-AU", localService: true, default: true}
8
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-IE.Moira", name: "Moira", lang: "en-IE", localService: true, default: true}
9
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-IN.Rishi", name: "Rishi", lang: "en-IN", localService: true, default: true}
10
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Trinoids", name: "Trinoids", lang: "en-US", localService: true, default: true}
11
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Albert", name: "Albert", lang: "en-US", localService: true, default: true}
12
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Hysterical", name: "Jester", lang: "en-US", localService: true, default: true}
13
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-US.Samantha", name: "Samantha", lang: "en-US", localService: true, default: true}
14
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Whisper", name: "Whisper", lang: "en-US", localService: true, default: true}
15
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Princess", name: "Superstar", lang: "en-US", localService: true, default: true}
16
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Bells", name: "Bells", lang: "en-US", localService: true, default: true}
17
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Organ", name: "Organ", lang: "en-US", localService: true, default: true}
18
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.BadNews", name: "Bad News", lang: "en-US", localService: true, default: true}
19
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Bubbles", name: "Bubbles", lang: "en-US", localService: true, default: true}
20
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Junior", name: "Junior", lang: "en-US", localService: true, default: true}
21
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Bahh", name: "Bahh", lang: "en-US", localService: true, default: true}
22
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Deranged", name: "Wobble", lang: "en-US", localService: true, default: true}
23
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Boing", name: "Boing", lang: "en-US", localService: true, default: true}
24
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.GoodNews", name: "Good News", lang: "en-US", localService: true, default: true}
25
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Zarvox", name: "Zarvox", lang: "en-US", localService: true, default: true}
26
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Ralph", name: "Ralph", lang: "en-US", localService: true, default: true}
27
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Cellos", name: "Cellos", lang: "en-US", localService: true, default: true}
28
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Kathy", name: "Kathy", lang: "en-US", localService: true, default: true}
29
SpeechSynthesisVoice {voiceURI: "com.apple.speech.synthesis.voice.Fred", name: "Fred", lang: "en-US", localService: true, default: true}
30
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-ZA.Tessa", name: "Tessa", lang: "en-ZA", localService: true, default: true}
31
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.es-ES.Monica", name: "Mónica", lang: "es-ES", localService: true, default: true}
32
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.es-MX.Paulina", name: "Paulina", lang: "es-MX", localService: true, default: true}
33
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.fi-FI.Satu", name: "Satu", lang: "fi-FI", localService: true, default: true}
34
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.fr-CA.Amelie", name: "Amélie", lang: "fr-CA", localService: true, default: true}
35
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.fr-FR.Thomas", name: "Thomas", lang: "fr-FR", localService: true, default: true}
36
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.he-IL.Carmit", name: "Carmit", lang: "he-IL", localService: true, default: true}
37
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.hi-IN.Lekha", name: "Lekha", lang: "hi-IN", localService: true, default: true}
38
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.hr-HR.Lana", name: "Lana", lang: "hr-HR", localService: true, default: true}
39
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.hu-HU.Mariska", name: "Tünde", lang: "hu-HU", localService: true, default: true}
40
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.id-ID.Damayanti", name: "Damayanti", lang: "id-ID", localService: true, default: true}
41
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.it-IT.Alice", name: "Alice", lang: "it-IT", localService: true, default: true}
42
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ko-KR.Yuna", name: "Yuna", lang: "ko-KR", localService: true, default: true}
43
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ms-MY.Amira", name: "Amira", lang: "ms-MY", localService: true, default: true}
44
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.nb-NO.Nora", name: "Nora", lang: "nb-NO", localService: true, default: true}
45
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.nl-BE.Ellen", name: "Ellen", lang: "nl-BE", localService: true, default: true}
46
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.nl-NL.Xander", name: "Xander", lang: "nl-NL", localService: true, default: true}
47
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.pl-PL.Zosia", name: "Zosia", lang: "pl-PL", localService: true, default: true}
48
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.pt-BR.Luciana", name: "Luciana", lang: "pt-BR", localService: true, default: true}
49
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.pt-PT.Joana", name: "Joana", lang: "pt-PT", localService: true, default: true}
50
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ro-RO.Ioana", name: "Ioana", lang: "ro-RO", localService: true, default: true}
51
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ru-RU.Milena", name: "Milena", lang: "ru-RU", localService: true, default: true}
52
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.sk-SK.Laura", name: "Laura", lang: "sk-SK", localService: true, default: true}
53
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.sl-SI.Tina", name: "Tina", lang: "sl-SI", localService: true, default: true}
54
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.sv-SE.Alva", name: "Alva", lang: "sv-SE", localService: true, default: true}
55
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.th-TH.Kanya", name: "Kanya", lang: "th-TH", localService: true, default: true}
56
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.tr-TR.Yelda", name: "Yelda", lang: "tr-TR", localService: true, default: true}
57
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.uk-UA.Lesya", name: "Lesya", lang: "uk-UA", localService: true, default: true}
58
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.vi-VN.Linh", name: "Linh", lang: "vi-VN", localService: true, default: true}
59
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.zh-CN.Tingting", name: "Tingting", lang: "zh-CN", localService: true, default: true}
60
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.zh-HK.Sinji", name: "Sinji", lang: "zh-HK", localService: true, default: true}
61
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.zh-TW.Meijia", name: "Meijia", lang: "zh-TW", localService: true, default: true}
62
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.tr-TR.Yelda", name: "Yelda", lang: "tr-TR", localService: true, default: true}
63
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.fr-FR.Thomas", name: "Thomas", lang: "fr-FR", localService: true, default: true}
64
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.de-DE.Anna", name: "Anna", lang: "de-DE", localService: true, default: true}
65
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.pl-PL.Zosia", name: "Zosia", lang: "pl-PL", localService: true, default: true}
66
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.vi-VN.Linh", name: "Linh", lang: "vi-VN", localService: true, default: true}
67
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.da-DK.Sara", name: "Sara", lang: "da-DK", localService: true, default: true}
68
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-IE.Moira", name: "Moira", lang: "en-IE", localService: true, default: true}
69
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.el-GR.Melina", name: "Melina", lang: "el-GR", localService: true, default: true}
70
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.es-ES.Monica", name: "Mónica", lang: "es-ES", localService: true, default: true}
71
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ru-RU.Milena", name: "Milena", lang: "ru-RU", localService: true, default: true}
72
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ca-ES.Montserrat", name: "Montse", lang: "ca-ES", localService: true, default: true}
73
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.es-MX.Paulina", name: "Paulina", lang: "es-MX", localService: true, default: true}
74
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-ZA.Tessa", name: "Tessa", lang: "en-ZA", localService: true, default: true}
75
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-AU.Karen", name: "Karen", lang: "en-AU", localService: true, default: true}
76
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.hu-HU.Mariska", name: "Tünde", lang: "hu-HU", localService: true, default: true}
77
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.nl-NL.Xander", name: "Xander", lang: "nl-NL", localService: true, default: true}
78
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ms-MY.Amira", name: "Amira", lang: "ms-MY", localService: true, default: true}
79
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.zh-CN.Tingting", name: "Tingting", lang: "zh-CN", localService: true, default: true}
80
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-IN.Rishi", name: "Rishi", lang: "en-IN", localService: true, default: true}
81
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ro-RO.Ioana", name: "Ioana", lang: "ro-RO", localService: true, default: true}
82
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.hi-IN.Lekha", name: "Lekha", lang: "hi-IN", localService: true, default: true}
83
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.sl-SI.Tina", name: "Tina", lang: "sl-SI", localService: true, default: true}
84
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.he-IL.Carmit", name: "Carmit", lang: "he-IL", localService: true, default: true}
85
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.fr-CA.Amelie", name: "Amélie", lang: "fr-CA", localService: true, default: true}
86
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.cs-CZ.Zuzana", name: "Zuzana", lang: "cs-CZ", localService: true, default: true}
87
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.hr-HR.Lana", name: "Lana", lang: "hr-HR", localService: true, default: true}
88
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.pt-PT.Joana", name: "Joana", lang: "pt-PT", localService: true, default: true}
89
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.zh-TW.Meijia", name: "Meijia", lang: "zh-TW", localService: true, default: true}
90
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.nb-NO.Nora", name: "Nora", lang: "nb-NO", localService: true, default: true}
91
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ko-KR.Yuna", name: "Yuna", lang: "ko-KR", localService: true, default: true}
92
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.pt-BR.Luciana", name: "Luciana", lang: "pt-BR", localService: true, default: true}
93
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.it-IT.Alice", name: "Alice", lang: "it-IT", localService: true, default: true}
94
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.id-ID.Damayanti", name: "Damayanti", lang: "id-ID", localService: true, default: true}
95
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.th-TH.Kanya", name: "Kanya", lang: "th-TH", localService: true, default: true}
96
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.sv-SE.Alva", name: "Alva", lang: "sv-SE", localService: true, default: true}
97
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.ar-001.Maged", name: "Majed", lang: "ar-001", localService: true, default: true}
98
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.en-US.Samantha", name: "Samantha", lang: "en-US", localService: true, default: true}
99
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.uk-UA.Lesya", name: "Lesya", lang: "uk-UA", localService: true, default: true}
100
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.sk-SK.Laura", name: "Laura", lang: "sk-SK", localService: true, default: true}
101
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.zh-HK.Sinji", name: "Sinji", lang: "zh-HK", localService: true, default: true}
102
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.nl-BE.Ellen", name: "Ellen", lang: "nl-BE", localService: true, default: true}
103
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.fi-FI.Satu", name: "Satu", lang: "fi-FI", localService: true, default: true}
104
SpeechSynthesisVoice {voiceURI: "com.apple.voice.compact.bg-BG.Daria", name: "Daria", lang: "bg-BG", localService: true, default: true}

As you can see, there are plenty of languages in there, just not Japanese.

Setting the lang of the utterance to ‘ja’ while leaving voice unset doesn’t work, it just uses the English voice and says nothing because it doesn’t know how to handle Japanese characters. This also has no effect on the array of voices (requesting the Japanese speech doesn’t trigger any Japanese voice to load).

MRE:

const voices = speechSynthesis.getVoices();
const voice = voices.filter((v) => v.lang.startsWith('ja'))[0];
const utterance = new SpeechSynthesisUtterance('こんにちは');
utterance.voice = voice;
utterance.lang = 'ja';
speechSynthesis.speak(utterance);

How do I get a function to get information from a textbox and display it in an alert when a button is clicked? [duplicate]

I am trying to get a simple button to work with a Javascript textbox. The textbox will take information from the user, and when the button is clicked, the alert will display the information from the textbox. I’ve been messing with this for a few days, and I just cannot get it to work. I would be so grateful if someone could please show me how to do this. Below is my code.

 <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <script type='text/javascript' src='main.js'></script>
        <title>Schedule Generator</title>
      </head>
      <body>
        <label for="tbuser">Number of Reviews</label>
        <input type="text" id="tbuser" class="numOfReviews" placeholder="Enter Number of Reviews">
        <button id='generateBtn' type='button' onclick='generateSchedule(numOfReviews.value)'>
          Generate Review Schedule
        </button>
      </body>
    </html>
    
    // External JavaScript file
    const numOfReviewsTxt = document.getElementById('numOfReviews');
    const genBtn = document.getElementById('generateBtn');
    
    function generateSchedule() {
        const reviewNum = numOfReviewsTxt.value;
        
        alert('numOfReviewsTxt.value: ');
    }
    
    genBtn.addEventListener('click', generateSchedule);

I have a problem with when I use it in the _Layout.cshtml file along with JavaScript

I have a problem that I am facing while working with Blazor Server in .NET 8. My JavaScript scripts stop working correctly when I try to load the script <script src="_framework/blazor.server.js"></script> in the _Layout.cshtml file.
When I include this script, my own JavaScript scripts stop working (they actually work for a fraction of a second, then the screen flickers and the scripts stop working). However, when I remove the references to .js files in _Layout.cshtml and place them directly in files like page1.razor, everything works fine.

File _Layout.cshtml:

<base href="~/" />

<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
    @RenderBody()

    <script src="js/test/custom.js"></script>
    <script src="js/test/swiper.js"></script>
    <script src="js/test/gallery.js"></script>
    <script src="js/test/Pager.js"></script>
    <script src="js/test/picture.js"></script>
    <script src="js/main.js"></script>

    <script src="_framework/blazor.server.js"></script>

I would like all my references to JavaScript files to be contained in the _Layout.cshtml file so that they are global and work correctly across the entire page. My JavaScript scripts are intended to trigger interactions, such as .

I have already searched through threads related to similar issues, including one on StackOverflow: Why can’t I load any js after my blazor.server.js?, but I couldn’t find a solution to my problem.

Has anyone encountered a similar issue and could help me? Maybe someone knows the solution to correctly load blazor.server.js in _Layout.cshtml so that my JavaScript scripts work properly across the entire page?”

App.jsx does not render imported JSX components -> shows blank page in browser

I’m trying to switch my static website to React. I’ve never used React before so I’m clueless to what the error could be.

My current App.jsx looks like the following:

import React from "react";

import Header from './components/Header.jsx';
import Home from './components/Home.jsx';
import About from './components/About.jsx';
import Contact from './components/Contact.jsx';
import Footer from './components/Footer.jsx';
import styles from './App.module.css';

function App() {
    return (
        <div className={styles}>
            <Header />
            <main>
                <Home />
                <About />
                <Contact />
            </main>
            <Footer />
        </div>
    );
}

export default App;

The other JSX Components all follow the same structure (e.g. About.jsx):

import React from "react";

import WorkExperience from './WorkExperience.jsx';

function About() {
    return (
        <section id="about">
            <h1 className="about-main">I&aposm a <span className="highlight">{`{Software Developer}`}</span></h1>
            <p className="about-current-situation">Currently, I&aposm studying at BZWU in Wil, St. Gallen, Switzerland,</p>
            <p className="about-self-taught">A self-taught Java and C# developer, working in this industry for 2 years now. My goal is to deliver solutions to customers which fit their needs and goals.</p>

            <h2 className="work-experience-header">Work Experience</h2>
            <div className="work-experience-container">
                <WorkExperience />
            </div>

            <div className="currently-looking">
                <p className="currently-looking-big">I&aposm currently looking to join a <span className="highlight2">cross-functional</span> team</p>
                <p className="currently-looking-small">that values improving people&aposs lives through high quality software</p>
            </div>
        </section>
    );
}

export default About;

I tested it with a test App.jsx provided by Copilot:

import React from 'react';

function App() {
    return (
        <div>
            <h1>App is rendering correctly</h1>
        </div>
    );
}

export default App;

Can anyone tell me where I’m going wrong or what I’m missing?

I’d appreciate it if anyone can help me in this matter and give me some advice on how to solve problems like these on my own.

I tried googling, React Docs and Copilot. I’m not getting any warnings nor errors.

The Website only shows a blank page when inserting my App.jsx. The main.jsx and the index.html function correctly when using the test app.jsx

The Indesign script returns the page number as a single-digit number

First of all, I would like to say that I have no idea about programming; I have simply been developing a script for InDesign using AI, and I have reached a point where I cannot continue. What I am looking for is for the script to go through the entire document to return an Excel file where the codes of the articles are located, as well as the page number where they are found. The problem is that in the resulting CSV file, the page number behaves correctly in documents with fewer than 10 pages, enumerating correctly. However, starting from page 10, it simply writes 1 for the pages from 10 to 19 and 2 for those from 20 to 29, and so on.

var now = new Date();
var hours = ("0" + now.getHours()).slice(-2); // Formato HH
var minutes = ("0" + now.getMinutes()).slice(-2); // Formato MM
var day = ("0" + now.getDate()).slice(-2); // Formato DD
var month = ("0" + (now.getMonth() + 1)).slice(-2); // Formato MM (mes)

// Crear el nombre del archivo CSV con la fecha y hora
var fileName = hours + minutes + "_" + day + month + ".csv";
var file = new File("~/Documentos/" + fileName);

try {
    file.open("w"); // Abrir el archivo en modo escritura
    file.writeln("Código,Página"); // Escribir el encabezado con la nueva columna

    // Comprobación de que hay un documento abierto
    if (app.documents.length > 0) {
        var doc = app.activeDocument;
        var totalCodigos = 0; // Variable para contar los códigos encontrados

        // Función para procesar elementos de texto
        function processTextFrames(textFrames, pageNumber) {
            for (var j = 0; j < textFrames.length; j++) {
                var textFrame = textFrames[j];

                // Recorrer todas las tablas en el marco de texto
                for (var k = 0; k < textFrame.tables.length; k++) {
                    var table = textFrame.tables[k];

                    // Acceder a la primera columna
                    var firstColumnCells = table.columns[0].cells;

                    // Recorrer cada celda en la primera columna
                    for (var l = 0; l < firstColumnCells.length; l++) {
                        var cellContent = firstColumnCells[l].contents;

                        // Buscar secuencias de 8 dígitos
                        var matches = cellContent.match(/bd{8}b/g);

                        if (matches) {
                            totalCodigos += matches.length; // Contar los códigos encontrados

                            for (var m = 0; m < matches.length; m++) {
                                // Escribir el código y el número de página en columnas separadas
                                file.writeln(matches[m] + "," + pageNumber);
                            }
                        }
                    }
                }

                // Buscar códigos en cajas de texto
                var textContent = textFrame.contents;
                var codigoMatches = textContent.match(/Cód:s*(d{8})/g);

                if (codigoMatches) {
                    totalCodigos += codigoMatches.length; // Contar los códigos encontrados

                    for (var n = 0; n < codigoMatches.length; n++) {
                        var codigo = codigoMatches[n].match(/d{8}/)[0]; // Extraer solo el código
                        // Escribir el código y el número de página en columnas separadas
                        file.writeln(codigo + "," + pageNumber);
                    }
                }
            }
        }

        // Función recursiva para procesar grupos
        function processGroups(groups, pageNumber) {
            for (var g = 0; g < groups.length; g++) {
                var group = groups[g];
                processTextFrames(group.textFrames, pageNumber); // Procesar marcos de texto dentro del grupo
                processGroups(group.groups, pageNumber); // Llamar a la función recursiva para grupos anidados
            }
        }

        // Recorrer todas las páginas del documento
        for (var i = 0; i < doc.pages.length; i++) {
            var page = doc.pages[i];

            // Procesar los marcos de texto en la página
            processTextFrames(page.textFrames, page.name);

            // Procesar grupos en la página
            processGroups(page.groups, page.name); // Procesar grupos en la página
        }

        // Mensaje final de confirmación
        if (totalCodigos > 0) {
            alert("Os códigos dos artigos foron exportados correctamente a " + file.fullName + ". Total de códigos: " + totalCodigos);
        } else {
            alert("Non se atoparon códigos de 8 díxitos no documento.");
        }
    } else {
        alert("Non hai documentos abertos en InDesign.");
    }
} catch (e) {
    alert("Ocurriu un erro: " + e.message);
} finally {
    file.close(); // Cerrar el archivo CSV
}

How to have rust floating point precision during operations function identical to javascript precision?

I am currently working on a project where I am porting js code to rust. There is a reoccurring issue that occurs in certain edge cases where two floating point numbers are added together and a certain bit of precision is lost.

When precision is lost in javascript, the float is truncated. However in rust, the float is rounded. Is there some way or implementation of f64 that can modify this behavior? I essentially need the rust code to perfectly mimic the js code.

Example:

-19.04345703125 + -7.9822540283203125 = -27.025711059570313 //rust

-19.04345703125 + -7.9822540283203125 = -27.025711059570312 //javascript

I’m making a language switcher to a website how can I disable it on mobile devices?

I am making a language switcher, but I need to change its location based on the screen size because on mobile it gets out of the screen. How would I be able to do that?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  $(function() { 
  /* SETUP MULTI-LANGUAGE */
  var defaultLanguage = 'en';
  var lang = location.pathname.split("/")[1];
  var defaultClass = 'lang-'+defaultLanguage+'';
  var itemParent = "nav [class*='collection'],nav [class*='folder'],nav [class*='index'],nav [class*='group']";
  if (lang == "" || lang.length > 2 ){
    var lang = defaultLanguage;
  }

  /* ADD LANGUAGE CLASSES */
  $('a[href="/"]').addClass('lang-'+defaultLanguage+'').parents(itemParent).addClass('lang-'+defaultLanguage+'');
  $('nav a:link:not([href^="http://"]):not([href^="https://"])').each(function () {
    var langType = $(this).attr('href').split("/")[1];
    var multiLanguageClass = 'multilanguage lang-' + langType + '';
    if (undefined !== langType && langType.length <= 2) 
      $(this).addClass(multiLanguageClass).parents(itemParent).addClass(multiLanguageClass);
  });
  $('nav button').each(function () {
    var langTypeFolder = $(this).attr('data-controller-folder-toggle').split("/")[0];
    var multiLanguageClass = 'multilanguage lang-' + langTypeFolder + '';
    if (undefined !== langTypeFolder && langTypeFolder.length <= 2) 
      $(this).addClass(multiLanguageClass);
  });

  /* HOMEPAGE-LOGO LINKS TO PROPER LANGUAGE HOMEPAGE */
  if (lang == "pt") {
    $('a[href="/"]').attr("href", "/pt/inicio/");
  }

  /* ADD EXCLUSION NAV ITEMS */
  $('.exclude-me,.exclude-me a').addClass('exclude');
  $('.sqs-svg-icon--list a,.SocialLinks-link,.header-menu-controls-control').addClass('exclude');

  /* REMOVE OTHER LANGUAGES AND KEEP EXCLUDED ITEMS */
  $('.multilanguage:not(".lang-'+lang+',.exclude")').remove();
});
</script>
<script>
/*setup language switcher*/
$('body').prepend('<div class="language"><a href="/en/home" class="lang-en">English</a> | <a href="/pt/inicio/" class="lang-pt">Português</a></div>');
</script>

I’m new to making websites and I don’t know how to change the location of my language switcher on mobile phones because it gets out of the screen oh, and if it helps I’m using squarespace to make the website and all the code is being injected on the footer. And I already tried this solution putting all the code inside a div element.

And maybe I am asking for too much but could anyone also help me make it so it adjusts to the size of the screen? Because it gets on top of other things when the screen is smaller.

<style>
  /* Hide content on mobile */
  @media only screen and (max-width: 768px) {
    .desktop-only {
      display: none;
    }
  }
</style>

How can I use javascript modules in a web extension?

My popup.html already includes:
<script type="module" src="./popup.js"></script>

When I try to import any resource inside the script file popup.js, like:
import { Dialer } from "../common/Dialer.js";

I get the following error:

Uncaught SyntaxError: Cannot use import statement outside a module

I am trying to add a click EventListener on all web pages, to listen to clicks in anchor elements of type tel, so that the extension makes the call…

Here is my manifest.json:

{
     "manifest_version": 3,
     "name": "My Extension",
     "description": "Extension"
     "version": "1.0.0",
     "permissions": [
         "storage",
         "activeTab",
         "scripting",
         "tabs"
     ],
     "action": {
         "default_popup": "./src/popup/popup.html"
     },
     "host_permissions": ["<all_urls>"],
     "content_scripts": [
         {
             "matches": ["<all_urls>"],
             "js": [
                 "./src/popup/popup.js",
                 "./src/common/DriverFactory.js",
                 "./src/chrome/ChromeDriver.js",
                 "./src/common/GenericDriver.js",
                 "./src/common/Dialer.js"
             ]
          }
     ],
     "web_accessible_resources": [{
     "resources": ["./src/images/*"],
     "matches": ["<all_urls>"]
     }],
     "background": {
     "service_worker": "background.js"
   }
}

I already checked the path of the imports,
Didn’t export as default… so the import is correct

Join two regexp in a single one

Hi I am performing two operation for correcting then spliting a string.
I want to join those two so as to make it faster.

Here is the two regexp

let css= "po:relative miw:100% fld :row juc : space-between ali:center mah:40 he:40 fl:0 flg-1 bac: transparent"
console.time()
css = css.replace(/( )?((:)|(-))( )?/gmi, "$2")
let match= css.trim().match(/(((|)).*?((|))|[^((|))s]+)+(?=s*|s*$)/g)

console.timeEnd()
console.log(match);

I am doing this operations ofton and joining this can make a diffrient in a long run.

Rules

1- Want to split this css by whitespace.

2- somtimes the css value could be incorrect and containes space between key:value notice that - could also sometimes count as :.
this is why I remove all white space that exist between : or -
so I replace all -, - , : ,: or -, : before spltting it.

otherwise splitting will result incorrect key/value result

Is it possible to stop a FastAPI StreamingResponse by using a JavaScript AbortController?

I’m working on an app that uses JS for the frontend with a FastAPI backend.
In my frontend, I could stop my stream fetch by passing an AbortController.signal in my fetch() function (but my backend still streams the data).
I was wondering if it is possible for my backend to get the information that the frontend has aborted the fetch?

I thank you in advance.

In frontend

Here is my function to fetch my readableStream:

const apiStreamFetch = async ( headers, body, signal) => {
    let response = null;
    response = await fetch ( "/stream", {
        method: "POST",
        headers: headers,
        body: body,
        signal: signal
    });
    parseReadableStream(response.body, signal)

I have used AbortSignal in my parseReadableStream function to confirm that my signal has been aborted.

const parseReadableStream = async (readableStream, signal) {
    const reader = readableStream.getReader();
    const decoder = new TextDecoder();
    try {
        while (true) {
            const { done, value } = await reader.read();
            if (done) break; 
            console.log('Parsed chunk:', decoder.decode(value));
        }
    } catch (error) {
        console.log(signal)
    }
}

What I’ve tried in my backend

I have tried to use request.is_disconnected() and asyncio.CancelledError but I can’t detect that the operation has been aborted.
My backend looks like something like this:

@app.post("/stream")
async def stream( request: Request, body ):
    if await request.is_disconnected():
        print("Client is disconnected")
    return StreamingResponse(generate(body), media_type="text/plain")


async def generate(body):
    try:
        for i in range(1, 101):
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("Streaming cancelled by client")