I’m trying to filter an array of objects based on a specific condition, but I’m not getting the expected output [duplicate]

I’m trying to filter an array of objects in JavaScript based on the age field. I expected the result to return objects with age === 25, but the output is an empty array. Here’s my code:

const data = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 25 }
];

const result = data.filter(person => person.age === "25");
console.log(result);

Expected Output:

[
  { name: "Alice", age: 25 },
  { name: "Charlie", age: 25 }
]

Actual Output:

[]

What I Tried:

  • Used == instead of === and it worked.
  • Checked data types using typeof person.age → it’s number.
  • Changed "25" to 25 in filter condition and it worked.

Question:

Is this a data type issue? What’s the best practice in such cases to avoid unexpected empty results?

When specifying the mimeType for a Gremlin connecting, what is the significance of ‘types=false’?

I am connecting to various implementations of Gremlin using the javascript library and websockets. I am attempting to make my code interoperable with various gremlin servers, all support roughly the same version of Gremlin.

A strange behaviour that I don’t quite grasp is the use of ‘types=false’ being added to the mimeType for some server configurations, i.e:

driver = new gremlin.driver.Client(`ws://localhost:8182/gremlin`,
{
  traversalsource: 'g',
  rejectUnauthorized: false,
  ssl: false,
  mimeType: 'application/vnd.gremlin-v3.0+json;types=false'
}

I understand, the above mimetype to be the default for Tinkerpop.

In some systems I’m testing against, with types=false, gremlin queries result in the following error (which is not present when types=false is omitted):

ResponseError: Server error (no request information): Invalid OpProcessor requested [null] (499)
    at /dev/node_modules/gremlin/lib/driver/connection.js:260:13
    at Array.forEach (<anonymous>)
    at Connection._handleMessage (/dev/node_modules/gremlin/lib/driver/connection.js:254:43)
    at WebSocket.<anonymous> (/dev/node_modules/gremlin/lib/driver/connection.js:131:43)
    at WebSocket.emit (node:events:507:28)
    at Receiver.receiverOnMessage (/dev/node_modules/ws/lib/websocket.js:789:20)
    at Receiver.emit (node:events:507:28)
    at Receiver.dataMessage (/dev/node_modules/ws/lib/receiver.js:413:14)
    at Receiver.getData (/dev/node_modules/ws/lib/receiver.js:352:17)
    at Receiver.startLoop (/dev/node_modules/ws/lib/receiver.js:138:22) {
  statusCode: 499,
  statusMessage: 'Invalid OpProcessor requested [null]',
  statusAttributes: {}

I’d like to understand what types=false does. I understand requests are matched with various opcodes for de-serialization, and eval’ed. When I stepped into Gremlin javascript, I saw both (opcode and bindings) as being undefined but can’t determine why.

In the documentation for GraphSON3, the section begins with:

Version 3.0

Version 3.0 of GraphSON was first introduced on TinkerPop 3.3.0 and is
the default format when not specified as of this version. It is quite
similar to GraphSON 2.0 and in most cases will appear compatible to
the eye, however there are some critical differences:

GraphSON 3.0 does not have an option to be typeless. Types are always
embedded.

GraphSON 2.0 relied on JSON data types for collections like Map and
List. In GraphSON 3.0, there is explicit typed support for Map, List
and Set as Gremlin relies on those types in quite specific ways that
are not directly compatible with the JSON definitions of those
collections. In the case of List and Set, it was important to
distinguish between the two and for Map it was necessary to have the
ability to return Map instances that did not have String keys (e.g.
g.V().out().groupCount()).

Does this imply types=false is invalid in my context? (incidentally, the same error occurs if I switch the mimeType to 'application/vnd.gremlin-v3.0+json;types=false')

Shared module is not available for eager consumption: webpack/sharing/consume/default/react/react

I am trying to run a React microfrontend application using Webpack Module Federation. The container app (container-app) loads remote apps (mfe-dashboard, mfe-portfolio) dynamically using promise new Promise(…).
But I am getting error in chrome console as

main.js:995 Uncaught Error: Shared module is not available for eager consumption: webpack/sharing/consume/default/react/react
    at __webpack_require__.m.<computed> (main.js:995:54)
    at __webpack_require__ (main.js:228:32)
    at fn (main.js:508:21)
    at eval (index.js:2:63)
    at ./src/index.js (main.js:201:1)
    at __webpack_require__ (main.js:228:32)
    at main.js:1623:37
    at main.js:1625:12

I have shared my code as below. Can anyone please suggest some solution.

container-app/webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ModuleFederationPlugin } = require("webpack").container;
const path = require("path");

module.exports = {
  entry: "./src/index.js",
  mode: "development",
  devServer: {
    port: 3000,
    historyApiFallback: true,
  },
  output: {
    publicPath: "auto",
  },
  module: {
    rules: [
      {
        test: /.jsx?$/,
        loader: "babel-loader",
        exclude: /node_modules/,
        options: {
          presets: ["@babel/preset-env", "@babel/preset-react"],
        },
      },
    ],
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "container",
      remotes: {
        portfolio: "portfolio@promise new Promise(resolve => {n    const script = document.createElement('script');n    script.src = 'http://localhost:3001/remoteEntry.js';n    script.onload = () => {n      resolve(window.portfolio);n    };n    document.head.appendChild(script);n  })",
        dashboard: "dashboard@promise new Promise(resolve => {n    const script = document.createElement('script');n    script.src = 'http://localhost:3003/remoteEntry.js';n    script.onload = () => {n      resolve(window.dashboard);n    };n    document.head.appendChild(script);n  })"
      },
      shared: {
        react: { singleton: true, strictVersion: true, requiredVersion: "18.2.0" },
        "react-dom": { singleton: true, strictVersion: true, requiredVersion: "18.2.0" },
      },
    }),
    new HtmlWebpackPlugin({
      template: "./public/index.html",
    }),
  ],
  resolve: {
    extensions: [".js", ".jsx"],
  },
};

mfe-dashboard/webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ModuleFederationPlugin } = require("webpack").container;

module.exports = {
  entry: './src/index.js',
  mode: 'development',
  devServer: {
    port: 3003,
    historyApiFallback: true
  },
  output: {
    publicPath: 'auto'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'dashboard',
      filename: 'remoteEntry.js',
      exposes: {
        './Dashboard': './src/components/Dashboard'
      },
     shared: {
        react: { singleton: true, strictVersion: true, requiredVersion: "18.2.0" },
        "react-dom": { singleton: true, strictVersion: true, requiredVersion: "18.2.0" },
      },
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
};

mfe-portfolio/webpack.config.js

-------------------------------------
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ModuleFederationPlugin } = require("webpack").container;
const path = require('path');

module.exports = {
  entry: './src/index.js',
  mode: 'development',
  devServer: {
    port: 3001
  },
  output: {
    publicPath: 'auto'
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ]
  },
    resolve: {
    extensions: ['.js', '.jsx']
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'portfolio',
      filename: 'remoteEntry.js',
      exposes: {
        './Portfolio': './src/components/Portfolio'
      },
      shared: {
        react: { singleton: true, strictVersion: true, requiredVersion: "18.2.0" },
        "react-dom": { singleton: true, strictVersion: true, requiredVersion: "18.2.0" },
      },
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ],
  resolve: {
    extensions: ['.js', '.jsx']
  }
};

enter image description here

enter image description here

Canvas svg manipulation and glsl

I am trying to build a 3d configurator application which you can select a pattern or sticker etc.. and it applies on model.

Before i was using glsl and shaders and it was perfect but i needed to switch to canvas, now i have a canvas and im trying to implement everything on it and canvas implemented on model through shaders.

right now im trying draw selected svg to canvas but it is very slow, inefficient, bad resolution and not all svg’s are working

Is there any way to do it better?
thank you

export const drawPatternsOnCanvas = (ctx, itemsOnTshirt, uvConditions) => {
  itemsOnTshirt.forEach((item) => {
    if (item.type !== "pattern" || !item.img) return;

    const uv = uvConditions[item.part];
    if (!uv) return;
    const canvasSize = 100;
    const img = new Image();
    img.src = item.pattern; //item.pattern="/pattern/pattern01.svg"

    img.crossOrigin = "anonymous";

    img.onload = () => {
      const minX = uv[0];
      const maxX = uv[1];
      const minY = uv[2];
      const maxY = uv[3];

      const regionWidth = maxX - minX;
      const regionHeight = maxY - minY;

      const coloredPattern = document.createElement("canvas");
      coloredPattern.width = img.width;
      coloredPattern.height = img.height;
      const cpCtx = coloredPattern.getContext("2d");

      cpCtx.drawImage(img, 0, 0);

      cpCtx.globalCompositeOperation = "source-atop";
      cpCtx.fillStyle = `rgb(${Math.floor(item.color[0] * 255)}, ${Math.floor(
        item.color[1] * 255
      )}, ${Math.floor(item.color[2] * 255)})`;
      cpCtx.fillRect(0, 0, img.width, img.height);
      cpCtx.globalCompositeOperation = "source-over";

      const fillPattern = ctx.createPattern(coloredPattern, "repeat");

      if (fillPattern.setTransform) {
        const rotationDegrees = parseFloat(item.rotation) || 0;
        const patternRatioX = img.width / canvasSize;
        const patternRatioY = img.height / canvasSize;

        const center = canvasSize * 0.5;

        const matrix = new DOMMatrix()
          .translateSelf(center, center)
          .rotateSelf(-rotationDegrees)
          .scaleSelf(item.scale / patternRatioX, -item.scale / patternRatioY)
          .translateSelf(item.moveX * canvasSize, item.moveY * canvasSize)
          .translateSelf(-center, -center);

        fillPattern.setTransform(matrix);
      }
      ctx.save();
      ctx.beginPath();
      ctx.rect(minX, minY, regionWidth, regionHeight);
      ctx.clip();

      ctx.fillStyle = fillPattern;
      ctx.fillRect(minX, minY, regionWidth, regionHeight);
      ctx.restore();
    };
  });
};

this is the code which implies pattern svg into canvas

export const createUnifiedCanvasTexture = (
  uvConditions,
  colorsForparts,
  itemsOnTshirt
) => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  const width = (canvas.width = 1000);
  const height = (canvas.height = 1000)
  
  //drawing colors
  drawUVRegions(ctx, uvConditions, colorsForparts);

  // Draw patterns
  drawPatternsOnCanvas(ctx, itemsOnTshirt, uvConditions);
  //inside color
  ctx.fillStyle = "#ffffff";
  ctx.fillRect(1, 180, 124, -179);

  const texture = new THREE.CanvasTexture(canvas);
  texture.flipY = false;
  texture.needsUpdate = true;

  return texture;
};

and this is my main canvas which is connected to shaders and model

Displaying Gantt Chart with Partial Date Data in Highcharts

How can I display this using a Highcharts Gantt chart? I reviewed this example: https://www.highcharts.com/demo/gantt/subtasks, but I only have start/end dates for Phase 3 — not for the other phases. I have the following code but not sure if thats the best way to display. Also I am not sure why the display for May 2025 is cut off? Any thoughts? Thanks in advance.

const statusColorMap = {
      "Completed": "#90ee90",
      "In Progress": "#f4e542",
      "Not Started": "#d3d3d3"
    };

    Highcharts.ganttChart('container', {
      title: { text: 'Project Timeline with Status' },
      tooltip: {
        pointFormatter: function () {
          return `<b>${this.name}</b><br/>Status: ${this.status || 'N/A'}<br/>` +
            (this.milestone ? `Milestone: ${Highcharts.dateFormat('%b %e, %Y', this.start)}` :
              `From: ${Highcharts.dateFormat('%b %e, %Y', this.start)} to ${Highcharts.dateFormat('%b %e, %Y', this.end)}`);
        }
      },
      series: [{
        name: 'Project',
        data: [
          // Parent Phases
          { id: 'phase1', name: 'Phase I: DEV' },
          { id: 'phase2', name: 'Phase II: TEST' },
          { id: 'phase3', name: 'Phase III: DEPLOY' },

          // Phase I
          { name: 'ABC', parent: 'phase1', start: Date.UTC(2025, 4, 14), milestone: true, status: 'Completed', color: statusColorMap['Completed'] },
          { name: 'XYZ', parent: 'phase1', start: Date.UTC(2025, 4, 15), milestone: true, status: 'Completed', color: statusColorMap['Completed'] },
          { name: 'XXXY', parent: 'phase1', start: Date.UTC(2025, 5, 30), milestone: true, status: 'In Progress', color: statusColorMap['In Progress'] },
          { name: 'SDD', parent: 'phase1', milestone: true, status: 'Not Started', color: statusColorMap['Not Started'] },
          { name: 'DFF', parent: 'phase1', start: Date.UTC(2025, 5, 30), milestone: true, status: 'Completed', color: statusColorMap['Completed'] },
          { name: 'DSD', parent: 'phase1', start: Date.UTC(2025, 7, 1), milestone: true, status: 'Not Started', color: statusColorMap['Not Started'] },

          // Phase II
          { name: 'SDEWR', parent: 'phase2', start: Date.UTC(2025, 5, 25), milestone: true, status: 'Completed', color: statusColorMap['Completed'] },
          { name: 'RERRE', parent: 'phase2', start: Date.UTC(2025, 5, 30), milestone: true, status: 'Completed', color: statusColorMap['Completed'] },
          { name: 'FDR', parent: 'phase2', start: Date.UTC(2025, 6, 30), milestone: true, status: 'In Progress', color: statusColorMap['In Progress'] },
          { name: 'DFFG', parent: 'phase2', start: Date.UTC(2025, 8, 30), milestone: true, status: 'Not Started', color: statusColorMap['Not Started'] },
          { name: 'ASSA', parent: 'phase2', start: Date.UTC(2025, 9, 1), milestone: true, status: 'Not Started', color: statusColorMap['Not Started'] },

          // Phase III
          { name: 'GF', parent: 'phase3', start: Date.UTC(2025, 9, 1), end: Date.UTC(2026, 8, 30), status: 'Not Started', color: statusColorMap['Not Started'] },
          { name: 'DFTT', parent: 'phase3', start: Date.UTC(2026, 9, 1), end: Date.UTC(2027, 8, 30), status: 'Not Started', color: statusColorMap['Not Started'] },
          { name: 'SERR', parent: 'phase3', start: Date.UTC(2027, 9, 1), end: Date.UTC(2028, 8, 30), status: 'Not Started', color: statusColorMap['Not Started'] }
        ]
      }]
    });
<!DOCTYPE html>
<html>
<head>
 
  <script src="https://code.highcharts.com/gantt/highcharts-gantt.js"></script>
</head>
<body>
  <div id="container" style="height: 900px; min-width: 1000px;"></div>

Slick Slider Ticker Gets Jittery After Window Resize

I have a Slick Slider on a page, and I have it setup as a ticker. It is setup to be responsive so it shows different amount of slides at different breakpoints. All seems to be working fine, but when you resize the browser window and it crosses one of these breakpoints everything becomes jittery. The slides jump back and forth instead of running smooth like before the resize.

I have a CodePen here: https://codepen.io/tmurren/pen/ByojoNZ

These are the Slick settings I’m using:

$('.ticker').slick({
  slidesToShow: 2,
  slidesToScroll: 1,
  infinite: true,
  autoplay: true,
  autoplaySpeed: 0,
  speed: 3000,
  cssEase:'linear',
  arrows: false,
  dots: false,
  pauseOnHover: false,
  pauseOnFocus: false,
  swipe: false,
  swipeToSlide: false,
  mobileFirst: true,
  responsive: [
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 3,
      }
    },
    {
      breakpoint: 768,
      settings: {
        slidesToShow: 4,
      }
    },
    {
      breakpoint: 992,
      settings: {
        slidesToShow: 5,
      }
    },
    {
      breakpoint: 1200,
      settings: {
        slidesToShow: 6,
      }
    },
    {
      breakpoint: 1440,
      settings: {
        slidesToShow: 7,
      }
    }
  ]
});

Deploy/update file without functions in it – Firebase Functions

I am trying to update a file named blues.cts because a function named fetchAllPacks uses it to update the client. I was wondering if, without updating the functions, I could update the JSON data in that file? The following is blues.cts that I would like to update. It has this data object, interfaces, and a few functions.

export const data = {
    "specials": {
        "Alien Cat": {
            "cost": 0,
            "bluedata": "Alien Cat",
...

This is my functions script, and I see there is no need to update this function.

export const fetchAllPacks = onCall({enforceAppCheck: true}, async (req) => {
    if (req.auth == null) {return {success: false, error: ReturnError.auth.invalid}}
    return {success:true, packs: shop.getAllPacks()};
});

Using Angular’s Custom Elements

I have to build a web component to inject inside a legacy code project;
I tried to follow the official documentation to do so using angular (https://v19.angular.dev/guide/elements) but I feel like is a bit incomplete: for example there is nothing about how do produce a js file to then refer in the html of the target project to be able to use the custom html tag.

I searched extensively for guides or more about the topic but nothing pops out on the Internet, at least not for the newer versions of Angular (newest stuff I found was 2 year old).

I followed the official guide ’till the end and tried to ng build and use the main.js and polyfill.js inside of an html file to reference the custom html tag created in Angular
but I get the following error that is not so explanatory.

enter image description here

Anyone out there building web components in angular that’s facing my same troubles?

This is my app.component.ts:
enter image description here

This is my notifications-center.ts and html;
enter image description here

enter image description here

As you can tell the component is default just because I wanted to test stuff before actually starting the developing.

This is the html file where I’m trying to use the web-component:
enter image description here

Why does my if statement that compares two characters return false when both characters are the same? [closed]

I wrote some code originally to test the eval() function, but now I’m turning it into a very basic calculator. Since it uses the eval() function to calculate the expressions entered in the input <textarea>, I had to make a system that prevents users from putting javascript code into the input and executing it (I think that’s what XSS is). To do this, I made a nested for loop that takes the input and uses charAt() to compare each character in the input to a each character in the disallowedChars string. If the two characters are the same, it’s supposed to set valid to false and break out of the entire loop (the parent loop is labelled charTest). If valid is true, it then uses eval() to evaluate the expression entered in the input, otherwise, it doesn’t.

The problem is that for some reason, the code doesn’t work. For example, if I input the string 2**63, it outputs 9,223,372,036,854,776,000. However if I input 1A, you’ll see that one of the things the console outputs is A is not A Approved! when they are both the same. I’m not using characters from another alphabet (like Greek or Cyrillic), as you’ll be able to check easily for yourself. Here’s all my code:

const expr = document.querySelector("#expr");
const result = document.querySelector("#result");

function calculate() {
  const disallowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`~!@#$%^&_=[]\{}|;':",./<>?";
  var input = expr.value;
  var valid = true;
  if (input != "") {
    charTest: for (var k = 0; k < input.length; k++) {
      console.log("The current character being checked is " + input.charAt(k) + " at position " + k);
      for (var i = 0; i < disallowedChars.length; i++) {
        console.log("Comparing " + input.charAt(k) + " at position " + k + " to " + disallowedChars.charAt(i) + " at position " + i);
        if (input.charAt(k) == disallowedChars.charAt[i]) {
          console.error("Denied");
          alert("For safety purposes, the character "" + input.charAt(k) + "" is not allowed");
          valid = false;
          break charTest;
        } else {
          console.log(input.charAt(k) + " is not " + disallowedChars.charAt(i));
          console.log("Approved!");
        }
      }
    }
    if (valid) {
      var resultText = new Number(eval(input)).toLocaleString();
      result.value = resultText;
    } else {
      alert("Failed to calculate expression")
    }
  } else {
    alert("Enter a valid expression");
  }
}

function resetHeights() {
  expr.style.height = result.style.height = "12.5vh"
}
<!DOCTYPE html>
<html>
  <head>
    <title>eval() test</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css">
  </head>
  <body>
    <textarea name="expr" id="expr" placeholder="Enter a mathematical expression..."></textarea>
    <textarea name="result" id="result" placeholder="Result will appear here..." disabled></textarea>
    <br>
    <button onclick="calculate()">Calculate</button>
    <button onclick="resetHeights()">Reset heights</button>
    <button onclick="location.reload()">Reset</button>
    <h6 class="h0">Allowed symbols:</h6>
    <ul>
      <ol><code>+</code> — addition</ol>
      <ol><code>-</code> — subtraction</ol>
      <ol><code>*</code> — multiplication</ol>
      <ol><code>/</code> — division</ol>
      <ol><code>**</code> — exponentiation</ol>
      <ol><code>()</code> — parentheses for grouping</ol>
    </ul>
    <script src="./main.js"></script>
  </body>
</html>

I’ve tried to figure it out myself for a total of around an hour, but I just couldn’t find where I may have messed up. Does anyone know what the issue might be and how I could go about fixing it?


(p.s. I hope this was one of my better Stack Overflow questions, I’ve asked pretty bad questions in the past. If anyone cares to do so, I’d appreciate feedback on the post itself because I’m still learning how to ask good questions on Stack Overflow)

vis.js shows items with no time starting at around 8PM instead of midnight

Just starting to play with vis.js, timeline mode. Going through the demos, and have everything working. However, when I zoom in on at object on CodePen, dates (without time) start at midnight, which is what you expect. On my computer, dates without time seem to start around 8 PM. In order to get it to start at midnight, i have to explicitly set the time at 00:00. I have tried both 4.19.1 and 4.21.0. I have also tried both Brave and Google Chrome.
The specific example I am trying is one codePen.

https://visjs.github.io/vis-timeline/examples/timeline-generated/codepen.3dc7091f5e57b7311a29e191620f46f17a8f393ee333be69f9391d5869de5ec0.html

When I copy this to my computer, while all nodes show correct, instead of starting at midnight, all start at around 8PM. I have to change the demo code of

var items = new vis.DataSet([
  {
    id: 1,
    content: "item 1 with overflowing text content",
    start: "2014-04-20",
    end: "2014-04-26",
  }, 

to

var items = new vis.DataSet([
  {
    id: 1,
    content: "item 1 with overflowing text content",
    start: "2014-04-20 00:00",
    end: "2014-04-26 00:00",
  },

Any idea why this is happening?

** Additional Info: The Codepen is using a different version of vis.js., which is https://visjs.github.io/vis-timeline/standalone/umd/vis-timeline-graph2d.min.js

Using Docxtemplater horizontally expand nested loop in a MS Word Table

We have data that looks like this:

[
  {
    firstName: 'Susan',
    lastName: 'Storm'
    meta: [
      {
        age: 30,
        email: '[email protected]'
      }
    ]
  },
  {
    firstName: 'Peter',
    lastName: 'Parker'
    meta: [
      {
        age: 30,
        email: '[email protected]'
      }
    ]
  }
]

We are trying to build an MS Word document with a table that includes the following columns:

First Name, Last Name, Age, Email
Susan, Storm, 30, [email protected]
Peter, Parker, 30, [email protected]

We have tried using multi-level loops using both the Vertical Table module and the built-in looping.

Any suggestions on how to achieve this in a Word document using Docxtemplater?

Rotate a label in Plotly Treemap with JavaSctipt

Sometimes there’re narrow bricks on treemaps. Plotly decrease the font size of such a labels, so you cannot read them. But another way is making thease labels horizontal. As far as I understood the only way to rotate labels in Plotly is using JavaScript. I’m new at it, please help to understand how to select some particular node with JS?
Here’s the example code, where I try to rotate the label ‘a1’ (but fail):

data = {'level1': ['A', 'A', 'B', 'B'], 'level2': ['a1', 'a2', 'b1', 'b2']}
fig = px.treemap(data, path=['level1', 'level2'])

js = """
   function rotateLabel(){
       const nodes = gd.querySelectorAll('slicetext');
       for (const node of nodes){
            const label = node.querySelector('[data-unformatted="a1"]');
            label.style.transform = 'rotate(90deg)';
       }
   }       
   const gd = document.querySelector('.plotly-graph-div');
   gd.on('plotly_afterplot', rotateLabel.bind(gd));
   gd.emit('plotly_afterplot');
   
   """

fig.show(post_script=[js])

How to add own pathfinder in GitHub PathFinding.js repository?

I have forked PathFinding.js and have added the IDDFS pathfinder. (It is based on this Java implementation.)

I followed some arbitrary guidelines and made it visible in the visual/index.html, yet it throws an error as soon as I press the Start Search button:

state-machine.min.js:1 Uncaught TypeError: Cannot read properties of undefined (reading 'findPath')
onsearch    @   controller.js:138
doCallback  @   state-machine.min.js:1
afterEvent  @   state-machine.min.js:1
transition  @   state-machine.min.js:1
(anonymous) @   state-machine.min.js:1
onstarting  @   controller.js:230
doCallback  @   state-machine.min.js:1
enterState  @   state-machine.min.js:1
transition  @   state-machine.min.js:1
(anonymous) @   state-machine.min.js:1
g   @   jquery-1.7.2.min.js:2
dispatch    @   jquery-1.7.2.min.js:3
i   @   jquery-1.7.2.min.js:3

Registration form not displaying validation error messages for input fields

I’m building a user registration form using HTML, CSS, and JavaScript, with Firebase Authentication handling the registration.

I wanted to add a common feature where errors are prompted when using an invalid email, a short password, or mismatched passwords. This is quite common with many registration forms.

I expected inline error messages like “Invalid email format” or “Passwords do not match”) to appear under the form fields when validation fails. For some reason, it doesn’t show up or give that prompt. It’s as if the JS doesn’t trigger to show that.

const form = document.getElementById('register-form');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
const repeatPasswordInput = document.getElementById('repeat-password');

function resetErrors() {
  [emailInput, passwordInput, repeatPasswordInput].forEach(input => {
    input.classList.remove('error');
    document.getElementById(`${input.id}-error`).classList.remove('show');
  });
}

function validateInputs() {
  let hasError = false;
  resetErrors();

  if (!emailInput.value.includes('@') || !emailInput.value.includes('.')) {
    emailInput.classList.add('error');
    document.getElementById('email-error').classList.add('show');
    hasError = true;
  }

  if (passwordInput.value.length < 6 || passwordInput.value.length > 32) {
    passwordInput.classList.add('error');
    document.getElementById('password-error').classList.add('show');
    hasError = true;
  }

  if (passwordInput.value !== repeatPasswordInput.value) {
    repeatPasswordInput.classList.add('error');
    document.getElementById('repeat-password-error').classList.add('show');
    hasError = true;
  }

  return !hasError;
}

form.addEventListener('submit', (e) => {
  e.preventDefault();
  if (!validateInputs()) {
    alert('Please fix the highlighted fields.');
  } else {
    alert('Form submitted!');
    form.reset();
    resetErrors();
  }
});
.register-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  gap: 4rem;
  padding: 5rem 2rem;
  max-width: 1100px;
  margin: 0 auto;
  flex-wrap: wrap;
}

#register-form {
  flex: 1;
  max-width: 400px;
  background-color: #fcfcfc;
  padding: 2rem 2.5rem;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(122, 132, 80, 0.2);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  box-sizing: border-box;
}



#register-form label {
  display: block;
  margin-bottom: 0.3rem;
  font-weight: 600;
  color: #4b5221;
}

#register-form input {
  width: 100%;
  padding: 0.6rem 0.8rem;
  margin-bottom: 1rem;
  border: 1.5px solid #c8ceaa;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

#register-form input:focus {
  border-color: #7a8450;
  outline: none;
}

#submit {
  width: 100%;
  background-color: #7a8450;
  border: none;
  color: white;
  font-weight: 700;
  padding: 0.75rem;
  border-radius: 25px;
  font-size: 1.1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.form {
  text-align: center;
  margin-top: 1.5rem;
  font-size: 0.95rem;
  color: #555;
}

.form a {
  color: #7a8450;
  font-weight: 600;
  text-decoration: none;
}

.form a:hover {
  text-decoration: underline;
}

.register-tip {
  font-size: 0.8rem;
  color: #7a8450;
  font-style: italic;
  margin-top: 0rem;
  margin-bottom: 1rem;
}

input.error {
  border: 2px solid red;
  background-color: #ffe6e6;
}

.error-message {
  color: red;
  font-size: 0.8rem;
  margin-top: 0rem;
  margin-bottom: 0.2rem;
  display: none;
}

#register-form .error-message.show {
  display: block;
}


@media screen and (max-width: 768px) {
  .register-container {
    padding: 2rem 1rem;
  }

  #register-form,
  .register-info {
    max-width: 100%;
  }
}
<form id="register-form">
  <label for="email">Email</label>
  <input type="email" id="email" placeholder="Email" />
  <div class="error-message" id="email-error">Please enter a valid email</div>

  <label for="password">Password</label>
  <input type="password" id="password" placeholder="Password" />
  <div class="error-message" id="password-error">Password too short</div>

  <label for="repeat-password">Repeat Password</label>
  <input type="password" id="repeat-password" placeholder="Repeat Password" />
  <div class="error-message" id="repeat-password-error">Passwords do not match</div>

  <button type="submit">Register</button>
</form>
  • I added console.log to confirm validateInputs runs (it sends the reports as intended).
  • Checked CSS for conflict. The displays should be correct.

“navigator.clipboard.writeText fails if tab loses focus — workaround?”

I’m using navigator.clipboard.writeText() to copy decrypted content after a button click.

The value is decrypted asynchronously (Promise / Observable in Angular), and once decrypted, I attempt to copy it to clipboard.

Problem

In practice, users click the “Copy” button and immediately switch to another app (like Notepad) or browser tab to paste the value.

This causes the document to lose focus before the asynchronous decryption completes, and the clipboard operation fails.

UX Issue

As a result — the copy silently fails, and the user ends up pasting nothing.

This is especially problematic because they don’t see the error, and it feels like the button is broken.

I understand this is a browser limitation for security reasons.

Are there any workarounds ? What should I do in this situation?
Here is my current implementation

 public copySecureField(key: keyof SecureInfoFields, value: string): void {
    this.getDecryptedDataForCopying({ [key]: value })
      .pipe(
        switchMap((data) => {
          return from(navigator.clipboard.writeText(data[key])).pipe(
            catchError(() => {
              this._notificationService.error(COPY_FAIL_FOCUS_MESSAGE);

              return EMPTY;
            }),
          );
        }),
        tap(() => this.setSecureFieldIsCopied(key, true)),
        delay(1000),
        finalize(() => this.setSecureFieldIsCopied(key, false)),
      )
      .subscribe();
  }