Monaco Editor PHP syntax is monotonous

I am creating a WordPress plugin to debug PHP. I was using Ace editor but, after some comments I decided to migrate to Monaco editor.

But it seems so monotonous that with large amount of code would be difficult to work, I guess:

In Visual Studio Code, the syntax is highlighted and detects whenever its SQL:

This is where I load the editor in the script:

    document.addEventListener("DOMContentLoaded", () => {
        const element = document.querySelector("#editor")
        const theme = getCookie("wp-phpp-theme") || "vs-dark"

        const requireConfig = {
            paths: {
                "vs": "https://unpkg.com/[email protected]/min/vs"
            }
        };

        window.MonacoEnvironment = {
            getWorkerUrl: () => proxy
        };

        let proxy = URL.createObjectURL(new Blob([`
    self.MonacoEnvironment = {
        baseUrl: 'https://unpkg.com/[email protected]/min/'
    };
    importScripts('https://unpkg.com/[email protected]/min/vs/base/worker/workerMain.js');
`], {
            type: 'text/javascript'
        }));

        window.require.config(requireConfig);

        window.require(["vs/editor/editor.main"], () => {

            const editor = monaco.editor.create(element, {
                value: "",
                language: "php",
                theme,
                automaticLayout: true
            });

            editor.getModel().onDidChangeContent(() => {
                document.querySelector("#code").value = editor.getValue()
            })

            // ... more irrelevant code

I haven’t found any other examples with PHP code so I wasn’t able to compare whether this is correct or something is missing for the syntax highlight. What are your thoughts?

Give all elements different background-colors with Javascript

I have a table with a variable amound of span-Elements (Bootstrap badges). Some of them have the same ID and some a different ID. I want each unique span-Element to have a unique color. Those colors should be dark enough to be a good background for white text and they should be as different (colofrul) to other elements as possible.

This is where I’m at:
enter image description here

This is how I apply different background-colors to them with JavaScript:

// Find all span-elements with .aktiviert in #region-main
const aktiviertSpans = document.querySelectorAll("#region-main .aktiviert");
const idColors = new Map();
let hue = 0;

// loop through all span-elements
for (let i = 0; i < aktiviertSpans.length; i++) {
    const span = aktiviertSpans[i];
    const id = span.id;

    // If ID exists, give her the existing color
    if (idColors.has(id)) {
        span.style.backgroundColor = idColors.get(id);
    } else {
        // else create a new color
        const color = `hsl(${hue}, 100%, 25%)`;
        idColors.set(id, color);
        span.style.backgroundColor = color;
        hue = (hue + (360 / idColors.size)) % 360;
    }
}

Now I have two issues/question:

  1. Is this a good approach or is there a better way? Would it be possible to include bright colors and black text as soon as too many entries exist?
  2. For some reason the first two entries get the same background-color (see “Max” and “Susanne”). How can I fix this?

Autofill dropdown form with a chrome extension using javascript [duplicate]

I Have a small button in HTML as a chrome extension that calls a javascript script to autofill a dropdown form . but I don’t really know what am I doing wrong .
nothing happens when I click on the button created .

manifest file:

{
  "manifest_version": 2,
  "name": "Dropdown Filler",
  "version": "1.0",
  "description": "A simple Chrome extension to fill out dropdown forms",
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "browser_action": {
    "default_icon": "icon16.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "contextMenus",
    "storage"
  ]
}

html button

<!DOCTYPE html>
<html>
<head>
  <title>Dropdown Filler</title>
  <script src="popup.js"></script>
</head>
<body>
  <button id="fillDropdown">Fill Dropdown</button>
</body>
</html>

this is the javascript script called Popup.js

const  selectElement = document.getElementById("incident.incident_state");
const options = selectElement.options;
for (let i = 0; i < options.length; i++) {
  if  (options[i].textContent === 6) {
     selectElement.value  = options[i].value;
     console.log("works");
break;
}
}

and this is the web element , the dropdown that I want to modify

<select aria-required="false" aria-labelledby="label.incident.incident_state" ng-non-bindable="true" name="incident.incident_state" id="incident.incident_state" onchange="onChange('incident.incident_state', arguments.length === 2 ? arguments[1] : false);" style="; " class="form-control  " choice="3"><option value="2" selected="SELECTED">In Progress</option><option value="4">On-Hold</option><option value="-1">Pending Assignment</option><option value="6">Resolved</option></select>

Video.js and .ts video files in Chrome

I have a .ts video file and player in Safari works great with it, but in Chrome, Firefox it doesn’t. Then I install mpegts.js videojs-mpegtsjs, but got an error with following code:

<template>
  <div :style="'background:#fff; min-width: 640px; aspect-ratio:1920/1070;'">
     <video
        id="video-js-node"
        class="vjs-matrix video-js"
        controls
        width="640"
        preload="auto"
        data-setup='{ "aspectRatio":"1920:1080", "playbackRates": [1, 1.5, 2] }'
     >
        <source :src="'path/to/video.ts'" type='video/mp2t' />
     </video>
   </div>
</template>
<script>
import { defineComponent, ref } from 'vue';
import videojs from 'video.js'
import 'videojs-mpegtsjs'

videojs('video-js-node', {
  mpegtsjs: {
    mediaDataSource: {
      isLive: true,
      cors: false,
      withCredentials: false,
    },
  },
  controls: 'control',
  preload: 'auto',
  height: '505',
});

export default defineComponent({
    name: 'ArchivePlayer',
    setup(){
        return {
           
        }
    },
});
</script>

Maybe you know what’s the problem? Also I don’t quite understand why styles cannot connect to player

D3 JS not display properly

I’m doing this program for my assignment. Here is my code

function init() {
    const margin = { top: 20, right: 20, bottom: 30, left: 50 };
    const width = 600 - margin.left - margin.right;
    const height = 400 - margin.top - margin.bottom;

    // Parse the date/time
    const parseDate = d3.timeParse("%Y");

    // Set the ranges
    const x = d3.scaleTime().range([0, width]);
    const y = d3.scaleLinear().range([height, 0]);

    // Define the line
    const valueline = d3.line()
      .x(d => x(d.Date))
      .y(d => y(d['High income']));

    // Create the SVG element
    const svg = d3.select("#lineChart")
      .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")");

    // Get the data
    d3.csv("../data/CPI.csv").then(data => {

      // Format the data
      data.forEach(d => {
        d.Date = parseDate(d.Date);
        d['High income'] = +d['High income'];
      });

      // Scale the range of the data
      x.domain(d3.extent(data, d => d.Date));
      y.domain([0, d3.max(data, d => d['High income'])]);

      // Add the valueline path.
      svg.append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", valueline);

      // Add the X Axis
      svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

      // Add the Y Axis
      svg.append("g")
        .call(d3.axisLeft(y));

    }).catch(error => console.log(error));
}

window.onload = init;

And here is the output
Output image

The output is not what I’m looking for. The shape of it is weird. Can anyone please give me solution for the line to be shown properly? Thank you

Show currentTime from wavesurfer.js triggers too many re-renders in React

I’m using this wavesurfer.js package with React for display wave form of audio. I want to display the current elapsed time using this getCurrentTime() method in their docs and answer here on github.

I got the elapsed time in seconds and update my React state to display it. However, it updates quite frequently, more than 10 times per second which trigger my component to re-render multiple times. I wonder if there is a way to make it only trigger state changes on each seconds pass?

export function Component(){
    const [currentTime, setCurrentTime] = useState(0)
    const wavesurferRef = useRef<any>(null)


    useEffect(()=>{
        if (wavesurferRef.current){
            wavesurferRef.current.on('audioprocess', function () {

                //ISSUE: THIS MAKE COMPONENT RE-RENDERING TOO MANY TIME
                setCurrentTime(wavesurferRef.current.getCurrentTime())
            })
        }
    },[])
    

    return(
        <div ref={wavesurferRef}>
        </div>
    )
}

Call to Ethereum API to make transaction making two transactions

I’m trying to make a transaction from one wallet to another using the Ethereum API via the Metamask API – the code should send a request to make a transaction to the Ethereum API, then log the hash of the transaction in the log once the transaction is made. However, for some reason two transactions are made when this code is run, even though the function is only run once (as far as I can tell at least) – both transactions are logged and made successfully, but I can’t tell why two are made. If it’s relevant, this code is running on a website using ReactJS and NextJS.

Here is my code:
` // Makes a request to make an ethereum transaction when button with ID transfer is pressed
const transfer = document.querySelector(‘#transfer’)

  transfer.addEventListener('click', () => {
    ethereum
      // Calls ethereum API to make transaction
      .request({
        method: 'eth_sendTransaction',
        params: [
          {
            // Address of the wallets transaction is going from and to
            from: 'address',
            to: 'address',
            // Hex of transaction amount in wei
            value: 'value'
          },
        ],
      })
      // Logs the hash of the transaction in console
      .then((txHash) => console.log(txHash))
      .catch((error) => console.error)
  })`

And the corresponding HTML:

<>
    <button id='transfer'>transfer</button>
</>

I’ve tried rewriting the function to run directly instead of when a button is clicked, but two transactions were still made – this makes me think that the problem is with the API call and not the JS/HTML, but I’m not certain of that.
I also tried giving the code to ChatGPT, but it says that in theory only one transaction should be made.

in chrome extension manifest v2 migration to v3 problem

I develop a chrome extension with manifet v2 but now google required manifet v3. So when i try to migrate v 2 to v 3 extension not working. but in v2 extension working fine.

please any expert update this code am in very trubbling for this error thanks
im triying from last 2 weeks but none of my idia is working correctly. so please update and describe yooure pnions. thanks amd begenir in englist so please don’t mind.

manifest.json v2

{
  "manifest_version": 2,
  "name": "Text Tool",
  "description": "A professional chrome extension for word and character count with and without spaces from selected text from any website.",
  "version": "1.0",
  "permissions": ["activeTab", "downloads"],
  "browser_action": {
    "default_title": "Text Tool",
    "default_popup": "popup.html"
  },
  "icons": {
    "16": "icons/icon16.png",
    "32": "icons/icon32.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  }
}

popup.js

function updateCounts(selectedText) {
  if (!selectedText) {
    return;
  }
  var words = selectedText.match(/b[-?(w+)?]+b/gi);
  var uniqueWords = [...new Set(words)];
  var wordCount = words?.length;
  var uniqueWordCount = uniqueWords?.length;
  var charCountWithSpaces = selectedText.length;
  var charCountWithoutSpaces = selectedText.replace(/s+/g, '').length;
  var sentenceCount = selectedText.split(/[.!?]+/g).filter(Boolean).length;
  var paragraphCount = selectedText.split(/n+/g).filter(Boolean).length;
  var textSize = (selectedText.length / 1024).toFixed(2) + ' KB';
  var totalWordLength = words.reduce((total, word) => total + word.length, 0);
  var avgWordLength = (totalWordLength / wordCount).toFixed(2);
  var avgSentenceLengthWords = (wordCount / sentenceCount).toFixed(2);
  var avgSentenceLengthChars = (charCountWithSpaces / sentenceCount).toFixed(2);

  document.getElementById('word-count').innerHTML = wordCount;
  document.getElementById('unique-words').innerHTML = uniqueWordCount;
  document.getElementById('char-count-with-spaces').innerHTML = charCountWithSpaces;
  document.getElementById('char-count-without-spaces').innerHTML = charCountWithoutSpaces;
  document.getElementById('sentence-count').innerHTML = sentenceCount;
  document.getElementById('paragraph-count').innerHTML = paragraphCount;
  document.getElementById('text-size').innerHTML = textSize;
  document.getElementById('avg-word-length').innerHTML = avgWordLength;
  document.getElementById('avg-sentence-length-words').innerHTML = avgSentenceLengthWords;
  document.getElementById('avg-sentence-length-chars').innerHTML = avgSentenceLengthChars;

  // Calculate reading time (based on 275 words per minute)
  var readingTime = Math.ceil(wordCount / 275);
  document.getElementById('reading-time').innerHTML = readingTime + ' minute(s)';

  // Calculate speaking time (based on 150 words per minute)
  var speakingTime = Math.ceil(wordCount / 150);
  document.getElementById('speaking-time').innerHTML = speakingTime + ' minute(s)';

  // Calculate handwriting time (based on 20 words per minute)
  var handwritingTime = Math.ceil(wordCount / 20);
  document.getElementById('handwriting-time').innerHTML = handwritingTime + ' minute(s)';
}

document.addEventListener("DOMContentLoaded", function() {
  chrome.tabs.executeScript({
    code: "window.getSelection().toString();"
  }, function(selection) {
    const selectedText = selection[0];
    document.getElementById("selectedText").textContent = selectedText;
    updateCounts(selectedText);
  });

  document.getElementById("copyButton").addEventListener("click", function() {
    const textarea = document.getElementById("selectedText");
    textarea.select();
    document.execCommand("copy");
  });

  document.getElementById("exportButton").addEventListener("click", function() {
    const selectedText = document.getElementById("selectedText").textContent;
    const blob = new Blob([selectedText], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    chrome.downloads.download({
      url: url,
      filename: "selectedText.txt",
      saveAs: true
    });
  });
});

(Dumb question) Looping through array doesn’t work as desired in JavaScript [duplicate]

I have a really dumb question. Why does my code not work?

let Categories = ('City', 'Country', 'River', 'Name');

let i = 0;

while (i < Categories.length) {
    console.log(Categories[i]);
    i++;
}

It just prints out this:

so the different letters of the fourth index. Why? I already tried using for loops but I’m a beginner to JavaScript and Lua is really different…

Retrieve dropdown selected id’s propertied in Javascript

I have a javascript function upon the selection of the ddl item I see it calls the this.value() function in which I can see only the id. I’m trying to retrieve the other properties of the selected item

Below is the current code, which retrieves only the id , I did tried to fetch the other properties it didn’t worked

      function updateBilling(data) {                  
                    $("#srchAcntList").kendoDropDownList({
                        dataSource: data,
                        dataTextField: "Text",
                        dataValueField: "Value",
                        template: " #=data.Text#",
                        optionLabel: {
                            Text: "Select...",
                            Value: 0
                        },
                        change: function (e) {
                            var value = this.value();
                            if (value != "") {                            
                                showAcntNumber(value);
                            }
                        }
                    });
}




 function showAcntNumber(acnt) {
                var AcntNumber = '';
                if (acntInfo.length > 0) {
                    billingAcntNumber = acntInfo;
                    document.getElementById("lblAcntNo3").innerText =  billingAcntNumber;
                }
            }

I tried to add below code to fetch EdcAcntNum of selected item , in this case it should bring 55078 EdcAcnt Num

 var acntNumber = this.data["EdcAcntNumber"];
                    console.log(acntNumber);

It didn’t worked

Upon change function I can see
I can see the code
var value = this.value();
retrieves only the Value:55078 but I wanted to get EdcAcntNum object value, kindly see the attach image too for reference

enter image description here

How to execute a function in ejs using a button

I want to execute a nodejs function in ejs template, the idea is when I click the button the function should be executed and the result should appear in the placeholder. As shown in the screen shoot below:

ejs

I have embeded the function to the ejs file like below:

router.get('/lottery/generator', (req, res) => {
  res
    .status(200)
    .render('generator', { generator: kaikkiController.uniqueRandomNumbers });
})

And then I tried to excute the function by click the button as shown in the generator.ejs file below:

<%- include('partials/header') -%>

<div class="container mt-5 w-50">
  <h2 class="mb-4">Generator</h2>

  <div id="true">RESULT SHOULD BE HERE</div>

  <button
    id="submit"
    onclick="<%= generator%>"
    class="btn btn-danger btn-block mt-3"
  >
    Generate
  </button>
</div>

<%- include('partials/footer') -%>

But I couldn’t get the result of the excution. Any suggestion please?

HTML “code” displayed merely instead of showing the content as usual

I was creating my first react project, notes app. when the “Enter” key is pressed it worked as expected while editing when i refresh, the the “Enter” space is gone and the words sits together like
from this:
“Hello
World”
to this:
“HelloWorld”

So i planned to store the note div’s innerHTML instead of textContent. So just i could preserve the format the user want. but it doesnt worked as i expected. the note section displays whole instead of the textContext without by processing the HTML code i passed as string.

the problem

but i’ve figured out the problem though. when i save the note (innerHTML)
it somehow converts “<” & “>” angle brackets ig into HTML entities like this

&lt;

&

&gt;

so thats y this is happening. all i wanna know now is to prevent this

actual problem

problem in browser

please help me solve this…

set environment variables in nuxt3 project

Hi I’m using nuxt3 to develop SSR project!
I want to set environment variables to control the API url.
I set it like this in the scripts of package.json.

"serve-dev": "set ENV=development && nuxt dev",
"serve-prod": "set ENV=production && nuxt dev",

When I console.log the env, I found that the setting is successful.
But the Judgment will log “false”.
enter image description here
enter image description here
You can find that the first two lines of console.log are correct, but the third line will display an error.

How did this happen.