Converting tensorflow model using tensorflowjs

Trying to convert a simple CNN using tfjs. The model gets converted, however it does not get loaded in properly. Error: ‘An InputLayer should be passed either a batchInputShape or an inputShape.’

tf.saved_model.save(model, 'my_model')

import tensorflowjs as tfjs
tfjs.converters.save_keras_model(model, 'tfjs')

I have tried converting the model from both .h5 and .keras formats. Sometimes I get a different error on the model configuration.
A few months ago I converted some similar models and never had any problems. Anyone got an idea?

File exists but I get a 404 error when reading it in Google Docs

I am trying to read the contents of a Google Docs file by using the JavaScript googleapis API. The file exists and I can send the request, but I get a 404 error when reading the contents.

To reproduce:

  1. Create a Google Cloud project as described in Create Google Cloud project
  2. In the Google project, enable the Google Docs API
  3. Create a service account with Owner role
  4. Edit the service account to create a json service account key
  5. Run the following Node.js code to get a 404 error:
const { google } = require("googleapis")

const auth = new google.auth.GoogleAuth({
    keyFile: "<path_to_service_account_key_json_file>",
    scopes: [
        "https://www.googleapis.com/auth/documents"
    ]
})

async function getDocumentContents(documentId) {
    try {
        const authClient = await auth.getClient()
        const docs = google.docs({ version: "v1", auth: authClient })
        const response = await docs.documents.get({ documentId })
        return response.data
    } catch (error) {
        console.error(error)
    }
}

(async () => {
    const documentId = "2PACX-1vRMx5YQlZNa3ra8dYYxmv-QIQ3YJe8tbI3kqcuC7lQiZm-CSEznKfN_HYNSpoXcZIV3Y_O3YoUB1ecq"
    const documentContents = await getDocumentContents(documentId)
    console.info(documentContents.body.content)
})()

I would expect the file contents of this file to be printed to the console, but instead I get a 404 error. What am I missing?

Show particular information from a response based off configuration a user select

I currently have a list of stats that are returned for a player for a particular league of legends game. I am displaying them all on screen when that player is clicked in a match in a very on the nose way:

popupContent.innerHTML = `
        <h2>${participant.championName}</h2>
        <p><strong>Summoner Name:</strong> ${participant.riotIdGameName}</p>
        <p><strong>Kills:</strong> ${participant.kills}</p>
        <p><strong>Deaths:</strong> ${participant.deaths}</p>
        <p><strong>Assists:</strong> ${participant.assists}</p>
        <p><strong>Champion Level:</strong> ${participant.champLevel}</p>
        <p><strong>Won:</strong> ${participant.win ? 'Yes' : 'No'}</p>
        <p><strong>Spell 1 ID:</strong> ${participant.spell1Id}</p>
        <p><strong>Spell 2 ID:</strong> ${participant.spell2Id}</p>
        <p><strong>Double Kills:</strong> ${participant.doubleKills}</p>
        <p><strong>Triple Kills:</strong> ${participant.tripleKills}</p>
        <p><strong>Quadra Kills:</strong> ${participant.quadraKills}</p>
        <p><strong>Penta Kills:</strong> ${participant.pentaKills}</p>
        <p><strong>Q casts:</strong> ${participant.spell1Casts}</p>
        <p><strong>W casts:</strong> ${participant.spell2Casts}</p>
        <p><strong>E casts:</strong> ${participant.spell3Casts}</p>
        <p><strong>R casts:</strong> ${participant.spell4Casts}</p>
        <p><strong>Summoner 1 casts:</strong> ${participant.summoner1Casts}</p>
        <p><strong>Summoner 2 casts:</strong> ${participant.summoner2Casts}</p>
        <p><strong>Command pings:</strong> ${participant.commandPings}</p>
        <p><strong>On My Way pings:</strong> ${participant.onMyWayPings}</p>
        <p><strong>Assist pings:</strong> ${participant.assistMePings}</p>
        <p><strong>Enemy Missing pings:</strong> ${participant.enemyMissingPings}</p>
        <p><strong>Need Vision pings:</strong> ${participant.needVisionPings}</p>
        <p><strong>Hold pings:</strong> ${participant.holdPings}</p>
        <p><strong>Retreat pings:</strong> ${participant.getBackPings}</p>
        <p><strong>Enemy vision pings:</strong> ${participant.enemyVisionPings}</p>
        <p><strong>All in pings:</strong> ${participant.allInPings}</p>
        <p><strong>Damage dealt:</strong> ${participant.totalDamageDealtToChampions}</p>
        
    `;

There is a lot more stats that can be returned from the API but I figured that people won’t want to see every single piece of information (some are meaningless really, if you don’t play league of legends things like seeing “enemy missing pings” is a bit of a joke stat)

I figure there is a better way to do this rather than just hardcoding every value but with fixing this is there also a way that I could set up a config button which would allow a user to tick which stats they’d like to see in the popup. For example if a user only wanted to see kills, deaths, assists and Q casts they’d tick those and next time they’d only see those.

I would also like to be able to store which are selected in local storage so that it will be saved for next time the site is loaded.

thanks a lot

How to know which modules do NOT need to be imported into Node project

I am writing a firebase app with NodeJS. I have noticed that I don’t actually need to import Buffer to use it. Is this because Buffer is a “built-in/core” module in my version of Node (18.5.0)? One tutorial I have read says that built-in modules can be used without importing; another says that they need to be imported still, they just don’t have to be installed first. Where can I view a list of which modules are available without

import { ExampleModule } from "examplemodule";

I suspect I may have many unnecessary imports and I’d like to clean up the code.

useCallback: dependency vs parameter

I wonder what the fundamental (or any kind, really) difference is between using a variable as a dependency in a useCallback()’d function and passing it to the function as a parameter.

a)

const s = useState(0);
const f = useCallback(() => {
 console.log(s);
}, [s]);
f(); // logs current value of s

b)

const s = useState(0);
const f = useCallback((s) => {
 console.log(s);
}, []);
f(s); // logs current value of s

I just can’t think of an example where they would be functionally different. (Except that in case b) the function reference doesn’t change even if s does, so that would be preferable…?)

In what case would you need a useCallback() with a non-empty dependency list at all then?

Make iOS public key useable in JavaScript

I have created a key pair in Swift using

let attributes: [String: Any] = [
  kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
  kSecAttrKeySizeInBits as String: 256,
  kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
  kSecPrivateKeyAttrs as String: [
    kSecAttrIsPermanent as String: true,
    kSecAttrApplicationTag as String: tag,
    kSecAttrAccessControl as String: accessControl
    ]
  ]
guard let privateKeyRef = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {...}

Then I have signed data with (which I have then exported as base64)

guard let signature = SecKeyCreateSignature(
  privateKey,
  .ecdsaSignatureMessageX962SHA256,
  data as CFData,
  &error
) else {...}

And I have exported also exported the public key in base64 with this

guard let publicKeyData as Data = SecKeyCopyExternalRepresentation(publicKey, &error) else { ... }

I want to then use all these base64 strings (data, signature and public key) to validate the signature. Using a code like this

 async function importPublicKey(publicKeyBase64) {
    const publicKeyBinary = atob(publicKeyBase64);
    const publicKeyArrayBuffer = new Uint8Array(publicKeyBinary.length);
    for (let i = 0; i < publicKeyBinary.length; i++) {
      publicKeyArrayBuffer[i] = publicKeyBinary.charCodeAt(i);
    }
  
    const publicKey = await crypto.subtle.importKey(
      "spki", 
      publicKeyArrayBuffer, 
      { name: "ECDSA", namedCurve: "P-256" },
      true, 
      ["verify"]
    );
  
    return publicKey;
  }

  async function verifyMessage(publicKey, signature, data) {
    const isValid = await crypto.subtle.verify(
      { name: "ECDSA", hash: { name: "SHA-256" } },
      publicKey,
      signature,
      new TextEncoder().encode(data)
    );
    return isValid;
  }

It does work when I generate the keys in JavaScript. But normally I get error messages around the missing SPKI format, which I could fix with this answer. But even if it runs without errors the signature is declared in invalid. If I run the same strings through Swift, the validation is valid. So there is a mismatch somewhere and I just do not see it.

getting lat and lng from leaflet map

I’m creating a contact list web page with vite-react and trying to have a map in a form element in order to get the user’s location to save that in it’s information so then in it’s card I can show the location of the person too.I made the marker draggable already so now I want to get the new lat and lng after submitting the form.do you have any Idea how can I do so?
this is my leaflet map code which is exactly before submit button of the form

<div
                    className="set-location"
                    style={{ width: "100%", height: "30%" }}
                >
                    <MapContainer
                        style={{ height: "40vh", width: "100%" }}
                        center={center}
                        zoom={13}
                        scrollWheelZoom={false}
                    >
                        <TileLayer
                            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                        />
                        <DraggableMarker />
                    </MapContainer>
                </div>
                <div className="submit-new-contact">
                    <button className="submit-button">submit</button>
                </div>
            </form>

how can I get the new lat and lng after fixing new location for map marker by user?

Real-time Audio Streaming chunk is not playing sequentially using javascript + elevenlabs

I am trying to play the audio stream chunks I receive from ElevenLabs in real time. When the next chunk is received, the audio player should preload the audio so that once the first chunk finishes, the second chunk automatically starts without any gap or overlap. I am using Plyr player to get the base64 and play the audio.

–App.js–

let player = new Plyr('#audioPlayer', {
        autoplay: false,
        muted: false,
        controls: ['play', 'progress', 'current-time', 'duration', 'volume', 'mute', 'fullscreen']
    });

    const ELEVENLABS_WS_URL = "wss://api.elevenlabs.io/v1/text-to-speech/language-id/stream-input?    model_id=eleven_multilingual_v1&inactivity_timeout=20&language=English_American";

    let ws = new WebSocket(ELEVENLABS_WS_URL);
    let audioQueue = [];
    let isPlaying = false;
    let countofchunk = 1;

    async function base64ToArrayBuffer(base64) {
        const binaryString = window.atob(base64);
        const len = binaryString.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        return bytes.buffer;
    }

    async function decodeAndQueueAudio(base64Audio) {
        console.log("loop ", countofchunk);
        const audioBuffer = await base64ToArrayBuffer(base64Audio);
        const blob = new Blob([audioBuffer], { type: 'audio/mpeg' });
        const audioUrl = URL.createObjectURL(blob);
        await audioQueue.push(audioUrl); // Always push to the queue
        console.log("audioQueue ", audioQueue);
        countofchunk++;
        if (!isPlaying) { // Only call playNextChunk if not currently playing
            playNextChunk();
        } else {
            console.log("Audio is already playing, buffering new chunk");
        }
    }

    function playNextChunk() {
    if (audioQueue.length > 0 && !isPlaying) {
      isPlaying = true;
      const audioUrl = audioQueue.shift();

      player.source = {
          type: 'audio',
          sources: [{
              src: audioUrl,
              type: 'audio/mpeg'
          }]
      };

      const playPromise = player.play();

      if (playPromise !== undefined) {
        playPromise.then(() => {
              player.on('ended', () => {
                  console.error("Autoplay was ended:", countofchunk, audioQueue);
                  isPlaying = false;
                  URL.revokeObjectURL(audioUrl);
                  playNextChunk();
              });
          }).catch(error => {
              console.error("Autoplay was prevented:", error, audioQueue);
              console.error("Autoplay was prevented count:", countofchunk, audioQueue);
              isPlaying = false;
              URL.revokeObjectURL(audioUrl);
              playNextChunk(); //Try to play next chunk even if current fails
          });
      } else {
          console.log("Audio started playing (no promise)");
          player.on('ended', () => {
              isPlaying = false;
              URL.revokeObjectURL(audioUrl);
              playNextChunk();
          });
      }
    } else {
      console.log("No more audio chunks in the queue or already playing.", audioQueue);
    }
    }

    ws.onmessage = async function (event) {
      const audioData = JSON.parse(event.data);
      console.log("Audio chunk received", audioData);
      if (audioData && audioData.audio) {
          const base64Audio = audioData.audio;
          await decodeAndQueueAudio(base64Audio);
      } else if (audioData.detail && audioData.detail.reason === "Stream timed out") {
          console.log("Stream timed out");
          if (player.playing) {
          player.stop();
          }
          audioQueue = [];
          isPlaying = false;
      } else if (event.data === '{"isFinal": true}'){
          console.log("Stream is final");
      } else {
          console.error("No audio data received or unexpected message:", event.data);
      }
    };

    document.getElementById("sendTextButton").addEventListener("click", function () {
      const inputText = document.getElementById("inputText").value.trim();
      if (inputText !== "") {
          const message = {
              text: inputText,
              voice_settings: { stability: 1, similarity_boost: true, optimize_streaming_latency: 0 },
              xi_api_key: "", // Replace with your API key
              streaming: true
          };
          if (ws.readyState === WebSocket.OPEN) {
              ws.send(JSON.stringify(message));
          } else {
              console.error("WebSocket is not open.");
          }
      }
    });

    ws.onopen = () => console.log("Connected to ElevenLabs WebSocket.");
    ws.onerror = error => console.error("WebSocket error:", error);
    ws.onclose = () => {
      console.log("Disconnected from ElevenLabs WebSocket. Attempting to reconnect...");
      setTimeout(() => {
          ws = new WebSocket(ELEVENLABS_WS_URL);
          ws.onopen = () => console.log("Reconnected to ElevenLabs WebSocket.");
          ws.onerror = error => console.error("WebSocket error:", error);
          ws.onmessage = ws.onmessage;
          ws.onclose = ws.onclose;
      }, 5000);
    };

–index.html–

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/plyr.css" rel="stylesheet" />
    <h1>Live TTS Streaming with ElevenLabs and Plyr.js</h1>
    <!-- Text Input and Send Button -->
    <div>
        <input type="text" id="inputText" placeholder="Enter text for TTS" value="Hi I have a front end application in react js. I using Elevenlabs to convert the text into audio. I am using streaming API of Elevenlabs "/>
        <button id="sendTextButton">Send Text</button>
    </div>
    <!-- Audio Player -->
    <audio id="audioPlayer" controls></audio>
    <!-- Messages Section -->
    <div>
        <h3>Messages Received:</h3>
        <div id="receive-box"></div>
    </div>
    <!-- WebSocket and Audio Handling Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/plyr.min.js"></script>
    <script src="app.js"></script>

The audio player should be able to play each chunk as it is received, with preloading, without any gaps or overlap issues.

How to Refetch Data from One Microservice After a Mutation in Another Using RTK Query?

I’m working with microservices in a React app using Redux Toolkit (RTK) Query. I have two separate APIs:

Service A: For posting data (postData).

Service B: For fetching data (getData).

After performing a POST request to Service A, I need to refetch data from Service B to update the UI without reloading the page. Here’s my setup:

// serviceA.ts (Microservice A)
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const serviceA = createApi({
  reducerPath: 'serviceA',
  baseQuery: fetchBaseQuery({ baseUrl: '/api/serviceA' }),
  endpoints: (builder) => ({
    postData: builder.mutation<void, { message: string }>({
      query: (body) => ({
        url: '/data',
        method: 'POST',
        body,
      }),
    }),
  }),
});

export const { usePostDataMutation } = serviceA;
// serviceB.ts (Microservice B)
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const serviceB = createApi({
  reducerPath: 'serviceB',
  baseQuery: fetchBaseQuery({ baseUrl: '/api/serviceB' }),
  tagTypes: ['Data'],
  endpoints: (builder) => ({
    getData: builder.query<string[], void>({
      query: () => '/data',
      providesTags: ['Data'],
    }),
  }),
});

export const { useGetDataQuery } = serviceB;

After calling postData in Service A, I want to automatically refetch data from Service B to update the UI. I’ve tried using refetch() manually, but I’m looking for a way to handle this automatically.

inject a line of code in a webpack module

On twitter/X website, the tweets with long text get cut and you have to press “view more” to view the whole tweet.

but after inspecting the HTTP call that get the tweet data, I saw that the response has the whole tweet text in result.note_tweet.text instead of result.full_text which has the short text.

so after inspecting the code that displays the tweet I found this line.

y.text = y.full_text || y.text || ""

so I want to make a userscript to replace this line with result.note_tweet.text but the problem is that this line of code is inside a function inside a webpack module

147093: (e, n, d) => {
        "use strict";
        d.d(n, {
            Z: () => h
        });
        var t = d(824797)
          , r = d(210023)
          , a = d(246685)
          , o = d(546395)
          , l = d(92174);
        const i = e => e.reduce(( (e, n) => {
            const {indices: d} = n;
            return e.some((e => e.url === n.url && e.id_str === n.id_str && e.indices?.[0] === d?.[0])) ? e : e.concat(n)
        }
        ), [])
          , s = /^(.*codecs=)([^";]+)(.*)$/
          , u = e => {
            const n = {
                ...e,
                sensitive_media_warning: e.sensitive_media_warning || e.ext_sensitive_media_warning,
                mediaStats: e.mediaStats || e.ext?.mediaStats?.r?.ok
            }
              , d = (e => {
                if (e.video_info)
                    return e.video_info.variants.map((e => {
                        return {
                            ...e,
                            content_type: (n = e.content_type,
                            s.test(n) ? n.replace(s, ( (e, n, d, t) => ${n}"${d}"${t})) : n)
                        };
                        var n
                    }
                    ))
            }
            )(n);
            return d && (n.video_info.variants = d),
            n
        }
          , c = (e=[]) => e.map((e => {
            return "photo" === e.type ? (n = e,
            {
                ...n,
                sensitive_media_warning: n.sensitive_media_warning || n.ext_sensitive_media_warning
            }) : u(e);
            var n
        }
        ))
          , b = e => e.initial ? e.initial : e.edit?.edit_control_initial ? {
            initial_tweet_id: e.edit.initial_tweet_id,
            edit_tweet_ids: e.edit.edit_control_initial.edit_tweet_ids,
            editable_until_msecs: e.edit.edit_control_initial.editable_until_msecs,
            is_edit_eligible: e.edit.edit_control_initial.is_edit_eligible,
            edits_remaining: e.edit.edit_control_initial.edits_remaining
        } : void 0;
        function h(e, n, d) {
            const {created_at: s, ext_edit_control: u, ext_has_birdwatch_notes: h, ext_limited_action_results: m, ext_views: p, extended_entities: A, in_reply_to_screen_name: D, in_reply_to_user_id_str: g, quoted_status_id_str: w, retweeted_status_id_str: M, user_id_str: _, ...S} = (0,
            o.Z)(e, n, d)
              , y = {
                ...S
            }
              , {article: f, birdwatch_pivot: k, entities: v, ext: T, ext_trusted_friends_metadata: C, full_text: P, grok_analysis_followups: R, has_birdwatch_notes: E, id_str: I, trend_id: B, withheld_entities: x, withheld_text: G} = e;
            G && (y.text = G,
            y.full_text = G,
            y.entities = x || {},
            y.withheld_text = P,
            y.withheld_entities = v),
            B && (y.trend_id = B),
            R && (y.grok_analysis_followups = R),
            A && (y.extended_entities = {
                ...A,
                media: c(A?.media)
            }),
            T?.voiceInfo?.r?.ok && (y.voiceInfo = T?.voiceInfo?.r?.ok,
            delete T?.voiceInfo),
            m && (y.limited_action_results = m.limited_actions.map((e => {
                const {limited_action_type: d, prompt: t} = e
                  , o = t?.cta_limited_action_prompt || t?.basic_limited_action_prompt
                  , l = (0,
                a.Z)(o, n)
                  , i = r.hd[d];
                return i && {
                    action: i,
                    prompt: l
                }
            }
            )).filter((e => e))),
            y.text = y.full_text || y.text || "",//*************************

And I tried so many ways to override the function but none worked.

so is there a way to inject this line into the module or is it impossible?

Curry Function with/without bracket in returned function

I am trying to understand why this piece of code does not work when I was trying to implement the curry function in JavaScript.

When I run the following piece of code, it prints undefined:

function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args)
    }

    return (arg) => {
      arg === undefined ? curried.apply(this, args) : curried.apply(this, [...args, arg])
    }
  }
}

const mul = (a, b) => a * b;
const curried = curry(mul);
console.log(curried(7)(3)) // undefined

However, once I remove the brackets in the return statement it now works:

function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args)
    }

    return (arg) => arg === undefined ? curried.apply(this, args) : curried.apply(this, [...args, arg]) // Brackets removed here
  }
}

const mul = (a, b) => a * b;
const curried = curry(mul);
console.log(curried(7)(3)) // 21

Anyone knows why this is the case?

Javascript Object, return a new array with the indexes that match the object

I have the following array containing object that holds details of a league venue and code.

I also have another array with just league codes.

I want to return a new array of the indexes of the league.venue object in the order of the league codes array.

For example the new array in this case would be – [4,5,0,3,2].

I am not sure if it is best to .map or .filter but I don’t want to use push().

league  = {};
league.venue  = [];
league.venue[0] = {};
league.venue[0].code  = 1000;
league.venue[0].team  = "Arsenal";

league.venue[1] = {};
league.venue[1].code  = 1001;
league.venue[1].team  = "Spurs";

league.venue[2] = {};
league.venue[2].code  = 1002;
league.venue[2].team  = "Liverpool";

league.venue[3] = {};
league.venue[3].code  = 1003;
league.venue[3].team  = "Manchester City";

league.venue[4] = {};
league.venue[4].code  = 1004;
league.venue[4].team  = "Manchester United";

league.venue[5] = {};
league.venue[5].code  = 1005;
league.venue[5].team  = "Everton";

league.code = [1004, 1005, 1000, 1003, 1002]

Tailwind CSS Styles not applying

Tailwind CSS Styles not applying using Live Server or no Live Server. The builds are working and I think the paths are already good. What else am I missing?

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/script/output.css">
</head>
<body>
    <div class="bg-red-500"> Testing </div>
</body>
</html>

INPUT CSS

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Package JSON FILE

{
  "devDependencies": {
    "tailwindcss": "^3.4.17"
  },
  "scripts": {
    "build": "npx tailwind -i ./input.css -o ./output.css --watch"
  }
}

Tailwind Config File

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./index/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

folders/directory

I tried the input.css changes where I added tailwindcss to the base and that’s mostly it.

How do I solve npm errno `4058

I was just about to start a project, but it returns an error message.

I typed in:

npm init

and here’s the error message

npm error code ENOENT
npm error syscall open
npm error path C:UsersaubreyastaDocumentsMC bottingpackage.json
npm error errno -4058
npm error enoent ENOENT: no such file or directory, open 'C:UsersaubreyastaDocumentsMC bottingpackage.json' 
npm error enoent This is related to npm not being able to find a file.
npm error enoent

Any ideas how to fix?

How to bypass numeric-only regex for LFI [closed]

I am working on a challenge where I need to exploit a Local File Inclusion vulnerability.

The application expects an id parameter and tries to open a file using the given value and appending .png at the end. However the value is validated using /^[0-9]+$/m and test() function in javascript so it only accepts numerical values.

URL encoding common payloads or using null bytes didn’t work.

I would appreciate any insights or suggestions.