Background-clip text mouse tracking animation

I would like to track user’s mouse and display a gradient text using background-clip: text;

The text should always be visible with a color of black. Only when hovering the text, the gradient should show up (inside of text) and move together with mouse movement.

Is something like this possible?

I found this tutorial where they’re animating the background. However when I am trying to add background-clip: text; it doesn’t work anymore.

Here is what I got:

const button = document.querySelector(".shiny");

button.addEventListener("mousemove", (e) => {
  const { x, y } = button.getBoundingClientRect();
  button.style.setProperty("--x", e.clientX - x);
  button.style.setProperty("--y", e.clientY - y);
});
.shiny {
  position: relative;
  display: block;
  color: black;
  padding: 10px 15px;
  background: #3984ff;
  border-radius: 10px;
  font-weight: bold;
  font-size: 33px;
  overflow: hidden;
}

.shiny::after {
  content: "";
  position: absolute;
  top: calc(var(--y, 0) * 1px - 50px);
  left: calc(var(--x, 0) * 1px - 50px);
  width: 100px;
  height: 100px;
  opacity: 0;
  transition: opacity 0.4s;
}

.shiny:hover::after {
  opacity: 0.9;
  background: radial-gradient(black, red 80%);
 
  *-webkit-background-clip: text;
    *background-clip: text;
    *-webkit-text-fill-color: transparent;
}
<a class="shiny" href="">BIG AND BOLD TEXT</a>

issues filtering react JSX State array

I have a state array using useState that keeps track of some components, I add components to the array with a click of a button i.e

const [answerLines, setAnswerLines] = useState<any[]>([])

adding to the array

const addAnswerLine=()=>       {   setAnswerLines([...answerLines,<NewTestAnswerLine key={answerLines.length} lineIndex={answerLines.length} isCorrect={answerLines.length===correctAnswer} setCorrectAnswer={setCorrectAnswer} deleteLine={()=>deleteAnswerLine(answerLines.length)} />])       }

when it comes deleting the lines by filtering out the array of the clicked line Id, it doesn’t work as expected, for instance if I click the 0 index item the array filters to null.

This is my delete function that I pass down through props:

const deleteAnswerLine = (index: number) => {
    setAnswerLines( answerLines.filter(item=>item.props.lineIndex!==index))
      }

How to read a .docx file with “js docx” library generated with it?

I want to read a file with the “docx” library.

I have already generated the docx document, but what I want to do is fetch the document again to validate it since I have added a “fingerprint” to it to validate if they have edited the originally generated document, kind of like what banks do.

I have seen examples like the following.

const buffer = fs.readFileSync('./uploads/ta.docx');
const doc = new Document(buffer);

But this is throwing me the following error:
TypeError: e.sections is not iterable

I have also tried the following code:

const buffer = fs.readFileSync('./uploads/ta.docx');
const doc = new Document();
doc.load(buffer);

And it gives me the same error again: TypeError: e.sections is not iterable

Is there another way to do the document validation or am I going astray?
I appreciate your time and thanks in advance.

res.sendFile() is not rendering in browser

I’ve been struggling with this for a few days. Anyone have any ideas? On click of a log in button I’m authorizing the user, generating a token, storing the token in cookies, then using the token in headers of a request to render to the homepage. I get no errors on the res.sendFile() and I’ve done some ordering with console.log() to make sure the order of events is proper. I can’t figure out what’s going wrong. Additionally, I know the res.sendFile works because in postman if I call the api route to take me to the homepage with the bearer token, the HTML is returned in the postman response. Below is the code – any help is appreciated!

index.js –>

document.getElementById('loginSubmit').addEventListener('click' , () => {
  var un = document.getElementById('username').value;
  var data = JSON.stringify({
    "username": un,
    "password": document.getElementById('password').value
  });
  document.cookie = 'user_name='+un;
  var req = new XMLHttpRequest();
  req.responseType = 'json'
  req.withCredentials = true;

  req.open("POST","~/users/authenticate", true);
  req.setRequestHeader("Content-Type", "application/json");
  req.send(data);
  
  req.addEventListener("readystatechange", function() {
    if(this.readyState === 4 && req.status == 200) {
          
    //save token to cookies
    var obj = req.response.token;
    document.cookie = 'user_token='+obj;
    console.log(document.cookie)

    //redirect home
    var req2 = new XMLHttpRequest();
    req2.open("GET","http://localhost:4000/homepage",true);
    req2.setRequestHeader("Authorization",'Bearer '+obj);
    req2.send(); 
    }
});

server.js –>

app.use('/users', require('./users/users.controller'));
app.use('/homepage', authorize(), (req,res) => {
    res.sendFile('/homepage.html', {root: publicDir}),function(err) { if (err) console.log(err);}
});

In postman, if I get ‘/homepage’ with the bearer token stored in the cookie and passed in the request header, I get the homepage.html as the response. But in browser, I get no error but also don’t get the ‘/hompage.html’ page. Everything else works as expected, user is authenticated, token generated, stored in cookie, etc. Verified the call is actually going through via console.log() and the request is correct.

Continuously running into errors with javascript chrome extension, made changes to manifest etc but errors persist

I wrote some code that uses face-api.js to detect and differentiate between male and female faces and then blur out female bodies, meant to be an experimental extension I’m working on that’ll eventually be used for censoring potentially unwanted media.

The code seems to be fine and loads well onto chrome, only repeatedly runs into errors and I don’t know why. I’ve made a contentScript.js file, a manifest.json file, a background.js file, popup.html, popup.css and popup.js file, some icons and a root directory, and gone through all of them repeatedly looking for what is wrong but can’t seem to find a solution. Any ideas?

contentScript.js:

// Load the face detection and gender classification models
Promise.all([
  faceapi.nets.ssdMobilenetv1.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api@latest/weights'),
  faceapi.nets.genderRecognitionNet.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api@latest/weights')
]).then(startVideo)

// Define the canvas element for drawing the boxes
const canvas = document.createElement('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
canvas.style.position = 'fixed'
canvas.style.top = '0'
canvas.style.left = '0'
canvas.style.pointerEvents = 'none'
document.body.appendChild(canvas)
const ctx = canvas.getContext('2d')

// Get the video element
const video = document.querySelector('video')

// Start the video playback and detection loop
async function startVideo() {
  // Play the video
  await video.play()

  // Define the face detection and gender classification options
  const options = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.5 })

  // Define the loop function
  async function detectFacesAndGender() {
    // Detect all faces in the video frame and classify their gender
    const detections = await faceapi.detectAllFaces(video, options).withFaceLandmarks().withGender()

    // Loop through each face and determine its gender
    detections.forEach(async detection => {
      const gender = detection.gender // "male", "female", or "genderless"

      // Determine whether to draw a box around the face or blur the body
      if (gender === "female") {
        // Place a red box around the face
        const box = detection.detection.box
        ctx.beginPath()
        ctx.lineWidth = '6'
        ctx.strokeStyle = 'red'
        ctx.rect(box.x, box.y, box.width, box.height)
        ctx.stroke()

        // Blur female bodies
        const image = await faceapi.bufferToImage(detection.detection._imageData)
        const canvas2 = faceapi.createCanvasFromMedia(image)
        const displaySize = { width: image.width, height: image.height }
        faceapi.matchDimensions(canvas2, displaySize)
        const resizedDetection = faceapi.resizeResults(detection, displaySize)
        const bodyPart = resizedDetection.detection.imageDims !== displaySize ? faceapi.CANVAS : undefined
        const blurAmount = 10
        faceapi.drawDetection(canvas2, resizedDetection, { color: 'rgba(255, 0, 0, 1)' })
        await faceapi.blurFaces(canvas2, [resizedDetection], blurAmount, bodyPart)
        const blurredImage = new Image()
        blurredImage.src = canvas2.toDataURL()
        const parentElement = detection.forSize(canvas.width, canvas.height).parentElement
        let femaleBody = parentElement.querySelector('.female-body')
        if (!femaleBody) {
          const img = document.createElement('img')
          img.classList.add('female-body')
          img.style.position = 'absolute'
          img.style.top = '0'
          img.style.left = '0'
          img.style.width = '100%'
          img.style.height = '100%'
          img.style.objectFit = 'contain'
          parentElement.appendChild(img)
          femaleBody = img
        }
        femaleBody.src = blurredImage.src
      } else if (gender === "male" || gender === "genderless") {
        // Unblur male and genderless bodies
        const parentElement = detection.forSize(canvas.width, canvas.height).parentElement
        const maleOrGenderlessBody
      } else if (gender === "male" || gender === "genderless") {
        // Unblur male and genderless bodies
        const parentElement = detection.forSize(canvas.width, canvas.height).parentElement
        const maleOrGenderlessBody = parentElement.querySelector(".body-male, .body-genderless")
        if (maleOrGenderlessBody) {
          maleOrGenderlessBody.style.filter = "none"
        }
      }

      // Add the modified canvas back to the DOM
      parentElement.appendChild(canvas)
    }
  }

  // Load the models and start the detection process
  Promise.all([
    faceapi.nets.tinyFaceDetector.loadFromUri(modelURI),
    faceapi.nets.faceLandmark68Net.loadFromUri(modelURI),
    faceapi.nets.faceRecognitionNet.loadFromUri(modelURI),
    faceapi.nets.faceExpressionNet.loadFromUri(modelURI),
    faceapi.nets.ageGenderNet.loadFromUri(modelURI),
    faceapi.nets.ssdMobilenetv1.loadFromUri(modelURI)
  ]).then(startDetection)

  // Display a message if an error occurs during detection
  const errorElement = document.getElementById("error-message")
  const displayError = (errorMessage) => {
    errorElement.innerHTML = errorMessage
    errorElement.style.display = "block"
  }
  window.onerror = (message, source, lineno, colno, error) => {
    displayError(`An error occurred: ${message}`)
    return true
  }
  Promise.all([
    faceapi.nets.tinyFaceDetector.loadFromUri(modelURI),
    faceapi.nets.faceLandmark68Net.loadFromUri(modelURI),
    faceapi.nets.faceRecognitionNet.loadFromUri(modelURI),
    faceapi.nets.faceExpressionNet.loadFromUri(modelURI),
    faceapi.nets.ageGenderNet.loadFromUri(modelURI),
    faceapi.nets.ssdMobilenetv1.loadFromUri(modelURI)
  ]).catch((error) => displayError(`There was an error loading the models: ${error}`))
}

manifest.json:

{
  "manifest_version": 3,
  "name": "Image/Video Blur",
  "version": "1.0",
  "description": "An extension to blur images and videos",
  "icons": {
    "16": "icon16.png",
    "32": "icon32.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "permissions": ["activeTab", "scripting", "tabs"],
  "host_permissions": ["*://*/*"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icon16.png",
      "32": "icon32.png",
      "48": "icon48.png",
      "128": "icon128.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["contentScript.js"]
    }
  ]
}

background.js:

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    files: ['contentScript.js']
  });
});

popup.html:

<!DOCTYPE html>
<html>
  <head>
    <title>My Extension</title>
    <link rel="stylesheet" href="popup.css">
  </head>
  <body>
    <h1>Welcome to my extension!</h1>
    <p>Click the button below to blur the current page.</p>
    <button id="blur-button">Blur Page</button>
    <script src="popup.js"></script>
  </body>
</html>

popup.css:

body {
  font-family: Arial, sans-serif;
  font-size: 16px;
  margin: 0;
  padding: 0;
}

h1 {
  font-size: 24px;
  margin-bottom: 10px;
}

p {
  margin-top: 0;
  margin-bottom: 20px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #3e8e41;
}

popup.js:

document.addEventListener('DOMContentLoaded', function() {
  var blurButton = document.getElementById('blur-button');
  blurButton.addEventListener('click', function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.runtime.sendMessage({action: 'blur'});
    });
  });
});

I keep getting errors on Chrome like:

“Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
Context
popup.html
Stack Trace
popup.html:0 (anonymous function)”

“Uncaught SyntaxError: Unexpected end of input
Context
example.org
Stack Trace
contentScript.js:87 (anonymous function)”

Errors like this repeatedly even after I make amends. Something is wrong I’m not able to tell and my little friend can’t tell either. Let me know if you’ve noticed what’s wrong.

How do I change date range on candlestick chart in javascript

So far I have a candlestick graph but the user cannot customise the date range to do this I would need to change the api url this is the documentation for my api.

I want it to be done through buttons to have the option of 1 day, 5 days, 1 month, 6 months, 1 year, 5 years, and all time. But I don’t know how to make pressing the buttons update the api url to display the new graph. Is there a way to do this?

this is the code:

`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Candlestick Chart Example</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv"></div>

<script>
    var symbol = 'AAPL';
    var interval = '1day';
    var apikey = 'apikeyiset';

    var url = 'https://api.twelvedata.com/time_series?symbol=' + symbol + '&interval=' + interval + '&apikey=' + apikey;

    Plotly.d3.json(url, function(data) {
    var trace = {
        x: data.values.map(function(d) { return d.datetime; }),
        open: data.values.map(function(d) { return d.open; }),
        high: data.values.map(function(d) { return d.high; }),
        low: data.values.map(function(d) { return d.low; }),
        close: data.values.map(function(d) { return d.close; }),
        type: 'candlestick',
    };

    var layout = {
        title: symbol + ' Candlestick Chart',
    };

    Plotly.newPlot('myDiv', [trace], layout);
    });
</script>
</body>
</html>`

I know how to add buttons in html but not sure how to make them change the api url.

openweather API, problem with reading “lat” and “lon” using geocoding in node.js

I was trying to write a program with node.js , using openweather API. in which user would enter the name of the city, then using provided Geocoding API extracting the latitude and longitude coordinates, and then implementing those coordinates to get weather data from current weather API. but somehow I get an error telling me “lat” and “lot” properties can not be read.

here is what I wrote in node:

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({extended: true}));

var apiKey = "-hidden-";

app.get("/", function(req, res){
    res.sendFile(__dirname+"/index.html")
})

app.post("/", function(req, res){
    var cityName = req.body.cName;
    var geoCodingApi = "http://api.openweathermap.org/geo/1.0/direct?q="+cityName+"&appid="+apiKey;
    var latitude = geoCodingApi.body.lat;
    var longitude = geoCodingApi.body.lon;
    var openWeather = "https://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&appid="+apiKey;
    res.send(openWeather)
})

app.listen(3000, function(){
    console.log("Server is running on port 3000")
})

and this is my HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Open Weather API</title>
  </head>
  <body>
    <form action="/" method="post">
      <label for="">Enter City Name</label>
      <input type="text" name="cName" />
      <button type="submit">Submit</button>
    </form>
  </body>
</html>

and here is the result:

TypeError: Cannot read properties of undefined (reading 'lat')

Can’t figure out what the problem is.

How to check balance parentheses?

True or False depending on nested or not.
For example {} return true.
{[(])} should return false.

var stdin = process.openStdin();
sstdin.addListener("data", function (d) {
  var opening = ["{", "[", "("];
  var closing = ["}", "]", ")"];
  d = d.toString.trim();
  var arr = d.split("");
  var open_arr = [];
  for (var s of arr) {
    var oid = opening.indexOf(arr);
    if (oid > -1) open_arr.push(oid);
    var cid = closing.indexOf(s);
    if (cid > 1) {
      var last_open_val = open_arr.pop();
      if (last_open_val != cid) {
        console.log("False");
        return;
      }
    }
  }

  console.log("True");
  return;
});

But I didn’t get intended output
{[]()} which return false. Where I mistaken?

css does not work on div elements imported from xml using javascript

Using typescript, I try to insert some elements starting from an xml structure. The real xml is big and comes from backend but, to over-simplify, I try something like:

let xmlSource = '<divr><div>recA</div><div>recB</div></divr>';
let xml2 = $.parseXML(xmlSource);
$(`#${this.someTextBoxId}`).append([].slice.call(xml2.getElementsByTagName('divr')[0].childNodes));

As a result I have in the page only standard, recognizable ‘div’ elements. The thing is that I can not use css on those divs?! They are inserted one after another having, as I suspect

display: inline

but I need them to appear one under another, so I need ‘display: block’. As a matter fact, it seems no css works on them. Not only I can not do it programmatically, it also doesn’t work from console or from Chrome Developer Tools either. In the Developer Tools, for those, I even don’t see usual sections:

element.style{
}

div {                  user agent stylesheet
}

I highlight that this happens only for those div’s. For other elements, the css works just fine. As an experiment, if I try

$(`#${this.someTextBoxId}`).append(xmlSource);

it works, the css is available.

So I need a way to make css work in that situation or another method to import/insert xml. Maybe, first to convert it to string?!

How can I programatically replace the text node within a NodeList? [duplicate]

I have the following HTML structure:

<div id="container">
  <b>Hello</b>
  World
</div>

and I’d like to replace World with Earth like this:

<div id="container">
  <b>Hello</b>
  Earth
</div>

I don’t want to modify the <b>Hello</b> element at all.

I can grab the container like this:

var el = document.querySelector("#container")

which has three element in childNodes, the last of which is a textNode:

childNodes

Is there a way to replace the text in the last element without modifying the entire innerHTML or innerText?

var el = document.querySelector("#container")

console.log(el.childNodes)
<div id="container">
  <b>Hello</b>
  World
</div>

Recover the original HTML or DOM before modification from Javascript

A legacy website uses Javascript to remove certain elements when not compatible with the current browser. Something like:

if (!navigator.javaEnabled())
  document.getElementById('greenscreen').innerHTML = '<p>Not Supported on this browser';

Is there a simple way to either recover the original HTML / DOM (at least of the deleted elements), or to ensure our script runs before this script, or to otherwise find out what was in #greenscreen? We can’t modify the existing Javascript, but need to somehow add new Javascript to parse the #greenscreen HTML and get the info.

Race condition with React hook

I’m putting the finishing touches on my first React application. But one annoying problem: I need to cache thumbnails for the items I am displaying. So I’m using a useEffect which can be simply stated like this:

  var thumbnailLookUp = {};

  useEffect(() => {
    fetch("http://localhost:3003/thumbnailPreload")
      .then((response) => response.json())
      .then((data) => {
        for (var row of data) {
          thumbnailLookUp[row.uuid] = row.thumb;
        }
      })
      .then(countClips())
      .catch((err) => {
        console.log(err.message);
      })
  }, []);

The countClips function assembles the data list which will be rendered by a map() in the primary render. This includes the following, where CardMedia is a @mui custom component:

              <CardMedia
                component="img"
                height="100"
                src={`https://d3pe68qfxlhu0a.cloudfront.net/${
                  thumbnailLookUp[event.uuid]
                }`}
              />

Well here’s the thing. When I do a full reload of the page, half the time this works, and the other half the time I get undefined for the results of every thumbnailLookUp[event.uuid]. It’s consistent: if one fails, they all fail, if one succeeds, they all succeed. This tells me there’s some kind of a race condition between the effect and the render, which is not something I’ve ever read about. I can guarantee success by placing a breakpoint!

How can I tighten this up so that thumbnailLookUp is always populated before the render (or a second render, if that’s really necessary)?