p5js stretching image by four corners

Using the p5js javascript library, is there any way that I can take four points in 2D space and stretch the image’s corners to fit those points? I can not use the texture function because it requires WEBGL which I am not using.

I know that there is an option to set the imageMode to CORNERS, but this only accepts two corners and doesn’t allow the image to be stretched to anything besides a rectangle.

How to have efficient separation of data and operation in javascript/typescript?

I learnt typescript in a hurry and still a newbie. Coming from a functional background I am used to seperate object data from its methods. For example let us consider a simple data object that i will want to augment as my code base grow :

export interface Data {
  readonly value: number;
}

export function Data(value: number): Data {
  return { value };
}

const data: Data = Data(2);
console.info(data); //output { value : 2 }

Data is a central brick of my code since it contains all the data defining a core object of my business model. My application growing in feature I want to augment it with dedicated methods.
I thought of two approaches.

I can use the “companion object” pattern :

export namespace Data {
  export function incr(self: Data): Data {
    return Data(self.value + 1);
  }
}

console.info(data); //output { value : 2 }
Data.incr(data);

With this approach data stay a simple data object, and I can enrich it. However, each time I will use it I will have a bloated syntax

I can use the interface pattern :

export namespace Data {
  export function Ops(self: Data) {
    return {
      self : self,
      incr(): Data(self.value + 1);
     }
  }
}

const data_withops = Data.Ops({ value : 2 });
console.info(data_withops.self); //output { value : 2 }
data_withops.incr() 

It is less bloated but I still have to manually encapsulate/decapsulate the data.

I can inject the operators into the data

export interface Data {
  readonly value: number,
  incr(): Data
}


const data: Data = Data(2);
console.info(data); //output { value : 2, incr : Function }

But then the object is bloated, bloating my console, my cache and my network.

Is it possible to do it without any of those problems?

  • data is not bloated : console.info(data); //output { value : 2 }
  • user of the object does not have to care about “loading/unloading” the operators
  • user has a light syntax : “data.incr()” is defined

I thought it would works with the prototypes but I didn’t succeed

declare global {
  export interface Data {
    incr(this: Data): number;
  }
}

Data.prototype.incr = function (this: Data): Data {
  return Data(this.value + 1);
};

console.info(data); //output { value : 2 }
data.incr();

Phaser 3 how to setup collision to multiple layers

strangely enough, I am not able to setup collision on multiple layers in Phaser 3. I’ve setup collision for specific indexes in walls layer and everythng works but I am not able to setup collision to waterLayer as a whole. Waterlayer renders correctly and I am able to log the waterLayer properties. For some reason still, player always is able to run trough the waterlayer. Here is relevant code:

  preload() {
    // Load spritesheet for the protagonist
    this.load.spritesheet('protagonist', '/assets/mainCH.png', { frameWidth: 100, frameHeight: 100 });
    this.load.spritesheet('enemy', '/assets/waterspirit.png', { frameWidth: 150, frameHeight: 150 });
   
   
   
    
  
    // Load tileset and tilemap
    this.load.tilemapTiledJSON('map', '/assets/maps/worldmap.json');

    
    
    this.load.image('spruce', '/assets/spruce.png', { frameWidth: 150, frameHeight: 150 });
    this.load.scenePlugin('AnimatedTiles', '/phaser-animated-tiles/src/plugin/AnimatedTiles.js', 'animatedTiles', 'animatedTiles');
    this.load.image('dark_tiles', 'assets/maps/terrain_dark.png');
  }

  create() {

    //resize canvas when coming from scene-two
    const gameConfig = this.sys.game.config;
            // Create the weather effects
            this.renderer.pipelines.addPostPipeline('rainPostFX', RainFX);
            this.cameras.main.setPostPipeline(RainFX);
    

    // Resize the game canvas
    this.scale.resize(sizes.width, sizes.height);
  // Create the protagonist sprite
    this.protagonist = this.physics.add.sprite(characterPositionInWorldMap, 250, 'protagonist');
    this.protagonist.body.setCollideWorldBounds(true);

    // Set the size and offset of the hitbox

    this.protagonist.body.setSize(hitboxWidth, hitboxHeight);
    this.protagonist.body.setOffset(hitboxOffsetX, hitboxOffsetY);
    
     // Initialize the hitbox sprite for collision detection

    this.enemy = this.physics.add.sprite(200, 100, 'enemy');
 

    // Set up properties for the water spirit
    this.enemy.speed = 100; // Adjust the speed as needed
    this.protagonist.setDepth(4);
   
    this.enemy.setDepth(1);
    const map = this.make.tilemap({ key: 'map' });
  
    this.animatedTiles.init(map);
    this.physics.world.createDebugGraphic();

// Add the tilesets
const darkTileset = map.addTilesetImage('dark_tiles', 'dark_tiles');

// Create layers from tilemap data using different tilesets
const groundLayer = map.createLayer('Groundlayer', darkTileset, 0, 0);
const waterLayer = map.createLayer('waterlayer', darkTileset, 0, 0);
const grassLayer = map.createLayer('grass_and_tree_layer', darkTileset, 0, 0);
const stoneLayer = map.createLayer('stones_n_stuff', darkTileset, 0, 0);

// Create hut layer using the hut tileset
const hutLayer = map.createLayer('hutLayer', darkTileset, 0, 0);
const transportlayer = map.createLayer('transportlayer', darkTileset, 0, 0);
const walls = map.createLayer('walls', darkTileset, 0, 0);


    // Adjust the depth of layers as needed
    groundLayer.setDepth(1);
    waterLayer.setDepth(1);
    grassLayer.setDepth(1);
    stoneLayer.setDepth(2);
    hutLayer.setDepth(30);
    walls.setDepth(2);
    transportlayer.setDepth(2);
   
// Enable collision for the specified tile indexes
// Set collision for specified tile indexes in the waterLayer
waterIndex.forEach(index => {
  map.setCollision(index, true, this.waterLayer);
});

    collidableTileIndexes.forEach(index => {
      map.setCollision(index, true, this.walls);
  });


    // Define animations.....
  
   
    // Set up keyboard input
    this.cursors = this.input.keyboard.createCursorKeys();
   
    this.physics.world.setBounds(0, 0, map.widthInPixels, map.heightInPixels);
 

 // Enable debug rendering for the tilemap layer representing water
waterLayer.renderDebug = true;
 
 this.groundLayer = groundLayer;
 this.waterLayer = waterLayer;
 this.grassLayer = grassLayer;
 this.stoneLayer = stoneLayer;
 this.hutLayer = hutLayer;
 this.walls = walls;
 this.transportlayer = transportlayer;


  // Listen for collision between protagonist and walls
  this.physics.add.collider(this.protagonist, this.walls, () => {
    // Disable movement controls for the protagonist
    //this.protagonist.setVelocity(0); // Stop the protagonist's movement
    console.log("wall hit")
    });
 // Set up collision detection between the protagonist and the waterLayer
 this.physics.add.collider(this.protagonist, this.waterLayer);
   // Set up camera to follow the player
   this.cameras.main.startFollow(this.protagonist);
this.enterHutText = this.add.text(this.protagonist.x, this.protagonist.y, 'Press f to enter the hut', { font: '24px Arial', fill: '#ffffff' });
this.enterHutText.setDepth(100);
this.physics.add.existing(this.protagonist);
this.physics.add.existing(this.waterLayer);
this.physics.add.collider(this.protagonist, this.waterLayer);

  }

  update() {
    
    // Reset velocity
    this.protagonist.setVelocity(0);
    this.physics.collide(this.protagonist, this.waterIndex, () => {
      console.log("hit");
  }, null, this);
 
   //some irrelevant logic....
   


    // Handle keyboard input......



 
    this.physics.moveToObject(this.enemy, this.protagonist, this.enemy.speed);
     // Play the appropriate animation based on the collision result





}



}

Promise.all() never resolving

I have a function which should get some data asynchronously.


  getPageEvents() {
    const promises = this.calendarPage.days.map(day => {
      return this.dataService.getEventsByDay(day)
      .then(events => {
        if(events){
          day.dailyEvents = events;
        }
      });
    });
    
    Promise.all(promises)
    .then((res) =>{
      console.log(res)
    })
    .catch(error =>{
      console.error(error)
    })
  }

The getEventsByDay() function returns data from a firestore database:

  async getEventsByDay(day: Day): Promise<Event[] | undefined>{
    return new Promise<Event[] | undefined>((resolve) =>{
      const date: string = day.dateFormatted
      let dailyEvents: Event[] = []
      this.getEvents()
      .then(events =>{
        if(events){
          events.forEach(event =>{
            if(event.durationDates?.includes(date)){
              dailyEvents.push(event)
            }
          })
          if(dailyEvents.length > 0){
            resolve(dailyEvents)
          }
        }else{
          resolve(undefined)
        }
      })
    })
  }

The problem is that the code inside the then() block of Promise.all() never runs, even though I can see (on the UI) the data beeing fetched.
Here is my getEvents() function:

  async getEvents(): Promise<Event[]> {
    return new Promise<Event[]>((resolve, reject) => {
      this.getTeams()
        .then(teams => {
          const teamList: string[] = teams.map(team => team.id);
          if (teamList) {
            const promises: Promise<Event[]>[] = [];
            teamList.forEach(team => {
              promises.push(this.getEventsByTeam(team));
            })
            // Quando ho tutti gli eventi di tutti i teams
            Promise.all(promises)
              .then(teamEvents => {
                const events: Event[] = [];
                teamEvents.forEach(eventsArray => {
                  eventsArray.forEach(event => {
                    const eventList = events.map(e => e.id)
                    if(!eventList.includes(event.id)){
                      events.push(event);
                    }
                  });
                });
                resolve(events);
              })
              .catch(error => {
                reject(error);
              });
          } else {
            reject("No teams");
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  }

Any guesses on what is wrong?
By the way I don’t know if this nesting tecnique for Promises is good. It’s still a quite difficult topic to handle for me so far.

Maintaining Selection Integrity: Zoom Effects on Image Cropping/Selection Functionality

I’m using the code from the repository https://www.npmjs.com/package/react-multi-crops to enable selection of various parts of an image. Initially, I adapted the code from https://www.npmjs.com/package/react-multi-crops to suit my needs.

While everything functions correctly, my requirement includes implementing a zoom feature within the image container. After implementing the zoom functionality, I noticed that while the current selections remain undisturbed, the position of the resize cursor, movement, and creation of new selection boxes are affected.

The issue arises particularly when the zoom value is increased e.g. chage it to 150 or 200. At this level, the creation of new selection blocks doesn’t align accurately with the mouse, and the resizing and movement of existing boxes fail to work properly.

Here’s the link to the sandbox with the code: https://codesandbox.io/p/sandbox/image-crop-multiple-m3flxr

I tried a lot to fix this issue but did not get success. Thanks if you can look into this and help me to solve this issue.

Render vanilla javascript and html within a Nextjs app

I have a file containing javascript and html similar to below. I am trying to render this within a nextjs app. The code in the file cannot be changed to jsx and the application that will render it is a Next app. I have tried using React Helmet by directly embedding it within the code but nothing gets rendered. Are there any other options?

Script file:

<!DOCTYPE html>
<html>
<head>
    <title>JSON to Table</title>
</head>
<body>
    <h1>JSON Data</h1>
    <table id="dataTable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <script>
// Sample JSON data
const data = [
    { name: "John Doe", age: 35, city: "New York" },
    { name: "Jane Smith", age: 28, city: "Los Angeles" },
    { name: "Bob Johnson", age: 42, city: "Chicago" },
    { name: "Sarah Lee", age: 31, city: "Miami" }
];

// Get the table body element
const tableBody = document.querySelector('#dataTable tbody');

// Loop through the data and create table rows
data.forEach(item => {
    const row = document.createElement('tr');

    const nameCell = document.createElement('td');
    nameCell.textContent = item.name;
    row.appendChild(nameCell);

    const ageCell = document.createElement('td');
    ageCell.textContent = item.age;
    row.appendChild(ageCell);

    const cityCell = document.createElement('td');
    cityCell.textContent = item.city;
    row.appendChild(cityCell);

    tableBody.appendChild(row);
});
</script>
</body>
</html>

Nextjs code:

"use client"
import {Helmet} from "react-helmet";

const Page = () => {
    return (
        <>
        <div className="w-screen h-screen flex items-start justify-start overflow-hidden">
            <Helmet>
                <title>Nested Title</title>
                <meta name="description" content="Nested component"/>
                <html>
                {`<!DOCTYPE html>
<html>
<head>
    <title>JSON to Table</title>
</head>
<body>
    <h1>JSON Data</h1>
    <table id="dataTable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <script>
// Sample JSON data
const data = [
    { name: "John Doe", age: 35, city: "New York" },
    { name: "Jane Smith", age: 28, city: "Los Angeles" },
    { name: "Bob Johnson", age: 42, city: "Chicago" },
    { name: "Sarah Lee", age: 31, city: "Miami" }
];

// Get the table body element
const tableBody = document.querySelector('#dataTable tbody');

// Loop through the data and create table rows
data.forEach(item => {
    const row = document.createElement('tr');

    const nameCell = document.createElement('td');
    nameCell.textContent = item.name;
    row.appendChild(nameCell);

    const ageCell = document.createElement('td');
    ageCell.textContent = item.age;
    row.appendChild(ageCell);

    const cityCell = document.createElement('td');
    cityCell.textContent = item.city;
    row.appendChild(cityCell);

    tableBody.appendChild(row);
});
</script>
</body>
</html>`}
                </html>
            </Helmet>
        </div>
        </>
    );
}

export default Page;

MSSQL connection from NODE.js getting Authenticaiton Error

I’m not having luck establishing a MS SQL connection.First time attempting to query MSSQL Sever from Node.js, I just want to try reading a table and dumping to a json file. To set this up, I took a connection string from a working .NET project, and parsed it into the config section of this a new node server.js script. I’m not seeing what’s wrong with the sql connection config but maybe I’m missing something. Any ideas of what I can try next in an effort to debug this would be appreciated. Code below:

Error: Login failed for user ‘web_preview’.

Error (encrypt: true): Failed to connect to WEBSRVR.xxx.com:1433 – self signed certificate

package.json

{
  "dependencies": {
    "mssql": "^10.0.2"
  }
}

server.js

const fs = require('fs');
const sql = require('mssql');

const config = {
  user: 'web_user',
  password: 'web_password;TrustServerCertificate=True',
  server: 'WEBSRVR.xxx.com', 
  database: 'reports',
  encrypt: false // Disable SSL encryption
};

// SQL query to execute
const query = 'SELECT top 10 * FROM myReports';

(async () => {
  try {
    // Connect to the database
    await sql.connect(config);

    // Execute the query
    const result = await sql.query(query);

    // Save the result to a JSON file
    const jsonResult = JSON.stringify(result.recordset, null, 2);
    fs.writeFileSync('query_result.json', jsonResult);

    console.log('Query result saved to query_result.json');
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    // Close the connection pool
    await sql.close();
  }
})();

Antd Table Pagination getting to stretched for no reason

i am making a project using React 18 Ant Design and running with vite.JS . But when i put a table component for the first time, the pagination of the bottom got’s like this:
enter image description here

I tried everthing. I serched it on internet, but anyone has passed for it yet.
I really don’t know how to solve it.

I was expecting that the table pagination got’s like the sample in the antd docs

React Audio Recorder returns null for recorded audio in useState hook

I am building a registration form in React where users can input their username and record audio using the react-audio-voice-recorder library. I am using the useState hook to manage the state of the recorded audio blob, but it’s returning null when I try to access it in the handleSubmit function.

Here’s a simplified version of my code:

import React, { useState } from 'react';
import { Button, TextField, Typography } from '@mui/material';
import { AudioRecorder } from 'react-audio-voice-recorder';

const Register = () => {
  const [username, setUsername] = useState('');
  const [recordedAudio, setRecordedAudio] = useState(null);

  const handleUsernameChange = (event) => {
    setUsername(event.target.value);
  };

  const handleRecordingComplete = (blob) => {
    console.log("Recording completed:", blob);
    setRecordedAudio(blob);
  };

  const handleSubmit = () => {
    if (!username || !recordedAudio) {
      alert('Please enter a username and record audio before submitting.');
      return;
    }

    console.log(`Username: ${username}`);
    console.log(`Recorded Audio Blob:`, recordedAudio);

    // Code to submit username and recorded audio for registration

    setUsername('');
    setRecordedAudio(null);
  };

  return (
    <div>
      <Typography variant="h4" gutterBottom>
        Register
      </Typography>
      <TextField
        label="Username"
        variant="outlined"
        value={username}
        onChange={handleUsernameChange}
        fullWidth
        margin="normal"
      />
      <AudioRecorder
        onRecordingComplete={handleRecordingComplete}
        audioTrackConstraints={{
          noiseSuppression: true,
          echoCancellation: true,
        }}
        onNotAllowedOrFound={(err) => console.error(err)}
        downloadOnSavePress={false}
        showVisualizer={true}
      />
      <Button variant="contained" color="primary" onClick={handleSubmit}>
        Submit
      </Button>
    </div>
  );
};

export default Register;

When I try to access recordedAudio in the handleSubmit function, it returns null. Is there something I’m missing or doing wrong in managing the state of the recorded audio blob?

Any insights or suggestions would be greatly appreciated. Thank you!

ReactReader epub js – open table of content on load

ReactReader epub js – open toc on load (toc is table of content, a small button) which should be open upon page loading.

Checking npm guide, it only has option to show or hide toc.

Expecting a way to call the onclick event on button, but since it has no better selector, looking for a parameter option in epub js/ react reade module if there is any.

Rendering data on Mapbox using geojson-vt

I see similiar questions were asked but could find a definite answer.
I’m using Mapbox-gl with Vue3 (v-mapbox) and trying to render a lot of data.
One solution that i’ve found is mapboxs geojson-vt library.
Its seems to convert geojson to vector tiles on the fly but not sure how it eventually renders on the map as a layer.

So i need to get from here

const geojsonvt = geojsonVt(...some_geo_json...)

To here

mapboxMapInstance.addSource(some_source_extracted) (maybe type:vector??)
mapboxMapInstance.addLayer(...)

I saw its possible via demo that the author of this library published but not sure how to implement myself.
Thank you in advance

How to use .js and .d.ts files in project

having this some.js file

export function myFunc(a, b) {
  return a.asdf + b;
}

I want to be able to write something like this let’s say in some.d.ts file

export declare function myFunc(a: number, b: number): number;

then run ‘npx tsc’ command which will give me ‘asdf is not a member of type number’,
but right now i get errors saying “parameter a implicitly has any type”.
I have this tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "strict": true,
    "skipLibCheck": false,
  },
  "include": ["**/*.js", "**/*.d.ts"]
}

Is it that I miss some ts options or I should declare types in .d.ts differently? If it is impossible, what is the general way to program in js but having typings and not in one global.d.ts file?

I also tried

declare namespace some {
  export function myFunc(a: number, b: number): number;
}

and

declare module "some" {
  export function myFunc(a: number, b: number): number;
}