TypeError: i.map is not a function

I’ve just added a new functionality to my project that needs .map(), in the dev environment all went well with no errors, but when I deployed the code to production, in the live environment this error appeared for some reason in the console of the browser. Uncaught TypeError: i.map is not a function.

this is the code that uses .map() I added:

function DisplayAutoSearchCompany({ autoSearch, input, handleClick }) {
  const companiesArray = [
    "GMS",
    "RT Colors",
    "Potência",
    "Kaitos",
    "Papel Safra",
  ];

  return (
    <>
      <ul
        className="autosearch"
        style={{ visibility: autoSearch ? "visible" : "hidden" }}
      >
        {companiesArray
          .sort()
          .filter((item) => item.toLowerCase().includes(input.toLowerCase()))
          .map((item, index) => (
            <textarea
              onClick={handleClick}
              key={index}
              value={item}
              name="company"
              readOnly
            >
              {item}
            </textarea>
          ))}
      </ul>
    </>
  );
}

export default DisplayAutoSearchCompany;

and this is the code where the props are coming:

import { useState } from "react";
import DisplayAutoSearchCompany from "./DisplayAutoSearchCompany.jsx";
import DisplayAutoSearchProduct from "./DisplayAutoSearchProduct.jsx";

function DisplayInput({ addCollect }) {
  const [autoSearchCompany, setAutoSearchCompany] = useState(false);
  const [autoSearchProduct, setAutoSearchProduct] = useState(false);
  const [input, setInput] = useState({
    company: "",
    date: "",
    product: "",
  });

  function handleInput(event) {
    setInput((i) => ({ ...i, [event.target.name]: event.target.value }));
  }

  function handleMouseDown(event) {
    if (event.target.name == "company") {
      setAutoSearchCompany(true);
      setAutoSearchProduct(false);
    }
    if (event.target.name == "product") {
      setAutoSearchProduct(true);
      setAutoSearchCompany(false);
    }
  }

  function handleClick(event) {
    setInput((i) => ({ ...i, [event.target.name]: event.target.value }));
    setAutoSearchCompany(false);
    setAutoSearchProduct(false);
  }

  return (
    <tbody>
      <tr>
        <td>
          <input
            onChange={handleInput}
            onMouseDown={handleMouseDown}
            value={input.company}
            type="text"
            name="company"
            placeholder="Empresa"
            required
            autoComplete="off"
          />
        </td>
        <td>
          <input
            onChange={handleInput}
            value={input.date}
            type="text"
            name="date"
            placeholder="Data"
            required
            autoComplete="off"
          />
        </td>
        <td>
          <input
            onChange={handleInput}
            onMouseDown={handleMouseDown}
            value={input.product}
            type="text"
            name="product"
            placeholder="Material"
            required
            autoComplete="off"
          />
        </td>
        <td>
          <img
            src="/assets/images/add.png"
            alt="add button"
            onClick={() => addCollect(input)}
          />
        </td>
      </tr>
      <tr>
        <td>
          <DisplayAutoSearchCompany
            autoSearch={autoSearchCompany}
            input={input}
            handleClick={handleClick}
          />
        </td>
        <td></td>
        <td>
          <DisplayAutoSearchProduct
            autoSearch={autoSearchProduct}
            input={input}
            handleClick={handleClick}
          />
        </td>
      </tr>
    </tbody>
  );
}

export default DisplayInput;

How can I know if there is another item with same property value with map JavaScript

I want to know how can I see if there is already an element with the same ia value and based on that asign the same posicion value

let data = [
    {
        "idMiembro": 6,
        "ia": "21.13"
    },
    {
        "idMiembro": 175,
        "ia": "20.89"
    },
    {
        "idMiembro": 165,
        "ia": "19.52"
    },
    {
        "idMiembro": 101,
        "ia": "18.83"
    },
    {
        "idMiembro": 51,
        "ia": "17.88"
    },
    {
        "idMiembro": 86,
        "ia": "17.83"
    },
    {
        "idMiembro": 195,
        "ia": "17.79"
    },
    {
        "idMiembro": 161,
        "ia": "17.65"
    },
    {
        "idMiembro": 103,
        "ia": "17.65"
    },
    {
        "idMiembro": 187,
        "ia": "17.57"
    },
    {
        "idMiembro": 178,
        "ia": "17.50"
    },
    {
        "idMiembro": 163,
        "ia": "17.42"
    },
    {
        "idMiembro": 28,
        "ia": "17.29"
    },
    {
        "idMiembro": 7,
        "ia": "17.21"
    },
    {
        "idMiembro": 104,
        "ia": "17.19"
    },
    {
        "idMiembro": 100,
        "ia": "17.12"
    },
    {
        "idMiembro": 84,
        "ia": "16.90"
    },
    {
        "idMiembro": 152,
        "ia": "16.89"
    },
    {
        "idMiembro": 184,
        "ia": "14.48"
    }
]

      data.map((item, index) => {
// here is where I want to add the same value if there is already an element with the same ia value but i dont know how to do it
        item.posicion = index + 1;
        item.totalPromocion = data.length;

        return null;
      });

The idea is that after that maps the array looked like this

let data2 = [
    {
        "idMiembro": 6,
        "ia": "21.13",
        "posicion": 1,
        "totalPromocion": 19
    },
    {
        "idMiembro": 175,
        "ia": "20.89",
        "posicion": 2,
        "totalPromocion": 19
    },
    {
        "idMiembro": 165,
        "ia": "19.52",
        "posicion": 3,
        "totalPromocion": 19
    },
    {
        "idMiembro": 101,
        "ia": "18.83",
        "posicion": 4,
        "totalPromocion": 19
    },
    {
        "idMiembro": 51,
        "ia": "17.88",
        "posicion": 5,
        "totalPromocion": 19
    },
    {
        "idMiembro": 86,
        "ia": "17.83",
        "posicion": 6,
        "totalPromocion": 19
    },
    {
        "idMiembro": 195,
        "ia": "17.79",
        "posicion": 7,
        "totalPromocion": 19
    },
    {
        "idMiembro": 161,
        "ia": "17.65",
        "posicion": 8,
        "totalPromocion": 19
    },
    {
        "idMiembro": 103,
        "ia": "17.65",
// this element has the same 'posicion' value than the previous one
        "posicion": 8,
        "totalPromocion": 19
    },
    {
        "idMiembro": 187,
        "ia": "17.57",
        "posicion": 10,
        "totalPromocion": 19
    },
    {
        "idMiembro": 178,
        "ia": "17.50",
        "posicion": 11,
        "totalPromocion": 19
    },
    {
        "idMiembro": 163,
        "ia": "17.42",
        "posicion": 12,
        "totalPromocion": 19
    },
    {
        "idMiembro": 28,
        "ia": "17.29",
        "posicion": 13,
        "totalPromocion": 19
    },
    {
        "idMiembro": 7,
        "ia": "17.21",
        "posicion": 14,
        "totalPromocion": 19
    },
    {
        "idMiembro": 104,
        "ia": "17.19",
        "posicion": 15,
        "totalPromocion": 19
    },
    {
        "idMiembro": 100,
        "ia": "17.12",
        "posicion": 16,
        "totalPromocion": 19
    },
    {
        "idMiembro": 84,
        "ia": "16.90",
        "posicion": 17,
        "totalPromocion": 19
    },
    {
        "idMiembro": 152,
        "ia": "16.89",
        "posicion": 18,
        "totalPromocion": 19
    },
    {
        "idMiembro": 184,
        "ia": "14.48",
        "posicion": 19,
        "totalPromocion": 19
    }
]

Thanks

where to store jwt tokens with angular [closed]

i have a web app and im using JWT token to identify users, for the moment im savng the token within the state using ngrx like this:

 export const authReducer = createReducer(
  initialAuthState,
  on(LoginSuccess, LoginSuccessNotEnabled, ValidationSuccess, LoginSuccessNotSetUp, (state, action) => ({
    ...state,
    isLoggedIn: true,
    token: action.token
  }))
);

but since the state gets lost when reloading pages, what is a more durable way of storing said token. i see localStorage floating around but that is exposed to XSS, and cookies are cumbersome since my backend is set to verify auth headers and not cookies.

Combining Multiple Toggle Functions

I have three clunky ‘open div/aside’ functions that I’d like to condense into one simple, streamlined function that will take any number of aside elements as arguments. I am only using Vanilla JS for this project, so any vanilla advice is appreciated.

Here is my clunky JS:

const buttonOne = document.querySelector("#toggle1");
const buttonTwo = document.querySelector("#toggle2");
const buttonThree = document.querySelector("#toggle3");    
const windowOne = document.querySelector("#window1");
const windowTwo = document.querySelector("#window2");
const windowThree = document.querySelector("#window3");
const windows = document.querySelectorAll("aside");

function toggleOne() {
    if (windowOne.style.display === "none") {windowOne.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; windowOne.classList.add('active')} else {  
        windowOne.style.display = "none";}
}

function toggleTwo() {
    if (windowTwo.style.display === "none") {windowTwo.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; windowTwo.classList.add('active')} else {  
        windowTwo.style.display = "none";}
}

function toggleThree() {
    if (windowThree.style.display === "none") {windowThree.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; windowThree.classList.add('active')} else {  
        windowThree.style.display = "none";}
}

And here is my non-functioning attempt at a general function; 100% chance I’m missing something obvious:

function toggle(event) {
    if (event.target.style.display === "none") {event.target.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; event.target.classList.add('active')} else {  
        event.target.style.display = "none";}
}

This is the body of my HTML, with toggle() as the onclick function:

<div id="frame">
      <button id="toggle1" onclick="toggle()">toggle 1</button>
      <button id="toggle2" onclick="toggle()">toggle 2</button>
      <button id="toggle3" onclick="toggle()">toggle 3</button>
      <aside
        draggable="true"
        id="window1"
        onclick="bringForward(this)"
        style="display: none"
      >
        I'm on the move!
      </aside>
      <aside
        draggable="true"
        id="window2"
        onclick="bringForward(this)"
        style="display: none"
      >
        Here we go!
      </aside>
      <aside
        draggable="true"
        id="window3"
        onclick="bringForward(this)"
        style="display: none"
      >
        All together now!
      </aside>
    </div>

How to go about converting Node.js Add-On bindings in C++ to target compilation to WASM?

Context

There’s an existing HTTP/3 and WebTransport library written exclusively for Node.js, using Node-API. The server implementation works with Chromium and Firefox as clients. node runs the server just fine. bun can run the server though exists with an error

E0413 22:42:56.932056   82865 quic_connection.cc:2613] quic_bug_12714_21: ProcessUdpPacket must not be called while processing a packet.
terminate called after throwing an instance of 'Napi::Error'
  what():  ReadableStream is not readable
Aborted

deno starts the server, then errors when client tries to connect

terminate called after throwing an instance of 'Napi::Error'
  what():  this.socketInt.getSendQueueCount is not a function
Aborted

Deno’s HTTP/3 WebTransport implementation works for deno and chrome as clients, does not work when Firefox is the client.

So I’m selecting the Node.js, Node-API implementation for my purposes, due to the broadest reach for usage among JavaScript runtimes.

Chore

Figure out a way to convert the Node-API bindings in C++ to WASM (with or without WASI support) for the capability to run the same server code using node, deno, bun, and eventually in chrome.

The binding look like this

    void Http3WTSessionJS::processStream(bool incom, bool bidi, uint64_t sendOrder, uint64_t sendGroupId, Http3WTStream *stream)
    {
        Napi::HandleScope scope(Env());
        Http3Constructors *constr = Env().GetInstanceData<Http3Constructors>();
        Napi::Object strobj = constr->stream.New({});
        Http3WTStreamJS *strjs = Napi::ObjectWrap<Http3WTStreamJS>::Unwrap(strobj);
        strjs->setObj(stream);
        if (!stream->gone())
            strjs->Ref();

        stream->setJS(strjs);

        Napi::Object objVal = Value().Get("jsobj").As<Napi::Object>();

        Napi::Object retObj = Napi::Object::New(Env());
        retObj.Set("stream", strobj);
        retObj.Set("incoming", incom);
        retObj.Set("bidirectional", bidi);
        retObj.Set("sendOrder", sendOrder);
        retObj.Set("sendGroupId", sendGroupId);

        objVal.Get("onStream").As<Napi::Function>().Call(objVal, {retObj});
    }

and there’s a bunch of them

Here are some pointers for http/3: https://github.com/fails-components/webtransport/blob/master/transports/http3-quiche/src/http3wtsessionvisitor.cc

all these use NAPI for node binding and would need a replacement, if compiled to wasm. (Including the mechanims for alarams and napialarmfactory and sockerjswriter.cc.

There’s a tsconfig.json and an existing build roadmap that uses cmake-js that includes lines such as

switch (argv[2]) {
    case 'prebuild':
      try {
        await prebuild([
          '-t',
          '6',
          '-r',
          'napi',
          '--strip',
          ...pbargspre,
          '--backend',
          'cmake-js',
          '--',
          ...pbargs
        ])
      } catch (error) {
        console.log('prebuild failed')
        process.exit(1)
      }
      break
    case 'install': 
      try {
        const pbres = await prebuildInstall([
          '-r',
          'napi',
          '-d',
          '-t',
          '6',
          '--verbose'
        ])

Status, options

If no one has encountered this case and documented their steps, then the default answer is do the necessary conversions in preparation for compilation to WASM, and eventually JavaScript, using Binaryen’s wasm2js, by hand.

Question

Has anybody encountered this kind of exiting code, and used some automated existing build system that converts Napi bindings, to exported functions which a tool such as WASI-SDK’s clang, or even Emscripten; if yes, what’s your roadmap?

Unable to read properties of document.body.style [duplicate]

I’m trying to set the style of a body element, but I’m getting this error:

Uncaught TypeError: Cannot read properties of null (reading 'style')
    at updateColour (coloured_fade.html:15:22)

I thought that this might be because the body element hasn’t loaded yet but it is scheduled in (and thus runs after) the onload event handler, which means the body should have loaded.

This is my code:

<!DOCTYPE html>
<html>
    <head>
        <title>Coloured Fade</title>
        <style>
            html, body {
              height: 100%;
            }
        </style>
        <script>
            let body = document.body;
            var i = 0;
            var timerId;
            function updateColour() {
                body.style.backgroundColor = "hsl(${i}, 100, 45)";
                i++;
            }
            window.onload = function() {timerId = setInterval(updateColour, 20);};
        </script>
    </head>
    <body>
        <!-- blank, this is where the colour should be -->
    </body>
</html>

If it’s relevent, I’m viewing the page in the Chromium browser.

How to run a button’s click event using just a keyboard shortcut instead of actually clicking

DevTools screenshot

I want to run the “share” action right away via keyboard shortcut, skipping the clicking. Is this possible?

Normally, what I do is

  1. Using AHK, click the top right share button.

  2. Wait a second for the “share chat” dialog.

  3. Then click the share (I want to run this action right away via keyboard shortcut)

function sK() {} <— this is the function that shows on all the button events; different actions, such as “new chat” and “share,” use the same function.

// ==UserScript==
// @name         TEST GLOBAL: DETECT KEY (ALT + K)
// @match        *://*/*
// ==/UserScript==

(function() {
    'use strict'

    document.addEventListener('keydown', function(event) {
        if (event.altKey && event.key === 'k') { // alt + key
            let SHARE_BUTTON = document.querySelector(".bg-text-000")

            // ---------- I COULD DO THIS, BUT THIS IS NOT WHAT I WANT ----------
            let TOP_RIGHT_SHARE_BUTTON = document.querySelector("#top-right-button")
            TOP_RIGHT_SHARE_BUTTON.click()
        }
    })
})()

Resolving CORS Error in Python Stock Analyzer

I’ve been working on this stock analysis and prediction web application (python backend, JS/React frontend) and I keep getting “Cross-Origin Request Blocked” when I have it try to calculate indicators. Backend code below, any assistance is appreciated.

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import yfinance as yf
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
from ta.trend import SMAIndicator, MACD
from ta.momentum import RSIIndicator
from ta.volatility import BollingerBands

app = FastAPI(title="Stock Analysis and Prediction Platform")

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"]
)

class StockRequest(BaseModel):
    symbol: str
    period: str = "1y"

class PredictionRequest(BaseModel):
    symbol: str
    features: List[str]
    target: str
    days_ahead: int = 5
    model_type: str

@app.get("/")
async def root():
    return {"message": "Welcome to Stock Analysis and Prediction API"}

@app.post("/stock/historical")
async def get_historical_data(request: StockRequest):
    try:
        # Get historical data
        stock = yf.Ticker(request.symbol)
        df = stock.history(period=request.period)
        
        if df.empty:
            raise HTTPException(status_code=404, detail=f"No data found for symbol {request.symbol}")
        
        # Convert DataFrame to list of dictionaries
        df.index = df.index.strftime('%Y-%m-%d')
        return df.reset_index().to_dict('records')
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/stock/indicators")
async def calculate_indicators(request: StockRequest):
    try:
        # Get historical data
        stock = yf.Ticker(request.symbol)
        df = stock.history(period=request.period)
        
        if df.empty:
            raise HTTPException(status_code=404, detail=f"No data found for symbol {request.symbol}")
        
        # Calculate indicators
        # RSI
        rsi = RSIIndicator(close=df['Close'], window=14)
        df['RSI'] = rsi.rsi()
        
        # MACD
        macd = MACD(close=df['Close'])
        df['MACD'] = macd.macd()
        
        # Bollinger Bands
        bollinger = BollingerBands(close=df['Close'])
        df['BB_high'] = bollinger.bollinger_hband()
        df['BB_low'] = bollinger.bollinger_lband()
        
        # Convert DataFrame to list of dictionaries
        df.index = df.index.strftime('%Y-%m-%d')
        return df.reset_index().to_dict('records')
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/stock/predict")
async def predict_stock(request: PredictionRequest):
    try:
        # Get historical data
        stock = yf.Ticker(request.symbol)
        df = stock.history(period="2y")
        
        if df.empty:
            raise HTTPException(status_code=404, detail=f"No data found for symbol {request.symbol}")
        
        # Prepare features
        for feature in request.features:
            if feature not in df.columns:
                raise HTTPException(status_code=400, detail=f"Feature {feature} not found")
        
        X = df[request.features].values
        y = df[request.target].values
        
        # Split data
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
        
        # Train model
        if request.model_type == "linear":
            model = LinearRegression()
        elif request.model_type == "random_forest":
            model = RandomForestRegressor(n_estimators=100, random_state=42)
        else:
            raise HTTPException(status_code=400, detail="Unsupported model type")
        
        model.fit(X_train, y_train)
        y_pred = model.predict(X_test)
        
        # Calculate metrics
        mse = mean_squared_error(y_test, y_pred)
        r2 = r2_score(y_test, y_pred)
        
        # Predict next n days
        last_data = df[request.features].values[-1:]
        future_pred = model.predict(last_data)
        
        return {
            "current_price": float(df['Close'].iloc[-1]),
            "predicted_price": float(future_pred[0]),
            "mse": float(mse),
            "r2": float(r2),
            "days_ahead": request.days_ahead
        }
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000) 

I expected it to calculate technical indicators (RSI, Bollinger bands, etc.), but I get “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/stock/indicators. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500.”

Angular Memory Management

I am trying to understand if there is an easy way to unsubscribe automatically from observables/subjects.

For example, lets say I have a component

@Component({
   selector: 'mySelector',
   template: `<div>Hello World</div>`,
   styleUrls: [ 'myStyles.scss' ]
})
export class MyComponent {
   constructor(private service: MyService){ }
   ngOnInit()
   {
      /// Forgot to store subscription!!!!!!!!!!!!!!!
      this.service.clickStream$.subscribe( clickEvent => {
         DoSomething();
      } );
   }

   DoSomething()
   {
      console.log('DoSomething');
   }

}
      

Here the developer has forgotten to store the subscription or call unsubscribe on the subscription. Ideally, should have stored the subscription and called subscription.unsubscribe() in the ngOnDestroy.

In C++, we have smartpointers like shared_ptr/auto_ptr. Is there anything similar in Angular/Typescript that automatically unsubscribes in case a developer forgets.

Authenticate to Google Language API using API Key for REST based web app

I am receiving an error 401 when trying to authenticate to Google API using an API Key.

The following is the javascript code used to make the call:

function test()
{
        const outputElement = document.getElementById('output');

        const apiUrl = 'https://translation.googleapis.com/language/translate/v2';

        const requestOptions = {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer APIKEYINSERTEDHERE',
                'x-goog-user-project': 'projectname',
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: {
                'q': 'the house is built with wood',
                'target': 'fr-CA'
            },
        };

        fetch(apiUrl, requestOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                outputElement.textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

Same results happen when using postman:
URL: https://translation.googleapis.com/language/translate/v2
Method: POST

Query Params:
q=the house is built with wood
target=fr-CA

Headers
x-goog-user-project: projectname
Authorization: Bearer APIKEYINSERTEDHERE
Content-Type: application/json; charset=utf-8

Response
{
“error”: {
“code”: 401,
“message”: “Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.”,
“errors”: [
{
“message”: “Invalid Credentials”,
“domain”: “global”,
“reason”: “authError”,
“location”: “Authorization”,
“locationType”: “header”
}
],
“status”: “UNAUTHENTICATED”,
“details”: [
{
“@type”: “type.googleapis.com/google.rpc.ErrorInfo”,
“reason”: “ACCESS_TOKEN_TYPE_UNSUPPORTED”,
“metadata”: {
“method”: “google.cloud.translate.v2.TranslateService.TranslateText”,
“service”: “translate.googleapis.com”
}
}
]
}
}

Appreciate any insights anyone has why I can’t make a basic request using the API key for authentication.

Various authentication methods.
Read the documentation. Debugged using POSTMAN
The error messages keep changing.

ENOENT: no such file or directory, open ‘E:Projectsreact_practiceNext-Projectchat-apptestdata5-versions-space.pdf’

While parsing the pdf in nextjs 15 javascript, I’m having an this error, ENOENT: no such file or directory, open ‘E:Projectsreact_practiceNext-Projectchat-apptestdata5-versions-space.pdf’

API –

import { NextResponse } from "next/server"
import pdfParse from 'pdf-parse'

export const POST = async (req) => {
    try {
        const formData = await req.formData()
        const file = formData.get('file')
        
        if (!file) {
            return NextResponse.json({ error: 'No file uploaded' }, { status: 400 });
          }
        
          const buffer = Buffer.from(await file.arrayBuffer());
          const data = await pdfParse(buffer);
        
          return NextResponse.json({ text: data.text }, { status: 200 });
    } catch (error) {
        console.error('PDF processing error:', error)
        return NextResponse.json({ message: 'PDF processing failed' }, { status: 500 })
    }
}

Page.jsx –

const handleUpload = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
  
    const response = await fetch('/api/convert', {
      method: 'POST',
      body: formData,
    });
  
    const data = await response.json();
    console.log(data.text);
  };

conflict mmenu.js and Google CSE

I use mmenu and want to implement the Google search engine.
All works fine, except that some results show “Close submenu”, then some keywords that are nowhere to be found in the source code of that page, and then again “Close submenu”. In other search results it shows “Open submenu”.

So in mmenu.js I adjusted this line of code:

    text:{closeMenu:"Close menu",closeSubmenu:"Close submenu",openSubmenu:"Open submenu",toggleSubmenu:"Toggle submenu"}

into

    text:{closeMenu:"",closeSubmenu:"",openSubmenu:"",toggleSubmenu:""}

but it still shows in the search results.

Did anyone else encounter this issue, and how to make sure it doesn’t appear?

Javascript Obfuscator and Decryption [closed]

I have a set of sequential APIs to crack.
I did manage to crack the initial ones, but I am stuck at the last stage.
Please check the json file here:
https://drive.google.com/file/d/11eL5RGz4LyHhPk45Ki_r_hGs8JNpzDOd/view?usp=sharing

Here is the code after De-Obfuscation:
https://drive.google.com/file/d/13hIAll0QN3ZFoD8LM3ifIvFPqBlSZOz2/view?usp=sharing

I am not sure about the encryption used for the text after the eval function.
Someone please decrypt it for me or at least tell me how to separate and decrypt using different methods.