I can’t move my GLTF model from AR mode from the camera with threejs and webxr

I’m new to using webxr with threejs and I’m doing AR experiences. I’ve been trying for 2 days to do a functionality that is within the examples on the threejs page https://threejs.org/examples/?q=webxr#webxr_xr_dragging_custom_depth

Basically it’s doing a dragging with a GLTF model, I’ve been looking for information on the internet but I couldn’t find the solution. I’ve done things in different ways but I still can’t move the object.

This is the code

import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { XRButton } from "three/addons/webxr/XRButton.js";
import { XRControllerModelFactory } from "three/addons/webxr/XRControllerModelFactory.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

let container;
let camera, scene, renderer;
let controller1, controller2;
let controllerGrip1, controllerGrip2;

let raycaster;

const intersected = [];

let controls, group;

init();

function init() {
  container = document.createElement("app");
  document.body.appendChild(container);

  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x808080);

  camera = new THREE.PerspectiveCamera(
    50,
    window.innerWidth / window.innerHeight,
    0.1,
    10
  );
  camera.position.set(0, 1.6, 3);

  controls = new OrbitControls(camera, container);
  controls.target.set(0, 1.6, 0);
  controls.update();

  const floorGeometry = new THREE.PlaneGeometry(6, 6);
  const floorMaterial = new THREE.ShadowMaterial({
    opacity: 0.25,
    blending: THREE.CustomBlending,
    transparent: false,
  });
  const floor = new THREE.Mesh(floorGeometry, floorMaterial);
  floor.rotation.x = -Math.PI / 2;
  floor.receiveShadow = true;
  scene.add(floor);

  scene.add(new THREE.HemisphereLight(0xbcbcbc, 0xa5a5a5, 3));

  const light = new THREE.DirectionalLight(0xffffff, 3);
  light.position.set(0, 6, 0);
  light.castShadow = true;
  light.shadow.camera.top = 3;
  light.shadow.camera.bottom = -3;
  light.shadow.camera.right = 3;
  light.shadow.camera.left = -3;
  light.shadow.mapSize.set(4096, 4096);
  scene.add(light);

  group = new THREE.Group();
  scene.add(group);


  const loader = new GLTFLoader();
  loader.load(
    "/models/model.glb",
    function (gltf) {
      const object = gltf.scene;
      object.position.set(0, 0.5, -2);
      object.scale.set(0.030, 0.030, 0.030);
      object.rotateY(3.1);
      group.add(object);
    },
    undefined,
    function (error) {
      console.error(error);
    }
  );

  // for ( let i = 0; i < 1; i ++ ) {

  //    const geometry = geometries[ Math.floor( Math.random() *1) ];
  //    const material = new THREE.MeshStandardMaterial( {
  //        color: Math.random() * 0xffffff,
  //        roughness: 0.7,
  //        metalness: 0.0
  //    } );

  //    const object = new THREE.Mesh( geometry, material );

  //    object.position.x = Math.random() * 4 - 2;
  //    object.position.y = Math.random() * 2;
  //    object.position.z = Math.random() * 4 - 2;

  //    object.rotation.x = Math.random() * 2 * Math.PI;
  //    object.rotation.y = Math.random() * 2 * Math.PI;
  //    object.rotation.z = Math.random() * 2 * Math.PI;

  //    object.scale.setScalar( Math.random() + 0.5 );

  //    object.castShadow = true;
  //    object.receiveShadow = true;

  //    group.add( object );

  // }

  //

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setAnimationLoop(animate);
  renderer.shadowMap.enabled = true;
  renderer.xr.enabled = true;
  container.appendChild(renderer.domElement);

  document.body.appendChild(
    XRButton.createButton(renderer, {
      optionalFeatures: ["depth-sensing"],
      depthSensing: {
        usagePreference: ["gpu-optimized"],
        dataFormatPreference: [],
      },
    })
  );

  // controllers

  controller1 = renderer.xr.getController(0);
  controller1.addEventListener("selectstart", onSelectStart);
  controller1.addEventListener("selectend", onSelectEnd);
  scene.add(controller1);

  controller2 = renderer.xr.getController(1);
  controller2.addEventListener("selectstart", onSelectStart);
  controller2.addEventListener("selectend", onSelectEnd);
  scene.add(controller2);

  const controllerModelFactory = new XRControllerModelFactory();

  controllerGrip1 = renderer.xr.getControllerGrip(0);
  controllerGrip1.add(
    controllerModelFactory.createControllerModel(controllerGrip1)
  );
  scene.add(controllerGrip1);

  controllerGrip2 = renderer.xr.getControllerGrip(1);
  controllerGrip2.add(
    controllerModelFactory.createControllerModel(controllerGrip2)
  );
  scene.add(controllerGrip2);

  //

  const geometry = new THREE.BufferGeometry().setFromPoints([
    new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(0, 0, -1),
  ]);

  const line = new THREE.Line(geometry);
  line.name = "line";
  line.scale.z = 5;

  controller1.add(line.clone());
  controller2.add(line.clone());

  raycaster = new THREE.Raycaster();

  //

  window.addEventListener("resize", onWindowResize);
}

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}

function onSelectStart(event) {
  const controller = event.target;

  const intersections = getIntersections(controller);

  if (intersections.length > 0) {
    const intersection = intersections[0];

    const object = intersection.object;
 
    controller.attach(object);

    controller.userData.selected = object;
  }
  alert(JSON.stringify(intersections))

  controller.userData.targetRayMode = event.data.targetRayMode;
}

function onSelectEnd(event) {
  const controller = event.target;

  if (controller.userData.selected !== undefined) {
    const object = controller.userData.selected;
    object.material.emissive.b = 0;
    group.attach(object);

    controller.userData.selected = undefined;
  }
}

function getIntersections(controller) {
  controller.updateMatrixWorld();

  raycaster.setFromXRController(controller);

 return raycaster.intersectObjects(group.children, false);

}

console.log(intersected)

function intersectObjects(controller) {
  // Do not highlight in mobile-ar

  if (controller.userData.targetRayMode === "screen") return;

  // Do not highlight when already selected

  if (controller.userData.selected !== undefined) return;

  const intersections = getIntersections(controller);

  if (intersections.length > 0) {
    const intersection = intersections[0];
    alert(JSON.stringify(intersection))
    const object = intersection.object;

    intersected.push(object);

  } 
}

function cleanIntersected() {
  while (intersected.length) {
    intersected.pop();
  
  }
}

//

function animate() {
  cleanIntersected();

  intersectObjects(controller1);
  intersectObjects(controller2);

  renderer.render(scene, camera);
}

I just hope that a dragging is done like in the example link that I passed but with only one model that appears in the code with a position and all that. Here is the example code I posted at the link
https://github.com/mrdoob/three.js/blob/master/examples/webxr_xr_dragging.html

How to get custom eslint working on Visual Studio 2022?

My package.json

{
    ...
    "main": "index.js",
    "type": "module",
    "scripts": {
        "start": "node index.js"
    },
    "dependencies": {
        ...
    },
    "engines": {
        "node": "18.x"
    },
    "devDependencies": {
        "@eslint/js": "^9.3.0",
        "eslint": "^9.9.1",
        "globals": "^15.3.0"
    },
    "eslintConfig": {}
}

Then i have on the root folder a file .eslintrc.cjs

module.exports = 
{
    "env"                   : 
    {
        "browser"           : true,
        "es2021"            : true
    },
    "extends"               : "eslint:recommended",
    "globals"               : 
    {
        "global"            : "writable",
        "isObject"          : "readonly",
        ...
    },
    "overrides"             : 
    [
        {
            "env"           : 
            {
                "node"      : true
            },
            "files"         : [ ".eslintrc.{js,cjs}" ],
            "parserOptions" : 
            {
                "sourceType": "script"
            }
        }
    ],
    "parserOptions"         :
    {
        "ecmaVersion"       : "latest",
        "sourceType"        : "module"
    },
    "rules"                 :
    {
    }
}

and eslint.config.js

import globals from "globals";
import pluginJs from "@eslint/js";

export default [
  {languageOptions: { globals: globals.browser }},
  pluginJs.configs.recommended,
];

I have isObject on another .js file as

globalThis.isObject = function(value)
{
    if (typeof value === 'object' && value !== null && !Array.isArray(value))
        return true
    return false
}

I dont know whats happening, looks like its ignoring the eslintrc.cjs file, because everywhere i have isObject(...)
eslint is throwing 'isObject' is not defined., this also happens with any other variables i define on the "globals" array.

My nodejs project is working correctly, just the eslint errors.

Similar question for VS 17/19 but the option on the accept answer no longer exists on VS22.

Unable to install Express with npm because of local certification problem

I tried installing the express module with the command:

npm install express

But I get this error:

npm warn old lockfile   code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
npm warn old lockfile   errno: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
npm warn old lockfile   type: 'system'
npm warn old lockfile }
npm warn old lockfile Could not fetch metadata for [email protected] FetchError: request to https://registry.npmjs.org/ini failed, reason: unable to get local issuer certificate

And it takes forever to load. Please help me if you’ve been through this or something similar.

I tried installing other packages such as lodash and got the same error. It seems I have a problem with certifications. But why would I need any certification to get a free package ?

I uninstalled node and then reinstalled so I have the latest version.

I tried disabling the SSL security with this command:

npm config set strict-ssl false

I also used:

npm config set registry https://registry.npmjs.org/

But nothing seems to work. I tried everything chatGPT advised me to do but all my attempts were unsuccessful. I haven’t found anyone on stack overflow with the same problem.

Advice regarding the design my service removal feature for my API gateway?

I’m a relatively inexperienced developer.

I have been recently trying to design an ad-hoc Restful API gateway as a personal project and I seem to have hit a roadblock with the service removal feature.

Here’s how my processed work, my custom loadbalancer creates a object for all the available services and endpoints the gateway provides access to. I also have an internal route which allows services to hit my gateway and add themselves to my service registry. The problem here lies the deletion of services from the data store if they are not accessible/non operational.

My current solution for this problem is to mark a service as down upon receiving a “ECONNREFUSED” signal from the service. This pushes the service to a global queue or in memory data store like Redis. A cron job will be active which monitors the queue in a set duration of time, retries the connection, and upon an error, removes the service from the service regsitry.

Does this sound like a relatively optimised solution to the problem or rather would you suggest a different approach. And if this is a good enough approach, how to go about setting up the architecture for the global queue and cron job. Thanks

how to click cq-toggle element dynamically using javascript

how to click cq-toggle element dynamically using javascript?
When i click manually on cq-toggle menu item it actually adds active class to the element cq-toggle and add one div content in document HTML. I want to click cq-toggle dynamically using javascript.

<div class="ciq-menu-section">
    <div class="ciq-dropdowns">
        <cq-toggle class="ciq-DT tableview-ui" cq-member="tableView">
              <span></span>
              <cq-tooltip>
                 <translate original="Table View">Table View</translate>
              </cq-tooltip>
        </cq-toggle>

I have tried

 const tableViewToggle = frameDocument.querySelector(".tableview-ui")
 tableViewToggle.click();

also

tableViewToggle.classList.toggle('active');

but it is not working.

My for loop isn’t running and I’m not sure why. It won’t even print anything to the console

I’m trying to make a jeopardy game and I need to add the questions to a table. I’m using a forEach loop to loop over all the categories first and then I want to use a for loop inside the forEach loop to loop over all the clue questions. I’ve been stuck on this for a while. I think having the forEach loop makes sense I’m just so confused as to why the for loop isn’t running at all.

let categories = [
    {title: "Art",
        clues: [
            {question: "Who painted the Sistine chapel ceiling?", answer: "Michelangelo", showing: null},
            {question: "Aureolin is a shade of what color?", answer: "yellow", showing: null},
            {question: "The Parthenon Marbles are controversially located in what museum?", answer: "the British Museum", showing: null},
            {question: "What is the real title of Salvador Dali’s “melting clocks” painting?", answer: "The Persistence of Memory", showing: null},
            {question: "Which art trend became incredibly popular in 2023, although originally first appeared in the 1960s?", answer: "AI art", showing: null},
            {question: "Which of the following is NOT a painting by Salvador Dali; ‘The Temptation of St. Anthony’, ‘The Hallucinogenic Toreador’ or ‘The Sleeping Gypsy’?", answer: "The Sleeping Gypsy", showing: null}
        ],
    },
    {title: "Tech",
        clues: [
            {question: "What app has a green owl as the mascot?", answer: "Duolingo", showing: null},
            {question: "What software company is headquartered in Redmond, Washington?", answer: "Microsoft", showing: null},
            {question: "What software development hosting company has an Octocat for the logo?", answer: "GitHub", showing: null},
            {question: "What programming language is named after a type of Indonesian coffee?", answer: "Java", showing: null},
            {question: "One gigabyte is equal to how many megabytes?", answer: "1000", showing: null},
            {question: "What company made the first portable computer in 1981?", answer: "Osborne Company", showing: null}
        ],
    },
    {title: "Music",
        clues: [
            {question: "What music festival is the most iconic and highly anticipated in the world?", answer: "Lollapalooza", showing: null},
            {question: "Which pop star uses the alias 'Mrs.Doubtfire'", answer: "Sabrina Carpenter", showing: null},
            {question: "Who released the album 'Swimming' in 2018", answer: "Mac Miller", showing: null},
            {question: "Who is the youngest person to headline the Pyramid stage at Glastonbury?", answer: "Billie Eilish", showing: null},
            {question: "Who is the worlds richest pop star?", answer: "Paul McCartney", showing: null},
            {question: "What artist was working at a summer camp as a counsellor just last year but is now a pop sensation?", answer: "", showing: null}
        ],
    },
    {title: "Nature",
        clues: [
            {question: "What is a group of crows called?", answer: "a murder", showing: null},
            {question: "Which planet has the most moons?", answer: "Saturn", showing: null},
            {question: "What is the slowest-moving mammal on earth?", answer: "a sloth", showing: null},
            {question: "Which animal sleeps the least at two hours a day on average?", answer: "an elephant", showing: null},
            {question: "What is the worlds fastest growing plant?", answer: "bamboo", showing: null},
            {question: "What animal are birds descended from?", answer: "dinosaurs", showing: null}
        ],
    },
    {title: "Random",
        clues: [
            {question: "According to Greek mythology, what famed warrior died because he took an arrow to the heel?", answer: "Achilles", showing: null},
            {question: "How many dots appear on a pair of dice?", answer: "42", showing: null},
            {question: "What is the dot over a lowercase letter 'I' called?", answer: "a title", showing: null},
            {question: "Who wrote the famous novel To Kill a Mockingbird?", answer: "Harper Lee", showing: null},
            {question: "How many zip codes are in the US?", answer: "41,642", showing: null},
            {question: "What is the name of the scale used to measure spiciness of peppers?", answer: "Scoville scale", showing: null}
        ],
    },

];

function fillTable() {
    const table = document.querySelector('table');
    const row = table.insertRow();
    categories.forEach( category => {
        const title = row.insertCell(0);
            title.innerHTML = category.title;
        
        for(let i = 0; i < category.clues[i].length; i++){
            console.log(category.clues[i])
            // const clue = row.insertCell 
            // clue.innerHTML = category.clues[i]
        }
    })
}  
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Jeopardy</title>
  <link rel="stylesheet" href="jeopardy.css">
</head>
<body>
    <h1>jeopardy</h1>
    <table>
        
    </table>
<script src="jeopardy.js"></script>

</body>
</html>

How to mix audio with specific delays in FFMPEG

I have an array that contains paths to audio files along with delay durations (in ms). Something like ["audio1.wav", 300, "audio2.wav", 350, "audio3.wav", 280, "audio4.wav"]

I want to mix the audio such that every subsequent audio file is added after X delay, where X is the immediately proceeding delay duration.

Here’s an illustration of what the final audio should look like:

Diagram of how audio should be concatenated

Here’s the code I’ve written (using the FFMpeg Kit library):

export const concatenateAudio = async (
  audioSequence: (string | number)[],
  outputFile: string
): Promise<string> => {
  try {
    let filterComplex = "";
    let inputs = "";
    let mixInputs = "";
    let currentOffset = 0;
    let inputIndex = 0;

    for (let i = 0; i < audioSequence.length; i++) {
      const item = audioSequence[i];
      if (typeof item === "string") {
        // It's an audio file
        inputs += `-i "${item}" `;
        if (inputIndex === 0) {
          filterComplex += `[${inputIndex}:a]`;
          mixInputs += `[${inputIndex}:a]`;
        } else {
          filterComplex += `[${inputIndex}:a]adelay=${currentOffset}|${currentOffset}[delayed${inputIndex}];`;
          mixInputs += `[delayed${inputIndex}]`;
        }
        inputIndex++;
      } else if (typeof item === "number" && i < audioSequence.length - 1) {
        // It's a silence duration, add it to the current offset
        currentOffset += item;
      }
    }

    filterComplex += `${mixInputs}amix=inputs=${inputIndex}:dropout_transition=0[out]`;

    const command = `${inputs} -filter_complex "${filterComplex}" -map "[out]" -y "${outputFile}"`;
    console.log(`Executing FFmpeg command: ${command}`);

    const session = await FFmpegKit.execute(command);
    const returnCode = await session.getReturnCode();
    const output = await session.getOutput();

    console.log(`FFmpeg output: ${output}`);

    if (ReturnCode.isSuccess(returnCode)) {
      return outputFile;
    } else {
      throw new Error(
        `FFmpeg process exited with returnCode ${returnCode}. Output: ${output}`
      );
    }
  } catch (error) {
    console.error(`Error concatenating audio files: ${error}`);
    throw error;
  }
};

I don’t think I’m using adelay properly. If anyone has any suggestions or advice, that would be super appreciated!

How to read prop value inside pseudo element in styled-components?

I’ve been trying to read the value which was passed down by a prop. I’m trying to read it inside ::before pseudo element:

Button/index.tsx

export const Button: FC<ButtonProps> = ({children, ...props}) => {
    return <_Button $textValue="TEST" {...props}>
        <p style={{color: 'red'}}>{children}</p>
    </_Button>
};

Button/styles.ts

import styled from "styled-components";

const colors = {black: 'var(--color-black)', white: 'var(--color-white)'};

type ButtonColors = "black" | "white";

export type ButtonProps = {
    $color?: ButtonColors;
    $background?: ButtonColors;
}

export const _Button = styled.button<ButtonProps & {$textValue: string}>`
    color: ${(props) => props.$color && colors[props.$color]};
    background: ${(props) => props.$background && colors[props.$background]};
    cursor: pointer;
    border-radius: 6px;
    border: none;
    padding: 14px 24px; 
    text-transform: uppercase;
    position: relative;
    &::before {
        content: ${(props) => props.$textValue};
        width: 2rem;
        height: 2rem;
        position: absolute;
        left: 0;
        top: 2rem;
        color: green;
    }
`;

_Button.defaultProps = {
    $color: "white",
    $background: "black"
}

However, it does not appear in the DOM (it doesn’t get rendered).

No ::before element seen

How can I do it? Is it even possible to read a value like that?

“TypeError: Cannot read properties of undefined” using clientside_callback in dash python

I am using dash and manitine components to create a website. To keep control over packages and running the website I am using poetry. The website should have a clientside_callback for when clicking a button (with any kind of action like alert or console.log() to see that it works). I wanted to use ClientsideFunction to register the callback.

When implementing the callback using ClientsideFunction and running the website with poetry run -m website I get the error

TypeError: Cannot read properties of undefined (reading 'showAlert')
    at _callee2$ (callbacks.ts:160:40)
    at tryCatch (callbacks.ts:2:1)
    at Generator.<anonymous> (callbacks.ts:2:1)
    at Generator.next (callbacks.ts:2:1)
    at asyncGeneratorStep (callbacks.ts:2:1)
    at _next (callbacks.ts:2:1)
    at callbacks.ts:2:1
    at new Promise (<anonymous>)
    at callbacks.ts:2:1
    at _handleClientside (callbacks.ts:209:2)

showAlert is defined like this in /assets/js/callbacks.js.

window.dash_clientside = Object.assign({}, window.dash_clientside, {
    clientside: {
        showAlert: function(n_clicks) {
            console.log("this worked!");
            return '';
        }
    }
});

In callbacks.py I have defined namespace and function_name that should be present in a js file (which is /assets/js/callbacks.js).

from dash import dash, Output, State, Input, callback_context, clientside_callback, ClientsideFunction

def get_callbacks(app):
    app.clientside_callback(
        ClientsideFunction(
            namespace="clientside",  # Namespace in the JavaScript file
            function_name="showAlert"  # Function name defined in the JavaScript file
        ),
        Output('connection_status', 'color'),
        Input('vnc_connect', 'n_clicks')
    )

This is __main__.py where the server gets the layout and callbacks.

import dash_mantine_components as dmc
from dash import Dash, _dash_renderer, html, Input, Output, callback, State
from website.layout import get_layout
from website.callbacks import get_callbacks

_dash_renderer._set_react_version("18.2.0")

app = Dash(assets_ignore=r"(?!callbacks.js).*") # I only want this file to run

app.layout = get_layout()

get_callbacks(app)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True, port="8000")

This is layout.py with three simple components from mantine.

import dash_mantine_components as dmc
from dash import html

def get_layout():
    return dmc.MantineProvider(
        [
            dmc.Container([
                dmc.Badge("Disconnected", variant="dot", color="yellow", id="connection_status"),
                dmc.Button("Connect to Server", id="vnc_connect", w=200),
                dmc.PasswordInput(label="Server Password", w=200, id="server_password",placeholder="Server password", required=True),
            ])
        ]
    )

This is my current directory structure

├── poetry.lock
├── pyproject.toml
└── website
    ├── __init__.py
    ├── __main__.py
    ├── assets
    │   └── js
    │       └── callbacks.js
    ├── callbacks.py
    └── layout.py

The error is not always 100% persistent when reloading the page, but persistent enough to cause trouble on the client side.

My problem seems to be a bit similar to this problem. When imbeding javascript in the callback directly like this it works much better.

def get_callbacks(app):
    app.clientside_callback(
        """
        function(value) {
            alert("asd");
        }
        """,
        Output('connection_status', 'color'),
        Input('vnc_connect', 'n_clicks')
    )

But why he gets undefined when trying to put the javascriot in a js file instead is not answered.

After digging a bit I saw that when putting the javascript in a file and it does work it is seen here, and when it doesnt work its not seen.

html from page

Why would my required js file sometimes appear, and other times not? And how do I fix it?

How to fix codeblock blocking execution

async function getMatchesByFixtureId(id){

  let count = 0;
  let request = true;
  let response;

  const options = {
    method: 'GET',
    url: 'https://api-football-v1.p.rapidapi.com/v3/fixtures',
    params: {id: id},
    headers: {
      'x-rapidapi-key': API_KEY,
      'x-rapidapi-host': 'api-football-v1.p.rapidapi.com'
    }
  };

  async function innerFunction(){
    
    
      if(request === true){

        response = await axios.request(options);
        const match = response.data.response;
        console.log(match);
        let status;
        console.log(1);


              if(["CANC", "FT", "AET", "PEN", "PST", "AWD", "WO"].includes(match.fixture.status.short)){
                status = "FT";
                if(count === 4){
                  request = false;
                }
                count++;
              }
              
              else if(["TBD", "NS"].includes(match.fixture.status.short)){
                status = "SC";
                count = 0;
              }
              else if(["HT", "LIVE", "1H", "2H", "ET", "BT", "P"].includes(match.fixture.status.short)){
                status="LIVE";
                count = 0;
              }
  
          console.log(2);
          
  
        const fixture = {
           Bunch of data
        }
  
        console.log(3);
  
        
        await client.db("db").collection("matches").replaceOne(fixture);

      }

      else{
        return;
      }

  }

  const task = cron.schedule("* * * * *", async() => {
    
    await innerFunction();

  }, {timezone: "UTC"});
  task.start();

  setTimeout(task.stop, 8.1e+6)

}

So basically the getMatchesByFixtureId() above is called by another function which schedules the execution of getMatchesByFixtureId() and getMatchesByFixtureId() requests from api-football a live football match with the matching fixture id every minute.

The problem is that the code between console.log(1) and console.log(2) blocks the execution of the code bellow and when I comment it out the code between console.log(2) and console.log(3) blocks the code below if anyone is wondering yes the api request work fine I receive the right data

How to scrolling a page just so that it doesn’t affect the background image and fixed element?

I make a page with support like in chatbots, that is, messages are added at the top, and Form Field is added at the bottom, when there are a lot of messages and they do not fit into the screen, they stand behind the form, they go down where the background image ends, I would like only messages to move when scrolling and do not go behind the form, that is, the background-attachment was fixed, but if I set background-attachment: fixed; It turns out not what he wanted
i tried using background-attachment: fixed; but it dont help. Fixed element it is form your text html code:

<div id="img">
    <div class="container-fluid justify-content-center d-flex">
        <div class="blur-us">
            {% for mess in messages %}
            <div class="d-flex {% if loop.index is odd %}justify-content-start{% else %}justify-content-end{% endif %} mb-2">
                <div class="message bg-dark p-3" style="color:white;">{{ mess }}</div>
            </div>
            {% endfor %}
            <div>
                <div class="container my-form d-flex">
                    <form action="/contact" method="post" id="myForm">
                        <div class="position-relative">
                            <textarea id="dynamic-textarea" oninput="adjustHeight(this)" name="txtarea" data-limit-rows="true" maxlength="450" rows="1" class="mb-3 bg-dark" placeholder="Ask about site"></textarea>
                            <button type="submit" class="arr">
                                <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 32 32" class="icon-2xl">
                                    <path fill="currentColor" fill-rule="evenodd" d="M15.192 8.906a1.143 1.143 0 0 1 1.616 0l5.143 5.143a1.143 1.143 0 0 1-1.616 1.616l-3.192-3.192v9.813a1.143 1.143 0 0 1-2.286 0v-9.813l-3.192 3.192a1.143 1.143 0 1 1-1.616-1.616z" clip-rule="evenodd"></path>
                                </svg>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

css code:

#img { background-image: url("coffeeShop.jpg"); height: 100vh; background-repeat: no-repeat; background-size: cover; } 

.blur-us {
height: 93vh;
width: 900px;
padding:50px;
padding-bottom:0px;
}

.my-form { position: fixed; bottom: 0; z-index:4; padding-top: 10px; }

#dynamic-textarea {
height: auto;
width: 800px;
padding: 15px;
padding-right: 70px;
box-sizing: border-box;
border-radius: 50px;
border: 1px solid #ccc;
resize: none;
color: #fff;
background-color: #333;
overflow-y: hidden;
}

Using Javascript in TPL

How can I use JavaScript code in a TPL file to make the content of the JavaScript code appear on the page?

When I enter the code there is no error message, but nothing appears on the page either.

This is an indication of how long the site has existed.

This is the code

<script type='text/javascript'>
<!--
today = new Date();
bYear  = 2021;  // Start Jahr
bMonth = 4;    // Start Monat
bDay   = 7;  // Start Tag
tYear  =  today.getFullYear();
tMonth =  (today.getMonth() ) + 1 ;
tDay   =  today.getDate();
tHour  =  today.getHours();
fYear  = 0;
fMonth = 0;
fDay   = 0;
fHour  = 0;
x = 0;
y = 0;
z = 0;
a = 0;
b = 0;
c = 0;
function testMonth() {
     if (y==4 || y==6 || y==9 || y==11) x=30
     else if (y==2) x=28
     else x=31
}
function testDay() {
     fDay = (z - bDay) + tDay;
          if (fDay > a) {
               fMonth += 1;
               fDay = fDay - a;
          }
}
y = bMonth;
testMonth();
z = x;
y = bMonth;
testMonth();
a = x;
if (bMonth <= tMonth) {
     fYear = tYear - bYear;
     fMonth = (tMonth - bMonth);
     testDay();
}
fYear = (tYear - bYear) - 1
fMonth = ((12 - bMonth) + tMonth) - 1;
testDay();
if (fMonth >= 12) {
     fYear += 1;
     fMonth -= 12;
}
with(Math) {
theYear=fYear;
tensYear=floor(theYear/10);
onesYear=theYear-(tensYear*1);
theMonth=fMonth
tensMonth=floor(theMonth/10);
onesMonth=theMonth-(tensMonth*1);
theDay=fDay
tensDay=floor(theDay/10);
onesDay=theDay-(tensDay*1);
var testArray = new makeArray("Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember");
for (z=1; z<=12; z++) {
  if (tMonth==z) {
      var b=testArray[z]
   }
}
for (z=1; z<=12; z++) {
  if (bMonth==z) {
      var c=testArray[z]
   }
}
}
var page
page = "<b><center>"+tDay+". "+b+" "+tYear+".</b><br /><br></center>"
page += "<b><center>Eröffnung </b><br> "+bDay+". "+c+" "+bYear+"</center><br>"
page += "<center><b>Forum online seit...</b><br> "
if(parseInt(tensYear+onesYear) == 1) {
    page += tensYear + onesYear + " Jahr</center></b>,<b> "
}
else {
    page += tensYear + onesYear + " Jahre , "
}
if(parseInt(tensYear+onesYear) == 0) {
    page += ""
}

if(parseInt(tensMonth+onesMonth) == 1) {
    page += tensMonth + onesMonth + " Monat und "
}
else {
    page += tensMonth + onesMonth + " Monate und "
}
if(parseInt(tensDay+onesDay) == 1) {
    page += tensDay + onesDay + " Tag</b>."
}
else {
    page += tensDay + onesDay + " Tage</b>."
}
function makeArray() {
      this.length = makeArray.arguments.length
      for (var i = 0; i < this.length; i++)
      this[i+1] = makeArray.arguments[i]
}
//-->
</script>

does anyone know a solution

I tried to insert it as a script into the TPL file and I tried to insert the script in {literal}{/literal}.

useState is not updating on an object type

const [firebaseUser, setfirebaseUser] = useState({});

const onSignUp = async (data: FormData) => {
    setDisableButton(true);
    try {
      const userCredential = await createUserWithEmailAndPassword(auth, data.email, data.password);
      const user = userCredential.user;

      console.log({ ...user });

      setFireBaseError(null);
      setfirebaseUser({ ...user });
      console.log("Firebase user:", firebaseUser); // empty object 

      if (user) {
        await sendEmailVerification(user);
      }

      navigate("/verify-email");
    } catch (err: any) {
      setDisableButton(false);
      if (err.message.includes("email-already-in-use")) {
        setFireBaseError("Email already in use");
      } else if (err.message.includes("weak-password")) {
        setFireBaseError("Password is too weak. Please use at least 6 characters");
      } else if (err.message.includes("invalid-email")) {
        setFireBaseError("Please enter a valid email address");
      }
    }
  };

I am trying to use the function setfirebaseUser so I can pass this useState to another page. It is never working as when I use the function and use the spread operator to setfirebaseUser and print out the firebaseUser on the next line, only an empty object shows. However when I console.log above using the spread operator on user when I use the setfirebaseUser, the whole object of the firebase user shows with its details.

Linear Programming with Multiple Constraints using javascript-lp-solver

const Solver = require('javascript-lp-solver');

// Define the available array
let available = [
    [3, 0, 1], [2, 0, 2], [0, 2, 3], [2, 2, 2], [3, 0, 4],
    [0, 0, 1], [4, 4, 4], [4, 4, 2], [1, 0, 0], [4, 3, 3],
    [0, 0, 0], [0, 3, 3], [4, 3, 0], [1, 2, 4], [1, 4, 0],
    [2, 4, 0], [0, 1, 2], [2, 3, 0], [2, 3, 4], [0, 2, 2],
    [3, 3, 1], [1, 1, 0], [3, 2, 1], [3, 0, 1], [4, 1, 1],
    [2, 4, 2], [2, 0, 3], [0, 3, 3], [4, 2, 1], [4, 2, 2]
];

// Define the row constraints (maximum sum for each row)
let row_constraints = [
    2, 2, 2, 1, 3, 2, 1, 1, 2, 1,
    1, 2, 1, 1, 2, 1, 2, 1, 2, 4,
    1, 2, 1, 1, 2, 1, 1, 2, 1, 1
];

// Initialize the problem
let problem = {
    "optimize": "randomObjective",
    "opType": "max",
    "constraints": {
        "total_sum": { "equal": 15 }
    },
    "variables": {},
    "ints": {}
};

// Define variables and constraints
for (let i = 0; i < 30; i++) {
    for (let j = 0; j < 3; j++) {
        let varName = `new_${i}_${j}`;

        // Initialize each variable in the problem
        problem.variables[varName] = { randomObjective: Math.random() };

        // Enforce the constraints from available[x][y]
        problem.constraints[varName] = {
            "max": available[i][j]
        };

        // Mark as an integer variable
        problem.ints[varName] = 1;

        // Row constraints
        if (!problem.constraints[`row_${i}`]) {
            problem.constraints[`row_${i}`] = { "max": row_constraints[i] };
        }
        problem.variables[varName][`row_${i}`] = 1;

        // Column constraints
        if (j === 0 && !problem.constraints[`col_0`]) {
            problem.constraints[`col_0`] = { "max": 5 };
        }
        if (j === 1 && !problem.constraints[`col_1`]) {
            problem.constraints[`col_1`] = { "max": 15 };
        }
        if (j === 2 && !problem.constraints[`col_2`]) {
            problem.constraints[`col_2`] = { "max": 5 };
        }
        problem.variables[varName][`col_${j}`] = 1;

        // Total sum constraint
        problem.variables[varName]["total_sum"] = 1;
    }
}

// Solve the problem
let solution = Solver.Solve(problem);

// Initialize the final array
let newArray = Array(30).fill(0).map(() => Array(3).fill(0));
let totalSum = 0;

// Populate the array while enforcing the total sum constraint
for (let i = 0; i < 30; i++) {
    for (let j = 0; j < 3; j++) {
        let varName = `new_${i}_${j}`;
        let value = solution[varName];

        // Handle undefined values by setting them to 0
        if (value === undefined) {
            value = 0;
        }

        // Enforce that value is within the allowed range
        if (value > available[i][j]) {
            value = available[i][j];
        }

        // Adjust total sum and assign value if it does not exceed total_sum constraint
        if (totalSum + value <= 15) {
            newArray[i][j] = value;
            totalSum += value;
        } else {
            // If adding this value would exceed the total sum constraint, adjust it
            let remaining = 15 - totalSum;
            newArray[i][j] = remaining > 0 ? Math.min(remaining, value) : 0;
            totalSum += newArray[i][j];
        }

        // Break the loop if the total sum has been reached
        if (totalSum === 15) {
            break;
        }
    }
    if (totalSum === 15) {
        break;
    }
}

// Output the solution and total sum
console.log(newArray);
console.log("Total Sum:", totalSum);

Constraints Summary

I’ve assigned available[x][y] manually. I want to generate new[x][y]

  1. Available Array Constraints:

    • new[x][y] <= available[x][y] for all x and y.
  2. Row Sum Constraints:

    • new[x][0] + new[x][1] + new[x][2] <= row_constraints[x] for each x.
  3. Column Sum Constraints:

    • Sum of (new[x][0] for all x) <= 5
    • Sum of (new[x][1] for all x) <= 15
    • Sum of (new[x][2] for all x) <= 5
  4. Total Sum Constraint:

    • Sum of all new[x][y] = 15
  5. Integer Constraint:

    • new[x][y] must be an integer for all x and y.

However, the total sum constraint is not working. What am I doing wrong?

Selected Option Not Displayed in Dropdown Placeholder After Fetching Data

I’m working on a project where I’m fetching data from a database using a Laravel API. The data is used to populate a dynamic dropdown list. When I select an option from the dropdown, the correct data is returned based on the selected option, but the selected option is not displayed in the dropdown’s placeholder bar after selection.
Here’s the relevant part of my code:

import { useState, useEffect } from "react";
import axios from "axios";
import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "@headlessui/react";
import { CheckIcon, ChevronDownIcon } from "@heroicons/react/20/solid";
import { HiOutlineUserGroup } from "react-icons/hi2";

export default function SelectCategory({ onChange ,value}) {
  const [categoryData, setCategoryData] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null); // Initially no category selected

  useEffect(() => {
    axios
      .get("http://127.0.0.1:8000/api/tourCategory")
      .then((response) => {
        const data = response.data || [];
        setCategoryData(data);
      })
      .catch((error) => {
        console.error("Error fetching category:", error);
      });
  }, []);

  const handleCategoryChange = (category) => {
    console.log("Selected Category:", category); // Debugging line
    setSelectedCategory(category.category);
    if (onChange) {
      onChange(category.category); // Pass the entire category object or adjust as needed
    } else {
      console.error("onChange function is not defined");
    }
  };
  
  return (
    <Listbox value={selectedCategory} onChange={handleCategoryChange}>
      <div className="relative">
        <ListboxButton className="relative w-full h-[5vw] border-x-[0.1vw] cursor-default text-center text-gray-900 hover:ring-1 hover:ring-inset hover:ring-gray-300 focus:outline-none ">
          <span className="mx-[0.5vw] border-b-[0.1vw] flex justify-between">
            <div className="mr-[0.7vw]">
              <HiOutlineUserGroup className="text-black h-[1.7vw] w-[1.7vw]" />
            </div>
            <label className="font-semibold mr-[0.7vw] text-[1.5vw]">Category</label>
            <div>
              <ChevronDownIcon
                aria-hidden="true"
                className="h-[2vw] w-[2vw] text-gray-800"
              />
            </div>
          </span>
          <span>
            <span className="ml-[1vw] text-sm text-gray-500 block truncate">
              {selectedCategory ? selectedCategory.category : "Select a category"}
            </span>
          </span>
        </ListboxButton>

        <ListboxOptions className="absolute z-10 mt-1 max-h-[20vw] w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
          {categoryData.length > 0 ? (
            categoryData.map((category, index) => (
              <ListboxOption
                key={index}
                value={category}
                className="group relative cursor-default select-none py-2 pl-3 pr-9 text-gray-900 hover:bg-[#247D7E] hover:text-white"
              >
                <div className="flex items-center">
                  <span className="block truncate font-normal group-data-[selected]:font-semibold">
                    {category.category}
                  </span>
                </div>
                <span className="absolute inset-y-0 right-0 flex items-center pr-4 text-[#247D7E] group-data-[focus]:text-white [.group:not([data-selected])_&]:hidden">
                  <CheckIcon aria-hidden="true" className="h-5 w-5" />
                </span>
              </ListboxOption>
            ))
          ) : (
            <p className="py-2 pl-3 pr-9 text-gray-900">
              No categories available.
            </p>
          )}
        </ListboxOptions>
      </div>
    </Listbox>
  );
}

  • The dropdown correctly fetches and displays the options.
  • After selecting an option, the expected data is returned, but the selected option is not shown in the dropdown’s placeholder he allways show “select category” text.