Line chart issue is chart.js

enter image description here
Hello I have an issue with my chart it only fills up halfway.

The code is bellow and when I only update the temperature the graph will be okay and when I add the humidity the chart is only filling up halfway

// Declare chart variables
let temperatureChart;
let humidityChart;

// Function to create the temperature and humidity charts
function createCharts() {
    const ctxTemp = document.getElementById('temperatureChart').getContext('2d');
    const ctxHum = document.getElementById('humidityChart').getContext('2d');

    // Create the temperature chart
    temperatureChart = new Chart(ctxTemp, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Temperature (°C)',
                data: [],
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 2,
                fill: false,
                tension: 0.4  // Smooth the line
            },{
                label: 'Humidity (%),
                data: [],
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 2,
                fill: false,
                tension: 0.4  // Smooth the line
        }]
        },
        options: {
            scales: {
                x: {
                    title: {
                        display: true,
                        text: 'Time'
                    }
                },
                y: {
                    min: 0,  // Minimum value for temperature
                    max: 60, // Maximum value for temperature
                    title: {
                        display: true,
                        text: 'Temperature (°C)'
                    }
                }
            },
            animation: {
                duration: 0  // Disable animation to make it feel more real-time
            }
        }
    });

    // Create the humidity chart
    humidityChart = new Chart(ctxHum, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Humidity (%)',
                data: [],
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 2,
                fill: false,
                tension: 0.4  // Smooth the line
            }]
        },
        options: {
            scales: {
                x: {
                    title: {
                        display: true,
                        text: 'Time'
                    }
                },
                y: {
                    min: 0,   // Minimum value for humidity
                    max: 100, // Maximum value for humidity
                    title: {
                        display: true,
                        text: 'Humidity (%)'
                    }
                }
            },
            animation: {
                duration: 0  // Disable animation to make it feel more real-time
            }
        }
    });
}

// Function to update the charts with new data
function updateCharts(data) {
    const currentTime = new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', second: '2-digit'});  // Get current time as "hh:mm:ss AM/PM"
    
    // Update the display box with the latest data
    document.getElementById('temperature').textContent = `${data.temperature}°C`;
    document.getElementById('humidity').textContent = `${data.humidity}%`;

    // Add the new data points to the charts
    temperatureChart.data.labels.push(currentTime);
    temperatureChart.data.datasets[0].data.push(data.temperature);
    humidityChart.data.labels.push(currentTime);
    humidityChart.data.datasets[0].data.push(data.humidity);

    // Update the charts
    temperatureChart.update();
    humidityChart.update();
}

window.onload = function() {
    createCharts();
    setInterval(fetchData, 1000);
}

I am having a hard time solving this issue. I am sorry for the troubles

event.preventDefault cannot block clipboard paste in chatgpt.com prompt box

I’m using following codes to block paste to certain webpages

document.addEventListener('paste', (event) => {
    event.preventDefault();
});

It works in most cases except for prompt box in https://chatgpt.com. here is what i did step by step:

  1. open https://chatgpt.com with chrome for windows
  2. open console and run above codes
  3. copy some texts and paste to prompt box with CTL+v or rightclick->paste
  4. texts are pasted successfully

I wonder how it pasts text and is there any way to block it.

How to make Image Magick upscaling operation run much faster? (It currently takes 10 seconds per image…)

My current workflow resizes/upscales images using Image Magick inside of an AWS Lambda function.

It uses the Image Magick layer, and the code is written in node.js as follows:

    // Step 1: Download the image from S3
    console.log("Downloading image from S3 bucket:", bucket, "with key:", key);
    const inputImagePath = path.join(os.tmpdir(), 'input.jpg');
    const outputImagePath = path.join(os.tmpdir(), 'resized-image.jpg');

    const downloadImageFromS3 = async () => {
        const getObjectCommand = new GetObjectCommand({ Bucket: bucket, Key: key });
        const s3Object = await s3Client.send(getObjectCommand);
        await pipeline(s3Object.Body, fs.createWriteStream(inputImagePath));
    };

    await downloadImageFromS3();
    console.log("Image downloaded successfully!");

    // Step 2: Resize the image using ImageMagick
    console.log(`Resizing image to ${desiredWidth}x${desiredHeight}...`);
    const command = `convert ${inputImagePath} -adaptive-resize ${desiredWidth}x${desiredHeight}! -density 300x300 ${outputImagePath}`;
    execSync(command);
    console.log("Image resized successfully!");

Since the images get upscaled to fairly large sizes (6000+ pixels for either the width or height), it takes the operation about 10 seconds to complete.

Things I have tried:

  1. I’ve tried increasing the memory allocation of the Lambda function to the currently-max-allowable 3008 MB. (I have also requested that my account be given access to the absolute maximum 10,280 MB level as well, to see if that will help speed it up.) “Max Memory Used” caps out at a surprisingly low level, around 300-500 MB. Is there any way I can somehow force it to use more CPU resources to process it faster? Like some kind of Image Magick and/or AWS Lambda command that explicitly says “use as much CPU power to do this as fast as possible”?

  2. Compressing the images in that same convert command, to see if it would return the output faster. This had no apparent impact on speed.

  3. Using a method that is not adaptive resize. “-resize” does execute about 2x faster. BUT the final image quality is poor — and the very best image quality is required for this workflow (and I’ve found “adaptive resize”, by far, produces the best-looking outputs.)

Other ideas I have:

  1. Since I need to resize each image to several slightly-different aspect ratios, instead of doing it sequentially in a loop, could I instead write the code to execute all of these different operations simultaneously — so instead of doing 3 in a row that takes 30 seconds total, all 3 can execute and finish at roughly the same time and therefore only take 10 seconds total?

  2. Is there a way to just avoid the “download my image” step altogether? Any way I can just have the upscaling operation act directly on the image that’s already in my S3 bucket? Like, have the Lambda function somehow pipe directly in there to just act on it instead of that intermediate download step where it gets converted to image data and that gets passed to Image Magick?

Any ideas/tips would be HIGHLY appreciated. Thank you!

The subject of closures and React useState hook

very young Padawan in the React universe here,

This question revolves around the inner mechanisms of the useState() hook. My gratitude in advance for your time taken! and my sincerest apologies for the lengthy post.

Would this explanation perfectly describe what is going on ?

Looking at the 1st challenge (Challenge 1 of 2: Fix a request counter)in the page: Queueing a series of state updates within the React.dev DOCs,

this line of code exists within the function component:

async function handleClick() {
    setPending(p => p + 1);
    await delay(3000);
    setPending(p => p - 1);
    setCompleted(c => c + 1);
  }

I modify this code to alert(pending) state variable to test a hypothesis in mind:

async function handleClick() {
    setPending(p => p + 1);
    await delay(3000);

    alert(pending)

    setPending(p => p - 1);
    setCompleted(c => c + 1);
  }

My explanatory attempt :

We learn that React batches multiple set state functions that occur within a single event trigger for its efficiency.

Without an async nature and delay present, for the first click after initial render, the alert() will display 0 since the state variable passed into it isnt the updated value, rather a snapshot of the state at the time of event triggering.

This is due to the fact that the state variable updates only after all code in event trigger function finishes running.

However in cases such as mentioned above, the batching breaks due to the function’s async nature. Specifically in the first setPending() before delay.

Here, the setPending() increments the pending variable and goes ahead and re-renders the component to reflect the changes, hence why we see the number change in the DOM.

After the delay, the alert() displays a surprising 0, along with the visual DOM change of pending and completed due to the followed setPending() that decrements the value and setCompleted().

Due to the batch breaking which re-renders the component and updates pending state variable’s value before the delay, it is expected that alert() receives the updated value.

But.. due to the concept of closure, the event trigger’s function does not have access to the updated values of state variables after the update, rather it owns the value at the start of event trigger, which in this case is initializer 0.

<button> click again will alert() the value 1 instead of actuall updated pending value of 2.

The following mentioned effects can be attributed to JS closure behavior and batch breaking.

Side note: I realllly wish React docs would have “Deep Dived” into this.

Thank you so much !

UI elements jitter when being conditionally rendered

I’m have an issue where buttons and links jitter on state change (when clicking on the “Sign Out” button). I tried both v-if and v-show and the jitter persists.
Video of the issue: https://www.veed.io/view/89672f51-f55c-411c-883f-440b02cfa4de?panel=share

<div>
  <div>
      <button @click="setColorTheme()">
          <IconDarkMode />
      </button>
      <div v-if="!signedIn && !pending">
          <NuxtLink to="/sign-in">
              <span>Sign In</span>
              <IconSignIn />
          </NuxtLink>
      </div>
  </div>
  <div
      v-if="signedIn && !pending">
      <NuxtLink to="/profile">
          <span>Profile</span>
          <IconProfile />
      </NuxtLink>
      <button to="/sign-in" @click="signOut">
          <span>Sign Out</span>
          <IconSignOut />
      </button>
  </div>
</div>

I also have a 300ms delay for signedIn state in signOut function to wait until page transition ends, but jitter still persists.

if (res.ok) {
    const data = await res.json();
    state.successMessage = data.message;
    if (route.path === '/') {
        window.location.reload();
    } else {
        window.location.href = '/';
    }
    setTimeout(() => {
        state.signedIn = data.signedIn;
    }, 300);
}

Looking for a possible solution.

Architectural pattern to use in React

I have a project in ReactJS that uses pg to connect with my Postgres DB, in addition I’m using GraphQL and Apollo Server Express to fetch the data. The way my project is now, it has UI, fetch data methods and business logic in the same file and I want to separe the concerns into different files. To achieve this I’m looking for the best software architectural pattern(like MVC, MVP, MVVM, MTV, etc) to use that fits well with these stack. What do you guys suggest? What changes I should do in my file tree to adapt to the architecture pattern?


My project file tree is like this:

/myProject
├── client
│   ├── assets
│   ├── contexts
│   ├── graphQL
│   │   ├── mutations
│   │   │   └── product
│   │   │       └── # CRUD operations
│   │   │   └── # other folders...
│   │   ├── queries
│   │   │   └── product
│   │   │       └── # queries
│   │   │   └── # other folders...
│   │   └── index.js    # Imports all queries and mutations
│   ├── pages
│   │   ├── product
│   │   │   └── product.jsx
│   │   └── # other pages...
│   ├── App.css
│   ├── App.js
│   ├── index.css
│   └── index.js
├── server
│   ├── config
│   │   └── db.js
│   ├── graphQL
│   │   ├── modules
│   │   │   └── product
│   │       │   ├── index.js
│   │       │   ├── resolver.js
│   │       │   └── typedef.js
│   │       └── # other folders...
│   └── schema.js       # Imports all modules to create the schema

How to delay collecting personal information from Stripe Express connected accounts?

I have a platform where teachers provide online lessons, and I’m using Stripe Express connected accounts to pay teachers when users subscribe to their lessons. The problem is that many of the onboarding teachers don’t want to provide personal information, like their SSN etc, upfront when they sign up—they’d prefer to wait until they’ve actually used the platform and see that it’s working.

My plan is to create a Stripe Express account for teachers when they sign up, and then allow them to provide the additional information (SSN, personal details) only when they want to get paid / cash out. However, when I try to create a transfer or do a destination charge, I get an error saying that users need to provide SSN and other personal information to enable transfers.

I know about KYC requirements, but is it possible to:

  1. Create the Stripe Express account for teachers with minimal information when they sign up(name, email).
  2. Allow them to start earning money (via destination charges or transfers).
  3. Delay collecting additional personal information (SSN, etc.) until they want to payout?

Currently, Stripe is blocking the transfers until they complete the full onboarding. Is there any way to allow earning and then request more information only at the payout stage?

Any advice or clarification would be greatly appreciated!

Efficient and reliable ways to adjust the size of the second image to be the same as the first image

I have two image tags displayed in a webpage, which may have different size. And since the images are dynamically generated, the size of both images may be different at each loading. I want to adjust the second image to have the same size as the first image. Here is what I have tried:

<img id='1' src='img1.jpg'>
<img id='2' src='img2.jpg'>
<script>
  const img1 = document.getElementById("1");
  const w = img1.offsetWidth;
  const h = img1.offsetHeight;
  const img2= document.getElementById("2");
  img2.style.width = w + 'px';
  img2.style.height = h + 'px';
</script>

What I found is that occasionally the width and height are read as 0, which may be caused by the script ran before the first image was loaded. I am thinking to put an onload() function to the first image, however, I think in case if image2 is not loaded when onload is fired, then it won’t be adjusted.

Also, if the browser is somehow running slow, such size change maybe sensible by the user. What’s a more efficient and reliable way to make two images displayed with the same size at the first place? Note I don’t want to put them both into a div with fixed size, I only want the 2nd image to have the same size as the 1st one.

Upgrading node/npm dist cofiguration

I have a ten-year old node application which I am now (at long last) upgrading to the latest packages. I have finally got everything compiled without error, and the reward is that npm creates a new dist folder which, I guess, should allow the browser to run the application. However, when I access the application from the web, it loads the index.html file but then nothing happens. The dist folder contains just two files: app.bundle.js and t.bundle.js. Now here is the odd thing: if I replace this dist folder by the original dist folder, as compiled months ago before I started the upgrade, everything works! This original dist folder contains 66 items,including app.bundle.js and t.bundle.js.

However, this is very unsatisfactory. The working dist folder is frozen, and all the changes I made in the last months to the source are ignored. I am guessing this is due to the configuration in the package.json and webpack.js files still pointing at the legacy implementation. However, I can not work out from all the documentation I have looked at just how thw package.json and webpack.js should be set up now.

Here is how files are arranged:

tc (top level)    
    -- package.json
    -- public folder
    -- various other folders containing source for the server backend
    -- node-modules folder

public (folder contained in tc)
   -- dist folder
   -- app folder
   -- index.html
   -- t.html
   -- webpack.js

app (folder contained in public)
   -- app.html 
   -- hundreds of files holding all the code presented by the browser

Here is the package.json file:

{
  "name": "tc",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "pm2 startOrReload pm2.json",
    "prod": "pm2 startOrReload pm2.json --env production",
    "logs": "pm2 logs",
    "test": "node --use_strict $(npm bin)/jasmine"
  },
  "dependencies": {
    "angular2": "2.0.0-beta.15",
    "async": "^3.2.6",
    "base64url": "^3.0.1",
    "bcrypt": "^5.1.1",
    "body-parser": "^1.20.2",
    "bootstrap": "^5.3.3",
    "bootstrap-less": "^3.3.8",
    "bson": "^6.8.0",
    "codemirror": "^5.65.17",
    "connect-flash": "^0.1.1",
    "connect-mongo": "^5.1.0",
    "cookie-parser": "^1.4.6",
    "dropzone": "^6.0.0-beta.2",
    "ejs": "^3.1.10",
    "express": "^4.19.2",
    "express-session": "^1.18.0",
    "file-saver": "^2.0.5",
    "gridfs-stream": "^1.1.1",
    "jquery": "^3.7.1",
    "jsdom": "^24.1.1",
    "jszip": "^3.10.1",
    "jszip-utils": "^0.1.0",
    "libxmljs": "^1.0.11",
    "lodash": "^4.17.21",
    "mongo-connect": "^0.0.6",
    "mongoose": "^8.5.3",
    "morgan": "^1.10.0",
    "multer": "^1.4.5-lts.1",
    "nodemailer": "^6.9.14",
    "nodemailer-mailgun-transport": "^2.1.5",
    "openseadragon": "^5.0.0",
    "passport": "^0.7.0",
    "passport-facebook": "^3.0.0",
    "passport-google-oauth": "^2.0.0",
    "passport-local": "^1.0.0",
    "passport-twitter": "^1.0.4",
    "promise-defer": "^1.0.0",
    "require-in-the-middle": "^7.4.0",
    "serve-favicon": "^2.5.0",
    "sort-array": "^4.1.5",
    "urijs": "^1.19.11"
  },
  "devDependencies": {
    "css-loader": "^7.1.2",
    "jasmine": "^5.2.0",
    "less": "^4.2.0",
    "less-loader": "^12.2.0",
    "mini-css-extract-plugin": "^2.9.1",
    "style-loader": "^4.0.0",
    "webpack": "^5.94.0"
  }
}

And here is the webpack.js file which creates the bundle for the browser:

var _ = require('lodash')
  , webpack = require('webpack')
  , ResolverPlugin = webpack.ResolverPlugin
  , ProvidePlugin = webpack.ProvidePlugin
  , IgnorePlugin = webpack.IgnorePlugin
//  , ExtractTextPlugin = require("extract-text-webpack-plugin")
  , path = require('path')
  , clientRoot = path.resolve(__dirname)
  , bowerRoot = path.resolve(clientRoot, '..', 'bower_components')
  , nodeRoot = path.resolve(clientRoot, '..', 'node_modules')
  , devtool = 'eval-source-map'
  , debug = true
;
switch (process.env.NODE_ENV) {
  case 'production':
    devtool = '#source-map';
    debug = false;
    break;
  case 'development':
    devtool = 'eval-source-map';
    debug = true;
    break;
}
var config = {
  context: clientRoot,
  mode: "development",
  entry: {
    app: path.join(clientRoot, 'app/boot.js'),
    t: path.join(clientRoot, 'app/t.js'),
  },
  output: {
    path: path.join(clientRoot, 'dist'),
    filename: '[name].bundle.js',
    devtoolModuleFilenameTemplate(info) {
     return `file:///${info.absoluteResourcePath.replace(/\/g, '/')}`;
   },
  },
  externals: {
    jquery: 'jQuery',
    rxjs: 'Rx',
    lodash: '_',
    bson: 'bson',
    'codemirror/lib/codemirror': 'CodeMirror',
    'codemirror/mode/xml/xml': false,
  },
  module: {
    rules: [
      {
        test: /.png(?v=d+.d+.d+)?$/,
        use: "url?limit=1000&minetype=image/jpg&prefix=dist/"
      }, {
        test: /.jpg(?v=d+.d+.d+)?$/,
        use: "url?limit=1000&minetype=image/jpg&prefix=dist/"
      }, {
        test: /.woff(?v=d+.d+.d+)?$/,
        use: "url?limit=1000&minetype=application/font-woff&prefix=dist/"
      }, {
        test: /.woff2(?v=d+.d+.d+)?$/,
        use: "url?limit=1000&minetype=application/font-woff&prefix=dist/"
      }, {
        test: /.ttf(?v=d+.d+.d+)?$/,
        use: "url?limit=1000&minetype=application/octet-stream&prefix=dist/"
      }, {
        test: /.eot(?v=d+.d+.d+)?$/,
        use: "url?limit=1000&minetype=application/vnd.ms-fontobject&prefix=dist/"
      }, {
        test: /.svg(?v=d+.d+.d+)?$/,
        use: "url?limit=1000&minetype=image/svg+xml&prefix=dist/"
      },
      {
        test: /.css$/, 
        use:["style-loader", "css-loader"]
        //loader: 'style!css'
      },
      {
        test: /.less$/,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              lessOptions: {
    //          javascriptEnabled: true,
              },
            }, 
          },
        ],
      },
    ], /*,
    noParse: [
    ] */
  },
  resolve: {
 /*   root: [clientRoot], */
    modules: [clientRoot, 'web_modules', 'node_modules', 'bower_components', ],
    fallback: {
        "fs": false,
        "tls": false,
        "net": false,
        "path": false,
        "zlib": false,
        "http": false,
        "https": false,
        "stream": false,
        "crypto": false,
        "crypto-browserify": false, //if you want to use this module also don't forget npm i crypto-browserify 
      },
    alias: {
      bower: bowerRoot,
      node: nodeRoot,
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
     new webpack.LoaderOptionsPlugin({
        debug: true
    }),
  ],
  devtool: devtool,
};
var compiler = webpack(config);
if (process.env.NODE_ENV === 'development') {
  compiler.watch({
    aggregateTimeout: 300,
    poll: 1000,
  }, handleError);
} else {
 compiler.watch({
    aggregateTimeout: 300,
    poll: 1000,
  }, handleError);
  //compiler.run(handleError);
}
function handleError(err, stats) {
  console.log(JSON.stringify({
    colors: true,
    cached: false,
  }));
}

I am running node 20.17.0.

Fancybox disable preload option does not work?

As I understand it, the “preload” in Fancybox means when I click open slide 2, it will automatically download and load slide 1 and slide 3, such that when I switch to prev or next slide, there will be no loading time. But either set preload to be true or false, I see that when I open one slide, the next slide is still fetched. Not sure if I set something incorrectly

<a data-fancybox="gallery" href="https://sample-videos.com/img/Sample-jpg-image-100kb.jpg" data-type="iframe" data-preload="false">
            <img src="https://sample-videos.com/img/Sample-jpg-image-50kb.jpg">
</a>
<a data-fancybox="gallery" href="https://sample-videos.com/img/Sample-png-image-200kb.png" data-type="iframe" data-preload="false">
            <img src="https://sample-videos.com/img/Sample-png-image-100kb.png">
</a>
<a data-fancybox="gallery" href="https://sample-videos.com/gif/1.gif" data-type="iframe" data-preload="false">
            <img src="https://sample-videos.com/gif/3.gif">
</a>

<script>
        Fancybox.bind("[data-fancybox]", { });
</script>

Cannot create a key using the specified key usages error when generating ECDSA keys using subtle crypto

I’m trying to generate ECDSA keys using subtle crypto without any external libraries (it’s important to me), but getting “Cannot create a key using the specified key usages.” error. Can anyone advise on what’s wrong with the below approach?

async function generateECDSAKeyFromSeed(seed) {
    // Convert the seed to an ArrayBuffer
    const enc = new TextEncoder();
    const seedBuffer = enc.encode(seed);

    // Step 1: Derive key material from seed using PBKDF2
    const baseKey = await crypto.subtle.importKey(
        'raw',
        seedBuffer,
        { name: 'PBKDF2' },
        false,
        ['deriveBits', 'deriveKey']
    );

    const salt = crypto.getRandomValues(new Uint8Array(16)); // Random salt
    const derivedBits = await crypto.subtle.deriveBits(
        {
            name: 'PBKDF2',
            salt: salt,
            iterations: 100000,
            hash: 'SHA-256',
        },
        baseKey,
        256
    );

    // Step 2: Import derived key material as a private key
    const privateKey = await crypto.subtle.importKey(
        'raw',
        derivedBits,
        { name: 'ECDSA', namedCurve: 'P-256' },
        true,
        ['sign']
    );

    // Step 3: Extract public key from private key
    const publicKey = await crypto.subtle.exportKey('jwk', privateKey);

    return {
        privateKey: privateKey,
        publicKey: publicKey
    };
}

// Example usage
generateECDSAKeyFromSeed("your_seed_value").then(keys => {
    console.log("Private Key:", keys.privateKey);
    console.log("Public Key:", keys.publicKey);
}).catch(x => {
    debugger;
    console.error(x);
});

There seems to be a bug in Firefox js engine

I made a code that emulates the behavior of the readline() function in This CodinGame exercise.
The code is the following:

 function* cutie(txt){
    const x=txt.split("n")
    const w=x.reduce((a,b)=>b.length>a?b.length:a,0)
    yield x.length+" "+w
    for(const i of x){yield i}
}

function readline(){
    return XX.next().value
}
XX=cutie(`##########
#S.......#
##.#####.#
##.#.....#
##########`)

For some strange reason that is beyond me, it works in Firefox’s console (when calling separately), and in Node.js v16.20.2, but it still gives undefined in the following code:

function* cutie(txt) {
  const x = txt.split("n")
  const w = x.reduce((a, b) => b.length > a ? b.length : a, 0)
  yield x.length + " " + w
  for (const i of x) {
    yield i
  }
}

function readline() {
  return XX.next().value
}
XX = cutie(`##########
#S.......#
##.#####.#
##.#.....#
##########`)

function setNb(x, y, val) {
  if (grid[y][y] === null) {
    grid[y][x] = val
  } else {
    grid[y][x] = val < grid[y][x] ? val : grid[y][x]
  }
  if (y - 1 > 0 && grid[y - 1][x] === null) setNb(x, y - 1, val + 1)
  if (x - 1 > 0 && grid[y][x - 1] === null) setNb(x - 1, y, val + 1)
  if (y + 1 < grid.length && grid[y + 1][x] === null) setNb(x, y + 1, val + 1)
  if (x + 1 < grid[y].length && grid[y][x + 1] === null) setNb(x + 1, y, val + 1)
}

var inputs = readline().split(' ');
const w = parseInt(inputs[0]);
const h = parseInt(inputs[1]);
let grid = [],
  start
for (let i = 0; i < h; i++) {
  let b = readline()
  grid.push(b.split("").map(a => a == "." ? null : a))
  if (b.indexOf("S") != -1) {
    start = {
      x: b.indexOf("S"),
      y: i
    }
  }
}
setNb(start.x, start.y, 0)
console.log(grid.map(a => a.map(b => isNaN(b) ? b : b.toString(36).toUpperCase()).join("")).join("n"))

The code will not run because I made a mistake in the recursion. But in the Firefox console on an about:blank tab, the code dies before it could reach the recursion.

What could be the issue?

Error displaying [object HTMLParagraphElement] in javascript

I’m new to javascript, I have an error displaying [object HTMLParagraphElement] instead of the chat content in the real-time chat function.

<script>
 // Configure Pusher
 Pusher.logToConsole = true;
 var pusher = new Pusher('...', {
     cluster: '...',
     encrypted: true
 });

 // Replace with actual sender and receiver IDs
 var senderId = 1;
 var receiverId = 2;

 // Subscribe to the private channel for the receiver
 var channel = pusher.subscribe(`private-chat-${receiverId}`);
 channel.bind('new_message', function (data) {
     var messageHistory = document.getElementById('message-history');
     var message = document.createElement('div');
     message.className = `message ${data.senderId === senderId ? 'sent' : 'received'}`;

     // Create and set message content
     var messageContent = document.createElement('p');
     // Ensure data.message is a string before assigning to textContent
     messageContent.textContent = `${String(data.message)} (Sent at ${data.sentAt})`;

     message.appendChild(messageContent);
     messageHistory.appendChild(message);
     messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom
 });

 // Load message history on page load
 document.addEventListener('DOMContentLoaded', function () {
     fetch(`/history/${senderId}/${receiverId}`)
         .then(response => response.json())
         .then(messages => {
             var messageHistory = document.getElementById('message-history');
             messages.forEach(message => {
                 var msgDiv = document.createElement('div');
                 msgDiv.className = `message ${message.senderId === senderId ? 'sent' : 'received'}`;

                 // Create and set message content
                 var msgContent = document.createElement('p');
                 // Ensure message.messageContent is a string before assigning to textContent
                 msgContent.textContent = `${String(message.messageContent)} (Sent at ${new Date(message.sentAt).toLocaleString()})`;

                 msgDiv.appendChild(msgContent);
                 messageHistory.appendChild(msgDiv);
             });
             messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom
         })
         .catch(error => console.error('Error loading message history:', error));
 });

 // Handle sending messages
 document.getElementById('send-button').addEventListener('click', function () {
     var messageContent = document.getElementById('message-input').value;

     fetch('/send', {
         method: 'POST',
         headers: {
             'Content-Type': 'application/json'
         },
         body: JSON.stringify({
             senderId: senderId,
             receiverId: receiverId,
             messageContent: messageContent
         })
     })
         .then(response => response.json())
         .then(data => {
             console.log(data);

             // Display the sent message in the chat history immediately
             var messageHistory = document.getElementById('message-history');
             var message = document.createElement('div');
             message.className = 'message sent';

             // Create and set message content
             var messageContent = document.createElement('p');
             // Ensure messageContent is a string before assigning to textContent
             messageContent.textContent = `${String(messageContent)} (Sent at ${new Date().toLocaleString()})`;

             message.appendChild(messageContent);
             messageHistory.appendChild(message);
             messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom

             // Clear the input field
             document.getElementById('message-input').value = '';
         })
         .catch(error => console.error('Error:', error));
 });
</script>

I tried using innerhtml but it still doesn’t work

How to stop webpack copyplugin from renaming files?

I have a folder called “Static” which includes the below files

enter image description here

I am using the copy-webpack-plugin to copy these files to a dist folder. For some reason the files are being renamed after running webpack. Below is what I see in dist folder:

enter image description here

Below is what I see when I run Webpack

enter image description here

This is problematic for Chrome as it expects to see manifest.json file name when testing Chrome extension.

Webpack.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve('src/static'),
          to: path.resolve('dist')
        }
      ]
    }),
  ]
};

Why is this happening and how can I prevent renaming? It is strange because for another project I have the same set up and the renaming does not occur.