Is it possible to use BigNumber together with Math.js in BOS?

I’ve been trying to use one of the Math library functions found within BOS but it doesn’t seem to exist.
The function I tried to use is Math.bigbumber().
This function is important since I need it to be able to have greater precision for my calculations in DeFi

I’m working on a series of components focused on the DeFi environment within BOS, I have been working with the Math library that is implemented using functions such as ceil, floor, exp and others to be able to perform the necessary calculations in the process to add liquidity , I encountered the problem that at some point in the calculations the result is rounded to a number of decimal places, this is a problem since I cannot be precise in the liquidity calculations, causing it to not enter the correct cases according to the formulas .

To solve the problem I had planned to use big numbers for the calculations, but when trying to use the function to declare bignumbers within math I realized that it was not available since it did not exist and gave a code error.

Is there a way to use big number within BOS to obtain greater precision in the calculations and for the formulas to work correctly?

is the big o runtime of an array.include method ran inside a for loop o(n) time?

this is my code. pretty simple code for finding unique values within an array. i’m confused on whether this is n time or n^2 time because the number of times the uniqueValues array is looped through is related to how big the length is. so that makes it somewhat unrelated to the for loop doesnt it?

function countUniqueValues(array) {
  let uniqueArray = []; //constant
  for (let i = 0; i < array.length; i++) { //n time
    if (uniqueArray.includes(array[i])) { //n time 
    } else {
      uniqueArray.push(array[i]); //constant time
    }
    console.log(i) //constant
    console.log(uniqueArray) //constant
  
  }
  console.log(uniqueArray.length);
  return uniqueArray.length;
}
countUniqueValues([1, 2, 3, 4, 4, 4, 7, 7, 12, 12, 13]);

I need help creating a form using HTML/JavaScript that can accept payment and text-input for user comments

As the title says, but to expand: I plan on using a payment processing service and I’d simply like a text-input space for users to submit a comment. Ideally, they’d also be able to upload a single image file (restricted to images, no other file types), but that’s not my main focus here. I’d love to get some advice on how you might go about creating a form that accepts payment and sends me the input from the comment box (to an email). Thank you in advance!

I’ll be frank, I haven’t even tried because I’m only so-so at JavaScript and I was having a devil of a time searching for the answer to my question elsewhere. I genuinely appreciate any assistance.

Counter Javascript

I’m trying to build a javascript counter, but my code bugged:
HTML:

let counterDisplayElem = document.querySelector('.counter-display');
let counterMinusElem = document.querySelector('.counter-minus');
let counterPlusElem = document.querySelector('.counter-plus');

let count = 0;

updateDisplay();

counterPlusElem.addEventListener("click", () => {
  count++;
  updateDisplay();
});

counterMinusElem.addEventListener("click", () => {
  count--;
  updateDisplay();
});

function updateDisplay() {
  counterDisplayElem.innerHTML = count;
}
<h1 class="counterdisplay">(..)</h1>
<button class="counter-minus">-</button>
<button class="counter-plus">+</button>

I looked online but I didn’t find an answer…

How do I dynamically import .ts files?

I’m working on a tool handler for OpenAI’s ChatGPT and aiming to make the tool system dynamic for easy additions. Currently, my code requires importing files containing tool information, but I’ve encountered an issue with dynamically importing TypeScript files (.ts).

Here’s my code:

// index.ts
(async () => {
    const file = await import('./time');
    console.log(file.configs);
})();
// time.ts
export function exec() {
    return "It is 12:00 AM";   
}

export const configs = {
    name: "get_time",
    description: "Get time for a specified timezone",
    props: {
        time_zone: {
            description: "The time zone you want the time for.",
            type: "string",
            required: true,
        }
    }
}

Here’s the error I run into:

Error: Cannot find module 'C:pathtime' imported from C:pathindex.ts

I attempted altering my tsconfig.json without success. Shifting the environment from Node to Bun was effective, but Bun doesn’t yet support node modules on Windows.

I switched from ts-node index.ts to node --loader ts-node/esm index.ts, which worked too. Yet, I’m unsure if this method is reliable; it appeared prone to errors.

Is there a better approach to handling tools, or is there a way to dynamically import TypeScript tools effectively?

duplicate/clone and altering content in 11ty

I have a standard group of Eleventy posts (markdown files in a folder) which build to the standard site.com/slug/index.html path. I would also like to generate an additional meta file for each of these posts at build time, which is of a different format, and would live at something like site.com/slug/file.ics. So the permalink must change. I only want to have to manage one set of files, the original markdown files contain the meta information required to build the additional file in the front-matter. So I assumed I’d be able to somehow use 2 different templates to manage how the final files were generated.

I’ve tried a handful of things, none work.

Creating a collection via glob, then using Eleventy’s pagination did not work (at least not the way I did it):

  /* in the config file */
  config.addCollection('articles_meta', (collectionAPI) => {
    return collectionAPI.getFilteredByGlob('_content/articles/*.md')
  })
/* in an article_meta.md */
---js
    pagination: {
      data: 'collections.articles_meta',
      size: 1,
      alias: 'article_meta'
    },
  
    permalink: function (data) {
        return (
          "/articles/" +
          `${this.slug(data.title)}` +
          "/file.ics"
        );
      },
  }
---

Which gives me an error about not finding collections.articles_meta. Similarly if I just try to create a data file that returns the collection directly I get the same error. I suspect I’m using the wrong tools for the job. Any suggestions?

Next.js 13.4 App Router API Route Issue: User Registration Component Failing with Undefined Request Body and res.status TypeError

I’m working on a Next.js 13.4 project and encountering issues with my API route. Despite sending data through a form, the API route receives undefined values for the request body, and I also encounter a TypeError related to the res.status function. Here’s the relevant part of my API route:

import { NextApiRequest, NextApiResponse } from 'next'
import argon2 from 'argon2'
import { RowDataPacket, ResultSetHeader } from 'mysql2'
import database from '../database'

export async function POST(req: NextApiRequest, res: NextApiResponse) {
  console.log('API Request received:', req.method, req.url)
  console.log('Solicitud recibida con datos:', req.body)
  const { firstName, lastName, email, password } = req.body

  console.log('Received data:', { firstName, lastName, email })

  if (typeof password !== 'string' || password.trim() === '') {
    console.log('Password validation failed')
    return res
      .status(400)
      .json({ message: 'Password is required and must be a string.' })
  }

  try {
    console.log('Querying for existing users with email:', email)
    const [existingUsers] = await database.query<RowDataPacket[]>(
      'SELECT id FROM Users WHERE email = ?',
      [email],
    )

    console.log('Query result:', existingUsers)
    if (existingUsers.length > 0) {
      console.log('Email already in use')
      return res.status(409).json({ message: 'Email already in use.' })
    }

    console.log('Hashing password')
    const hashedPassword = await argon2.hash(password)

    console.log('Inserting new user into database')
    const [result] = await database.query<ResultSetHeader>(
      'INSERT INTO Users (first_name, last_name, email, hashed_password) VALUES (?, ?, ?, ?)',
      [firstName, lastName, email, hashedPassword],
    )

    console.log('Insert query result:', result)
    if (result.affectedRows === 0) {
      console.log('User could not be created')
      return res.status(400).send('User could not be created.')
    }

    console.log('User created successfully:', result.insertId)
    return res
      .status(201)
      .json({ message: 'User created.', userId: result.insertId })
  } catch (error) {
    console.error('Error occurred:', error)
    return res.status(500).send('Internal Server Error')
  }
}

When I send a POST request, the console logs indicate that firstName, lastName, and email are all undefined, and I encounter a TypeError as follows:

TypeError: res.status is not a function
    at POST <route details>

I’ve verified that the frontend sends the correct data. The issue seems to be with the Next.js 13.4 App Router handling the API request.

Has anyone encountered similar issues with Next.js 13.4, specifically with the App Router and API routes? Any insights or solutions would be greatly appreciated.

How to send a form data in testcafe API request

I’m using testcafe API to make an API request. I need to use form data as the body of the post request. (The request looks something similar to ‘curl -F username=xxx -F password=xxx https://xxxxx/api/login)

const response = await t.request.post({
      url: "https://xxxxx/api/login",
      body: {'username': 'xxx', 'password':'xxxx'},
      headers: { "content-type": "multipart/form-data" }
    });

    console.log(JSON.stringify(response));
}

This question may look similar to my requirement. But I dont need a ‘Form’ option. I just want to make a post request with form data.

Unable to fetch, HTTP POST method, AWS

I have an AWS lambda funtion. It works well and returns the following:

        return {
            statusCode: 200,
            headers: {
              'Access-Control-Allow-Origin': '*',
              'Access-Control-Allow-Credentials': true,
              'Access-Control-Allow-Headers': 'Content-Type',
              'Access-Control-Allow-Methods': 'OPTIONS, PUT, POST, GET, DELETE',
            },
            body: JSON.stringify('Success'),
        };

I created an API Gateway resource and a POST method within the resource.

I made the following configuration:

  1. For the resource I enabled CORS. I selected all methods and pressed save.
  2. In the method request section I set the Request body content tyoe as application/json and Model as Empty.
  3. Mapping templates within the Integration request is set like content type equals to ‘application/json’ and the Template body contains the following code:
{
    "company": "$input.json('$.company')",
    "newGoalGroups": $input.json('$.newGoalGroups')
}
  1. The response header within the Method response section contains 3 items: ‘Access-Control-Allow-Headers’, ‘Access-Control-Allow-Methods’ and ‘ Access-Control-Allow-Origin’.
  2. The content type within the Response body equals to ‘application/json’.

I tested the method in the API gateway console and it ran successfully.

I wanted to call the lambda function from the frontend (hosted at AWS amplify):

  try {
    console.log(`Url: ${apiGatewayUrl}${resourcePath}`);
    console.log(body);
    const response = await fetch(`${apiGatewayUrl}${resourcePath}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return response;
  } catch (error) {
    console.error('Error:', error);
  }

The parameter of the fetch is correct (I have a well working GET method within the same resource group. I copied the code from there)

The error what I got: TypeError: Failed to fetch

In the console of the browser, I see the following message:

Access to fetch at ‘https://xx.execute-api.eu-north-1.amazonaws.com/prod/GoalGroup’ from origin ‘https://dev.xy.amplifyapp.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘https://dev.xy.amplifyapp.com/’ that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Within the same resource I have a GET, PUT and POST methods. The GET works well while PUT and POST run to the same error.

Please help how I can make PUT and POST work.

jQuery Trigger Key Event Failing

The site I’m trying to userscript for requires an account to see where the issue is occurring.

https://www.recipal.com/log_in

[email protected]

Then visit https://www.recipal.com/recipes/1698297/edit to see the input box in question. The script successfully inputs a value, the front-end reflects that the box is focused, but the anticipated result does not occur from simulating the keypress.

From comparing the console outputs of a simulated press and a real one, the only thing I can see that varies is the originalEvent attribute, which seemingly cannot be spoofed?

Any insights would be greatly appreciated.

jQuery code used to produce the input:

var press = jQuery.Event("keypress");
press.which = 13;
press.keyCode = 13;
press.charCode = 13;
press.key='Enter';
press.bubbles=true;

$('#search_field').attr('tabindex',1);
$('#search_field').focus().trigger('click').val("chicken");
setTimeout(()=>{

    $('#search_field').trigger(press).trigger('keyup');
},1000);

console output:

{
    "type": "keypress",
    "timeStamp": 1704464067050,
    "jQuery34105937047508940263": true,
    "which": 13,
    "keyCode": 13,
    "charCode": 13,
    "key": "Enter",
    "bubbles": true,
    "isTrigger": 3,
    "namespace": "",
    "rnamespace": null,
    "target": {
        "jQuery341059370475089402631": {
            "events": {
                "focus": [
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 118,
                        "namespace": false
                    },
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 117,
                        "namespace": ""
                    }
                ]
            },
            "focus": false
        }
    },
    "delegateTarget": {
        "location": {
            "ancestorOrigins": {},
            "href": "https://www.recipal.com/recipes/1230714/edit",
            "origin": "https://www.recipal.com",
            "protocol": "https:",
            "host": "www.recipal.com",
            "hostname": "www.recipal.com",
            "port": "",
            "pathname": "/recipes/1230714/edit",
            "search": "",
            "hash": ""
        },
        "jQuery341059370475089402631": {
            "events": {
                "mouseup": [
                    {
                        "type": "mouseup",
                        "origType": "mouseup",
                        "guid": 3,
                        "namespace": ""
                    }
                ],
                "change": [
                    {
                        "type": "change",
                        "origType": "change",
                        "guid": 5,
                        "selector": "#faSizeIngred",
                        "needsContext": false,
                        "namespace": ""
                    }
                ],
                "keypress": [
                    {
                        "type": "keypress",
                        "origType": "keypress",
                        "guid": 6,
                        "selector": "#search_field",
                        "needsContext": false,
                        "namespace": ""
                    }
                ],
                "focusin": [
                    {
                        "type": "focusin",
                        "origType": "focus",
                        "guid": 7,
                        "selector": "#search_field",
                        "needsContext": false,
                        "namespace": ""
                    }
                ],
                "click": [
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 8,
                        "selector": ".btn-addtorecipe:not(.btn-mini)",
                        "needsContext": false,
                        "namespace": ""
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 10,
                        "selector": "#pushMacs",
                        "needsContext": false,
                        "namespace": ""
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 30,
                        "namespace": "menu1"
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 54,
                        "namespace": "menu3"
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 78,
                        "namespace": "menu5"
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 102,
                        "namespace": "menu7"
                    }
                ],
                "keyup": [
                    {
                        "type": "keyup",
                        "origType": "keyup",
                        "guid": 9,
                        "selector": "#faAggredName",
                        "needsContext": false,
                        "namespace": ""
                    }
                ]
            },
            "focusin": 1
        }
    },
    "currentTarget": {
        "jQuery341059370475089402631": {
            "events": {
                "focus": [
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 118,
                        "namespace": false
                    },
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 117,
                        "namespace": ""
                    }
                ]
            },
            "focus": false
        }
    },
    "handleObj": {
        "type": "keypress",
        "origType": "keypress",
        "guid": 6,
        "selector": "#search_field",
        "needsContext": false,
        "namespace": ""
    }
}

Human input event data:

{
    "originalEvent": {
        "isTrusted": true
    },
    "type": "keypress",
    "target": {
        "jQuery341059370475089402631": {
            "events": {
                "focus": [
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 118,
                        "namespace": false
                    },
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 117,
                        "namespace": ""
                    }
                ]
            },
            "focus": false
        }
    },
    "currentTarget": {
        "jQuery341059370475089402631": {
            "events": {
                "focus": [
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 118,
                        "namespace": false
                    },
                    {
                        "type": "focus",
                        "origType": "focus",
                        "guid": 117,
                        "namespace": ""
                    }
                ]
            },
            "focus": false
        }
    },
    "timeStamp": 24011519.5,
    "jQuery34105937047508940263": true,
    "delegateTarget": {
        "location": {
            "ancestorOrigins": {},
            "href": "https://www.recipal.com/recipes/1230714/edit",
            "origin": "https://www.recipal.com",
            "protocol": "https:",
            "host": "www.recipal.com",
            "hostname": "www.recipal.com",
            "port": "",
            "pathname": "/recipes/1230714/edit",
            "search": "",
            "hash": ""
        },
        "jQuery341059370475089402631": {
            "events": {
                "mouseup": [
                    {
                        "type": "mouseup",
                        "origType": "mouseup",
                        "guid": 3,
                        "namespace": ""
                    }
                ],
                "change": [
                    {
                        "type": "change",
                        "origType": "change",
                        "guid": 5,
                        "selector": "#faSizeIngred",
                        "needsContext": false,
                        "namespace": ""
                    }
                ],
                "keypress": [
                    {
                        "type": "keypress",
                        "origType": "keypress",
                        "guid": 6,
                        "selector": "#search_field",
                        "needsContext": false,
                        "namespace": ""
                    }
                ],
                "focusin": [
                    {
                        "type": "focusin",
                        "origType": "focus",
                        "guid": 7,
                        "selector": "#search_field",
                        "needsContext": false,
                        "namespace": ""
                    }
                ],
                "click": [
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 8,
                        "selector": ".btn-addtorecipe:not(.btn-mini)",
                        "needsContext": false,
                        "namespace": ""
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 10,
                        "selector": "#pushMacs",
                        "needsContext": false,
                        "namespace": ""
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 30,
                        "namespace": "menu1"
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 54,
                        "namespace": "menu3"
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 78,
                        "namespace": "menu5"
                    },
                    {
                        "type": "click",
                        "origType": "click",
                        "guid": 102,
                        "namespace": "menu7"
                    }
                ],
                "keyup": [
                    {
                        "type": "keyup",
                        "origType": "keyup",
                        "guid": 9,
                        "selector": "#faAggredName",
                        "needsContext": false,
                        "namespace": ""
                    }
                ]
            },
            "focusin": 1
        }
    },
    "handleObj": {
        "type": "keypress",
        "origType": "keypress",
        "guid": 6,
        "selector": "#search_field",
        "needsContext": false,
        "namespace": ""
    }
}

argument of type string is not assignable to type never

I have the following variable in file Test.ts

@state()
public controller? = new Editor(this);

In one of the functions handleAssetClick in Test.ts I call the function controller.closeEditor() which is an asynchronous function

await controller.closeEditor()

I am trying to write a test for Test.ts. How do I stub closeEditor so that I can write a unit test for handleAssetClick to test whether it calls dispatchEvent. Here’s the code for handleAssetClick in Test.ts

private handleAssetClick() {
    await controller.closeEditor();
    this.dispatchEvent("event-name");
} 

Regex extract and replace HTML entities

I have some data source that I cannot control which returns strings. Sometimes these strings may have HTML character entities in them that I need to replace (only the apostrophe, &$82167;, has been identified so far, but it would be wise to consider all entities and multiple occurrences).

For example, the string The cat&#8217;s dog&#8217;s hamster ran away. should become The cat's dog's hamster ran away.

I’ve identified a starting point of a solution using fromCodePiont() along with this answer to another thread, but where I’m struggling is it does not replace the special characters and fails with multiple occurrences. I’ll keep playing around with this, but my current experiment looks as follow:

const str = "The cat&#8217;s dog's hamster ran away.";

// (?<=&#) -> postive lookbehind for '&#'
// d+     -> match for multiple digits
// (?=;)   -> lookahead for ';'
const regex = new RegExp(/(?<=&#)d+(?=;)/g);
const matched = str.match(regex); // Finds 8217

const replaced = str.replaceAll(regex, String.fromCodePoint(matched));
console.log(replaced);

This yields The cat&#';s dog's hamster ran away., which is getting there, but still some work to do. Not to mention it fails if more/other code entities are added.

API unable to fetch temperature

I want to show the temperature from ma current location.

I have put my files on the server; unblocked the location on GoogleChrome.

I have subscribed to OpenWeatherMap and copy paste the correct apiKey and I do still have this error: Unable to fetch temperature

Here is the error message from my console log:
Unchecked runtime.lastError: The message port closed before a response was received.

GET https://api.openweathermap.org/data/2.5/weather?lat=pastenumber&lon=pastenumber&units=metric&appid=YOUR_API_KEY net::ERR_INTERNET_DISCONNECTED

Error fetching weather data: TypeError: Failed to fetch at script.js:9:34

Here is the script.js :

window.addEventListener('load', () => {
    const latitude = pastenumber; 
    const longitude = pastenumber; 
    const apiKey = 'pasteNumberFromOpenWeatherMapApp';
  
    const apiUrl = `https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${latitude},${longitude}`;
  
    fetch(apiUrl)
      .then(response => {
        if (!response.ok) {
          throw new Error('Weather data not available');
        }
        return response.json();
      })
      .then(data => {
        const temperature = data.current.temp_c;
        console.log(`Current Temperature: ${temperature}°C`);
      })
      .catch(error => {
        console.error('Error fetching weather data:', error);
      });
  });
  

I am expecting to get the temperature of my current location.

Thanks for your help.

Javascript – Creating an li element using a checkbox array but with two values per checkbox?

Alright so I have three checkboxes with the values of Profile, Online, and Storage. I can get all those pushed to an array when checked and I can get the li elements created per checked item.

The issue is that each of those items also has a second “value” being “+$1/mo”, “+$2/mo”, and “+$2/mo”.

Where I’m stuck is figuring out how to attach those second “values” to the first values so that when an item is checked, it creates an li element with one p element being the name value (i.e. Profile) and a second p element with the cost value (i.e. “+$2/mo”).

Here is the code for one of the inputs:

 <input
    id="profile-checkbox"
    type="checkbox"
    value="Custom profile"
    name="add-ons"
    onclick="getAddons()"
    class="w-5 h-5 mr-2 text-blue-600 bg-gray-100 border-light-gray rounded"
  />

The JS global variables

const addonsResultList = document.getElementById("add-ons-result-list");
let addonsResult = [];

The function to get the checkbox values

// Step 3, add-ons
function getAddons() {
    let checkboxes = document.getElementsByName("add-ons");

    addonsResult = [];

    for (let i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked) {
            addonsResult.push(checkboxes[i].value);
        }
    }
}

And the function that adds everything to the results page:

function setResultsPage() {
addonsResult.forEach(function (addon) {
        const li = document.createElement("li");
        const pName = document.createElement("p");
        const pAmount = document.createElement("p");
        const text = document.createTextNode(addon);

        li.classList.add("flex", "justify-between");

        pName.appendChild(text);
        pName.classList.add("text-cool-gray", "text-sm");

        pAmount.appendChild();
        pAmount.classList.add("text-sm", "text-marine-blue");

        li.appendChild(pName);
        addonsResultList.appendChild(li);
    });
}

As of right now, I can successfully create an li element for which ever checkboxes were checked but only for the name. Getting the second “value” (amount) to be linked up with the correct first value (name) and added into the pAmount element is where I’m stuck.