Sort Object Array by dependant property

I have an unsorted objects array with strings like this:

const unsortedArr =  [
  {
  id: "test13",
  startAfter: "test15"
  },
  {
  id: "test20",
  startAfter: "test5"
  },
  { 
  id: "test5",
  startAfter: "test1"
  },
  {
  id: "test15",
  startAfter: "test20"
  },
]

You get the idea.

I also have a start ID: const startId = "test1";

With my start ID as the first value, I want to sort the array according to the “startAfter” property. Create a chronological chain, so to speak.

The result should look like this:

const sortedArr =  [
    {
    id: "test5",
    startAfter: "test1"
    },
    {
    id: "test20",
    startAfter: "test5"
    },
    {
    id: "test15",
    startAfter: "test20"
    },
    {
    id: "test13",
    startAfter: "test15"
    },
    ]

What is the easiest way to sort this array in JS? Thx in advance.

Configure ESLint to throw error if hooks have no dependency array but array would require dependencies if put in

Is there a way to configure ESLint to throw an error or warning if a hook, like a useEffect, doesn’t have a dependency array, but if a dependency array is put in, that array would require deps?

For example, the below useEffect doesn’t throw an error or warning without a dependency array, but if I put one in, it throws a warning that it requires setIsQSDashboardEnabled as a dependency.

useEffect(() => {
    setIsQSDashboardEnabled(true);
    return () => {
      setIsQSDashboardEnabled(false);
    };
  });

why the parameter does not passed Axios requests?

I had following code to setup urls for Axios requests. In razor page, I have this.

    var urls = {
         Value1Validate: '@Url.Action("Method1", "Controler1")',
         Value2Validate: '@Url.Action("Method2", "Controler2")',
     };

In js file, I have code as below. Anyone could help me find out why this elem.val() parameter value could not be passed to the /controller2/method2?

    App.Value2OnChange = (e) => {
        let elem = $(e);
        alert("parameter value " + elem.val());

        axios.get(`${urls.Value2Validate}${elem.val()}`).then((response) => {
            if (response.data === 'ok') {
                 //dispay msg ('PASSED');
            } else {
                //dispay msg ('Failed');
            }
        });
    }

Here are the code in Controller2.

    public async Task<JsonResult> Method2(string parameterValue)
    {
        var response = await MediatR.Send(new ValidateionQuery(parameterValue)));
        return JsonSuccess(response ? "ok" : "error");
    }

I tried the code and it called …/controller2/method2 but did not pass the parameter value. Any wrong in here?

How to extrude polygon in three.js?

In general I want the user to be able to click on a horizontal plane, and create a polygon, which is then automatically extruded up. I am using three.js and react-three-fiber, and I can add spheres where the user clicks but when it comes to extruding it I get very weird results (the extrusions go towards the x or z direction not up).

Here is my function:

 const handleFloorClick = (event) => {
        const mouse = new THREE.Vector3();
        const { offsetX, offsetY } = event;
    
        // Normalize mouse coordinates to the range [-1, 1]
        mouse.x = (offsetX / window.innerWidth) * 2 - 1;
        mouse.y = -(offsetY / window.innerHeight) * 2 + 1;
    
        // Update the raycaster with the normalized mouse coordinates
        raycaster.setFromCamera(mouse, camera);
    
        // Intersect the ray with the floor to get the 3D coordinates
        const intersects = raycaster.intersectObject(floorRef.current);
    
        if (intersects.length > 0) {
            const { x, y, z } = intersects[0].point;
            console.log('Mouse click location:', x, y, z);
        

            // Create a new circle mesh
            const geometry = new THREE.SphereGeometry(0.12, 32);
            const material = new THREE.MeshBasicMaterial({ color: 'black' });
            const sphere = new THREE.Mesh(geometry, material);

            // Position the circle at the clicked coordinates
            sphere.position.set(x, y + 0.1, z); 

            // Add the circle to the scene
            scene.add(sphere);

            // Save the circle in state for later removal or manipulation
            // Save the sphere and its coordinates in state
            setSpheres((prevSpheres) => [
                ...prevSpheres,
                {
                    mesh: sphere,
                    coordinates: { x, y, z },
                },
            ]);

            // Create a polygon mesh when at least three spheres are present
            if (spheres.length >= 2) {
                const points = spheres.map(({ coordinates }) => new THREE.Vector3(coordinates.x, -1, coordinates.z));
                console.log('Points:', points);
                const shape = new THREE.Shape(points);
                const geometry = new THREE.ShapeGeometry(shape);
                const polygonMaterial = new THREE.MeshBasicMaterial({ color: 'red'});
                const mesh = new THREE.Mesh(geometry, polygonMaterial);


                console.log(mesh)

                // Add the new polygon mesh to the scene
                scene.add(mesh);
                setPolygonMesh(mesh);

                // Log polygon position for debugging
                console.log('Polygon position:', mesh.position);

                // Extrude the polygon to create a 3D shape
                const extrusionSettings = { depth: 30, bevelEnabled: false};
                const extrudedGeometry = new THREE.ExtrudeGeometry(shape, extrusionSettings);
                const extrudedMaterial = new THREE.MeshStandardMaterial({ color: 0xFFFF00, side: THREE.DoubleSide });
                const extrudedMesh = new THREE.Mesh(extrudedGeometry, extrudedMaterial);

                // Position the extruded mesh at the clicked coordinates
                extrudedMesh.position.set(x, y + 1, z);
                scene.add(extrudedMesh);
            }
        }
    };

Here is what it does, as you can see it just creates flat shapes at weird spots:

enter image description here

How do you access an HTTP request body in vanilla Node.js?

If you’re making a project using vanilla Node.js (i.e. not Express) how do you access the request body (say, for a POST request)?

Tried a bunch of things, but I got this to work:

let body = [];
req.on('data', chunk => body.push(chunk));

req.on('end', () => {
    body = JSON.parse(body[0].toString());
    console.log(body); // the actual data
}

There’s got to be a better way, though, right?

How can i use Replicate llama-2 LLM in Llamaindex.ts SDK for Node.js?

How can I use Replicate llama-2 LLM in Llamaindex.ts SDK for Node.js? Can anyone please help me? I want to ask questions based on my data with Replicate LLM with RAG.

I can’t find any code example on the internet to do that.

import { DeuceChatStrategy, LlamaDeuce } from "llamaindex";

(async () => {
  const deuce = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
  const result = await deuce.chat([{ content: "Hello, world!", role: "user" }]);
  console.log(result);
})();

Ignoring decimals when formatting

I’m trying to write the regex that will format the number like 1231231.00 to 1,231,231.00. I’ve written something like this:

let test = "1231231.00";
console.log(test.replace(/(d)(?=(d{3})+$)/g, "$1,"))

But I still have problem when I try to format 1231231.00. Can anyone give me a hint?

Make hitArea of sprite to be of path of svg

I just began learning pixi today so don’t be so critical of the code please

DESCRIPTION

I am developing a game where you’re searching an item on the screen with circle that is following mouse movements. Item that has to be found is just SVG that is imported as Sprite object and set on the specific position on the screen.

My goal is to draw a stroke to this SVG when it collides with circle.

PixiJS collision example provides us good ready function to check collision. Here occurs a problem that SVG is imported with rectangular hitarea that gives me a problem that when circle collides this hitarea but doesn’t collide real svg boundes it registers collision anyway.

target svg import:

const vaseSprite = app.stage.addChild(
    Sprite.from(await Assets.load("/games/scavenger-hunt/vase.svg"))
);

The circle logic that is happening when user is moving mouse is happening in repaint function

FULL CODE

const app = new Application({
                resizeTo: window,
                // background: 0x333333,
                antialias: true,
            });

            mainPageRef.current?.appendChild(app.view as unknown as Node);

            // Background texture
            const backgroundTexture = await Assets.load(
                "/games/scavenger-hunt/background.png"
            );
            const background = app.stage.addChild(
                Sprite.from(backgroundTexture)
            );
            background.position.set(
                window.innerWidth / 2,
                window.innerHeight / 2
            );
            background.anchor.set(0.5);

            // Target vase sprite
            const vaseSprite = app.stage.addChild(
                Sprite.from(await Assets.load("/games/scavenger-hunt/vase.svg"))
            );

            // Add graphics for stroke
            const vaseStroke = new Graphics();
            vaseSprite.addChild(vaseStroke);

            vaseSprite.anchor.set(0.5);
            vaseSprite.position.set(
                window.innerWidth / 2 + 307,
                window.innerHeight / 2 + 47
            );

            // Circle texture
            const circle = app.stage.addChild(new Graphics());
            circle
                .beginFill(0xffffcc, 0.3)
                .drawCircle(window.innerWidth / 2, window.innerHeight / 2, 145)
                .endFill();

            // App settings
            app.stage.eventMode = "static";
            app.stage.hitArea = app.screen;
            app.stage.on("pointermove", (e) => {
                repaint(e);
            });

            const repaint = (e: any) => {
                const hole = new Graphics();

                const filter = new DropShadowFilter({
                    color: 0xffffff,
                    alpha: 1,
                    blur: 100,
                    distance: 100,
                    rotation: 45,
                });

                hole.filters = [filter];

                hole.beginFill(0xffffcc, 0.3).arc(
                    e.clientX,
                    e.clientY,
                    145,
                    0,
                    Math.PI * 2
                );

                circle
                    .clear()
                    .beginFill(0x000000, 0.3)
                    .drawRect(0, 0, window.innerWidth, window.innerHeight)
                    .beginHole()
                    .drawPolygon(hole.currentPath)
                    .endHole()
                    .endFill();

                if (checkObjectsCollision(vaseSprite, hole)) {
                    drawStroke();
                } else {
                    clearStroke();
                }

                console.log(checkObjectsCollision(vaseSprite, hole));
            };

            const drawStroke = () => {
                vaseStroke.clear().lineStyle(5, 0xff0000).drawCircle(0, 0, 50);
            };

            const clearStroke = () => {
                vaseStroke.clear();
            };

failed to load pdf document on download in React

I am trying to create a button that downloads my cv onto the device onClick for a website portfolio.
It works on my localhost but it returns this error when once it is pushed to AWS-Amplify.
error on the aws-deployment

I changed my imports from relative to absolute but this hasn’t fixed the issue.
The cv is currently in the root folder.

import resume from './KuroUsaResume.pdf'
import 'stylesheets/Home.css';


function Home() {
  return (
    <div className="home">

      .....
      
      .....

        <a href= {resume} download="KuroUsa's_Resume.pdf">
          <button className='home--download-button'>Download CV</button>
        </a>
        
      </div> 

      <div className="home--body">
        <img src={me} className="logo" alt="logo" />
      </div>
    </div>

  );
}

export default Home;

My jsconfig file:

{
    "compilerOptions": {
      "baseUrl": "src"
    },
    "include": ["src"]
}

Cookie not setting path default to page

Ater migrating our application, cookies have stopped setting the path to the current page, always setting it to root. The cookie path is not specified, and that should default to the current page. For example, on page /cat, if I open the console and run:

document.cookies = "foo=bar"

Then the path of the cookie is root, not /cat.
enter image description here

On the pre-migration server, the default behavior sets the path to /cat.

enter image description here

Can the server affect the cookie path default behavior?

How to wait for a javascript function to finish before executing it again?

I’m trying to mimic an LCD panel to pass information about a game. Letters appear one by one, with a little delay in-between. The problem is, when the function gets called again before having finished displaying the first string, it starts displaying the new string, mixing up all letters.
I would need to find a way to delay the displaying of the second (or following strings) until it has finished to display the first one.

I’ve tried by usind setInterval, as I thought it should be syncronous, but it seems it is not. I’m not familiar with Promise or other ways of doing it
Here’s the code of the function:

function updateMonitor(ujo, str) {
    ujo.html('');
    var currentIndex = 0;
    intervalId = setInterval(function(){
        ujo.text(ujo.text() + str.substring(currentIndex, currentIndex + 1))
        currentIndex++;

        // We've reached the end of the string, stop calling this function
        if (currentIndex == str.length) clearInterval(intervalId);
    }, 5);
}

Issue with Page Refresh after executing some JavaScript code

I am facing difficulties with refreshing the page after clicking the “Yes” (Submit) button in the Script section of my ASP.NET MVC application view. Upon pressing the button, I expect the page to be reloaded, but I am not observing the intended behavior.

The part of the code in the Script section looks something like this (the rest works fine, and function clickOnButton is being called):


<dialog id="dialogConfirmEmail">
    <p>Do you want to confirm e-mail?</p>
        <button id="submit" value="submit">Yes</button>
        <button id="close" value="close" formmethod="dialog">Back</button>
</dialog>

<script>
    function clickOnButton(id) {
        var dialog = document.getElementById("dialogConfirmEmail");
        var buttonSumbit = document.getElementById("submit");
        dialog.show();

        buttonSumbit.onclick = () => {

            updateData(id);
            window.location.href = '@Url.Action("ConfirmUsersEmails", "Admin")';
        }

    }

    function updateData(id) {

        var confirmEmailRequest = {
            Id: id
        };

        fetch('@Url.Action("ConfirmEmailAsync", "Admin")', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'RequestVerificationToken': document.getElementsByName('__RequestVerificationToken')[0].value
            },
            body: JSON.stringify(confirmEmailRequest),
        })
        .then(response => response.json())
        .then(data => {
            console.log('success:' + data);
        })
        .catch(error => {
            console.log('Error updating item:' + error);
        });
    }
</script>

What should I improve to make it work?

How to enable the ‘Next’ button when specific conditions are met in a JavaScript code for WP Forms

How can I modify the provided JavaScript code to ensure that the “Next” button is shown only on pages where at least one item from the ‘wpforms-icon-choices-item’ class has the ‘.wpform-selected’ class or on the page following a click on the ‘wpformButtonBack’ button, while preserving the existing functionality of the ‘progressNextReset’ and ‘progressBackReset’ functions?
Additionally I provide the appropriate HTML markup for this code

Javascript:

const choiceItems = document.querySelectorAll('.wpforms-icon-choices-item');
const wpformsPage = document.querySelectorAll('.wpforms-page')
const wpformButtonNext = document.querySelectorAll('.wpforms-page-next');
const wpformButtonBack = document.querySelectorAll('.wpforms-page-prev');
const wpformsFields = document.querySelectorAll('.wpforms-field');
const wpformsIndicatorWrap = document.querySelector('.wpforms-page-indicator-page-progress-wrap');
const wpformsIndicatorProgress = document.querySelector('.wpforms-page-indicator-page-progress');
const wpformsIndicatorContainer = document.createElement('div');
wpformsIndicatorContainer.className = 'wpforms-page-indicator-container';
wpformsIndicatorProgress.appendChild(wpformsIndicatorContainer);
const wpformsIndicatorText = document.createElement('div');
wpformsIndicatorText.className = 'wpforms-page-indicator-text';
wpformsIndicatorContainer.appendChild(wpformsIndicatorText);
const wpformsIndicatorProgressWidth = Math.round(parseFloat(wpformsIndicatorProgress.style.width));
wpformsIndicatorText.innerText = wpformsIndicatorProgressWidth + '% geschaft';

for (var item = 0; item < choiceItems.length; item++) {
    const choiceItemOnHover = document.createElement('div');
    choiceItemOnHover.className = "wpforms-choices-header-onhover";
    const label = choiceItems[item].querySelector('.wpforms-icon-choices-label');
    choiceItemOnHover.innerText = label ? label.innerText : '';
    choiceItems[item].append(choiceItemOnHover);
}

wpformButtonNext.forEach((button) => {
    button.style.visibility = 'hidden'
});

function showButton() {

    // Toggle the class on wpformButtonNext elements based on the condition
    wpformButtonNext.forEach((button) => {
        button.style.visibility = 'visible'
    });
}

function hideButton() {

    const currentPageIndex = Array.from(wpformsPage).findIndex(
        (page) => page.getAttribute('data-page') === '1'
    );

    // Check if the current page has any item without 'wpforms-selected' class
    const isItemSelected = Array.from(wpformsPage[currentPageIndex].querySelectorAll('.wpforms-icon-choices-item')).some(
        (item) => !item.classList.contains('wpforms-selected')
    );

    // Toggle the visibility of wpformButtonNext elements on the current and next pages
    for (let a = 0; a < wpformButtonNext.length; a++) {
        if (a === currentPageIndex || a === currentPageIndex + 1) {
            // Check if the current page or next page
            if (isItemSelected) {
                console.log('7707');
                wpformButtonNext[a].style.visibility = 'visible';
            } else {
                console.log('666');
                wpformButtonNext[a].style.visibility = 'hidden';
            }
        }
    }
}

function progressNextReset() {
    const pixelProgressWidth = window.getComputedStyle(wpformsIndicatorProgress).getPropertyValue('width');
    const currentIndicatorWidth = window.getComputedStyle(wpformsIndicatorWrap).getPropertyValue('width');
    const percentageValue = Math.round((parseFloat(pixelProgressWidth) / parseFloat(currentIndicatorWidth)) * 100);
    const actualPercentValue = wpformsIndicatorProgressWidth + percentageValue;
    wpformsIndicatorText.innerText = actualPercentValue + '% geschaft';
    hideButton();
}

function progressBackReset() {
    const pixelProgressWidth = window.getComputedStyle(wpformsIndicatorProgress).getPropertyValue('width');
    const currentIndicatorWidth = window.getComputedStyle(wpformsIndicatorWrap).getPropertyValue('width');
    const percentageValue = Math.round((parseFloat(pixelProgressWidth) / parseFloat(currentIndicatorWidth)) * 100);
    const actualPercentValue = wpformsIndicatorProgressWidth - percentageValue;
    wpformsIndicatorText.innerText = -actualPercentValue + '% geschaft';
    showButton();
}

if (choiceItems) {

    for (var i = 0; i < wpformButtonNext.length; i++) {
        wpformButtonNext[i].addEventListener('click', progressNextReset);
    }
    for (var i = 0; i < wpformButtonBack.length; i++) {
        wpformButtonBack[i].addEventListener('click', progressBackReset);
    }
    for (var i = 0; i < choiceItems.length; i++) {
        choiceItems[i].addEventListener('click', progressNextReset);
    }

} else {
    console.error('wpformButtonNext not found');
}

HTML markup via link view-source:https://staging-new.deutsche-thermo.de/elementor-13377/

I try to modify JavaScript code to display the “Next” button on ‘wpforms-page ‘ pages when any item in the ‘wpforms-icon-choices-item’ class has the ‘.wpform-selected’ class, or after clicking the ‘wpformButtonBack’ button. Ensure that the ‘progressNextReset’ and ‘progressBackReset’ functions continue to function correctly