NodeJS Dynamic Import Modules from another module

ModuleA
    src
        index.js
        modules
            utility.js


ModuleB
    src
        framework
            activities
                activity.js

ModuleA is my main “runnable” module.
ModuleB is like a framework library or SDK that Module A depends on.

The activity.js in ModuleB has to dynamically invoke a module in ModuleA.

const module = await import(await import.meta.resolve(`${moduleName}`, import.meta.url));
await module.execute(...);

The problem I have is the moduleName string that Module B expects is looking ugly.

"../../../../ModuleA/src/modules/utility.js"

I’m imagining there must be a better way to express this path.

I simply want to be able to pass this:

"modules/utility.js"

Everything upto ModuleA/src must be made implicit and made aware to ModuleB somehow.

iterate NodeList [] Object with for..of but can’t log values involved

studying this self-executing function -trying to understand what it’s doing
can’t log E to see values of -from E.ep it’s clearly an object

setTimeout pulls values out to define what the for-loop is using -but
how to log E and see the value(s) of?
try to push E into a pulled const array but array remains same

someone to help me understand value of E object?

const pulled = [];//added study
(function(){
  const r=document.createElement("link").relList;
    const za = r.supports("modulepreload");//added study
    const zb = document.querySelectorAll('link[rel="modulepreload"]');//added study
    const zc = document.createElement("link");//added study
    pulled.push('za');pulled.push(za);//added study
    pulled.push('zb');pulled.push(zb);//added study
    pulled.push('zc');pulled.push(zc);//added study
  if(r&&r.supports&&r.supports("modulepreload"))return;
  for(const E of document.querySelectorAll('link[rel="modulepreload"]'))
    A(E);
  new MutationObserver(
    E=>{
      for(const e of E)
        if(e.type==="childList")
          for(const C of e.addedNodes)C.tagName==="LINK"&&C.rel==="modulepreload"&&A(C)
    }).observe(document,{childList:!0,subtree:!0});
  function t(E){
    const e={};
    return E.integrity&&(e.integrity=E.integrity),E.referrerPolicy&&(e.referrerPolicy=E.referrerPolicy),E.crossOrigin==="use-credentials"?e.credentials="include":E.crossOrigin==="anonymous"?e.credentials="omit":e.credentials="same-origin",e}
  function A(E){
    if(E.ep)return;
    E.ep=!0;
    const e=t(E);
    fetch(E.href,e)}
})();


//added study.. 
setTimeout(function () {
    console.log("pulled", pulled)   
  for(const E of document.querySelectorAll('link[rel="modulepreload"]'))
    A(E);
  new MutationObserver(
    E=>{pulled.push(E);
      for(const e of E)
        if(e.type==="childList")
          for(const C of e.addedNodes)
            C.tagName==="LINK"&&C.rel==="modulepreload"&&A(C)
            pulled.push(E);
    }).observe(document,{childList:!0,subtree:!0});
  function A(E){pulled.push(E);
    if(E.ep)pulled.push(E);
    E.ep=!0;
    const e=t(E);
    pulled.push(E.href,e);}
  function t(E){pulled.push(E);
    const e={};
    pulled.push(E.integrity);pulled.push(e.integrity);pulled.push(E.referrerPolicy);pulled.push(E.crossOrigin);pulled.push(e.credentials);}
}, 9000);
setTimeout(function () {console.log(":pulled:", pulled)},12000);

log results..

pulled 
Array(6) [ "za", true, "zb", NodeList [], "zc", link ]

:pulled: 
Array(6) [ "za", true, "zb", NodeList [], "zc", link ]
  • notice E never gets pushed into pulled array that I can’t further
    understand it’s value why not?
  • lines marked with ‘added study’ were
    added in an attempt to pull out the value of E and log it
  • within setTimeout replaced return statements with array push operations in
    attempt to collect value of E (no value pushed)

Using jQuery to color background, text and svg on scroll

I’m very much a novice here, but pushing myself to learn. I’ve been building a site from scratch using HTML, Tailwind CSS and (now) jQuery (after failing miserably with JavaScript) for the last few days. In my site I have a “navigation bar” and in this bar I have some text links and an svg icon that is also a link. I’ve added some neat hover effects like changing the color of the text links and having a line grow from left-to-right underneath those links. All that was working fine so I moved on to add an effect where once you scroll down the background-color of the navbar changes from transparent to white. The text links also change color from white to black. The trouble I am having and can’t seem to figure out:

  1. I can’t get the svg icon color change on scroll to work as expected. The on hover color change effect works, and I can get it to change from black to white after scrolling down then back up to the top…but I can’t seem to set the default/starting color for this icon to be white without it overriding any scroll-color-change effects. As of now, it starts off black (which you can barely see it as the navbar sits on top of a darkish looping video).

  2. Whenever I scroll down and the jQuery script kicks in, the background and text links change color as expected, however I lose the on hover color change effect for the text links. Normally it changes from white to gold, but this is lost after scrolling. The animated growing underline still works though.

HTML & jQuery:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="./output.css" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body>
  
    <nav class="navigation h-20 sticky top-0 flex items-center justify-between flex-wrap p-6 z-20">
      <div class="flex items-center flex-shrink-0 mr-6">
        <a href="#" class="nav-item block mt-2 lg:inline-block lg:mt-0 hover:text-custom-gold">NAME GOES HERE</a>
      </div>
      <div class="block lg:hidden">
        <button cla ss="flex items-center px-3 py-2 border rounded text-white-200 border-white-400 hover:text-black hover:border-black">
          <svg class="fill-current h-3 w-3" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><title>Menu</title><path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z"/></svg>
        </button>
      </div>
      <div class="w-full block flex-end lg:flex lg:items-center lg:w-auto">
        <div class="text-base lg:flex-end">
          <a href="#responsive-header" class="nav-item block mt-2 lg:inline-block lg:mt-0 mr-9 nav-link-container">
            ABOUT
          </a>
          <a href="#responsive-header" class="nav-item block mt-2 lg:inline-block lg:mt-0 mr-9 nav-link-container">
            EXPERIENCE
          </a>
          <a href="#responsive-header" class="nav-item block mt-2 lg:inline-block lg:mt-0 mr-9 nav-link-container">
            CREDENTIALS
          </a>
          <a href="#responsive-header" class="nav-item block mt-2 lg:inline-block lg:mt-0 mr-9 nav-link-container">
            PORTFOLIO
          </a>
          <a href="#" class="linkedin-logo inline-block"> <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" class="block mt-2 lg:inline-block lg:mt-0 nav-link-container" viewBox="0 0 16 16">
            <path d="M0 1.146C0 .513.526 0 1.175 0h13.65C15.474 0 16 .513 16 1.146v13.708c0 .633-.526 1.146-1.175 1.146H1.175C.526 16 0 15.487 0 14.854zm4.943 12.248V6.169H2.542v7.225zm-1.2-8.212c.837 0 1.358-.554 1.358-1.248-.015-.709-.52-1.248-1.342-1.248S2.4 3.226 2.4 3.934c0 .694.521 1.248 1.327 1.248zm4.908 8.212V9.359c0-.216.016-.432.08-.586.173-.431.568-.878 1.232-.878.869 0 1.216.662 1.216 1.634v3.865h2.401V9.25c0-2.22-1.184-3.252-2.764-3.252-1.274 0-1.845.7-2.165 1.193v.025h-.016l.016-.025V6.169h-2.4c.03.678 0 7.225 0 7.225z"/>
          </svg>
          </a>
        </div>
      </div>
    </nav>

  <div class="h-screen mx-auto bg-black flex flex-col items-center relative video-container">
    <video autoplay loop muted class="w-auto min-w-full min-h-full max-w-none absolute top-0 left-0 z-10">
      <source src="this is a link to a local video file (looping) which serves as the background for my navigation bar and first section" type="video/mp4" />Your browser does not support the video tag.</video>
  </div>

  <div class="h-80 mx-auto bg-green-300 flex flex-col justify-center items-center text-5xl">
      CONTENT TO BE ADDED
  </div>

  <div class="h-20 mx-auto bg-black text-white flex flex-col justify-center items-center text-5xl">
      CONTENT TO BE ADDED 
  </div>

<script>jQuery(document).scroll(function() {
  if (jQuery(this).scrollTop() > 80) {   
    jQuery('.navigation').css({"background":"white"});
    jQuery('.nav-item').css({"color":"black"});
    jQuery('.linkedin-logo').css({"fill":"black"});
  } else {
    jQuery('.navigation').css({"background":"transparent"});
    jQuery('.nav-item').css({"color":"white"});
    jQuery('.linkedin-logo').css({"fill":"white"});
  }
});</script>

</body>
</html>

CSS:

@tailwind base;
@tailwind components;
@tailwind utilities;

.video-container { 
  position: static !important;
}

.video-container video { 
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}

.nav-link-container {
  position: relative;
}

.nav-link-container::after {
  content: "";
  width: 0%;
  height: 2px;
  position: absolute;
  bottom: 0;
  left: 0;
  background-color: #e0bc75;
  -webkit-transition: .3s;
  -moz-transition: .3s;
  -ms-transition: .3s;
  -o-transition: .3s;
  transition: all .3s ease;
}

.linkedin-logo {
    fill:white;
}

.nav-link-container:hover::after {
  width: 100%;
}
  
.nav-link-container {
    position: relative;
}
  
.nav-link-container path {
    transition: fill 0.3s ease;
}

.navigation {
    background-color: transparent;
    color: white;
}

.nav-item {
    color:white;
}

.navigation:hover {
    color: #e0bc75;
    transition: all .3s ease
}

Maybe I’m just tired and need to take a break as I’ve been at it 10+ hours a day, but this is the only way I learn anything (obsessive focus). 😉

I think I covered this in the previous section, sorry I didn’t realize there would be another section so I crammed it all into the first one! 🙂

XSS working with html tags but not javascript

So i have found an xss in a website where i could inject up html in the url, any html tags are not encoded and they are executed by the browser, its an case of DOM XSS, the problem comes when i try to execute javascript, it does not happen, maybe it could be some form of WAF but i doubt it is the case

im able to inject html tags, the script tags does not show either on the DOM, only the html tags, every javascript instance i tried, did not show up neither execute, the parameter im in is in a , tried breaking out of it but had no luck, anyone got an idea of what could i do to perform an xss with javascript?

Anyway to obfuscate a input field to show only the last 4 digits when typing and still maintaining the full output?

In other words the exact same thing as with password fields but show the last 4 digits instead of all stars.

I have somewhat of a weird working way to do this and was wondering if anyone has anything better.

https://codesandbox.io/p/sandbox/objective-shamir-d6n68k?file=%2Fsrc%2FApp.js

import React, { useState } from "react";

function InputComponent() {
  const [typedValue, setTypedValue] = useState("");

  const handleKeyDown = (event) => {
    const keyPressed = event.key;
    setTypedValue((prevValue) => prevValue + keyPressed);
    event.preventDefault();
  };

  const maskLastFourDigits = (value) => {
    const maskedValue = value.replace(/d(?=(?:D*d){4})/g, "*");
    return maskedValue;
  };

  return (
    <div>
      <input
        type="text"
        value={maskLastFourDigits(typedValue)}
        onKeyDown={handleKeyDown}
      />
      <p>Typed Value: {typedValue}</p>
    </div>
  );
}

export default InputComponent;

I used maskLastFourDigits function to update the value while the user types. Then I record the actual value in the handleKeyDown. It works but there are several edge cases like backspaces I need to update. Is there a better way? A library perhaps?

Apexcharts, join up series lines

I have an issue when trying to join 2 series lines in apexcharts.

{
name: 'trend-1'
trend: [
      {
        time: '2024-02-15 00:00',
        value: '99.6',
      },
      { time: '2024-02-15 01:00', value: '98.7' },
      {
        time: '2024-02-15 02:00',
        value: '98.1',
      },
      { time: '2024-02-15 03:00', value: '97.2' },
      {
        time: '2024-02-15 04:00',
        value: '97.0',
      },
      { time: '2024-02-15 05:00', value: '98.2' },
      { time: '2024-02-15 06:00', value: '98.5' },
    ],
target: '98.0'
}

I can process this data into a green and red series lines with the code below

const greenSeries = {
  name: 'KPI -1',
  data: data.trend.map(item => ({
    x: item.time,
    y: parseFloat(item.value) >= parseFloat(data.target) ? item.value : null
  }))
};

const redSeries = {
  name: 'KPI -1',
  data: data.trend.map(item => ({
    x: item.time,
    y: parseFloat(item.value) < parseFloat(data.target) ? item.value : null
  }))
};

Which gives this output

greenSeries =
    { 
        name: 'KPI -1',
        data: [
            {
                x: '2024-02-15 00:00',
                y: '99.6',
            },
            {
                x: '2024-02-15 01:00'
                y: '98.7',
            },
            {
                x: '2024-02-15 02:00'
                y: '98.1',
            },
            {
                x: '2024-02-15 03:00'
                y: null,
            },
            {
                x: '2024-02-15 04:00'
                y: null,
            },
            {
                x: '2024-02-15 05:00'
                y: '98.2',
            },
            {
                x: '2025-02-15 06:00'
                y: '98.1',
            }
        ]
    }


redSeries =
    { 
        name: 'KPI -1',
        data: [
            {
                x: '2024-02-15 00:00',
                y: null,
            },
            {
                x: '2024-02-15 01:00'
                y: null,
            },
            {
                x: '2024-02-15 02:00'
                y: null,
            },
            {
                x: '2024-02-15 03:00'
                y: '97.2',
            },
            {
                x: '2024-02-15 04:00'
                y: '97.0',
            },
            {
                x: '2024-02-15 05:00'
                y: null,
            },
            {
                x: '2024-02-15 06:00'
                y: null,
            }
        ]
    }

And the chart looks like this…

enter image description here

The issue I’ve been really struggling to get is to join the lines up…

From the data at the very top, target is 98.0, so green if above and red if below the target.

How can I join up the lines from green to red and red to green please??

Push single key with multiple values

I have an object array with the following structure:

{id: 'TestId', name: 'TestNameString', type: 'TestType' }, ...

I want to restructure the following format so that the id is the key:

TestId : { name: 'TestNameString', type: 'TestType' }

And then push them into an array.

I cant find a way to do so, so far.

Thanks in advance.

How to tell if Shift key is being held down

I am making a first-person game using Babylon.js and I’m trying to add a feature where the player can sprint (camera.speed is increased) when holding SHIFT, but SHIFT doesn’t trigger the keydown event, so I was wondering if there is a way to add this trigger, either with Babylon or just with Javascript.

making a basic todo list. on refresh when accessing local storage to keep todo list I get {“TODO_ITEM:1″:”wash dishes”} instead of wash dishes

I’ve made a very basic, bare bones todo list. When I add to the list through the input (wash dishes) it comes out as wash dishes. but on refresh when accessing the object in the array from local storage I get back {“TODO_ITEM:1″:”wash dishes”}. My main question is where did I mess up and how do I go about fixing it. I’m assuming its a mess up in how I’m accessing the data. everything I look up and find on accessing the value of an object either doesn’t work, says its not a function or comes back as [object object]. this is probably my fifth project in coding as a first timer, any and all advice helps!

//Select everything
const list = document.querySelector('#todo-list');
const form = document.querySelector('#create-todo');
const input = document.querySelector('#new-todo');
let todoCount = 1;
let obj = {};
let todo = [];


// let data = localStorage.getItem('')
//Remove button to remove li
list.addEventListener('click', function(e){
    if (e.target.tagName === 'LI'){
        e.target.classList.toggle('done');
    } else if (e.target.tagName === 'BUTTON'){
        e.target.parentElement.remove();
    }
})
// creating a new todo
form.addEventListener('submit', function(e){
    //preventing refresh
    e.preventDefault();
   //adding array to local storage
    addToLocalStorage(todo)
    //creating and adding new li w/button to list
    createLi()

console.log(localStorage)
})
//accessing local storage
function getFromLocalStorage() {
    const reference = localStorage.getItem('TODO_LIST')
    if (reference){
        todo = JSON.parse(reference) 
        renderTodo(todo)
    }
}
//new Li function
function createLi() {
    const newLi = document.createElement('li');
    const newBtn = document.createElement('button');

    newLi.innerText = input.value;
    list.append(newLi);

    newBtn.innerText = 'Remove';
    newLi.append(newBtn);
    input.value = '';
}
//add to local storage function
function addToLocalStorage(todo){
    let obj = {}

    let key = 'TODO_ITEM:' + todoCount
    console.log(obj)
    todoCount++
    obj[key] = input.value
    todo.push(obj)
    localStorage.setItem('TODO_LIST', JSON.stringify(todo))

}
// keep todo list on refresh function
function renderTodo(){
    list.innerHTML = '';


    for (let i = 0; i < todo.length; i++) { 
        console.log(todo[i])
        let indx = todo[i]
        const newLi = document.createElement('li');
        const newBtn = document.createElement('button');
        newLi.innerText = JSON.stringify(indx);
        list.append(newLi);
        console.log()
        newBtn.innerText = 'Remove';
        newLi.append(newBtn);
        console.log(indx)
    
    }
    
}
getFromLocalStorage();

Laravel Error 500 when consuming REST API

I get a 500 error

I have already applied the commands

composer dump-autoload
php artisan cache:clear
php artisan view:clear
php artisan config:clear
php artisan route:clear

but no matter what I do I get error 500 when I click.

My route/view route from routesweb.php file

Route::post('CheckApiBalance', 'CollectionController@CheckApiBalance');

My Controller file path appHttpControllersCollectionController.php

public function CheckApiBalance(Request $request)
     {
         $user = Auth::user()->email;
$rules = array(
'cedula' => 'required',
);
$validator = Validator::make ( Input::all(), $rules);
if ($validator->fails()){
return response()->json(['errors' => $validator->getMessageBag()->toarray()], 400);
}
else {
$json_response = '[{"Identity": "NO DEBT", "DetailOpe": null}]';
$cedula = $request->cedula;
$cedula = '0928356583';
// Validate that the ID contains only digits and is at least 10 characters
if ( !is_numeric($cedula) || strlen($cedula) < 10 ) {
return response()->json(['error' => 'The ID must contain only digits and be at least 10 characters'], 400);
} else {

$domiciliarioIcesa = domiciliary::where("CEDULA_CNS", "=", $cedula)->first();
$portfolio = $domiciliaryIcesa->WALLET;
// REST API URL
$url = 'https://api/Detection';

// Data to send in the POST request
$data = [
'cedula' => $cedula,
// Add other parameters if necessary
];
// Convert data to JSON format
$data_json = json_encode($data);

// Configure HTTP request options
$options = array(
'http' => array(
'header' => "Content-Type: application/jsonrn",
'method' => 'POST',
'content' => $data_json
)
);

// Create the request context
$context = stream_context_create($options);

// Make the request to the REST API
$response = @file_get_contents($url, false, $context);

// Decode the JSON response
$json_response = json_decode($response, true);

// Check if there is an error in the response
if ($json_response === null && json_last_error() !== JSON_ERROR_NONE) {
// Error decoding JSON
return response()->json(['error' => 'Error decoding JSON response'], 400);
} else {
// Verify the JSON structure
if (isset($json_response['Identity']) && isset($json_response['DetailOpe'])) {
// The JSON structure seems correct
// Handle the API response
if (!empty($json_response)) {
return response()->json($json_response);
} else {
// No response from the API
return response()->json(['error' => 'No response was received from the APIn'], 400);
}
} else {
return response()->json(['error' => 'The JSON does not have the expected structure.'], 400);
}
}
// Return the API response
return response()->json($json_response);
}
}
     }

My template

// Click event of the "Check balance" button
$(document).on('click', '#consultaBtn', function(event) {
     event.preventDefault(); // Prevent the button's default behavior from being executed
     // let url = 'route("iceBalanceconsultation")';
     console.log("Consult the ICESA_COBRANZA API");
     let url = '../../CheckApiBalance';

     $.ajax({
       type: "POST",
       // Get the route URL using the route() function
       url: url,
       data: {
         'cedula': $("#cedula_icesa").val(),
       },
       success: function(data) {
         // Clear the previous content of the modal
         $('#icesaaccounts').empty();
         if (data && data.length > 0 && data[0].Identity !== 'NO DEBT' && data[0].DetailOpe !== null) {
           // Loop through the details of the operation and display them in the table
           $.each(data[0].DetailOpe, function(index, detail) {
             var row = '<tr>' +
               '<td>' + detail.IdClient + '</td>' +
               '<td>' + detail.Assignor + '</td>' +
               '<td>' + detail.Operation + '</td>' +
               '<td>' + detail.Names + '</td>' +
               '<td>' + detail.Dayslate + '</td>' +
               '<td>' + detail.Product + '</td>' +
               '<td>' + detail.Channel + '</td>' +
               '<td>' + detail.Agency + '</td>' +
               '<td>' + detail.Payment + '</td>' +
               '</tr>';
             $('#icesaaccounts').append(row);
           });
         } else {
           // If there are no transaction details or the identity is NO DEBT, display a message
           $('#accountsIcesa').html('<tr><td colspan="9" class="text-center">There are no details of the operation</td></tr>');
         }
       },
       error: function(data) {
    let message = 'Query failed:' + data.statusText;
         $('#icesaaccounts').html('<tr><td colspan="9" class="text-center">' + message + '</td></tr>');
         console.log(message);
       }
     });
});

PS: I don’t want to add libraries to the project because it is an older version and I have an error with them

Three body problem using Runge Kutta on JS

I am trying to simulate the three body problem, my current code is:

// Mass of planets
const mass = {m_1: 1, m_2: 1, m_3: 1}

function vector_sum(p1, p2){
    let vec = p1.slice()
    for(let i=0; i< p1.length; i++){
        vec[i] += p2[i]
    }
    return vec
}

function const_multiplication(c, p){
    let vec = p.slice()
    for(let i=0; i<p.length; i++){
        vec[i] *= c
    }
    return vec
}

function solve(){
    // Starting coordinates for planets
    var p1_start = {x: -1, y: 0}
    var v1_start = {x: 0.306893, y: 0.125507}

    var p2_start = {x: 1, y: 0}
    var v2_start = {x: 0.306893, y: 0.125507}

    var p3_start = {x: 0, y: 0}
    var v3_start = {x: -0.613786, y: -0.251014}
    
    let y = [p1_start.x, p1_start.y, v1_start.x, v1_start.y, 
            p2_start.x, p2_start.y, v2_start.x, v2_start.y, p3_start.x, p3_start.y, v3_start.x, v3_start.y]
    
    y = [-1, 0, 0.306893, 0.125507, 1, 0, 0.306893, 0.125507, 0, 0, -0.613786, -0.251014]

    function f(yprime, y, t){
        // We copy the values know from state into yprime
        yprime[0] = y[2]
        yprime[1] = y[3]

        yprime[4] = y[6]
        yprime[5] = y[7]

        yprime[8] = y[10]
        yprime[9] = y[11]

        yprime[2] = (y[8]-y[0]) / (Math.sqrt((y[8]-y[0])**2 + (y[9]-y[1])**2))**3 * mass.m_3 + 
                    (y[4]-y[0]) / (Math.sqrt((y[4]-y[0])**2 + (y[5]-y[1])**2))**3 * mass.m_2
        
        yprime[3] = (y[9]-y[1]) / (Math.sqrt((y[8]-y[0])**2 + (y[9]-y[1])**2))**3 * mass.m_3 +
                    (y[5]-y[1]) / (Math.sqrt((y[4]-y[0])**2 + (y[5]-y[1])**2))**3 * mass.m_2
        
        yprime[6] = (y[0]-y[4]) / (Math.sqrt((y[0]-y[4])**2 + (y[1]-y[5])**2))**3 * mass.m_1 +
                    (y[8]-y[4]) / (Math.sqrt((y[8]-y[4])**2 + (y[9]-y[5])**2))**3 * mass.m_3
        
        yprime[7] = (y[1]-y[5]) / (Math.sqrt((y[0]-y[4])**2 + (y[1]-y[5])**2))**3 * mass.m_1 +
                    (y[9]-y[5]) / (Math.sqrt((y[8]-y[4])**2 + (y[9]-y[5])**2))**3 * mass.m_3
        
        yprime[10] = (y[0]-y[8]) / (Math.sqrt((y[0]-y[8])**2 + (y[1]-y[9])**2))**3 * mass.m_1 +
                    (y[4]-y[8]) / (Math.sqrt((y[4]-y[8])**2 + (y[5]-y[9])**2))**3 * mass.m_2
        
        yprime[11] = (y[1]-y[9]) / (Math.sqrt((y[0]-y[8])**2 + (y[1]-y[9])**2))**3 * mass.m_1 +
                    (y[5]-y[9]) / (Math.sqrt((y[4]-y[8])**2 + (y[5]-y[9])**2))**3 * mass.m_2
        
        
    }

    // Parameters
    const delta_t = 0.01
    const n = 10000

    
    function runge_Kutta(t, y, f, delta_t){
        
        let k1 = Array(12).fill(0);
        let k2 = Array(12).fill(0);
        let k3 = Array(12).fill(0);
        let k4 = Array(12).fill(0);
        // K1 = f(t, p1, p2, p3)
        f(k1, y)
        // K2 = f(t + delta_t/2, (p1, p2, p3) + delta_t/2*k1)
        f(k2, vector_sum(y, const_multiplication(delta_t/2, k1)))
        // K3 = f(t + delta_t/2, (p1, p2, p3) + delta_t/2*k2)
        f(k3, vector_sum(y, const_multiplication(delta_t/2, k2)))
        // K4 = f(t + delta_t, (p1, p2, p3) + delta_t*k3)
        f(k4, vector_sum(y, const_multiplication(delta_t, k3)))
        // v(t + delta_t) = v(t) + delta_t/6*(k1 + 2*k2 + 2*k3 + k4)
        return vector_sum(y, const_multiplication(delta_t/6, vector_sum(k1, vector_sum(const_multiplication(2, k2), vector_sum(const_multiplication(2, k3), k4)))))
    }
      
    // Trajectory arrays
    p1 = [p1_start]
    v1 = [v1_start]

    p2 = [p2_start]
    v2 = [v2_start]

    p3 = [p3_start]
    v3 = [v3_start]

    // Evolution of the system
    for(let i = 0; i < n; i++){
        y = runge_Kutta(i, y, f, delta_t)
        
        p1[i+1] = {x: y[0], y: y[1]}

        p2[i+1] = {x: y[4], y: y[5]}

        p3[i+1] = {x: y[8], y: y[9]}
    }
}

The code runs fine but the results don’t make sense. The initial conditions set in the code should yield a periodic orbit representing a butterfly. Instead when I check p1[1000], I get around {x: -8, y: 19} which means is not periodic because according to the solution: https://observablehq.com/@rreusser/periodic-planar-three-body-orbits#computeShape
x and y never leave the range of (-2,2).

I believe the error is withing Runge Kutta but I don’t seem to find it.

Any help would be appreciated

Sliding input box to the bottom of the screen

I’m trying to make it so that when a user clicks on the input box, it will glide to the bottom of the screen, but with the way I have it implemented right now, it moves too far down and you have to scroll down on the page to actually see the input box.

Code for the page:

'use client';
import { useState, useRef, useEffect } from 'react';
import Header from '@/components/Header';
import SendChatButton from '@/components/buttons/SendChatButton';

export default function Home() {
  const [isInputFocused, setInputFocused] = useState(false);
  const formRef = useRef(null);
  const [formHeight, setFormHeight] = useState(0);

  useEffect(() => {
    if (formRef.current) {
      setFormHeight(formRef.current.offsetHeight);
    }
  }, []);

  const formStyle = isInputFocused
    ? { transform: `translateY(calc(100vh - ${formHeight}px))` }
    : {};

  return (
    <main>
      <section className='p-4 pt-32'>
        <div>
          <h1 className='text-6xl font-bold'>
            Your very own<br /> personal designer
          </h1>
          <h2 className='text-xl mt-6'>Makes finding outfits so much easier</h2>
        </div>
        <form 
          ref={formRef}
          style={formStyle}
          className="mt-6 flex shadow-md transition-transform duration-1000 ease-in-out"
        >
          <input
            type="text"
            placeholder='Message your personal designer...'
            className="p-2 border border-gray-300 rounded-md block w-full text-sm outline-none"
            onFocus={() => setInputFocused(true)}
            onBlur={() => setInputFocused(false)}
          />
          <SendChatButton />
        </form>
      </section>
    </main>
  );
}


Issue with Fetching Data from Alphavantage API in Google Apps Script

Im encountering an issue with fetching data from the Alphavantage API using Google Apps Script. I have a script set up to fetch data for four specific functions (“OVERVIEW”, “BALANCE_SHEET”, “CASH_FLOW”, “INCOME_STATEMENT”), with the ticker symbol dynamically retrieved from cell I6 in my Google Sheets.

However, when I run the script, it fetches data successfully for the ticker symbol, for the first 4 cycles it fetches data succesfuly (as it should) but in fifth, additional unwanted cycle the function name passed to the API changes to undefined, resulting in a URL like: https://www.alphavantage.co/query?function=undefined&symbol=aapl&apikey=9R6A1KGBO4C1CYWD.

I’ve checked my code thoroughly and ensured that the function names are correctly passed to the getStock function, yet the issue persists. Any insights or suggestions on resolving this would be greatly appreciated!

const apiKey = "XXXXXX"; 
const alphaVantageBaseUrl = "https://www.alphavantage.co/query";

async function fetchData(functionUrl) {
  try {
    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    const sheetWithTicker = spreadsheet.getSheets()[2]; 
    const tickerSymbol = sheetWithTicker.getRange("I6").getValue();
    const url = `${functionUrl}&symbol=${tickerSymbol}&apikey=${apiKey}`;
    console.log("URL to fetch: " + url);

    const response = await UrlFetchApp.fetch(url);
    if (response.getResponseCode() === 200) {
      return JSON.parse(response.getContentText());
    } else {
      throw new Error(`Unable to fetch data. Err: ${response.getResponseCode()}`);
    }
  } catch (error) {
    throw new Error(`Error occurred during fetch: ${error}`);
  }
}

async function fetchAllData() {
  try {
    const functionUrls = [
      `${alphaVantageBaseUrl}?function=OVERVIEW`,
      `${alphaVantageBaseUrl}?function=BALANCE_SHEET`,
      `${alphaVantageBaseUrl}?function=INCOME_STATEMENT`,
      `${alphaVantageBaseUrl}?function=CASH_FLOW`
    ];

    const fetchedData = await Promise.all(functionUrls.map(url => fetchData(url)));
    console.log("Fetched data:", fetchedData);
      
    } catch (error) {
    console.error(`Error occurred: ${error}`);
  }
}

fetchAllData();

console logs:

URL to fetch: https://www.alphavantage.co/query?function=OVERVIEW&symbol=aapl&apikey=XXXXXX
URL to fetch: https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol=aapl&apikey=XXXXXX
URL to fetch: https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol=aapl&apikey=XXXXXX
URL to fetch: https://www.alphavantage.co/query?function=CASH_FLOW&symbol=aapl&apikey=XXXXXX
URL to fetch: undefined&symbol=aapl&apikey=XXXXXX   
Error   Error: Error occurred during fetch: Exception: Bad request: http://undefined&symbol=aapl&apikey=XXXXXX
fetchData   @ Code.gs:19