How to extend the Request type in Express by declaring and merging the type?

This is my type declaration file types/index.d.ts:

declare module 'express-serve-static-core' {
  export interface Request {
    user: User
  }
}

While this adds the user property, it makes all my standard router arguments throw a TS error that the arguments implicitly have any type:

// the req, res, next have the ts error
router.get('/', async (req, res, next) => { 

I can fix this by adding an import to the index.d.ts file, but I don’t understand why this works or if it is correct:

import { Request } from 'express-serve-static-core'

declare module 'express-serve-static-core' {
  export interface Request {
    user: User
  }
}

Alternatively, I can also fix it by declaring the Express namespace:

declare namespace Express {
  export interface Request {
    user: User
  }
}

That also works, but again, I don’t know if it’s correct. From everything I’m reading, the first option should work. This is my tsconfig file:

{
  "compilerOptions": {
    "lib": ["ES2019"],
    "module": "NodeNext",
    "rootDir": "./src",
    "allowJs": true,
    "checkJs": true,
    "sourceMap": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*", "types"]
}

Javascript 3D projection, avoid objects rotating around themselves

I am working with 3D projection in Javascript canvas and I’m encountering an issue with the camera.

(Note that in this scene, the camera is fixed and the world objects move/rotate around the camera.)

When the mouse (set to look around fps style) does circular movements, the objects in the scene appear to rotate around themselves.

This should in theory not be happening since I set the rotation of the Meshes to be around the camera when the mouse moves. Any ideas how I could fix this behaviour ?

When running the program :
Lock/hide the mouse by clicking once into the screen, then its basic FPS controls, WASD to move, QE to go up or down, mouse to look around.

Here is the code :

//GLOBAL CONSTANTS
const MOVESPEED = 0.5;
const MOUSESPEED = 0.0006;

//GLOBAL VARIABLES
let canvas;
let ctx;
let prevMouseX = 0;
let prevMouseY = 0;


//OBJECTS
let camera = {x: 0, y: 0, z: -30, fov: 60};
let world = [];


//CLASSES
class Tri
{
  constructor(v1,v2,v3,col)
  {
    this.points = [v1, v2, v3];
    this.color = col;
    this.behind = false;
  }

  normal()
  {
    let v1 = this.points[1].sub(this.points[0]);
    let v2 = this.points[2].sub(this.points[0]);

    let n = v1.cross(v2);

    return n.normalize();
  }

  facing()
  {
    let cam = new Vector3(camera.x,camera.y,camera.z);

    let n = this.normal();
    let vc = cam.sub(this.points[0]);
    let d = n.dot(vc);

    if (vc.z >= -9) this.behind = true;
    else this.behind = false;

    return d > 0;
  }

  rotate(ax,ay,center)
  {
    let x = ax * (180 / Math.PI);
    let y = ay * (180 / Math.PI);

    const cosX = Math.cos(x);
    const sinX = Math.sin(x);
    const cosY = Math.cos(y);
    const sinY = Math.sin(y);

    let nt = [];

    this.points.forEach(p =>
    {
      //translate to center
      let point = {x: p.x - center.x, y: p.y - center.y, z: p.z - center.z};

      // Rotate around X-axis
      const y1 = point.y * cosX - point.z * sinX;
      const z1 = point.y * sinX + point.z * cosX;

      // Rotate around Y-axis
      const x2 = point.x * cosY + z1 * sinY;
      const z2 = -point.x * sinY + z1 * cosY;

      nt.push(new Vector3(x2 + center.x, y1 + center.y, z2 + center.z));
    });

    return new Tri(nt[0],nt[1],nt[2],this.color);
  }
}

class Mesh
{
  constructor(tris)
  {
    this.tris = tris;
    world.push(this);
  }

  draw()
  {
    this.tris.forEach(e=>
    {
      if (!e.facing() && !e.behind) draw(e);
    })
  }

  rotate(ax,ay)
  {
    let rtris = [];

    //rotate around Camera
    let cx = camera.x;
    let cy = camera.y;
    let cz = camera.z;

    /* rotate around center of Mesh
    this.tris.forEach(e=>
    {
      cx += (e.points[0].x + e.points[1].x + e.points[2].x);
      cy += (e.points[0].y + e.points[1].y + e.points[2].y);
      cz += (e.points[0].z + e.points[1].z + e.points[2].z);
    })
    cx = cx / (this.tris.length * 3);
    cy = cy / (this.tris.length * 3);
    cz = cz / (this.tris.length * 3);
    */

    let center = {x: cx, y: cy, z: cz};

    this.tris.forEach(e=>
    {
      rtris.push(e.rotate(ax,ay,center));
    })
    this.tris = rtris;
  }
}

class Vector3
{
  constructor(x,y,z)
  {
    this.x = x;
    this.y = y;
    this.z = z;
  }

  add(v)
  {
    return new Vector3(
      this.x + v.x,
      this.y + v.y,
      this.z + v.z
    )
  }

  sub(v)
  {
    return new Vector3(
      this.x - v.x,
      this.y - v.y,
      this.z - v.z
    )
  }

  cross(v)
  {
    return new Vector3(
      this.y * v.z - this.z * v.y,
      this.z * v.x - this.x * v.z,
      this.x * v.y - this.y * v.x,
    )
  }

  dot(v)
  {
    return this.x * v.x + this.y * v.y + this.z * v.z;
  }

  normalize()
  {
    let m = Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2);

      return new Vector3(
        this.x / m,
        this.y / m,
        this.z / m,
      )
  }
}


//FUNCTIONS
function init()
{
  canvas = document.createElement('canvas');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  canvas.style.display = 'block';
  ctx = canvas.getContext('2d');

  canvas.onclick = function()
  {
    canvas.requestPointerLock();
  }

  document.body.appendChild(canvas);
}

function project(point)
{
  let d = camera.z - point.z;
  let s = canvas.width / (2 * Math.tan((camera.fov * Math.PI) / 360) * d);
  let nx = canvas.width / 2 - point.x * s;
  let ny = canvas.height / 2 + point.y * s;

  return {x: nx, y: ny};
}

function draw(t)
{
  let pa = project(t.points[0]);
  let pb = project(t.points[1]);
  let pc = project(t.points[2]);
  
  ctx.strokeStyle = 'white';
  ctx.beginPath();
  ctx.moveTo(pa.x, pa.y);
  ctx.lineTo(pb.x, pb.y);
  ctx.lineTo(pc.x, pc.y);
  ctx.closePath();
  ctx.stroke();
  ctx.fillStyle = t.color;
  ctx.fill();
}

function mouseDir(e)
{
  let deltaX = e.movementX;
  let deltaY = e.movementY;
  let dir = {x: 0, y: 0};

  if (deltaX > 3) dir.x = 'right';
  if (deltaX < -3) dir.x = 'left';

  if (deltaY > 3) dir.y = 'down';
  if (deltaY < -3) dir.y = 'up';

  return dir;
}

// EVENT LISTENERS
//resize canvas with window
window.addEventListener('resize', e=>
{
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
})

//fps kb movements
window.addEventListener('keydown', e=>
{
  if (e.key == 'w') world.forEach(f=>
  {
    f.tris.forEach(g=>
    {
      g.points.forEach(h=>
      {
        h.z -= MOVESPEED * 2;
      })
    })
  })

  if (e.key == 's') world.forEach(f=>
  {
    f.tris.forEach(g=>
    {
      g.points.forEach(h=>
      {
        h.z += MOVESPEED * 2;
      })
    })
  })

  if (e.key == 'a') world.forEach(f=>
  {
    f.tris.forEach(g=>
    {
      g.points.forEach(h=>
      {
        h.x += MOVESPEED;
      })
    })
  })

  if (e.key == 'd') world.forEach(f=>
  {
    f.tris.forEach(g=>
    {
      g.points.forEach(h=>
      {
        h.x -= MOVESPEED;
      })
    })
  })

  if (e.key == 'q') world.forEach(f=>
  {
    f.tris.forEach(g=>
    {
      g.points.forEach(h=>
      {
        h.y -= MOVESPEED;
      })
    })
  })

  if (e.key == 'e') world.forEach(f=>
  {
    f.tris.forEach(g=>
    {
      g.points.forEach(h=>
      {
        h.y += MOVESPEED;
      })
    })
  })

  if (e.key == 'ArrowUp') camera.fov--;

  if (e.key == 'ArrowDown') camera.fov++;

  if (e.key == 'ArrowLeft')
  {
    world.forEach(e=>
    {
      e.rotate(0,MOUSESPEED);
    })
  }

  if (e.key == 'ArrowRight')
  {
    world.forEach(e=>
    {
      e.rotate(0,-MOUSESPEED);
    })
  }
})

//fps mouse movements
window.addEventListener('mousemove', (e) =>
{
  let dir = mouseDir(e);

  world.forEach(e=>
  {
    if (dir.x == 'left') e.rotate(0, MOUSESPEED);
    if (dir.x == 'right') e.rotate(0, -MOUSESPEED);
    if (dir.y == 'up') e.rotate(MOUSESPEED, 0);
    if (dir.y == 'down') e.rotate(-MOUSESPEED, 0);
  })

  prevMouseX = e.clientX;
  prevMouseY = e.clientY;
});


//RUNTIME

init();

// CCwise = front facing / Cwise = back facing
let cube = new Mesh([
  //front face CCW
  new Tri(new Vector3(10,10,0), new Vector3(0,0,0), new Vector3(10,0,0), 'salmon'),
  new Tri(new Vector3(0,10,0), new Vector3(0,0,0), new Vector3(10,10,0), 'salmon'),

  //back face CCW
  new Tri(new Vector3(0,10,10), new Vector3(10,10,10), new Vector3(0,0,10), 'mediumorchid'),
  new Tri(new Vector3(10,0,10), new Vector3(0,0,10), new Vector3(10,10,10), 'mediumorchid'),
  
  //top face CCW
  new Tri(new Vector3(0,10,0), new Vector3(10,10,0), new Vector3(0,10,10), 'gold'),
  new Tri(new Vector3(10,10,10), new Vector3(0,10,10), new Vector3(10,10,0), 'gold'),

  //bottom face CW
  new Tri(new Vector3(0,0,0), new Vector3(0,0,10), new Vector3(10,0,0), 'cyan'),
  new Tri(new Vector3(10,0,10), new Vector3(10,0,0), new Vector3(0,0,10), 'cyan'),

  //left face CCW
  new Tri(new Vector3(0,0,0), new Vector3(0,10,0), new Vector3(0,0,10), 'red'),
  new Tri(new Vector3(0,10,10), new Vector3(0,0,10), new Vector3(0,10,0), 'red'),

  //right face CCW
  new Tri(new Vector3(10,0,0), new Vector3(10,0,10), new Vector3(10,10,0), 'blue'),
  new Tri(new Vector3(10,10,10), new Vector3(10,10,0), new Vector3(10,0,10), 'blue'),
]);

cube.draw();

let update = ()=>
{
  ctx.clearRect(0,0, canvas.width, canvas.height)
  cube.draw();
  requestAnimationFrame(update);
}

requestAnimationFrame(update);
body, html
{
    margin: 0 !important;
    padding: 0 !important;
    overflow: hidden;
    background-color: black;
}
<!DOCTYPE html>

<html>

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">

    <title>3DSCAM</title>
</head>


<body>
</body>

<script src="main.js"></script>

</html>

Cheers

How to automate Ad Topic removal [closed]

I’ve recently been looking through various privacy settings on social media platforms – I’ve always had all forms of tracking disabled as much as possible; despite this I noticed that apart from tailoring ads to your browsing habits, Instagram (and presumably the other Meta products) also collect Ad Topics, which to me sounds like a loophole in regulations that still allows them to direct adverts to people albeit based on a less specific criteria. You can locate this window in Settings > Accounts Centre > Ad Preferences which is separate from Ad Settings (located in the same place). You can click each one and select “See less” – however, the div that houses the names of Ad Topics is ~48,000px high with individual elements at 52px, that’s ~923 topics associated with my account which irks me – am I being paranoid, or does anyone else feel that if you disable Ad Tracking, then there should be no Ad Topics associated with your account beyond maybe language settings at most? I’ve asked with Advertising Standards Agency, but like most regulators I might as well be screaming into the void.
In the meantime, I feel like there must be a way to iterate through those divs with Javascript because obviously it’s absurd to expect anyone to click ~2,700 times to disable these Topics.

I had a look at the page source in the inspector, but honestly it’s so big my computer really wasn’t happy opening it and everything slowed down dramatically – I tried to read through the classes associated with the div elements, there is a little repetition but it seems safer to just iterate through the child elements of the overarching div – the issue I’m encountering though is that the page source changes so dramatically when I click into one element that I’m not sure how to automate iterating through the child elements and then selecting the appropriate check box in the new window – could somebody offer some advice on how to automate this behaviour please?

Many thanks,

Sash

Getting ERROR: Please install mysql2 package manually, even though installed

Here are my index.js and config.json files:

const { Sequelize } = require('sequelize');
const env = process.env.NODE_ENV || 'development';
const config = require('../config/config.json')[env];

const sequelize = new Sequelize({
  dialect: config.dialect,
  storage: config.storage,
  dialectModule: require('mysql2')
});

sequelize.authenticate()
  .then(() => {
      console.log('Connection has been established successfully.');
  })
  .catch(err => {
      console.error('Unable to connect to the database:', err);
  });

module.exports = sequelize;

config.json:

{
  "development": {
    "dialect": "sqlite",
    "storage": "./database.sqlite3",
    "migrations-path": "./migrations" 
  },
  "test": {
    "dialect": "sqlite",
    "storage": "./database_test.sqlite3",
    "migrations-path": "./migrations"
  },
  "production": {
    "dialect": "sqlite",
    "storage": "./database.sqlite3",
    "migrations-path": "./migrations"
  }
}

Error after running npx sequelize-cli db:migrate:

Loaded configuration file “config/config.json”.
Using environment “development”.

ERROR: Please install mysql2 package manually

I have tried installing mysql2 globally and using this command:
npx sequelize-cli db:migrate --env development, but nothing worked

Check if property is undefined using bracket notation

I’m struggling a bit with checking if the property value of an object is undefined when I access it dynamically through bracket notation. Below is an example of my code which uses JSX.

type ProjectDates = {
  start_date?: string;
  end_date?: string;
}
const project: ProjectDates = {
  start_date: "2023-09-13",
  end_date: "2023-09-29"
}

function toBritishDate(dateToFormat: Date | string): string {
  const date: Date = typeof dateToFormat === 'string' ? new Date(dateToFormat) : dateToFormat;
  return new Intl.DateTimeFormat('en-gb', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    timeZone: 'Europe/Berlin',
  }).format(date);
}

{['start_date', 'end_date'].map((element): 'start_date' | 'end_date') => (
  <div>
  {project[element] !== undefined
    ? toBritishDate(project[element])
    : 'Not important'
  }
  </div>
)

When calling toBritishDate I get the following error on match.project[element]:

Argument of type ‘string | undefined’ is not assignable to parameter of type ‘string | Date’.
Type ‘undefined’ is not assignable to type ‘string | Date’. (tsserver 2345)

It seems like match.project[element] !== undefined only checks if the property exists, it doesn’t check if the actual value is undefined. Does anyone know how I can check if the property exists, and that the value is not undefined?

Issue with default audio player in Chromium based browsers

I’m working on a website but I am having issues with the audio player in Chromium based browsers. The audio files play correctly in all browsers but the controls only show up in Firefox. In Chrome or Edge there are no controls, it is only blank space. If I switch the tags to then Chromium browsers have controls, but I can’t get it to work with the tag.

Here are screenshots of what I mean
Firefox
Chrome

Does anyone know what is happening? Here is my HTML for this section of the site

<body>
    <script>
        var dailyAgent = "{{ daily_agent }}";
        var dailyAgentImageFilename = "{{ daily_agent_image_filename }}"; // Add this line
        var selectedFiles = JSON.parse('{{ selected_files | tojson | safe }}');
        var maps = JSON.parse('{{ maps | tojson | safe }}');
    </script>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>      

    <!-- Start of site content-->
    <h1>STEPDLE</h1> 

    <button id="howToPlayBtn" class="how-to-play-button">How to Play</button> 

    <div id="gameArea">
        <div id="mediaContainer">
            <img id="gameImage" src="" alt="Map">
            <audio controls id="agentSound">
                <source src="" type="audio/mpeg">
                Your browser does not support the audio element.
            </audio>            
        </div>
        
        <div id="agentGrid">
            {% for agent_name, agent_data in agents.items() %}
                <div class="agent-container">
                    <img class="agent" src="{{ url_for('static', filename='agents/' + agent_name + '/' + agent_data['icon']) }}" alt="{{ agent_name }}">
                    <div class="agent-marked"></div>
                </div>
            {% endfor %}
        </div>               
    </div>

This is a dynamic website built with Flask, where my app.py script sends a
render_template containing the filenames it wants the site to load. This is my CSS for this portion of the site

body {
    font-family: Arial, Helvetica, sans-serif;
    text-align: center;
    margin: 0;
    padding: 20px;
    color: #ffffff;
    background-color: var(--primary-blue);
    overflow-x: hidden;
}

h1 {
    font-family: 'VALORANT Font', sans-serif;
    font-size: 7em;
    color: var(--primary-red);
    margin-bottom: 5px;
    margin-top: 5px;
}

#gameArea {
    display: grid;
    max-width: 50%;
    min-width: 80%;
    margin: auto;
    grid-template-columns: 72% 28%;
    align-items: stretch;
    gap: 20px;
    padding: 20px;
}

#mediaContainer {
    border: 10px solid var(--primary-red);
    background-color: var(--primary-blue);
    padding: 0px;
}

#mediaContainer img,
#mediaContainer audio {
    width: 100%;
    height: auto;
}

#agentSound {
    filter: hue-rotate(165deg) brightness(0.9);
    min-width: 280px;
}

#agentGrid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    background-color: var(--primary-blue);
    align-items: flex-start;
    border: 6px solid var(--primary-red);
}

Also I will include the JS that is loading the audio

// Function to play the sound file for the current guess
    const playSound = (guessNumber) => {
        if (guessNumber < 5) {
            const soundFileName = selectedFiles[guessNumber];
            const mapName = maps[guessNumber];
            if (soundFileName && mapName) {
                const soundPath = `static/agents/${dailyAgent}/${soundFileName}`;
                const imagePath = `static/maps/${mapName}.png`;
                //console.log("Playing sound:", soundPath);
                agentSound.src = soundPath;
                document.getElementById('gameImage').src = imagePath; // Update map image
                if(guessNumber > 0){
                    agentSound.play().catch(e => console.error("Error playing sound:", e));
                }
            } else {
                console.error("Sound file or map not found for guess number", guessNumber);
            }
        }
    };

Does anyone have an idea of what is going on? You can actually test this site for yourself, it is live https://stepdle.fun

I have tried setting a defined width, changing to and tried a bunch of CSS tags

How to make closing of all columns in group possible

So I have columns grouped like this:

public columnDefs = [
    {
      headerName: '',
      children: [
        { field: 'field1', },
        { field: 'field2' },
        {
          field: 'field3',
        },
      ],
    },
    {
      headerName: 'second_group',
      children: [{ field: 'field4' }, 
   { field: 'field5', columnGroupShow: 'open' }],
    },
  ];

This adds little arrow icon that makes it possible to toggle visibility of field5. Hovewer if I add columnGroupShow: open property to field4 there will be no expand/collapse button anymore. I would like to be able to hide all columns in second_group the same way it already works for mixed visibility.

Why is he using .every method in that line of code?

I watch a tutorial where the author makes a e-commerce website.
Now he iterates through the products and returns only the products that match the filters

The filters structure is {"color": "red", "size": "M"} , or only one of the key/value pair.

const [filteredProducts, setFilteredProducts] = useState([]);

useEffect(() => {
    setFilteredProducts(
        products.filter((item) =>
            Object.entries(filters).every(([key, value]) =>
                item[key].includes(value)
            )
        )
    );
}, [products, filters]);

This is what he wrote. I don’t understand why he added .every method.

How do I scroll an element to a specific height of a page in JavaScript?

I have this function to scroll the selected day to the top of the page, but I actually need it to scroll 24rem below the top

useEffect(() => {
  // Scroll to the selected day when the component mounts or when the selected date changes
  if (scrollRef.current) {
    const selectedDayElement = scrollRef.current.querySelector(".selected-day");
    if (selectedDayElement) {
      selectedDayElement.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });

      scrollRef.current.scrollTop;
    }
  }
}, [value]);

I tried ‘block: “center”‘ and ‘nearest’ but I need a more specific position. Chat GPT suggested some things using an offset property but none of them seemed to have any effects.

I have a next js App in netlify and once in a while when I refresh homepage ,other pages doesnt happen ,It gives me plain txt instead of html

has anyone expirienced this issue when deploying a next js 14 website to neltify .?In vercel it works perfectly fine but I have already a costum domain ns connected with netlify .I was thinking layout.js was the issue but still cant figure it out.If anyone has come around this can you please post a solution?

Anyone else experienced this ?

Wocommerce Update Cart Button Not Updating Cart

I am having problem updating the cart when i click the update cart button nothing happens. The day i changed the cart.php file this started to happen i changed the table with divs it works fine with old table code and classes but with new code it does not works well.

Below is the code for old and new code with js files.

This is the link for new cart.php file sorry i could not post code because it had formating errors that i could not solved.

https://shop.mmstore.be/newcart.txt

This is the link for old cart.php file i cannot post the code due to formating errors which i could not solve.

https://shop.mmstore.be/oldcart.txt

This is the link for wocommerce cart.js file due to words limit i had to post the code from the link.

https://shop.mmstore.be/wp-content/plugins/woocommerce/assets/js/frontend/cart.js

Please tell me what is going on wrong.

Thanks

I tried to make ajax call but it is not working with the new code with old code the ajax calls goes out well.

How do I access a javascript variable in the argument of the table tag?

I know very little about JavaScript and I’ve done some research on google about using JavaScript variables in HTML but I’m not finding exactly what I’m looking for.

What I’m trying to do is change the table row height based on the resolution of the monitor, I have one monitor that is 3840×1600 and another that is 1920×1080. This works just fine with the 3840×1600 (the monitor the JS and HTML was developed on) but with the 1920×1080 the clock sits over the eyes of the Alienware background. I’m trying to adjust the table to move the table rows up so the clock is placed on the forehead of the Alienware logo. I want to insert the height into the height argument of the table row tag.

<head>
<link rel="stylesheet" href="css.css">
</head>

<body onload="load()">
    
    <div id="background">
        <div id="overlay">
            <table width="100%" height="100%" border="0">
                <tr width="100%" height="300">
                    <td colspan="3">
                    </td>
                </tr>
                <tr width="100%" height="600">
                    <td width="1448" height="100%">
                    </td>
                    <td width="1448" height="100%" margin="0" padding="0" valign="middle">
                        <div id="time">
                            <div id="gradient">
                                <span id="clock"></span><br>
                            </div>
                            <!-- <div id="gradient">                -->
                            <!--    <span id="weekday"></span><br>      -->
                            <!-- </div>                     -->
                            <!-- <div id="gradient">                -->
                            <!--    <span id="date"></span>         -->
                            <!-- </div>                     -->
                        </div>
                    </td>
                    <td width="1448" height="100%">
                    </td>
                </tr>
                <tr width="100%" height=" 600">
                    <td colspan="3">
                    </td>
                </tr>
            </table>                
        </div>
    </div>

    <script src="js.js"></script>
</body>