Blurring effect also applying on Navbar and the Navbar Menu

In this code, although I applied,

nav.classList.toggle("blur-0");
list.classList.toggle("blur-none");

but the Navbar and the Navbar Menu get blurred.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="./output.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Document</title>
</head>
<body>
    <nav class="flex bg-green-600 w-screen h-[40px] max-md:h-[65px] sticky top-0">
        <div class="max-md:ml-[15px] font-bold w-[5%] h-[75%] p-[2px] m-[7px] flex justify-center items-center">Logo</div>
        <div class="font-bold p-[2px] h-[75%] m-[7px] w-[35%] flex justify-center items-center max-sm:w-[20%] max-md:mx-auto">Title</div>
        <div class="bg-green-600 flex md:space-x-10 max-md:space-y-5 justify-end items-center w-[60%] max-md:w-screen max-md:flex-col max-md:absolute max-md:top-[-170%] duration-500" id="list">
            <div class="font-bold">Services</div>
            <div class="font-bold">About</div>
            <div class="font-bold">Contact Us</div>
        </div>
        <div class="hidden max-md:flex justify-center items-center mr-[2%] w-[6%] h-[75%] p-[6px] m-[7px] cursor-pointer rounded-full hover:bg-green-700 duration-500 max-sm:w-[11%]">
            <i class="fa fa-bars" id="icon"></i>
        </div>
    </nav>
    
    <div class="h-[2000px] flex justify-center items-start bg-black w-screen">Helo</div>
    <div class="w-screen h-[50px] bg-cyan-500 sticky top-0">hwlooo</div>
    <div class="h-[2000px]">Helo</div>
    <script>
        const x = document.getElementById("icon");
        const list = document.getElementById("list");
        const nav = document.querySelector("nav");
        x.onclick = (e)=>{
            e.target.classList.value = (e.target.classList.value == "fa fa-bars") ? "fa fa-close" : "fa fa-bars";
            list.classList.toggle("max-md:top-[99%]");
            nav.classList.toggle("blur-0");
            list.classList.toggle("blur-none");
            document.body.classList.toggle("blur");
        }
    </script>
</body>
</html>

I also tried with some custom CSS, like I added two classes and applied the backdrop filter with 0 and blur(10px) and toggled those classes in body and navbar and navbar menu also, but nothing is working.

How to configure loader for specific file types (xml) in vite

I am using vite 5.1, and have got xml files required in JavaScript like require('file.xml')

But when I am running dev, I am getting the error:

ERROR No loader is configured for ".xml" files

My vite configuration looks like:

export default defineConfig({
  plugins: [react()],
  assetsInclude: ['**/*.xml']
})

I cannot modify the require like require('file.xml?raw') since that line of code comes from a dependency which I don’t own.

Change reused JSON body variable in Pre-request script – Postman

I have a collection of JSON requests for the same API. API is the same as well as the request structure, only few values are changing within the same JSON body which will change the business scenario. What I wanted to achieve is to store a standard request in a variable and change only affected values within a pre-request script.
That has to be dynamic and reusable.

I did configure in the Collection pre-request script the following (I’ll make it simple)
const StandardCreateOnbReq =

const StandardCreateReq = {
  "AddressHouseNumber": "25",
  "ApplicantWebGuid": `${pm.environment.get('APPWEBGUID')}`,
  "Address": "Main Street"
};
pm.environment.set("CreateRequest" , JSON.stringify(StandardCreateReq));

Within the request body, instead of writing the full JSON body I’m just configuring it like this:

{{CreateRequest}}

So far so good, it works and I’m able to send the request correctly.
What I would like to do is, within the pre-request script of the single request (N.B. not in the pre-request script of the collection) to be able to change few values, for instance either the address with a specific value, or an environment variable like EXISTING_APPWEBGUID instead of the one I’m using which is APPWEBGUID.

I’d need to do this for several requests and I don’t want to rewrite the json body everytime and just changing values, I want only within the specific request and as a pre-request action, to be able to change only one or two values.

I tried with JSON.parse but I’m not able to make it work 🙁
Hope you did get my point and you can help me

Module not found: Error: can’t resolve ‘web3’

I am trying to import web3 module to my code but it seems that the code cannot recognize. I have tried using npm install web3, but it made the whole thing down. May I ask is there any solutions for this? I have also tried deleting the node_modules and reinstall using npm install but it still doesn’t work.

Below is my code:

//usePools.js
import Web3 from  'web3';
import { useState, useEffect } from 'react';
import { useConfig } from '@usedapp/core';

import { ROUTER_ADDRESS } from '../config';
import { getFactoryInfo, getRouterInfo } from '../utils';

export const loadPools = async (providerUrl) => {
    const provider = new Web3.providers.HttpProvider(providerUrl);
    const web3 = new Web3(provider);

    const routerInfo =  await getRouterInfo(ROUTER_ADDRESS, web3);
    const factoryInfo = await getFactoryInfo(routerInfo.factory, web3);

    return factoryInfo.pairsInfo;

}


export const usePools = () => {
    const { readOnlyChainId, readOnlyUrls } = useConfig();
    const [loading, setLoading] = useState(true);
    const [pools, setPools] = useState({});


    useEffect(() =>{
        loadPools(readOnlyUrls[readOnlyChainId])
        .then((pools) => {
            setPools(pools)
            setLoading(false)
        })
    }, [readOnlyUrls, readOnlyChainId]);
    

    return [loading, pools];
}
//Package.json
{
  "name": "@my-app/react-app",
  "version": "1.0.0",
  "homepage": "./",
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "dependencies": {
    "@my-app/contracts": "^1.0.0",
    "@apollo/client": "^3.5.10",
    "@ethersproject/contracts": "^5.6.0",
    "@ethersproject/providers": "^5.6.0",
    "@testing-library/dom": "^8.11.3",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "@types/react": "^17.0.40",
    "graphql": "^16.3.0",
    "ipfs-deploy": "^11.2.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.3",
    "@usedapp/core": "^1.1.5",
    "@uniswap/sdk": "^3.0.2",
    "@uniswap/v2-core": "^1.0.1",
    "@uniswap/v2-periphery": "^1.1.0-beta.0",
    "ethers": "^5.7.0",
    "web3": "^4.5.0"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "scripts": {
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "ipfs": "yarn build && ipfs-deploy build/",
    "start": "react-scripts start",
    "test": "react-scripts test"
  }
}

Original Error
Error after installing web3

¿Cómo formatear números en un ChartJS de tipo Donut o Pie? [closed]

quiero trabajar con graficos ChartJs y me gustaria saber como formatear los números a mostrar en el gráfico, ya que no aparecen con formato, por ejemplo asi como se muestra en la imagen, en lugar de que muestre 7000000, mostrará $7,000,000

var donutChartCanvas = $('#donutChart').get(0).getContext('2d')
    var donutData        = {
      labels: [
          'Chrome',
          'IE',
      ],
      datasets: [
        {
          data: [7000000,500000],
          labels: ['70','50'],
          backgroundColor : ['#f56954', '#00a65a'],
        }
      ]
    }
    var donutOptions     = {
      maintainAspectRatio : false,
      responsive : true,

    }
    //Create pie or douhnut chart
    // You can switch between pie and douhnut using the method below.
    new Chart(donutChartCanvas, {
      type: 'doughnut',
      data: donutData,
      options: donutOptions,

    })

gráfico

Will Chrome extension be disabled for current users if I add a new host permission to match the current content script matches?

My understanding of adding new permissions, matches, or host permissions to your chrome extension’s manifest is that it will automatically disable the extension for any current users, until they have had a chance to view and accept the new permissions (and it doesn’t seem to do much to notify them, it just disables the extension).

However, I found this answer which says that if you are simply adding a host permission to include something already covered in your content script matches, that it may not trigger a new warning.

Testing with getPermissionWarningsByManifest seems to confirm that it does not trigger any new installation warnings, but does anyone know if it also does not auto-disable the extension?

For illustration, I would be updating this:

{
    "manifest_version": 3,
    "name": "extension name",
    "description": "extension description.",
    "permissions": ["activeTab", "storage", "tabs", "scripting"],
    "content_scripts": [
      {
        "matches": ["*://www.examplewebsite.com/*"],
        "js": ["content.js"],
      }
    ],
    "background": {
      "service_worker": "background.js"
    },
}

To this:

{
    "manifest_version": 3,
    "name": "extension name",
    "description": "extension description.",
    "permissions": ["activeTab", "storage", "tabs", "scripting"],
    "host_permissions": [
      "*://www.examplewebsite.com/*"
    ],
    "content_scripts": [
      {
        "matches": ["*://www.examplewebsite.com/*"],
        "js": ["content.js"],
      }
    ],
    "background": {
      "service_worker": "background.js"
    },
}

I tried to look this up but could not find a straight answer. Testing it by “load unpacked” in your own browser doesn’t work bc it just auto-accepts all the permissions.

File runs twice when using Webpack Bundle when I move to new HTML page

I have a file of JS code that is running twice when using my webpack bundler. I am bundling two files into one entry point: fetchSymptoms.js and diagnosisSymptoms.js. I have one output: bundle.js. I start off on an html page called index.html, and when I move to a new HTML page, the code in fetchSymptoms.js runs all over again. I know this because I’ve used console.log() statements that print again on the new HTML page.

I am not sure how to stop the code from running twice inside fetchSymptoms.js. I can’t figure out what is triggering it, the only thing I can think of is it’s somehow because I am navigating to two different HTML page but using one bundle.js output? I also import the same function (fetchToken) in fetchSymptoms.js and diagnosisSymptoms.js, and maybe somehow that’s causing it? I also have two functions declared globally in diagnosisSymptoms.js, perhaps that is somehow a trigger?

For some more explanation of how I get from one HTML page to the other: I start from index.html, press a button which triggers getChecked() and moves me to the html page next.html, and onLoad in next.html I call printChecked(). getChecked() and printChecked() are global functions.

Here is the relevant code from fetchSymptoms.js, the console.log() statements are what print twice, once per HTML page:

import { fetchToken } from './getAPIToken.js';
   
 fetchToken()
    .then(token => {
        console.log("before adultmalesymptoms");
        fetchAdultMaleSymptoms(token);
        //fetchAdultMaleSymptoms is an async function that fetches
        //symptoms from an API... it triggers a lot of other async functions, cut for brevity
        console.log("after adultmalesymptoms");
    })
    .catch(error => {
        console.error('Error in fetchSymptoms ', error);
    });

Here is the code from diagnosisSymptoms.js:

const { fetchToken } = require('./getAPIToken');

function getChecked(){ //displays symptoms from checked checkboxes
    console.log("getChecked running");
    //alert("hello!");
    const checkboxes = document.getElementsByName("symptom"); //items contains nodelist with the checked symptoms
    const array=[]; //create empty array
    const idArray= [];

    for (var i = 0; i < checkboxes.length; i++){ //run through the nodelist
        if (checkboxes[i].type == "checkbox" && checkboxes[i].checked == true){
            if (!array.includes(checkboxes[i].value)){ //if the symptom is not already in array, then push
                array.push(checkboxes[i].value); //add checked items to array
                idArray.push(checkboxes[i].id);
            }
        }
    }

    //remove any non-digit characters from idArray
    const numericIds = idArray.map(id => id.replace(/D/g, '')); //regex
    //console.log(numericIds);

    const jsonArray = JSON.stringify(array); //converts to json string
    sessionStorage.setItem("checked", jsonArray); //will disappear when browser window closed, can use localStorage

    const jsonIDArray = JSON.stringify(numericIds); //converts to json string
    sessionStorage.setItem("ids", jsonIDArray);
}
window.getChecked = getChecked;


function printChecked(){
    //console.log("hello there!");
    const string = sessionStorage.getItem("checked"); //get the json string
    const parsedArray = JSON.parse(string); //parse to get a json object
    const valuesArray = Object.values(parsedArray); //convert object values into array
    var stringUnderscores = valuesArray.join(', '); //converts array into string including underscores
    var stringWithSpaces = stringUnderscores.replace(/_/g, ' '); //remove underscores

    const newText = document.createTextNode(stringWithSpaces); //create new text node
    document.getElementById("potentialDiagnosis").append(newText); //append text node to h2

    const idString = sessionStorage.getItem("ids");

    fetchDiag(idString);
}
window.printChecked = printChecked;


function fetchDiag(idString){
  //this is where I'd run the fetchToken function again, cut for brevity
}

And here is my webpack config file:

const path = require('path');
const Dotenv = require('dotenv-webpack');

module.exports = {
  entry: ['./public/js/fetchSymptoms.js', './public/js/diagnosisSymptoms'],
  output: {
    filename: 'bundle.js', //output bundle filename, where result is going to go
    path: path.resolve('public'), //output directory
  },
  mode: 'none',
  module: {
    rules: [
      {
        test: /.js$/, // Match JavaScript files
        exclude: /node_modules/, // Exclude node_modules
        use: {
          loader: 'babel-loader', // Use Babel to transpile JavaScript
          options: {
            presets: ['@babel/preset-env'] // Use the preset for modern JavaScript
          }
        }
      }
    ]
  },
  plugins: [
    new Dotenv(),
  ],
  resolve: {
    extensions: ['.js'],
    alias: {
      'crypto-js': path.resolve(__dirname, 'node_modules/crypto-js'),
    },
  },
};


Calculating duration of colliding events on a timeline with a capacity per hour

I would like to create a timeline of colliding events where the events represent a certain amount of kg to be processed and the timeline has a certain capacity per hour. The events have a static start time but the end time is calculated based on the weight to be processed and the capacity of the timeline.

I have tried to calculate the end time of events based on their weight and the timeline capacity but ran into multiple challenges because if two events are colliding and their end time increases because they have to share resources for the time they are overlapping, it could cause a new collision with a third event and so on.

How to write an algorithm in JavaScript (or a similar language if you prefer) to calculate how long each event takes to finish based on its weight and the timeline capacity? If items collide they should share the capacity per hour for the time they are overlapping. Any direction in how to approach this is really appreciated.

Limit searchable columns

I am using the following code to add multiple search parameters to my results but I do not want to search on all results just certain columns but I can’t figure out how to only display the search box on selected columns. I tried using columndefs but I could not get it to work. Any suggestions?

                .columns()
                .every(function () {
                    var that = this;
 
                    $('input', this.footer()).on('keyup change clear', function () {
                        if (that.search() !== this.value) {
                            that.search(this.value).draw();
                }
                    });
                });
        },
            buttons: [ {
                extend: "edit",
                editor: editor
            }, ]
        } );```

is there anything possible whenever A song is chosen, the lyrics of that song will be shown in the lyrics-container? HTML [closed]

So currently this is for a school project, i was assigned to make a Video Playlist with Lyrics of the MV(music video) – the teach said to have at least 40 MV in the playlist. Now, my question-
Can the lyrics of a selected song be automatically displayed in the lyrics-container when the song is chosen? and what may be the for this? i dont mind if its offline(.txt) or online(url)

this is the code — – –

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap');

* {
    margin: 50;
    padding: 50;
    font-family: 'Poppins', sans-serif;
}

body {
    background-color: rgb(230, 230, 230);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 90vh;
}

h1 {
    font-size: 40px;
    margin: 5px;
}

.main {
    display: flex;
    width: 1250px;
    height: 500px;
    border-radius: 20px;
    padding: 50px;
    box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
}

.video-container {
    width: 650px;
    padding: 10px;
    border-radius: 10px;
    box-shadow: rgba(55, 55, 55, 0.2) 0px 7px 29px 0px;
}

.video-playlist {
    padding: 10px;
}

.video-playlist h2 {
    margin-left: 10px;
}

.video-container iframe {
    width: 630px;
    height: 375px;
    border-radius: 10px;
}

.playlist-selector {
    width: 300px;
    padding: 10px;
    overflow-y: scroll;
    border-radius: 10px;
    box-shadow: rgba(55, 55, 55, 0.2) 0px 7px 29px 0px;
}


.playlist-selector button {
    display: flex;
    align-items: center;
    width: 280px;
    height: 60px;
    border-radius: 10px;
    border: none;
    margin: 3px;
    box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
    cursor: pointer;
}

.lyrics-text{
    width: 260px;
    align-items: top;
    padding: 10px;
    border-radius: 10px;
    display: flex; /* Initially displayed */
    overflow-y: scroll;
    box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
}

.lyrics-container {
    width: 260px;
    align-items: top;
    padding: 10px;
    border-radius: 10px;
    display: flex; /* Initially displayed */
    overflow-y: scroll;
    box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
}


.playlist-selector button:hover {
    background-color: rgb(200, 200, 200);
}

.active {
    background-color: rgb(200, 200, 200);
}

h4 {
    margin: 5px;
    font-size: 16px;
}

.playlist-selector button img {
    width: 70px;
    height: 60px;
    border-radius: 10px 0px  0px 10px;
    margin-right: 10px;
}


h5{ 
    font-size: 16px;
    margin: 5px;
} 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Playlist</title>

    <!-- Style CSS -->
    <link rel="stylesheet" href="./style.css">
</head>
<body>

    <h1>Video Playlist</h1>

    <div class="main">
        

        <div class="video-container">

            <div class="video-playlist-1">
                <iframe src="dos.png" frameborder="0" allowfullscreen></iframe>
                <h2>Made for Grade 11 - Mother Rosario of AaMB</h2>
            </div>
           </div>
   
          
             
               <div class="lyrics-container" id="lyricsContainer">
                <h5>Lyrics</h5>
                       

                
               </div>

                       
                
        


        <div class="playlist-selector"> 

            <h4>Playlist</h4>
                    
            <button class="select-video active" id="selectVideo1" onclick="changeVideo(this,                'two3.mp4', 'Lyrics1.txt', 'Two Step From Hell by Victory');">
                <img src="TWO2.png" alt="">
                <h3>Two Step From Hell</h3>  //THIS IS Repeated for various songs--

</div>
        </div>
    
    </div>

   

        
    </div>

    <!-- Script JS -->
    <script src="./script.js"></script>
</body>
</html>

function changeVideo(button, videoUrl, title) {
    document.querySelectorAll('.select-video').forEach(function(btn) {
        btn.classList.remove('active');
    });

    button.classList.add('active');

    var videoContainer = document.querySelector('.video-container');

    videoContainer.innerHTML = `
        <div class="video-playlist">
            <iframe src="${videoUrl}" frameborder="0" allowfullscreen></iframe>
            <h2>${title}</h2>
        </div>
    `;

   
}

i tried asking for help on discord groups and came back empty-handed

Javascript: Change images in a webpge

I have a web page that I want to be able to have one location for an image and then on click a bit of text it changes to another image.

I have tried this code, but I cannot get this to work:

function ChangeImage(fileName) {
  let img = document.querySelector('#bannerImage');
  img.setAttribute('src', fileName);

}
<img id="bannerImage" src="https://via.placeholder.com/600x100" width="600" />
<br />
<br />
<button onClick="changeimage('image1.jpg')">Image 1</button>
<button onClick="changeimage('image2.jpg')">Image 2</button>
<button onClick="changeimage('image3.jpg')">Image 3</button>

Also instead of buttons I’d prefer some text for example:

|
<a href="#" onClick="changeimage('image1.jpg')">Image One</a> | 
<a href="#" onClick="changeimage('image2.jpg')">Image One</a> |
<a href="#" onClick="changeimage('image3.jpg')">Image One</a> |

Thanks for any help you can give me

Can’t install node-sass, I always get this error

I started programming recently, and I was studying by myself now. Trying to do some projects to learn better.

I was trying to install node-sass, but I always get this error, I’ve already tried to uninstall node.js, and didn’t solved. Anyone can help?
I’m using npm install node-sass

npm ERR! code 1
npm ERR! path C:UserspedroOneDriveImagensDocumentosreponetflix-practicenode_modulesnode-sass
npm ERR! command failed
npm ERR! command C:WINDOWSsystem32cmd.exe /d /s /c node scripts/build.js
npm ERR! Building: C:Program Filesnodejsnode.exe C:UserspedroOneDriveImagensDocumentosreponetflix-practicenode_modulesnode-gypbinnode-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp verb cli [
npm ERR! gyp verb cli   'C:\Program Files\nodejs\node.exe',
npm ERR! gyp verb cli   'C:\Users\pedro\OneDrive\Imagens\Documentos\repo\netflix-practice\node_modules\node-gyp\bin\node-gyp.js',
npm ERR! gyp verb cli   'rebuild',
npm ERR! gyp verb cli   '--verbose',
npm ERR! gyp verb cli   '--libsass_ext=',
npm ERR! gyp verb cli   '--libsass_cflags=',
npm ERR! gyp verb cli   '--libsass_ldflags=',
npm ERR! gyp verb cli   '--libsass_library='
npm ERR! gyp verb cli ]
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | win32 | x64
npm ERR! gyp verb command rebuild []
npm ERR! gyp verb command clean []
npm ERR! gyp verb clean removing "build" directory
npm ERR! gyp verb command configure []
npm ERR! gyp verb download using dist-url https://npm.taobao.org/dist
npm ERR! gyp verb find Python Python is not set from command line or npm configuration
npm ERR! gyp verb find Python Python is not set from environment variable PYTHON
npm ERR! gyp verb find Python checking if "python3" can be used
npm ERR! gyp verb find Python - executing "python3" to get executable path
npm ERR! gyp verb find Python - executable path is "C:UserspedroAppDataLocalMicrosoftWindowsAppsPythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0python.exe"
npm ERR! gyp verb find Python - executing "C:UserspedroAppDataLocalMicrosoftWindowsAppsPythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0python.exe" to get version
npm ERR! gyp verb find Python - version is "3.12.2"
npm ERR! gyp info find Python using Python version 3.12.2 found at "C:UserspedroAppDataLocalMicrosoftWindowsAppsPythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0python.exe"
npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 20.11.1
npm ERR! gyp verb command install [ '20.11.1' ]
npm ERR! gyp verb download using dist-url https://npm.taobao.org/dist
npm ERR! gyp verb install input version string "20.11.1"
npm ERR! gyp verb install installing version: 20.11.1
npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed
npm ERR! gyp verb install version not already installed, continuing with install 20.11.1
npm ERR! gyp verb ensuring nodedir is created C:UserspedroAppDataLocalnode-gypCache20.11.1
npm ERR! gyp verb created nodedir C:UserspedroAppDataLocalnode-gypCache20.11.1
npm ERR! gyp http GET https://npm.taobao.org/dist/v20.11.1/node-v20.11.1-headers.tar.gz
npm ERR! gyp WARN install got an error, rolling back install
npm ERR! gyp verb command remove [ '20.11.1' ]
npm ERR! gyp verb remove using node-gyp dir: C:UserspedroAppDataLocalnode-gypCache
npm ERR! gyp verb remove removing target version: 20.11.1
npm ERR! gyp verb remove removing development files for version: 20.11.1
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: ENOENT: no such file or directory, open 'C:mycacert.pem'
npm ERR! gyp ERR! System Windows_NT 10.0.19045
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\pedro\OneDrive\Imagens\Documentos\repo\netflix-practice\node_modules\node-gyp\bin\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd C:UserspedroOneDriveImagensDocumentosreponetflix-practicenode_modulesnode-sass
npm ERR! gyp ERR! node -v v20.11.1
npm ERR! gyp ERR! node-gyp -v v8.4.1
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

Cropperjs – Cannot read properties of null error when is not null?

I’m trying to implement cropping images in my webapp. What I am trying to achieve is crop an image to have a 3/4 ratio, and crop that cropped image to have an avatar (ratio 1). Basically I am cropping twice the same image.
When I upload an image for the first time it works fine.
When I upload a second time (swapping the image for another one), I have the following error:

Uncaught TypeError: Cannot read properties of null (reading 'toDataURL')

Which is weird because is not null (is a base64 image). And not just that, I am also creating the file of the image as well. I know this because I am printing the values.
What am I doing wrong?

This is my code:

  let croppedImage
  let croppedImageUrl
  let croppedAvatar

  $( "#profile_picture_upload" ).change( function() {
    const input = document.getElementById( "profile_picture_upload" )
    const imageFile = input.files[ 0 ]
    const image = $( ".crop-image" )
    let cropper

    if( imageFile ) {
      const reader = new FileReader()
      reader.onload = function( e ) {
        if( cropper ) cropper.destroy()
        const imageDataUrl = e.target.result
        $( ".crop-image" ).attr( "src", imageDataUrl )
        $( "#cropModalLabel" ).text( "Profile photo" )
        $( "#cropModal" ).modal( "show" )
        // Initialize the cropper after the modal shown completely.
        // Otherwise, we will not get a correct cropper.
        $( "#cropModal" ).on( "shown.bs.modal", function() {
          // eslint-disable-next-line no-undef
          cropper = new Cropper( image[ 0 ], {
            aspectRatio: 3 / 4,
            viewMode: 1,
            autoCropArea: 1,
            ready: function() {
              $( ".crop-button-image" ).on( "click", function() {
                croppedImage = cropper.getCroppedCanvas( {
                  width: 375,
                  height: 500
                } ).toDataURL( "image/jpeg" )
                console.log( "1. image (dataurl)", croppedImage )
                croppedImageUrl = croppedImage
                croppedImage = dataURLtoFile( croppedImage, "croppedImage.png" )
                console.log( "2. image (file)", croppedImage )
                // Now crop the cropped image to have an avatar
                $( ".crop-image" ).attr( "src", croppedImageUrl )
                cropper.replace( croppedImageUrl )
                cropper.setAspectRatio( 1 )
                $( ".crop-button-avatar" ).on( "click", function() {
                  croppedAvatar = cropper.getCroppedCanvas( {
                    width: 200,
                    height: 200
                  } ).toDataURL( "image/jpeg" )
                  console.log( "1. avatar (dataurl)", croppedAvatar )
                  croppedAvatar = dataURLtoFile( croppedAvatar, "croppedAvatar.png" )
                  console.log( "2. avatar (file)", croppedAvatar )
                  cropper.destroy()
                  $( "#cropModal" ).modal( "hide" )
                } )
              } )
            }
          } )
        } )
      }
      reader.readAsDataURL( imageFile )
    }
  } )

How to convert this text contrast function to version for hsl values

I needed a function that takes a color as input which is a background color for text. Based on that given color, the function should return the color white or black that can be used as the text color for the best contrast.

I once copied the function below from the internet and it works great for a hex color string as input.
Now the requirements have changed, and I want to convert this function for an input value in hsl. The input should not be a string of a color format anymore, but just the hsl values, like: getContrastTextColor(h, s, l).

It seems to be simple but I don’t know how to do this. The problem is not Javascript, but the logic.

function getContrastTextColor(hex)
{
    /*
    From this W3C document: http://www.webmasterworld.com/r.cgi?f=88&d=9769&url=http://www.w3.org/TR/AERT#color-contrast

    Color brightness is determined by the following formula: 
    ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
    */

    const threshold = 130; /* about half of 256. Lower threshold equals more dark text on dark background  */

    const hRed = hexToR(hex);
    const hGreen = hexToG(hex);
    const hBlue = hexToB(hex);


    function hexToR(h) { return parseInt((cutHex(h)).substring(0, 2), 16) }
    function hexToG(h) { return parseInt((cutHex(h)).substring(2, 4), 16) }
    function hexToB(h) { return parseInt((cutHex(h)).substring(4, 6), 16) }
    function cutHex(h) { return (h.charAt(0) == "#") ? h.substring(1, 7) : h }

    const cBrightness = ((hRed * 299) + (hGreen * 587) + (hBlue * 114)) / 1000;
    if (cBrightness > threshold) { return "#000000"; } else { return "#ffffff"; }
}