Errors with Calculating the Second Focus Point of an Orbit (Ellipse)

I’m currently coding a 2d physics sim in javascript and am trying to determin the second focus of an ellipse. My current systems ecentricity is way too low and I’ve debugged it, but can’t find what is wrong with my maths. Additionally, the points moves around way too much and isn’t where it should be. I understand that it should oscillate a little bit as the other planets will also tug on the planet I’m trying to measure, but its completeley unrealistic.

The maths I’ve tried replicating
Currently I’m getting the velocity of the orbiting planet with respect to its parent (the sun) and the distance between the planet and the sun to try calculating the escentricity using e = (v × h)/μ – r/|r|. Then using this I ofset another point away from the centre of the elipse in the same direction as the semi-major axis in the opposite direction the the sun to try finding the second focus point.
My current code ↓

export function findSecondFocus(i) {
    let parentIndex = bodies[i].parentIndex;
    let parent = bodies[parentIndex];
    const relativeSpatiumVector = [
        bodies[i].position[0] - parent.position[0],
        bodies[i].position[1] - parent.position[1],
    ];
    //calculate the relative position vector of the body relative to what its orbiting
    const relativeVelocityVector = [
        bodies[i].velocity[0] - parent.velocity[0],
        bodies[i].velocity[1] - parent.velocity[1],
    ];
    //calcualte the relative velocity
    const r = Math.hypot(relativeSpatiumVector[0], relativeSpatiumVector[1]);
    // r represents the distance between the body and what it is orbiting
    // uses math.hypot to form a right angle to triangle to use pythagoras theorem to calculate the scalar distance
    const velocityScalar = Math.hypot(
        relativeVelocityVector[0],
        relativeVelocityVector[1]
    );


    const mu_sim = gravity * parent.mass; 
    const specificOrbitalEnergy = velocityScalar ** 2 / 2 - mu_sim / r;
    //calcualtes specific orbital energy which is the sum of their potetial and kinetic energies.
    //it is given by ε=v^2/2 -μ/r where μ=GM

    const a = -mu_sim / (2 * specificOrbitalEnergy);
    //calcualte the semi-major axis by rearranging ε=-μ/(2a)

    // The eccentricity vector formula is: e = (v × h)/μ - r/|r|
    const rvDot = relativeSpatiumVector[0] * relativeVelocityVector[0] +
              relativeSpatiumVector[1] * relativeVelocityVector[1];

    const rUnit = [
        relativeSpatiumVector[0] / r,
        relativeSpatiumVector[1] / r
    ];

    const eccentricityVector = [
        ((velocityScalar**2 - mu_sim / r) * rUnit[0] - rvDot * relativeVelocityVector[0]) / mu_sim,
        ((velocityScalar**2 - mu_sim / r) * rUnit[1] - rvDot * relativeVelocityVector[1]) / mu_sim,
    ];
    const eccentricityScalar = Math.hypot(
        eccentricityVector[0],
        eccentricityVector[1]
    );
    //calculate the eccentricity of the orbit
    const eccentricityUnitVector = [
        eccentricityVector[0] / eccentricityScalar,
        eccentricityVector[1] / eccentricityScalar,
    ];
    //convert ecentricity to a unit vector by dividing by its magnituted so that it has a length of 1
    const distanceFromCentre = a * eccentricityScalar; // c = ae

    // First focus is at parent position
    // Center is OPPOSITE to eccentricity direction from first focus
    const ellipseCenter = [
        parent.position[0] - distanceFromCentre * eccentricityUnitVector[0],
        parent.position[1] - distanceFromCentre * eccentricityUnitVector[1],
    ];

    // Second focus is equal distance on OTHER side of center
    const secondFocus = [
        ellipseCenter[0] - distanceFromCentre * eccentricityUnitVector[0],
        ellipseCenter[1] - distanceFromCentre * eccentricityUnitVector[1],
    ];

    //finally calculate the position of the second focus point by offsetting the position of the first focus (parent planet) by 2 times the distance from the centre of the ellipse

    console.log(secondFocus);
    console.log("Eccentricity:", eccentricityScalar);
    console.log("Semi-major axis:", a);
}

I appreciate any help 🙂

Prevent from reloading on component re-render in a tabbed Next.js dashboard

I’ve developed a tabbed UI dashboard in Next.js and React, where each new menu item opens in a new tab inside the dashboard panel. I can manage the tab mount state without issues.

However, I’m facing a problem with my component: whenever I switch tabs and the component re-renders, the reloads its URL. I want the to retain its state and not reload when the tab changes or the component re-renders.

How can I prevent the from reloading in this scenario?

Thank you for your help!

Error 405: Moved Temporarily from Google Apps Script even though server still accepts the payload

Assume the following simple setup for sending telemetry to Google Sheets:

Curl -> Google Apps Script deployed as Web App -> Google Sheet -> Cell 1:1

Google Apps script is a simple doPost() that prints the json payload into the Cell 1:1 of the Sheet it is an extension of.

This works fine for the most part. Data sent by Curl is being received by Google Sheet. However, the response from google’s server comes with an Error 405: Moved Temporarily:

<H1>Moved Temporarily</H1>
The document has moved <A HREF="https://script.googleusercontent.com/macros/echo?user_content_key=balhblah"

But, even though the response indicates an error, the data still appears in the Google Sheet. What is the reason for 405-ing, and why does Google still accept data despite throwing an error?

Curl script line:

curl -X POST "https://script.google.com/macros/s/xxxxxxxx/exec" -H "Content-Type: application/json"

Google Apps Script code for the doPost():

function doPost(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var rawData;
  if (e.postData) {
    rawData = e.postData.contents;   // get the request's payload
  } else {
    rawData = "";                    // fallback to empty string if there is no data
  }

  // Append to the end of the sheet
  sheet.appendRow([rawData]);

  return ContentService
    .createTextOutput("Data received.");
}

Separate out data from AI response

I am making a AI powered SAAS dashboard and if I send some query to backend I want to separate out the text, code-block and graphs from the response of AI backend to separately render them on different parts of the screen.

I haven’t tried it yet still don’t know how the response of the backend will be.

What really happens in the browser when you swtich from landscape to portrait mode in a tablet?

Currently I am working on very strange bug in a legacy ASP.NET MVC application and it is reproducible only on IPads. One of the page does not fit screen and strangely when I switch to landscape and back to portrait issue gets fixed and page fully fits into the screen. My question is as a workaround solution is there any way to programatically rotate the page to landscape and back to portrait without user noticing on the page load? More essential question is what really happens in the browser when you switch from landscape to portrait?

Blazor – when JavaScript runs for custom context menu, app navigates back to homepage

Background

I have a Blazor server-side app I’m building which will be a music sheets website. I’m having trouble running JavaScript code for a context menu. I’ve started adding a custom context menu, so users will be able to right-click on the page and I give them a list of custom actions they can take.

Problem

When I pull up the context menu on the UI, then click on one of the menu items, the script executes but it navigates back to the home page and I have no idea why. After putting in a bunch of console logging and using a sleep timer, it seems to just happen when the JavaScript finishes running, not on any particular action.

Code Details

Basically all the JavaScript code is doing is logging to the console and then closing the menu, I haven’t programmed any of the actions the menu will eventually take. Below is the code for NewSheet.razor. I’m only including relevant code for now, but I can add more details upon request.

@*HTML for context menu*@
<nav id="context-menu" class="context-menu">
    <ul class="context-menu__items">
        <li class="context-menu__item">
            <a href="#" data-action="add-verse" class="context-menu__link"> Add Verse</a>
        </li>
        <li class="context-menu__item">
            <a href="#" class="context-menu__link"> Add Chorus</a>
        </li>
        <li class="context-menu__item">
            <a href="#" class="context-menu__link"> Add Bridge</a>
        </li>
        <li class="context-menu__item">
            <a href="#" class="context-menu__link"> Add Line (notes and lyrics)</a>
        </li>
    </ul>
</nav>
<script>
    var MenuOpen = false;
    var ContextMenuActive = "context-menu--active";
    var MenuElement = document.querySelector("#context-menu");


    function clickInsideElement(e, className) {
        var el = e.srcElement || e.target;

        if (el.classList.contains(className)) {
            return el;
        } else {
            while (el = el.parentNode) {
                if (el.classList && el.classList.contains(className)) {
                    return el;
                }
            }
        }

        return false;
    }


    function getPosition(e) {
        var posx = 0;
        var posy = 0;

      if (!e) var e = window.event;

      if (e.pageX || e.pageY) {
          posx = e.pageX;
          posy = e.pageY;
      } else if (e.clientX || e.clientY) {
          posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
          posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      }

      return {
          x: posx,
          y: posy
      }
    }


    function init() {
        contextListener();
        clickListener();
        keyupListener();
        resizeListener();
    }


    function contextListener() {
        document.addEventListener("contextmenu", function(e) {
            //var taskItemInContext = clickInsideElement(e, "task"); // this should check if the click is on one of the context menu items, but instead causes the menu to never open.
            //if (taskItemInContext) {
                if (MenuOpen) {
                    toggleMenuOff();

                } else {
                    e.preventDefault();
                    toggleMenuOn();
                    positionMenu(e);
                }
        });
    }


    function clickListener() {
        document.addEventListener("click", function(e) {
            var clickeElIsLink = clickInsideElement(e, "context-menu__link");

            if (clickeElIsLink) {
                e.preventDefault();
                menuItemListener(clickeElIsLink); // logs the data attribute to the console. This essentially tells you which menu option was selected.
            } else {
                var button = e.which || e.button;
                if (button === 1) {
                    toggleMenuOff();
                }
            }
        });
    }


    // If user presses esc button then close the menu
    function keyupListener() {
        window.onkeyup = function(e) {
            if (e.keyCode === 27) {
                toggleMenuOff();
            }
        }
    }


    // If the user is resizing the browser window then close the context menu for now.
    function resizeListener() {
        window.onresize = function(e) {
            toggleMenuOff();
        };
    }


    // Safe method for toggling on the context MenuElement. Does check first to make sure menu is closed before attempting to open.
    function toggleMenuOn() {
        if (!MenuOpen) {
            MenuElement.classList.add(ContextMenuActive);
            MenuOpen = true;
        }
    }


    // Safe method for toggling off the context MenuElement. Does check first to make sure menu is open before attempting to close.
    function toggleMenuOff() {
        if (MenuOpen) {
            MenuElement.classList.remove(ContextMenuActive); // this doesn't seem to be causing an issue. Page still redirects, even when this is commented out.
            MenuOpen = false;
        }
    }


    function positionMenu(e) {
        var clickCoords = getPosition(e);
        var clickCoordsX = clickCoords.x;
        var clickCoordsY = clickCoords.y;

        var menuWidth = MenuElement.offsetWidth + 4;
        var menuHeight = MenuElement.offsetHeight + 4;

        var windowWidth = window.innerWidth;
        var windowHeight = window.innerHeight;

        if ((windowWidth - clickCoordsX) < menuWidth) {
            MenuElement.style.left = windowWidth - menuWidth + "px";
        } else {
            MenuElement.style.left = clickCoordsX + "px";
        }

        if ((windowHeight - clickCoordsY) < menuHeight) {
            MenuElement.style.top = windowHeight - menuHeight + "px";
        } else {
            MenuElement.style.top = clickCoordsY + "px";
        }
    }


    // Function called to take an action from clicking on one of the menu items. After action is taken, closes the menu.
    function menuItemListener(link) {
        console.log(link.getAttribute("data-action")); // this is where the data action attribute is logged to the console.
    }


</script>

Main Question:

Why does the app keep navigating back to the home page when the script runs?

Steam inventory API returns 403 when fetching user’s CS:GO inventory from backend

I’m building a website that requires Steam login. After the user logs in I call Steam’s inventory endpoint to show their cs inventory, but im getting that error. After logging in console shows

Fetching inventory for SteamID: 7656119xxxx
Trying new API: https://steamcommunity.com/inventory/xxxxxxxxxxx/730/2?l=english&count=5000
Steam returned status 403

app.get('/inventory', async (req, res) => {
  if (!req.user) return res.status(401).json({ error: 'Not logged in' });

  const steamid = String(req.user._json?.steamid || req.user.id);
  const url = `https://steamcommunity.com/inventory/${steamid}/730/2?l=english&count=5000`;

  const response = await fetch(url, {
    headers: { 'User-Agent': 'Mozilla/5.0' }
  });

  if (!response.ok) {
    return res.status(500).json({ error: `Steam returned status ${response.status}` });
  }

  const json = await response.json();
  // …process json…
});

What’s the best way to create a mutex lock in JavaScript?

So far I have created a function used to set a timeout to simulate a mutex. I’m thinking there has to be a better way to do this though, maybe a built in function?

function RenderTreeMutex() {
    if(rendering || dragging || resetting) {
        setTimeout(RenderTreeMutex, 50);
        return;
    }
  }

This method seems a bit unorthodox, there must be a cleaner way?

Good luck with that one is pawrfoll

New geem to promote

Financial services good network maining token maining app Turn your sestam check out the email to promote the same thing about my account KYC approved please help recowist me know what playing with my account rajistar 8

How can I know when a child element is created on a parent element in javascript/typescript?

I have three custom components, MyParentElement and MyChildElement1 and MyChildElement2:

class MyParentElement extends HTMLElement 
{
  connectedCallback() 
  {
    console.log('MyParentElement connectedCallback()');
    for (let i = 0; i < this.children.length; ++i)
    {
      const elem = this.children[i];
      if (elem.tagName.toLowerCase() == 'my-child-element-1' || elem.tagName.toLowerCase() == 'my-child-element-2')
      {
        console.log(`elem.sortValue: ${elem.sortValue}`);
      }
    }

    setTimeout(() => 
    {
      for (let i = 0; i < this.children.length; ++i)
      {
        const elem = this.children[i];
        if (elem.tagName.toLowerCase() == 'my-child-element-1' || elem.tagName.toLowerCase() == 'my-child-element-2')
        {
          console.log(`elem.sortValue: ${elem.sortValue}`);
        }
      }
    }, 10);
  }
}
customElements.define("my-parent-element", MyParentElement);


class MyChildElement1 extends HTMLElement 
{
  constructor()
  {
    super();
    console.log(`MyChildElement1: ${this.sortValue}`);
  }

  get sortValue() { return 1; }
}
customElements.define("my-child-element-1", MyChildElement1);


class MyChildElement2 extends HTMLElement 
{
  constructor()
  {
    super();
    console.log(`MyChildElement2: ${this.sortValue}`);
  }

  get sortValue() { return 2; }
}

customElements.define("my-child-element-2", MyChildElement2);
<my-parent-element>
  <my-child-element-1></my-child-element-1>
  <my-child-element-2></my-child-element-2>
</my-parent-element>

When connectedCallback() is called for MyParentElement, sortValue gives me undefined. After the constructor is called for the two child elements, sortValue will work as expected.

Is there a way to know in the parent element when the child elements are ready without a timeout? MutationObserver didn’t seem to work for children that already exist as part of the HTML (but it will work if I create the elements and use appendChild(), however I am hoping to avoid that).

React Testing Library: Unable to find text in custom modal using MUI Dialog

I’m writing a test for a React component that shows an error modal when a fetch fails. The component internally uses a custom modal that wraps @mui/material/Dialog. Here’s a simplified version of my test:

it('should show error message when fetch fails', async () => {
  // simplified test
  fireEvent.click(searchButton);

  expect(screen.queryByText('[email protected]')).not.toBeInTheDocument();
  expect(screen.queryByText('Account Test')).not.toBeInTheDocument();

  await waitFor(() => {
    expect(screen.getByText(/Error fetching accounts/i)).toBeInTheDocument();
  });
});

The problem is that the test fails with the following error:

Unable to find an element with the text: Error fetching accounts. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

Things I’ve tried:

  1. Using a regex:
const modalTitle = await screen.findByText(/Error fetching accounts/i);
expect(modalTitle).toBeInTheDocument();

Same error

  1. Using a custom function:
const modalTitle = await screen.findByText((content) =>
  content.includes('Error fetching accounts')
);
expect(modalTitle).toBeInTheDocument();

Error:

Unable to find an element with the text: (content) => content.includes('Error fetching accounts'). This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
  1. Querying the dialog by role:
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText(/Error fetching accounts/i)).toBeInTheDocument();

Error:

Unable to find role="dialog"

I suspect the problem is that the modal is rendered asynchronously or in a portal (MUI Dialog uses ReactDOM.createPortal). How should I correctly test that the error message is displayed in a MUI Dialog using React Testing Library?

iOS 26: Camera video works but QR/barcode detection (zxing, html5-qrcode) silently fails in all browsers

My team has developed a web application that uses the device’s camera to decode QR codes and barcodes from labels. After the recent iOS 26 update, our application has completely stopped working on devices running this version of iOS. The camera feed works fine (video stream is visible), and we have confirmed that all necessary permissions are granted. However, the barcode/QR code detection engine fails silently, and we have been unable to identify a workaround so far.

Implementation Details:

  • Libraries Used: We are using the ZXing library and the html5-qrcode library for barcode/QR code scanning.

  • Affected Platform: The issue occurs only on iOS 26. Other iOS versions and Android devices work as expected.

  • Browsers Tested: We have tested the application on major browsers available on iOS, including Safari, Chrome, and Firefox. The issue persists across all browsers, so it does not appear to be specific to Safari.

  • Additional Testing: We attempted to disable QR code detection in the iPhone settings (Settings > Camera > Scan QR Codes), but this had no effect on the issue.

Problem:

  • The barcode/QR code detection fails without throwing any errors or logs, making it difficult to debug.
  • No workaround has been found yet.

Question:

Has anyone else encountered a similar issue with barcode/QR code detection on iOS 26 using ZXing or html5-qrcode libraries? If so, were you able to find a solution or workaround? Any insights or suggestions on how to debug or resolve this issue would be greatly appreciated.

Thank you!

*Cookies* sent by server is not Visible from frontEnd (CORS applicable)

The cookies created in server side(HTTP server) isnt visible to FrontEnd script
I have created an Array of Cookies using Set-Cookie inside createServer method

`res.setHeader('Set-Cookie',` [
        'sessionId=abc123; SameSite=None;Secure;',
        'username=ratul; SameSite=None;Secure;',
        'name=Ratul; SameSite=None;Secure;'
    `]);`

According to Cross Origin resource sharing if my domain or PORT is different then i have to used

`"Access-Control-Allow-Origin":'http://X.X.X.X:3000'
 "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
 'Access-Control-Allow-Headers': 'Content-Type,user-agent,X-Client-Header',
 'Access-Control-Allow-Credentials': `'true'`

YES I Have used it and Since my frontend sending CORS request hence i have also used

`'credentials':'include'`

STILL
whensoever i do on (FrontEnd Script)
document.cookie
this gives empty string
OR
res.headers.get('Set-Cookie')
gives
null

I have attached my repo below
HTML_CSS_JS_PRACTICE/HTML_CSS_JS_30/PS3

The cookies sent from the HTTP server:
null

But why? I have done acess-control-allow-credentials:'True'
as Well as credentials:'include'
also exposed that header of set-cookie using access-control-allow-headers

Sorry if i have any misconceptions about HTTP Server headers and cookies
Thank you in advance!