Add and remove event listeners conditionally in useEffect

On right click, context menu appear in my app with button which set’s a isSelecting state to true. In the same time, two event listeners are added to a document – one to handle mouse over and one to handle click. Both these event should be active only when isSelecting is true and the onclick event set isSelecting to false. Unfortunately, currently one I add event listeners in useEffect via setting isSelecting to true in my context menu, onclick event is immidiately called. How to prevent its execution until I click one more time?

  const handleMouseOver = (e: any) => {
    let target = e.target as HTMLElement;
    let selectableTarget: HTMLElement | null = target.hasAttribute('data-type')
      ? target
      : null;
    while (selectableTarget === null && target.parentElement) {
      target = target.parentElement;
      selectableTarget = target.hasAttribute('data-type') ? target : null;
    }

    if (selectableTarget !== prevRef.current) {
      prevRef.current?.classList.remove(...highlightClasses);
      prevRef.current = selectableTarget;
      prevRef.current?.classList.add(...highlightClasses);
    }
  };

  const handleClick = async () => {
    setIsSelecting(false);
    prevRef.current?.classList.remove(...highlightClasses);
    toast({
      title: 'Skopiowano!',
      description: 'Teraz wklej zawartość do edytora Wizards',
    });
    await navigator.clipboard.writeText(prevRef.current?.outerHTML || '');
  };

  useEffect(() => {
    if (isSelecting) {
      document.addEventListener('mouseover', handleMouseOver);
      document.addEventListener('click', handleClick);
    } else {
      document.removeEventListener('mouseover', handleMouseOver);
      document.removeEventListener('click', handleClick);
    }

    return () => {
      document.removeEventListener('mouseover', handleMouseOver);
      document.removeEventListener('click', handleClick);
    };
  }, [isSelecting]);

  return (
    <ContextMenu open={open} setOpen={setOpen} targetElement={editor.view.dom}>
      {(event) => (
        <div>
          {mathPanel && (
            <Button
              onClick={async () => {
                await navigator.clipboard.writeText(mathPanel.node.attrs.id);
                close();
              }}
              variant='ghost'
            >
              Kopiuj #ID
            </Button>
          )}
          <Button
            variant='ghost'
            onClick={() => {
              // close();
              setIsSelecting(true);
            }}
          >
            Kopiuj fragment
          </Button>
        </div>
      )}
    </ContextMenu>
  );
};

My desired behaviour is: set isSelecting to true by using context menu -> add event lsiteners to document -> set isSelecting to false on the next click -> disable event lsiteners

Problems with datatable using jQuery and perl

I need help with my Datatable data processing

Am having a problem with my Script below of Server Side Processing (Datatable) its not displaying the data from backend script

The problem it just hangs on processing while not displaying the data from backend script

This is my backend script, its working and returns

{"748847":"Jane Deo"}
#!/usr/bin/perl -wT

use strict;
use warnings;
use DBI;
use JSON;
use CGI qw/:standard/;

my $Cgi = CGI->new();

my $host =   "host";
my $usr =    "user";
my $pwd =    "pwd";
my $dbname = "datname";


my $dbh = DBI->connect("DBI:mysql:$dbname:$host", $usr, $pwd, {
                                  RaiseError => 1,
                                  }) or die $DBI::errstr;
                                  
my $Test = $dbh->prepare("SELECT idnum, fname FROM dbuser");
$Test->execute();


my (@data,$idnum,$fname);
 
 
 foreach (@data = $Test->fetchrow_array()) {
    $idnum = $data[0];
    $fname = $data[1];

}


my $json = encode_json(
  { $idnum, $fname}
);
print $Cgi->header( -type => 'application/json' ),$json;

And this is my html front end

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/jq-3.3.1/dt-1.10.18/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs/jq-3.3.1/dt-1.10.18/datatables.min.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script>
        jQuery(function($){
            $("#table_id").DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "file.pl"
            });
            
        });
</script>
</head>

<body>
    <h1>sample dataTable</h1>
    <table id="table_id" class="table table-hover">
    <thead>
        <tr>
            <th>ID</th>
            <th>NAME</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
        
    </tbody>
</table>
</body>
</html>

Reload page without refresh

I have a page with some charts and i want to “Real-time” update them without refreshing the whole page.

ATM in test phase i’m running with this reload function.

function autoRefresh() {
    window.location = window.location.href;
}
setInterval('autoRefresh'), 60000);

I’ve tried a lot of different things but with no result.

Why is my jsondata undefined outside of the fetch function? [duplicate]

I used fetch to retrieve data from a local JSON file stored in the same folder as where the javascript file is but when I console.log the variable jsondata, two things happen, jsondata comes back undefined but I also get the JSON data back.

but when I try to console.log outside of fetch I only get jsondata is undefined. I understand this is probable due to fetch being a promise but how do I get the JSON data outside of the fetch function?

fetch ('/data.json')
.then(function(u) { return u.json();}
).then(
  function(json){
   
    const jsondata = json
      console.log(jsondata)
    }
  )

Fehler mit js – Uncaught TypeError: $(…).DataTable is not a function [closed]

ich bekomme leider folgenden Fehler egal was ich versuche nicht weg: Uncaught TypeError: $(...).DataTable is not a function

Auch die Reihenfolge ist meiner Meinung nach richtig?

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <title>Hostdetails</title>
</head>

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.1.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/2.0.0/js/dataTables.min.js"></script>


Hat jemand von euch eine idee?

I need to get all the values from the html page (content=””), but I do not know which tag to search for (content=””)

this is how the html code with the price looks like

<meta itemprop="price" content="121080">

I made this search code, but I don’t know which tag to look for the price by

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch({headless: false})
    const page = await browser.newPage()
    await page.goto('https://')

    let arr = await page.evaluate(() => {

        let text = document.getElementsByClassName('')
        return text
    })

    console.log(arr)

})()

How to make a mask for an image and turn it to different colors in PyQt6?

I have the below image.

image.png

I make it a mask in javascript and this lets me turn the image to every color that I want. here is the code.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body style="background-color: darkgray;">
    <canvas id="theCanvas" style="background-color: lightgray;"></canvas>
    <script src="main.js"></script>
</body>

</html>

main.js

const theCanvas = document.getElementById("theCanvas");
const ctx = theCanvas.getContext("2d");
theCanvas.width = 150;
theCanvas.height = 150;
const image = new Image();
image.onload = drawImageActualSize;
image.src = "image.png";
color = "red";

function drawImageActualSize() {
    ctx.fillStyle = color;
    ctx.rect(0, 0, theCanvas.width, theCanvas.height);
    ctx.fill();
    ctx.globalCompositeOperation = "destination-atop";
    ctx.drawImage(this, 0, 0, theCanvas.width, theCanvas.height);
    ctx.globalCompositeOperation = "multiply";
    ctx.drawImage(image, 0, 0, theCanvas.width, theCanvas.height);
}

and this gives me the below image.

image

now I want to do the same job in Python using PyQt6 but how should I make an image mask in pyqt6?

so far I did this below code.

main.py

from sys import argv
from sys import exit as ex
from pathlib2 import Path
from PyQt6.QtWidgets import QApplication, QWidget, QSizePolicy, QVBoxLayout
from PyQt6.QtCore import Qt, QRectF, QTimer
from PyQt6.QtGui import QPaintEvent, QPainter, QImage, QPen, QColor, QBrush


class PaintWidget(QWidget):
    def __init__(self, parent=None) -> None:
        super().__init__()
        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        )
        self.image = QImage(str(Path(Path(__file__).parent, "image.png")))
        self.image.scaledToWidth(150)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update)
        self.timer.start(17)

    def paintEvent(self, event: QPaintEvent | None) -> None:
        painter = QPainter()
        painter.begin(self)
        painter.setPen(QPen(QColor(169, 169, 169), 0, Qt.PenStyle.SolidLine))
        painter.setBrush(QBrush(QColor(169, 169, 169), Qt.BrushStyle.SolidPattern))
        painter.drawRect(0, 0, 1920, 1080)
        rect = QRectF(0, 0, self.image.width(), self.image.height())
        painter.drawImage(rect, self.image)
        painter.end()
        return super().paintEvent(event)


class MainWindow(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.setup_ui()
        self.show()

    def setup_ui(self) -> None:
        self.showFullScreen()
        self.main_window_layout = QVBoxLayout()
        self.painter_widget = PaintWidget()
        self.main_window_layout.addWidget(self.painter_widget)
        self.setLayout(self.main_window_layout)


if __name__ == "__main__":
    app = QApplication(argv)
    main_window = MainWindow()
    ex(app.exec())

that gives me this.

image

I try this code

self.masking = self.image.createMaskFromColor(0, Qt.MaskMode.MaskInColor)

painter.drawImage(rect, self.masking)

but it turns everything to black and white and gives me this.

image

Why is the canvas not drawing a line?

It is my first time using a canvas and was trying to test it by drawing a line through the specified coordinates. Can someone explain why it is not working?

const c = document.getElementById("chessBoard");
const canvas = c.getContext("2d");

canvas.beginPath();
canvas.moveTo(75, 0);
canvas.lineTo(75, 600);
canvas.stroke();
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Chess Project</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="index.css">
        <script src="board.js"></script>
    </head>
    <body>
        <section>
            <header id="header">
                Chess Project
            </header>
        </section>
        <section>
            <canvas id="chessBoard"></canvas>
        </section>
    </body>
</html>
body {
    margin: 0;
}

#header {
    background-color: black;
    color: white;
    font-size: 40px;
    height: 50px;
    text-align: center;
}

#chessBoard {
    position: absolute;
    left: 550px;
    top: 150px;
    border: 1px solid #000000;
    border-radius: 5px;
    width: 600px;
    height: 600px;
}

If someone could please take a look at the code and give me any advice that would be greatly appreciated.

I am unable to retrieve data from mongoDB [closed]

I created a collection in the MongoDB database and filled it with data from my form;

However, when fetching this data, I receive the 400 Bad request error;

//This route worked and I have the data in the Database
routes.post("/circuits", async (req, res) => {
const Circuit = await CircuitModel.create(req.body)
res.status(201).json({
error: false,
message: "Registered successfully!"
data: Circuit})
}

routes.get("/table, async (req, res) => {
try {
const circuits = await CircuitModel.find()
res.json(circuits)
} catch (error) {
res.status(400).json({
error: true,
message: "Something went wrong"
})
}
})

form URL; "http://localhost:5173/circuits"
Table URL; "http://localhost:5173/table"

//Client-side request on Table;
useEffect(()=>{
axios.get("http://localhost:3001/table")
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
}, [])

React can’t store in Local Storage before navigating to another page

I have a useLocalStorage hook:

export const useLocalStorage = <T,>(key: string, initialValue: T | (() => T)) => {
  const [value, setValue] = useState<T>(() => {
    const jsonValue = localStorage.getItem(key)
    if (jsonValue !== null) {
      return JSON.parse(jsonValue)
    }

    if (typeof initialValue === "function") {
      return (initialValue as () => T)()
    }
    else {
      return initialValue
    }
  })

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value))
  }, [key, value])

  return [value, setValue] as [typeof value, typeof setValue]
}

I’m trying to store a value in local storage before calling navigate(“/new-page”). The value is not stored in local storage.

savedVehicles.push(vehicle!)
setSavedVehicles([...savedVehicles])
navigate(`/new-page`)

How can I store the value in local storage and navigate to another page?

how I can import easyeditor Jquery plugin as ES-6 into my project?

I am importing this lib into my laravel project:

npm i easyeditor --save

And I load it into my vite setting:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import inject from "@rollup/plugin-inject";

import { readdirSync,lstatSync } from 'fs';
import { resolve } from 'path';


function getFilesFromDir(dir) {
    const filesToReturn = [];

    function walkDir(currentPath) {

        if(lstatSync(currentPath).isFile()){
            filesToReturn.push(currentPath);
            return;
        }

        const files = readdirSync(currentPath);
        for (let i in files) {
            console.log(files[i]);
            const curFile = resolve(currentPath, files[i]);
            if(lstatSync(curFile).isDirectory()){
                walkDir(curFile);
                continue;
            }
            const file = resolve(currentPath, files[i]);
            filesToReturn.push(file);
        }
    }

    walkDir(resolve(__dirname, dir));
    return filesToReturn;
}


const js = getFilesFromDir('./resources/js');

const paths = [

    ...js,

    'node_modules/jquery/dist/jquery.js',

    'node_modules/bootstrap/dist/css/bootstrap.css',
    'node_modules/bootstrap/dist/js/bootstrap.bundle.js',
  
    "node_modules/easyeditor/src/easyeditor.css",
    "node_modules/easyeditor/src/jquery.easyeditor.js"
]

console.log(paths);

export default defineConfig({
    plugins: [
        laravel({
            input:paths,
            refresh: true,
        }),
        inject({
            $: 'jquery',
            jQuery: 'jquery',
        }),
    ],
    build: {
        rollupOptions: {
            external: [
                "js/modules/*",
            ],
            include:[
                'assets/js/utils.js'
            ]
        }
    }
});

But I want instead of loading as:

@vite("node_modules/easyeditor/src/jquery.easyeditor.js","assets/js/myjs.js")

To use it as ES-6 module:

import $ from 'jquery';
// Import easy editor here

But as I can see the lib is not exported as a module:
https://github.com/im4aLL/easyeditor/blob/master/src/jquery.easyeditor.js

How I can do this?

Callback hell in javascript sample [closed]

I need to create a sample code of callback hell for a trainee. Is this code a correct sample of callback hell in javascript older than es6:

function first( a,b, callback){
      setTimeout(function(){
        x = a * b;
          console.log(x);
          callback(x);
      }, 1000);
  }
  function second( a ,b ,callback){
      setTimeout(function(){
        y = a + b;
          console.log(y);
          callback(y);
      }, 1000);
  }
    function third( a ,b ,callback){
        setTimeout(function(){
            z = a - b;
            console.log(z);
            callback(z);
        }, 1000);
    }
    function fourth( a ,b ,callback){
        setTimeout(function(){
            w = a / b;
            console.log(w);
            callback(w);
        }, 1000);
    }

    first(2,3, function(result){
        second(result, 4, function(result){
            third(result, 5, function(result){
                fourth(result, 6, function(result){
                    console.log('done');
                });
            });
        });
    });

If you have a better example please help me.

What does the following code taken from the Emscripten project mean?

I was reading the following code from the Emscripten project:

// The following operations have very fast WebAssembly opcodes. Therefore they are not
// exposed as individual functions:

// Math.abs(x) -> f32.abs and f64.abs. (use fabsf() and fabs() from math.h)
// Math.ceil -> f32.ceil and f64.ceil (ceil() and ceilf() in math.h)
// Math.clz32(x) -> i32.clz and i64.clz (call __builtin_clz() and __builtin_clzll())
// Math.floor -> f32.floor and f64.floor (floor() and floorf() in math.h)
// Math.fround -> f64.promote_f32(f32.demote_f64()) (call double d = (double)(float)someDouble;)
// Math.imul(x, y) -> i32.mul and i64.mul (directly multiply two signed integers)
// Math.min -> f32.min and f64.min (fminf() and fmin() in math.h)
// Math.max -> f32.max and f64.max (fmaxf() and fmax() in math.h)
// Math.trunc -> f32.trunc and f64.trunc (truncf() and trunc() in math.h)

Can anyone please explain what exactly is meant by the statement “very fast WebAssembly opcodes”.

I have a slight understanding of WebAssembly also about opcodes. However, I can’t understand how come, for example, Math.floor() produces a fast opcode when it internally relies on the floor() function in C, from the math.h library.

The confusion starts off when I read the code that follows in the given link. Math.round() from JavaScript isn’t considered to produce a “fast WebAssembly opcode”, yet it also uses a C function, in particular round() again from math.h.

How is round() in C any different from floor() in C, and how that does difference equate to one call being able to produce a quicker opcode.

I am getting this error, (Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.)

I am having this weird error in next.js 14, and I am only having this error when i put the condition (role === “admin”), Why is that?

{role === "admin" && (
<Link
href={"/admin/overview"}
<Image className="transition-all duration-200"src="/assets/sidebar/my_feed.svg" alt={"overview"} height={24} width={24}/>

<p>Overview</p></div>

</Link>)}

Cannot read property ‘caseSensitive’ of undefined in express router

javaScriptcode
app.js
const express = require('express')
const app = express()
const {route} = require('./routes/route')
app.use(express.static('./public'));
app.use(express.json());
app.use(express.urlencoded());
app.use(route)app.listen(5000,()=>{
console.log('server is listening at port 5000...')
})
route.js
const { items } = require("../data");
const express = require("express");
const route = express.Router();
route.get("/", (req, res) => {
  res
    .send('<h1>Home Page</h1><a href="/api/v1/items">products</a>')
    .status(200);
});
route.get("/api/v1/items", (req, res) => {
  const newItems = items.map((item) => {
    const { id, name, img, price, desc, category } = item;
    return { id, name, img, price, desc, category };
  });
  res.json(newItems);
});
route.get("/login.html", (req, res) => {
  res.sendFile(__dirname + "/public/sigup.html");
});

route.post("/", (req, res) => {
  console.log(req.body.emailid);
  if (req.body.emailid === "[email protected]") {
    res.status(200).redirect("signup.html");
    console.log(req.body.emailid);
  } else {
    route.get("/errormsg", (req, res) => {
      const msg = "please Enter valid Email id";
      res.status(401).json({ msg });
    });
  }
});
module.exports = route;

what wrong with my code
TypeError: Cannot read property ‘caseSensitive’ of undefined
at route (D:node_jsmyownapinode_modulesexpresslibrouterindex.js:506:21)
at Layer.handle [as handle_request] (D:node_jsmyownapinode_modulesexpresslibrouterlayer.js:95:5)
at trim_prefix (D:node_jsmyownapinode_modulesexpresslibrouterindex.js:328:13)
at D:node_jsmyownapinode_modulesexpresslibrouterindex.js:286:9
at Function.process_params (D:node_jsmyownapinode_modulesexpresslibrouterindex.js:346:12)
at next (D:node_jsmyownapinode_modulesexpresslibrouterindex.js:280:10)
at urlencodedParser (D:node_jsmyownapinode_modulesbody-parserlibtypesurlencoded.js:91:7)
at Layer.handle [as handle_request] (D:node_jsmyownapinode_modulesexpresslibrouterlayer.js:95:5)
at trim_prefix (D:node_jsmyownapinode_modulesexpresslibrouterindex.js:328:13)
at D:node_jsmyownapinode_modulesexpresslibrouterindex.js:286:9