How can I blur an image in a specific spot?

I am trying to make an effect where, when I hover over an image, that part of the image where my cursor is becomes blurred.

I’ve tried multiple methods to approach this problem, such as using SVGs (Code for what I’m currently trying is provided below), as well as just a normal div with a blur backdrop-filter. However, they all lead to the same problem in which the border of the blurring element is sharp, so it ends up looking like the image provided. Instead, I want the blur effect to look like it slowly merges into the image. How can I achieve that effect? Also, I am a beginner at web development, so I would appreciate answers which explain everything in baby steps. Thanks a lotThe output of previously tried solutions

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Blurred Circle Effect</title>
  <link rel="stylesheet" href="styles.css">
  <style>
    .container {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url('https://via.placeholder.com/400');
  background-size: cover;
}

.container::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: inherit;
  background-size: inherit;
  filter: blur(10px);
  clip-path: circle(20% at center); /* Adjust the circle size */
  pointer-events: none; /* Prevent interaction with the pseudo-element */
}

  </style>
</head>
<body>

  <div class="container"></div>

</body>
</html>

jQuery in functions.php – Uncaught TypeError: $ is not a function

I’m trying to add a small amount of code to a WordPress site in the functions.php file. I’ve tested the code in Codepen and it works perfectly.

However, when I add it to the site, I get the following error message in the console

Uncaught TypeError: $ is not a function

I feel like I’m close, but obviously not close enough! I’d be grateful for any advice.

add_action('wp_footer', 'wpb_hook_javascript_footer');
function wpb_hook_javascript_footer() {
    ?>
    <script>
var thehours = new Date().getHours();
var theday = new Date().getDay();
    var themessage;
    var morning = ('Order before 2pm for guaranteed dispatch TODAY');
    var evening = ('Order now for guaranteed dispatch TOMORROW');
    var friday = ('Order now for guaranteed dispatch on MONDAY');

    if ((thehours >= 0 && thehours < 14 && theday == 1) ||
    (thehours >= 0 && thehours < 14 && theday == 2) ||
    (thehours >= 0 && thehours < 14 && theday == 3) ||
    (thehours >= 0 && thehours < 14 && theday == 4)) {
     themessage = morning;

    } else if ((thehours >= 14 && thehours < 24 && theday == 1) ||
               (thehours >= 14 && thehours < 24 && theday == 2) ||
               (thehours >= 14 && thehours < 24 && theday == 3) ||
               (thehours >= 14 && thehours < 24 && theday == 4) ||
               (thehours >= 0 && thehours < 24 && theday == 0)) {
                themessage = evening;

    } else if ((thehours >= 14 && thehours < 24 && theday == 5) ||
               (thehours >= 0 && thehours < 24 && theday == 6)){
                themessage = friday;
  }

    $('.checkout_dispatchtime').append(themessage);
    </script>
    <?php
}

Playwright Test Running Twice Even with Worker Set to 1

I’m facing an issue where my Playwright test runs twice, even though I’ve configured the workers option to 1 in my Playwright config. Below is a snippet of my configuration:

timeout: 20 * 60 * 1000,
/* Run tests in files in parallel */
fullyParallel: false,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 1 : 0,
/* Opt out of parallel tests on CI. */
workers: 1,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */

Here’s an example of my test structure:

test.describe("First Step", () => {
  test.beforeAll(async () => {
    // Setup code
  });

  test("Single test", async () => {
    // Test code
  });

  test.afterAll(async () => {
    // Teardown code
  });
});

However, when I run this single test, it shows the following in the console:
Running 2 tests using 1 worker

Even though I only have one test defined, Playwright identifies it as two tests.

What I’ve Tried
Ensured the workers option is set to 1 in the configuration.
Verified the test structure to confirm there’s only one test present.
Consulted ChatGPT, but the suggestions didn’t resolve the issue.
Goal
I need my test to execute only once, regardless of the worker count or configuration.

Has anyone encountered a similar issue? If so, how did you resolve it?

Saving scroll momentum for touch interface devices when using scrollTo

I am currently writing a website where, when you reach a certain position, you are thrown up to an identical position without any animation. Because of this, it should feel like you’re endlessly scrolling. I used the window.scrollTo function to implement this. At the same time, it works perfectly on a computer and laptop. However, when used on a phone, the scroll speed is reset when moving up. How can this be fixed?

You need to at least understand the cause of the problem, and at best immediately find out its direct solution.

This is example of code

HTML

<section class="galery">
    <section class="column1">
        <section class="item" id="101">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="102">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="103">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="104">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="105">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="106">
            <img class="galery_item" alt="Picture">
        </section>
        <section class="item" id="107">
            <img class="galery_item" alt="Picture">
        </section>
    </section>
    ***Other column***
</section>

JS

if('ontouchstart' in window || navigator.maxTouchPoints){
    window.addEventListener('touchend', () =>{
        flag = true;
    });
    window.addEventListener('touchstart', () =>{
        flag = false;
    });
    window.addEventListener('scroll', () =>{
        if(flag){
            if(***coordinates of the lower boundary*** <= pageYOffset){
                window.scrollTo(0, ***coordinates of the indented upper boundary***);
            }
            else if(***coordinates of the upper boundary*** >= pageYOffset){
                window.scrollTo(0,  ***coordinates of the indented lower boundary***);
            }
        }
    });
}

this is what the site looks like

enter image description here

when the user reaches a certain lower limit, he is thrown up to the same picture. The result is a visual effect of endless scrolling. But on devices with touch interface, the scrolling pulse is not saved when the scrollTo function is triggered and the screen stops abruptly. This needs to be fixed.

There have been attempts to make the main event trigger a function like touchend rather than scroll, but this has led to the user reaching the bottom of the site too quickly and having to greatly increase the html code.

How to achieve a very smooth native like scrolling on mobile browser?

I have exhausted all my CSS and javascript knowledge and I still could not figure out how they optimize their mobile website so much that it scrolls like a native app, even with images and videos that are occupying most of the viewport, it still scrolls very smooth.

I have tried

scroll-behavior: smooth;

in my CSS containers

and javascript

document.querySelector(target).scrollIntoView({ behavior: 'smooth' });

and I have even tried

will-change: transform;

attribute on a parent container that transforms content upwards computed by javascript. That is probably the worst performing one in my test.

How does facebook do it?

FabricJS v6 set Background Image

The documentation of Fabric JS says they dropped support for setBackgroundObject and setBackgroundImage both of which could be set to update the canvas to have a background image:

e.g

canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
    backgroundImageOpacity: 0.5,
    backgroundImageStretch: false
});

//or the more convoluted:
const rect = new Rect({
  left: 0,
  top: 0,
  width: canvas.width || 0,
  height: canvas.height || 0,
  fill: "transparent",
  opacity: 0,
  stroke: "transparent",
  strokeWidth: 0,
  selectable: false,
  hasControls: false,
});
const img = new FabricImage(url, {
  crossOrigin: "anonymous",
});
img.scaleToHeight(canvas.width || 0);
img.scaleToWidth(canvas.height || 0);
rect.set("backgroundImage", img);
canvas.setBackgroundObject(rect);

How to do it in V6?

The documentation is not clear in how they expect this to be done:

rm setBackgroundColor, setBackgroundImage, setOverlayColor, setOverlayImage: assign the property directly and render the canvas

Attempts:

// Attempt A: (doesn't update the background)
const img =  FabricImage.fromURL(url, { crossOrigin: 'anonymous' });
canvas.set("backgroundImage", img);
canvas.renderAll();

//Attempt B: 
// This leads to the error below:
canvas.backgroundImage = FabricImage.fromURL(url, { crossOrigin: 'anonymous' });
canvas.renderAll();

Type ‘Promise<FabricImage<Partial, SerializedImageProps, ObjectEvents>>’ is missing the following properties from type ‘FabricObject<Partial, SerializedObjectProps, ObjectEvents>’: noScaleCache, lockMovementX, lockMovementY, lockRotation, and 223 more.ts(2740)
(property) StaticCanvas.backgroundImage?: FabricObject<Partial, SerializedObjectProps, ObjectEvents>
Background image of canvas instance. since 2.4.0 image caching is active, please when putting an image as background, add to the canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom vale. As an alternative you can disable image objectCaching

The scaleX() function in the Konva.js library shifts the coordinates of the Konva.Text() object

I need to recreate an inverted version of an original 2d model side by side.

I can achieve this with scaleX(-1) but the text is upside down.

When I scaleX(-1) again on the inverted model, the coordinates of the text are distorted, how can I solve this problem?

the one on the left is the original model and the one on the right is the reversed model. I made the backgrounds yellow to make it clearer that it has shifted.

to give an example from part of the code

function mmToPx(mm) {
    return mm * dimensions.currentScale;
}
 // Bobin
    const coil = new Konva.Rect({
        x : centerX - (mmToPx(dimensions.R1 - dimensions.r2) - mmToPx(1)) / 2,
        y : centerY - (mmToPx(dimensions.Ls) - mmToPx(1)) / 2,
        width : mmToPx(dimensions.R1 - dimensions.r2) - mmToPx(1),
        height : mmToPx(dimensions.Ls - dimensions.ts) - mmToPx(1),
        fill: '#ff7f27',
        stroke: 'black',
        strokeWidth: 5,
    });
    
 const lines = [
...,
{
            isText : true, 
            width : coil.width(),
            text: 'N,I',
            textX: coil.x(),
            textY: (coil.y() + (coil.height() / 2)) - (dimensions.currentScale / 2),
            textColor : 'black',
        },
...,
];

lines.forEach(line => {
...,
if(line.isText){
            var text = new Konva.Text({
                x: line.textX,
                y: line.textY,
                text: line.text,
                fill: line.textColor,
                fontFamily: 'Calibri',
                fontSize: 14,
                align : 'center',
                width : line.width,
            });
            
            
            const textBackground = new Konva.Rect({
                x: line.textX,
                y: line.textY,
                width: line.width,
                height: 20, 
                fill: 'yellow',
                cornerRadius: 4, 
            });
            originalGroup.add(textBackground);
            originalGroup.add(text);
        }
});

and here is the scaleX() method

   const mirrored = originalGroup.clone();
    mirrored.x(centerX * 2.35)
    mirrored.scaleX(-1);
    mirrored.find('Text').forEach((textNode) => {
        textNode.scaleX(-1);
    });
[![enter image description here][1]][1]

How to Identify a image is portrait or landscape image in react js?

how to dynamically identify whether an image is in portrait or landscape orientation using React.js. This guide explains the steps to analyze image dimensions and apply conditional styling to ensure your application adapts seamlessly to varying image formats.

I attempted to calculate the image’s width and height using React.js and conditionally applied styles based on the orientation (portrait or landscape). I expected the component to accurately detect the image orientation and dynamically adjust the styling to fit the layout requirements.

How can I “include” js-code from several js-files into main html-file?

I had a lot of javascript(js)-code in my previous html-file.
I have moved part of the code in another js-files – file1, file2 – see code below.
Before moving I didn’t take care about order of functions declarations. It was OK.
After moving the order began to matter.

I have used defer attribute to force the browser to download all the scripts before they start executing.
But when the main code starts to execute the browser reported an error – function in file1/2 are not defined.

The question is: how can I move a part of js-code into another js-file and not worry about the order of inclusion of additional files and the order of functions declarations in the main code?

html...
 
<script>
     the main js-code - previously all js-code, including file1 and file2, was placed here
</script>
 
<script defer src="file1.js"></script>
<script defer src="file2.js"></script>

The login system works on localhost but fails on the online server [closed]

I developed a website with the possibility to register and log in, using the following structure:

|-- includes
|-- public_www
|---|-- src
|---|-- private
  • includes: Contains sensitive files (configuration, etc.).
  • public_www: Contains my web pages (index.php, signin.php, signup.php, etc.).
  • src: Contains resources for my pages.
  • private: Contains processing files (process_signin.php, process_signup.php, etc.).

In the private folder, there is a .htaccess file to enhance security by blocking direct access to the .php files, except from the server itself.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

<FilesMatch ".php$">
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</FilesMatch>

-> Problem encountered:
The form in signin.php (form) uses process_signin.php (logic), which is located in the private folder. After submitting the form, I return to the signin.php page without any processing being done. Here is an excerpt of the code:

<?php

include __DIR__ . '/../../includes/db_connection.php';
include_once __DIR__ . '/../../includes/logger.php';

session_start();

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    // More code .....
   
} else { // I encountered this situation
    $_SESSION['error_message'] = "";
    header("Location: /sign-in.php");
    exit();
}
?>

The following elements are well-defined: folder security and accessibility, page and directory names.

I have already tested these files on my local environment (localhost), and everything works perfectly. However, when I upload the site online, this problem occurs. I even tried moving process_signin.php to public_www (while respecting the directory changes), but the problem persists. Has anyone encountered the same issue, or do you have any suggestions for resolving this?

TypeError: This WritableStream is currently locked to a writer

I’m experimenting with cloudflare’s workers to connect to an SMTP server (port 2525 instead of 25). While trying to use multiple writers by closing one before starting another, I always got the error: TypeError: This WritableStream is currently locked to a writer.. What am I doing wrong? This is my code:

export default {
  async fetch(req){
    const addr = { hostname: "mail.domain.example", port: 2525 };

    try {
      const socket = connect(addr, { secureTransport: "starttls", allowHalfOpen: false });
      const encoder = new TextEncoder();

      let encoded = encoder.encode("EHLO examplern");

      const writer1 = socket.writable.getWriter();
      await writer1.write(encoded);
      await writer1.close();

      const writer2 = socket.writable.getWriter();
      await writer2.write(encoded);
      await writer2.close();

    } catch (error) {
      console.log(error);
    }
  }
}

When running this code, it logs the error message. When I run tcpdump on my server, I can see the first EHLO, but not the second one.

Arrow Function in React JS

I was creating a form using React, and displaying an array of users’ names and Ids. while adding a delete button to allow deleting a user from the list.

my question is when I added the handleDelete function

const handleDelete = (id) => { const newUsers = users.filter((person) => person.id !== id); setUsers(newUsers); };
when I add this function the the button as onClick={handleDelete(user.id)}

it doesn’t work but when I add it as onClick={() => handleDelete(user.id)}
it work, can anyone explain the difference between these two ways?

Html table with images

I have few tables with images in certain column when I tried to convert all my tables as pdf the column with image cells are shown to empty even if I use doc.addImage its position is not correct. How to incorporate images from the table into pdf

I use doc.addImage its position is not correct

D3 network graph

I have created a d3 network graph which is working fine, issue is if there is a connection between (A -> B and B -> A) i want separate links for that. How can i do that?

This is what i have done so far

onMount(() => {
      const svg = d3
        .select(svgContainer)
        .attr('width', width)
        .attr('height', height);
  
      const tooltip = d3.select(tooltipElement);
  
      // Modify nodes to ensure they have vx, vy, x, y properties
      const nodesWithPositions = data.nodes.map((node: CustomNode) => ({
        ...node,
        vx: 0,  // Initialize vx for D3 simulation
        vy: 0,  // Initialize vy for D3 simulation
        x: node.x || 0,  // Ensure x is initialized if missing
        y: node.y || 0,  // Ensure y is initialized if missing
      }));
  
      // Create a force simulation using nodes and links
      const simulation = d3
        .forceSimulation(nodesWithPositions)  // Use the updated nodes
        .force(
          'link',
          d3
            .forceLink(data.links)
            .id((d) => (d as CustomNode).id)  // Use the correct id function
            .distance(200)  // Define the link distance
        )
        .force('charge', d3.forceManyBody().strength(-300))  // Charge force to push nodes apart
        .force('center', d3.forceCenter(width / 2, height / 2));  // Center force
  
      // Add links to the SVG and apply the arrow marker
      const link = svg
        .append('g')
        .selectAll('line')
        .data(data.links) // Use the original links (no duplication)
        .enter()
        .append('line')
        .attr('stroke', '#999')
        .attr('stroke-opacity', 0.6)
        .attr('stroke-width', (d) => Math.sqrt(Number(d.cycleCount)))  // Set link stroke width based on cycle count
  
      // Add cycleCount label to the middle of each link
      const linkText = svg
        .append('g')
        .selectAll('text')
        .data(data.links)
        .enter()
        .append('text')
        .attr('x', (d: any) => (d.source.x + d.target.x) / 2)  // Calculate midpoint of the link
        .attr('y', (d: any) => (d.source.y + d.target.y) / 2)  // Calculate midpoint of the link
        .attr('dy', -10) // Move the text slightly above the midpoint
        .attr('text-anchor', 'middle')
        .attr('font-size', 12)
        .attr('fill', '#333')
        .text((d: any) => d.cycleCount);  // Display the cycle count
  
      // Add nodes to the SVG
      const node = svg
        .append('g')
        .selectAll('circle')
        .data(nodesWithPositions)  // Pass the updated nodes with vx, vy, x, y
        .enter()
        .append('circle')
        .attr('r', 10)  // Set the radius of the nodes
        .attr('fill', '#69b3a2')  // Set the fill color of the nodes
        .attr('stroke', '#333')  // Set the border color of the nodes
        .attr('stroke-width', 1.5)  // Set the border width
        .call(
          d3.drag<SVGCircleElement, CustomNode>()
            .on('start', (event: d3.D3DragEvent<SVGCircleElement, CustomNode, CustomNode>, d: CustomNode) => {
              if (!event.active) simulation.alphaTarget(0.3).restart();
              d.fx = d.x;  // Set the fixed x position
              d.fy = d.y;  // Set the fixed y position
            })
            .on('drag', (event: d3.D3DragEvent<SVGCircleElement, CustomNode, CustomNode>, d: CustomNode) => {
              d.fx = event.x;  // Update fixed x position during drag
              d.fy = event.y;  // Update fixed y position during drag
            })
            .on('end', (event: d3.D3DragEvent<SVGCircleElement, CustomNode, CustomNode>, d: CustomNode) => {
              if (!event.active) simulation.alphaTarget(0);
              d.fx = null;  // Release the fixed x position
              d.fy = null;  // Release the fixed y position
            })
        );
  
      // Add tooltips on node hover
      node
        .on('mouseover', (event, d: CustomNode) => {
          tooltip
            .classed('opacity-100', true)
            .classed('opacity-0', false)
            .style('left', `${event.pageX + 10}px`)
            .style('top', `${event.pageY - 25}px`)
            .html(`Geozone: ${d.name}`);
        })
        .on('mouseout', () => {
          tooltip.classed('opacity-0', true).classed('opacity-100', false);
        });
  
      // Update link and node positions on each tick
      simulation.on('tick', () => {
        link
          .attr('x1', (d: any) => d.source.x)
          .attr('y1', (d: any) => d.source.y)
          .attr('x2', (d: any) => d.target.x)
          .attr('y2', (d: any) => d.target.y);
  
        node.attr('cx', (d: any) => d.x).attr('cy', (d: any) => d.y);
  
        // Update link text position to remain at the midpoint
        linkText
          .attr('x', (d: any) => (d.source.x + d.target.x) / 2)
          .attr('y', (d: any) => (d.source.y + d.target.y) / 2);
      });
    });

I want all nodes and i want separate links if there is a connection from (A -> B) and then again from (B -> A)

Why a JS method in Odoo 16 works only sometimes with similar environments?

I’m working with Odoo 16. I’ve installed the Enterprise Barcode app, and I’ve made a generic development over it.

The Barcode app has a menu which shows pickings in a kanban view. What I’m doing with my development is to automatically fill in a picking field each time an user belonging to a specific group clicks on its kanban card to open it.

Example: the barcode app shows three pickings (PICK001, PICK002, PICK003) in a kanban view. I’m the user Administrator and I click on the kanban card of PICK003 and this way I’m redirected to other view which shows the stock move lines of the PICK003. At the same time, my development sets the picking field preparer_id (a Many2one pointing to res.users) to Administrator.

Now, the code of my development:

/** @odoo-module **/
import { StockBarcodeKanbanController } from '@stock_barcode/kanban/stock_barcode_kanban_controller';
import { patch } from 'web.utils';
import { useService } from "@web/core/utils/hooks";
import { session } from "@web/session";

const originalOpenRecord = StockBarcodeKanbanController.prototype.openRecord;

patch(StockBarcodeKanbanController.prototype, 'StockBarcodeKanbanControllerIchExt', {
    setup() {
        this._super.apply(this, arguments);
        this.rpc = useService("rpc");
    },

    async openRecord(record) {
        // Check if preparer_id is empty
        if (!record.data.preparer_id) {
            // Check if current user is preparer (belong to preparers group)
            const isPreparer = await this.rpc("/web/dataset/call_kw", {
                model: 'res.users',
                method: 'has_group',
                args: ['ich_stock_ext.group_stock_preparer'],
                kwargs: {}
            });
            if(isPreparer) {
                // Call RPC to update preparer_id value with the current user
                await this.rpc('/web/dataset/call_kw/stock.picking/write', {
                    model: 'stock.picking',
                    method: 'write',
                    args: [[record.resId], { 'preparer_id': session.uid }],
                    kwargs: {}
                });
                // Refresh view
                this.model.load({reload: true});
            }
        }
        // Call "super" to execute whatever the original method did
        return originalOpenRecord.apply(this, arguments);
    },

});

This code seems to work perfect. However, sometimes, especially when I log in through the Odoo mobile app, if I click on PICK003, then on PICK002, and afterwards on PICK003 again, the field preparer_id remains empty, instead of showing the user again.

I’ve checked the field during every step. I have another development which empties the field when going back to the kanban view. This other development always works fine, so before clicking on a kanban card, the preparer_id is always empty.

What could be happening? How can I change the code to ensure that the preparer_id is updated in every situation?