Parse error with ImportJSON in google sheets, too many arguments

While trying to build a price tracking app in google sheets I’m running into an issue. I have added the following function to google sheets App Scripts:
https://github.com/bradjasper/ImportJSON/blob/master/ImportJSON.gs

Now when I try to call this function from any cell I’m getting a parse error.

I am a total novice at this, but I believe I am following the proper syntax mentioned in ImportJSON github page liked above, and in this article issued by to the site I am trying to call data from:
https://www.coingecko.com/learn/crypto-portfolio-tracker-google-sheets

I can access the API url without issue.
API request

For example when I try this:
=IMPORTJSON(“https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=1&sparkline=true&price_change_percentage=1h%2C24h%2C7d%2C30d&locale=en&precision=3?&x_cg_demo_api_key=MY_KEY”,“/name,/current_price,/market_cap,/price_change,/total_volume,/high_24h,/low_24h”,“noTruncate”,doNotDelete!$A$1)

(note I omitted my private API key above)

error says ImportJSON only takes 3 arguments, hinting at the underlined red section

Error: Operator ‘-‘ cannot be applied to types ‘bigint’ and ‘number’.ts(2365) in Typescript

I am working on a Web3 Project which is a combination of JavaScript + Typescript.

When I try to start my project it throws an error

Operator '-' cannot be applied to types 'bigint' and 'number'.ts(2365)

this error is showing on the below function on line number 10

let endBlock = startBlock + 99 > currentBlockNumber ? currentBlockNumber - 2 : startBlock + 99

Complete Function for the review:

async startBlockEvent() {
        let success = true
        schedule.scheduleJob("*/10 * * * * *", async () => {
            try {
                const provieder = new Web3(Config[this.chainId].prc)
                let currentBlockNumber = await provieder.eth.getBlockNumber()
                if (currentBlockNumber > this.asyncHeight + 3 && success) {
                    success = false
                    let startBlock = this.asyncHeight + 1
                    let endBlock = startBlock + 99 > currentBlockNumber ? currentBlockNumber - 2 : startBlock + 99
                    try {
                        let result = await this.blockTx.batchGetBlock(startBlock, endBlock, provieder)
                        let deployCollection = await this.insertCollection(result.collections)
                        let updateCollection = await this.updateCollection(result.updateCollections)
                        let updateHolder = await this.updateHolder(result.holders)
                        let insertTransfer = await this.insertTransfer(result.orders)
                        let updateDeposit = await this.updateDepositEvent(result.depositEvents)
                        let insertBlockHash = await this.insertBlockHash(result.blockHashs)
                        if (deployCollection && updateCollection && updateHolder && insertTransfer && updateDeposit && insertBlockHash) {
                            this.asyncHeight = endBlock
                            let updateConfig = this.sqlConfig ? this.sqlConfig : { chainId: this.chainId, asyncHeight: 0 }
                            updateConfig.asyncHeight = endBlock
                            this.sqlConfig = updateConfig
                            await this.Db.update("config", updateConfig)
                            console.log(`sync ${endBlock},deploy ${result.collections.length},mint ${result.mints.length} ,update collection ${result.updateCollections.length},wallet ${result.holders.length},request time ${result.requestTime} ms,handler data time ${result.handleDataTime} ms,validate block ${result.blockHashs.length}`)
                        }
                        success = true
                    } catch (error) {
                        console.log(error)
                        success = true
                    }
                }
            } catch (error) {
                success = true
            }
        })
    }

I am a newbie in typescript coding and I cloned the repository from GitHub so I didn’t try much.

that’s why I need StackOverflow’s community help regarding this issue

Why Can’t Phaser Load a Sprite when it’s in another function?

Hello community of Stack Overflow,

I’m getting started with using both JavaScript and the Phaser framework. I’m playing around with creating sprites right now, and the code from where I’m creating the sprite from is in a separate function from the “create”/creator function. This is my sprite code:

player1 = this.physics.add.sprite(100, 450, 'Billy')

player1.setBounce(0.2);
player1.setCollideWorldBounds(true);

So far, when I put the code to create the sprite in my “create” funtion, it loads in fine without issues. However, once I put it into a separate function (which I will refer to as player1Create) and call it from the create function, it ceases to work, and gives me the following error message:

Cannot read properties of undefined (reading 'add')
    at player1Create (playerRules.js?autoVer=%270.00002%27:2:24)

I tried to include the function into the scene property in the config object, but this doesn’t change the result or error log. I also added “return player1” to the function and assigned the variable of the same name in the creator function to equal player1Create, but again, doesn’t change anything.

Any help is greatly appreciated! (sorry if my question sounds a little noobish)

Redux Toolkit Returns FETCH ERROR, Network Request Failed In React Native

I am using React Native for the frontend of my project, and is using redux toolkit to parse the data to the backend. I am also using an external API in my backend, and the backend communication with the external API is working well. However, when I try to call the function in the frontend, it returns Network Request Failed. Can someone help me to pinpoint where in the codes did I make a mistake?

Here is the snippet to my APISlice in the frontend

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

const baseUrl = 'http://localhost:8080/'

export const apiSlice = createApi({
    reducerPath: 'api',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        // Payments
        createTopupIntent: builder.mutation({
            query: (data) => ({
                url: 'topup/intents',
                method: 'POST',
                body: data,
            })
        })
    })
})

export const {
    useCreateTopupIntentMutation,
} = apiSlice

Here is the code to the index.js stored inside the store folder in the frontend.

import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from './apiSlice';

export const topup = configureStore({
  reducer: {
    api: apiSlice.reducer,
  },
  // Adding the api middleware enables caching, invalidation, polling,
  // and other useful features of `rtk-query`.
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
});

And this is where the function is actually called in the frontend.

import { useCreateTopupIntentMutation } from '../../store/apiSlice'

const total = navigation.getId("amount")
  const [createTopupIntent] = useCreateTopupIntentMutation()

  const onCheckout = async () => {
    // 1. Create a payment intent
    const response = await createTopupIntent({
      amount: Math.floor(total * 1000),
    })
    console.log(response)

And here is the routes in my backend index.js.

const express = require('express')
const topupRoutes = require('./src/router/topupRoutes')
const bodyParser = require('body-parser')

const app = express()
const PORT = 8080

app.use(bodyParser.json())
app.use('/topup', topupRoutes)

app.get('/', (req, res) => {
    res.send('<h2>Hello World</h2>')
})

app.listen(PORT, "0.0.0.0",  () => {
    console.log('API is listening on PORT', PORT)
})

This is the route endpoint specification snippet.

const express = require('express')
const router = express.Router()
const stripe = require('stripe')(
    'STRIPE_SECRET_KEY'
    )

// ALL ROUTER ENDPOINTS
router.post('/intents', async(req, res) => {
    try {
        // CREATE TOP UP INTENT
        const topupIntent = await stripe.paymentIntents.create({
            amount: req.body.amount, // INTEGER
            currency: 'usd',
            automatic_payment_methods: {
                enabled: true
            }
        })
    // RETURN THE SECRET
    res.json({topupIntent: topupIntent.client_secret})
    } catch (e) {
        res.status(400).json({
            error: e.message,
        })
    }
})

module.exports = router

Javascript function not loading in Django template

I have a HTML tag that is supposed to run a function in my javascript file (app.js) when it gets clicked (this is implemented using the onclick tag property)
but instead I get the following error:
Uncaught ReferenceError: summon_chat is not defined at HTMLLIElement.onclick

But when in my javascript file I code something like this:

const list-item = document.querySelector('#listId')
list-item.onclick = function () {
    my_function()}

Then the onclick event works, what am I doing wrong?
My base.html file is located at templates/layouts/
and my index.html is located at templates/

This is my index.html fragment that calls the function:

<li onclick="console.log('CLICKED'); summon_chat(this);" class="list-group-item p-3">

This is my base.html:

{% load static %}
<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{% endblock title %}</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'styles.css' %}">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css">
    <script src="https://unpkg.com/[email protected]" integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC" crossorigin="anonymous"></script>
    <script src="{% static 'app.js' %}" type="module"></script>
    {% block script %}{% endblock script %}
</head>
<body>
    <div class="container-fluid">
        <main>{% block content %}{% endblock content %}</main>
    </div>
    
    
</body>
</html>

I already checked the dev console in my browser and the javascript file is loading correctly, I even added a console.log at the beginning of my JS file and it prints in the console, I already deleted the browser cache like 20 times, I inspected the rendering HTML and there’s nothing wrong, I already searched here for a solution, I already extended my base.html correctly in my index.html file, I already used {% load static %} in both my index.html and base.html.

How to mock const coming from process.env[Key] in vitest for a remix app

I have a function calling OpenAI fine. The API key is coming from dotenv_config_path .env file locally. For a unit test wanted to mock

import OpenAI from 'openai';


export const OPENAI_API = new OpenAI({
    apiKey: process.env['API_KEY'],
  });
  
const DEFAULT_PROMPT = `my prompt`;

export const foo = async (myprompt: string) => {
  try {
    const prompt = `${DEFAULT_PROMPT}. ${myprompt}. `;
    const model = 'gpt-3.5';

const { data, response } = await OPENAI_API.chat.completions
  .create(
    {
      model,
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 2500,
      presence_penalty: 2.0,
      temperature: 0,
      frequency_penalty: 0.05,
    },
    { timeout: 5000 }
  )
  .withResponse();


let content: string | undefined;
content = data.choices[0].message.content!;
const toReturn = { responseBody: content };

return toReturn;


 } catch (e: any) {

    throw e;
  }
};

Getting error:

Error: The API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).

The error is only when I run tests. When I actually run my app everything runs fine. My unit test:

    mockOpenAI.mockImplementationOnce(() => ({
  chat: {
    completions: {
      create: vi.fn().mockResolvedValue({
        data: { choices: [{ message: { content: 'Mocked response from OpenAI' } }] },
      }),
    },
  },
}));

vi.mock('./foo.js', () => ({
    OPENAI_API: mockOpenAI,
  }));

describe('foo', () => {
    it('should call OpenAI with the correct prompt and return the mocked response', async () => {
        const myPrompt = 'Test prompt';
        const result = await foo(myPrompt);
    
        // Assert expected behavior
        expect(mockOpenAI.chat.completions).toHaveBeenCalledWith({
          model: 'gpt-3.5',
          messages: [{ role: 'user', content: 'my prompt. Test prompt. ' }],
          // ...other options
        });
    
        expect(result).toEqual({ responseBody: 'Mocked response from OpenAI' });
      });
    
});

Navigating through div using up and down arrow keys in React

I am using arrow keys to move through the different type in Grouping:

interface GroupingInterface {
  results: Item[];
  type: Type;
  selectedIndex: number;
  onClick: (item) => void;
}

function Grouping({
  results,
  type,
  selectedIndex,
  onClick,
}: GroupingInterface) {
  switch (type) {
    case 'type1':
      return (
        <div>
          <div className="text-sm font-bold">type1</div>
          {results.map((item, index) => (
            <div
              onClick={() => onClick(item)}
              key={item.id}
              className={`cursor-pointer rounded-md px-3 py-1 hover:bg-neutral-100 ${
                index === selectedIndex ? 'bg-gray-200' : ''
              }`}
            >
              <div>
                <div>{item.id}</div>
                <div className="text-sm opacity-60">type1</div>
              </div>
            </div>
          ))}
        </div>
      );
    case 'type2':
      return (
        <div>
          <div className="text-sm font-bold">type2</div>
          {results.map((item, index) => (
            <div
              onClick={() => onClick(item)}
              key={item.id}
              className={`cursor-pointer rounded-md px-3 py-1 hover:bg-neutral-100 ${
                index === selectedIndex ? 'bg-gray-200' : ''
              }`}
            >
              <div>
                <div>{item.id}</div>
                <div className="text-sm opacity-60">type2</div>
              </div>
            </div>
          ))}
        </div>
      );
    case 'type3':
      return (
        <div>
          <div className="text-sm font-bold">type3</div>
          {results.map((item, index) => (
            <div
              onClick={() => onClick(item)}
              key={item.id}
              className={`cursor-pointer rounded-md px-3 py-1 hover:bg-neutral-100 ${
                index === selectedIndex ? 'bg-gray-200' : ''
              }`}
            >
              <div>
                <div>{item.id}</div>
                <div className="text-sm opacity-60">type3</div>
              </div>
            </div>
          ))}
        </div>
      );
  }
}

function Search({ open, setOpen }) {
  const [search, setSearch] = useState('');
  const searchResults = useSearch(search);
  const [selectedIndex, setSelectedIndex] = useState(-1);

  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    console.log(event.key);
    switch (event.key) {
      case 'ArrowUp':
        setSelectedIndex((prevIndex) => Math.max(prevIndex - 1, 0));
        break;
      case 'ArrowDown':
        setSelectedIndex((prevIndex) =>
          Math.min(prevIndex + 1, searchResults.length - 1),
        );
        break;
      case 'Enter':
        if (selectedIndex !== -1) {
          handleOnItemClick(selectedItem);
        }
        break;
      default:
        break;
    }
  };

  const groupresults = searchResults.reduce((items: any, obj) => {
    if (!items[obj.type]) items[obj.type] = [];
    items[obj.type].push(obj);
    return items;
  }, {});

  return (
    <Dialog.Root open={open} onOpenChange={(e) => setOpen(e)}>
      <Dialog.Content className="h-[24rem]">
        <TextField.Root>
          <TextField.Slot>
            <FontAwesomeIcon icon={duotone('magnifying-glass')} />
          </TextField.Slot>
          <TextField.Input
            placeholder="Search..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </TextField.Root>
        <div
          className="mt-4 flex flex-col"
          onKeyDown={handleKeyDown}
          tabIndex={0}
        >
          {Object.keys(groupresults).map((type) => (
            <Grouping
              key={type}
              results={groupresults[type]}
              type={type}
              onClick={handleOnItemClick}
              selectedIndex={selectedIndex}
            />
          ))}
        </div>
      </Dialog.Content>
    </Dialog.Root>
  );
}

export default Search;

However, the issue I am having is that it’s selecting the element at the same index in every single type. So type1 might have 3 elements and type2 has 2, but when I use the arrow key to move up or down, it selects both the first element in type1 and type2, then selects the second element in type1 and type2…etc. How do I fix this issue so that when I hit the up or down arrow, it’s moving up or down the list of <div> regardless of the type? I know it has to do with the selectedIndex being used for all types.

Any help is greatly appreciated!

Generate css using EJS?

EJS renders dynamic HTML. That’s easy. But, I would like to render css as well. EJS doesn’t support rendering of css. Sure, there are some static options available. I would like to have a few elements in the css file be changeable, for example, colours. Some users would like a dark mode. I could simply have Node.js serve up two different css files depending on user setting, that would work, but then would need another CSS file for every possible option. I would like to embed JS inside a CSS file and have Node.JS render it in the exact same fashion it currently performs on HTML.

Why? Because, that’s the easiest solution. I don’t see a reason why EJS can’t be made to work in the same fashion on a CSS file, it’s not like the syntax is complex, and surely <%= %> and <% %> could be embedded into it?

Other alternatives would be generating the css file in straight JS without any embedding. That’s a possibility.

What is the easiest way to convert a PKCS8 formatted EC Key string into a JWK using ECSDA?

I don’t care if it is the OpenSSL, Python or other ways.

The reason why I want to convert from PKCS8 string (with Elliptic Curve key) to JSON Web Key (JWK), so I can see the claims like kid, etc

I’ve tried using the eckles library.

var Eckles = require('eckles');
var pem = require('fs')
  .readFileSync('./node_modles/eckles/fixtures/privkey-ec-p256.sec1.pem', 'ascii');

Eckles.import({ pem: pem }).then(function (jwk) {
  console.log(jwk);
});

but the output only returns the kty, crv, d, x, y .. but not the kid claims.

How to make video unaccessible outside the HTML code?

I am trying to create a video streaming application. In this application, the users will be able to upload their video, which will be stored in AWS S3. When some other authorized user (followers) wants to access this video,I generate a presigned URL for the object and use this URL in the video source in HTML. It works fine, but the issue is, the users will be able to access the video link from the HTML code (if they do an inspect). They can share this link with other unauthorized people. I don’t want them to be able to access the video directly using the link.

How do I implement this?

Alternative approach – is there a way to disable “inspect” and also “save file as” ?

How to properly use Stripe Customer API for Radar when not storing any customer information

We use Stripe for customer purchases. We send their info off to stripe, get a token, pass that token to our backend and create a charge.

I’m trying to add a “Customer” object to the process to hopefully enhance the Radar fraud detection features on Stripe. Now I’m taking that token from the front-end and on the backend I look up customers with the “similar” matching name, email, and phone number, or create one if none exist.

If an exact match is found and only one result is returned I use that one, if there isn’t an exact match I take all that are available and match all the fields provided by the customer with what Stripe gives me and “add up” the number of matching fields to try to find the “best one” that matches the best.

If it’s a new Customer (to Stripe), I create the Customer and assign the payment token we received from the front-end to the customer’s payment source and then create the charge as before but with the Customer now associated with the Charge.

If there was an existing Customer, I took whatever was the best match (or the only match) and “update” that Customer with whatever information the user has provided, and assign that token to their payment method.

We don’t have customer or user accounts, we don’t store any information about them other than their purchase. So we don’t retain the Customer ID that Stripe gives us. So I have to search for it from stripe every time.

This is working just fine in testing/development, but it seems kinda weird to me to do it this way. Since I have to update the user (even if it’s just their payment method/token) every single time, I wonder if that will make tracking purchases and fraud more difficult or less reliable if I’m constantly looking up users and updating their information (or even just payment source token).

Update index position of orchard

I’m not sure where im going wrong in this code as the position doesn’t update:

function findWrongWayFruit(orchard) {
  let position = 0;

  for (let i = 0; i < orchard.length; i++) {
    if (orchard[i] === orchard[i].split('').reverse().join('')) {
      position = i;
    }
  }
  return position;
}

I am trying to update the position of the index discovered during the for loop.

Problem setting up persisted permissions for mid-level roles

I’ve been exploring CASL for managing persisted permissions. But I am stuck on assigning permissions to roles such as team managers and department heads, who are more mid-level employees. So far I have:

const roles = [
  {
    id: 1,
    name: "admin", // Has access to everything
    permissions: JSON.stringify([{ action: "manage", subject: "all" }]),
  },
  {
    id: 2,
    name: "manager", // Has access to people who they directly manage and anyone below them
    permissions: JSON.stringify([
      {
        action: "manage", //direct employee under user
        subject: "Order",
        conditions: { "owner.managerId": "{{user._id}}" },
      },
      {
        action: "manage", // his own orders
        subject: "Order",
        conditions: { "owner._id": "{{user._id}}" },
      },


    ]),
  },
];

I can give permissions to direct employees that work under a manager, but not indirect employees that work under employees he/she manages. Think tree-model

I can give permissions to direct employees that work under a manager, but not indirect employees that work under employees he/she manages. Think tree-model

Why does OpenLayers use several canvas elements for rendering when the pixel ratio is a fractional number?

I am building a feature where we export an OpenLayers map as a PNG or JPEG image. To do this we grab the OpenLayers map’s canvas element and convert it to BLOB.

I have noticed that while usually all the layers are rendered into a single canvas, sometimes OL uses several canvas elements:

enter image description here

Where I don’t understand the logic is that the trigger seems to be when the device pixel-ratio is a fractional number. For example, pixel ratios of 1.0 and 2.0 result in a single canvas being used, but 1.2 or 1.5 result in several canvases.

It’s not really a problem as I can just grab all the canvases and draw their content in a new one and so get the complete map. But I am curious to understand what the logic is behind this and if it is some kind of optimization.

Processing in JSON, Javascript Array vrs. XSLT

The input data is coming this way.

"request": "INPUT_DATA:INV_COLLECTION_{LOC0001001}:{1;2}:{00000P123456;00000P123457}_{LOC0001002}:  {2;3}:{00000P234567;00000P234568}"

Response will be:

<Output>
   <LocationList>
        <Location>LOC0001001</Location>
      <ProductList>
           <ProductRequested>00000P123456</ProductRequested>
           <SubstituteProduct>00000P123456</SubstituteProduct>
           <QuantityOnHand>1</QuantityOnHand>
           <QuantityReOrder>1</QuantityReOrder>
        </ProductList>
     </LocationList>
   <LocationList>
        <Location>LOC0001002</Location>
     <ProductList>
           <ProductRequested>00000P234567</ProductRequested>
           <SubstituteProduct>00000P234568</SubstituteProduct>
           <QuantityOnHand>2</QuantityOnHand>
           <QuantityReOrder>3</QuantityReOrder>
      </ProductList>
   </LocationList>
</Output>

Reference:
How do we process in set? Each set is separated by ‘_’ .

  1. 1st set : {LOC0001001}:{1;2}:{00000P123456;00000P123457}
  2. 2nd set : {LOC0001002}:{2;3}:{00000P234567;00000P234568}
    {LOC0001001} represents Location
    {1;2} represents Quantity On Hand, Quantity Reorder Point respectively.
    {00000P123456;00000P123457} represents Product Requested, Substitute Product
    Please advise.
var mydata = {LOC0001001}:{1;2}:{00000P123456;00000P123457}_{LOC0001002}:  {2;3}:{00000P234567;00000P234568};
var site = mydata["Location"]["QtyOH"]["QtyROP"]["Product"]["SubstProduct"];