Trying to highlight words in image using ocr

When I try to highlight words in chosen image it fails saying there’s no words for the text(Tessereact.js) and I tried many things to make it mark words in the image after the ocr but still fails to, this is the last code edit after failing many times, I want it to be like tesseract.js website demo where it can mark where is words after performing ocr

script.js

const langSelect = document.getElementById('langSelect');
const fileInput = document.getElementById('fileInput');
const ocrButton = document.getElementById('ocrButton');
const extractSelect = document.getElementById('extractSelect');
const extractButton = document.getElementById('extractButton');
const imageContainer = document.getElementById('imageContainer');
const textOutput = document.getElementById('textOutput');
var input_overlay = document.getElementById('highlightCanvas')
var ioctx = input_overlay.getContext('2d')
let extractedText = '';

fileInput.addEventListener('change', function () {
  const file = fileInput.files[0];
  imageContainer.src = URL.createObjectURL(file);
});

async function performOCR() {
  const lang = langSelect.value;

  if (lang && fileInput.files.length > 0) {
    const file = fileInput.files[0];
    ocrButton.disabled = true;
    ocrButton.classList.add('disabled');
    textOutput.innerHTML = '<div class="loading"><span class="loader animate" aria-label="Processing your request"></span><span>Loading...</span></div>';

    try {
      const { createWorker } = Tesseract;
      let tessdata;

      if (lang === "eng") {
        tessdata = 'eng.traineddata';
      }

      const worker = await createWorker(lang, 1,{
        workerPath: "./dist/worker.min.js",
        logger: m => console.log(m),
        tessdata: tessdata
      });

      const { data: { text } } = await worker.recognize(file);

      if (text) {
        result(text);
        await worker.terminate();
      } else {
        textOutput.innerText = 'No text found.';
        extractedText = '';
        await worker.terminate();
      }

      imageContainer.innerHTML = `<img src="${URL.createObjectURL(file)}" alt="Uploaded Image">`;
    } catch (error) {
      textOutput.innerText = 'Error: OCR failed.';
      textOutput.classList.add('error');
      console.log(error);
      extractedText = '';
    }

    ocrButton.disabled = false;
    ocrButton.classList.remove('disabled');
  } else {
    textOutput.innerText = 'Please select a language and an image file.';
  }
}

function extractText() {
  const fileType = extractSelect.value;

  if (fileType && extractedText) {
    const blob = new Blob([extractedText], {
      type: `text/${fileType}`
    });

    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `extracted_text.${fileType}`;
    link.click();
  } else {
    textOutput.innerText = 'Please select a file type and perform OCR first.';
  }
}
function result(res){
    // octx.clearRect(0, 0, output.width, output.height)
    // octx.textAlign = 'left'

    console.log('result was:', res)
    // output_overlay.style.display = 'none'
    // output_text.innerHTML = res.text
    textOutput.innerText = res.text;
    extractedText = res.text;
    res.words.forEach(function(w){
        var b = w.bbox;

        ioctx.strokeWidth = 2

        ioctx.strokeStyle = 'red'
        ioctx.strokeRect(b.x0, b.y0, b.x1-b.x0, b.y1-b.y0)
        ioctx.beginPath()
        ioctx.moveTo(w.baseline.x0, w.baseline.y0)
        ioctx.lineTo(w.baseline.x1, w.baseline.y1)
        ioctx.strokeStyle = 'green'
        ioctx.stroke()


        // octx.font = '20px Times';
        // octx.font = 20 * (b.x1 - b.x0) / octx.measureText(w.text).width + "px Times";
        // octx.fillText(w.text, b.x0, w.baseline.y0);
    })
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OCR Reader</title>
    <script src="./dist/dist-tesseract.min.js"></script>

    <link rel="stylesheet" href="./7.css">
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
    <div class="center">
        <select id="langSelect">
            <option value="eng">English</option>
        </select>
        <input type="file" accept="image/png, image/jpeg" id="fileInput">
        <button onclick="performOCR()" id="ocrButton">Perform OCR</button>
        
        <div id="content">
                <div>
                <canvas id="highlightCanvas"></canvas>

                    <img id="imageContainer"><div id="textOutput" class="output-box"></div>
                </div>
        <select id="extractSelect">
            <option value="">Select File Type</option>
            <option value="txt">Text File (.txt)</option>
            <option value="docx">Word Document (.docx)</option>
        </select>
        <button onclick="extractText()" id="extractButton">Extract Text</button>
    </div>
    


    <script src="./dist/worker.min.js"></script>
    <script src="./script.js"></script>

</body>
</html>

tried many things and even libraries to make it mark the words using ocr in the chosen image and still doesn’t work

Face detection rest api

I’ve returned to a WordPress project that used the javascript code for Face Detection which has been deprecisted, so I’m looking for an alternative, which I think is a REST api, but I cannout find an example. Has anyone implemented Face Detection in wordpress?

I’d rather do it on the frontend than in PHP as i’ve got a complex ACF Repeater to update.

I’ve tried the following code

const PAT = 'mypat';
// Specify the correct user_id/app_id pairings
// Since you're making inferences outside your app's scope
const USER_ID = 'myuser';
const APP_ID = 'myapp';
// Change these to whatever model and image URL you want to use
const MODEL_ID = 'face-detection';
const MODEL_VERSION_ID = '6dc7e46bc9124c5c8824be4822abe105';
// old const MODEL_VERSION_ID = "45fb9a671625463fa646c3523a3087d5";
// Change this to whatever image URL you want to process

const IMAGE_URL = document.querySelectorAll(".show-if-value img")[0].src;concept
const CONCEPT_ID = 'ai_fvlBqXZR';

///////////////////////////////////////////////////////////////////////////////////
// YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE
///////////////////////////////////////////////////////////////////////////////////

const raw = JSON.stringify({
    "user_app_id": {
        "user_id": USER_ID,
        "app_id": APP_ID
    },
    "searches": [
        {
            "query": {
                "ranks": [
                    {
                        "annotation": {
                            "data": {
                                "concepts": [
                                    {
                                        "id": CONCEPT_ID,
                                        "value": 1
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        }
    ]
});

const requestOptions = {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Key ' + PAT
    },
    body: raw
};

fetch(`https://api.clarifai.com/v2/annnotations/searches`, requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

</script>

but I get an error “Uncaught SyntaxError: Unexpected token ‘export’ (at face-api:7:1326838)”

navigation to definitions not working in plain js in VsCode

Trials for both of my Webstorm and Enterprise version of Intellij have exprired, so to be able to work with the JS/HTML/CSS part of my project, I am trying to switch to VsCode for the time being.
Right off the bat, I faced a problem with not being navigate to definitions of anything i.e. not just entities in my code, but even native functions e.g. getElementById():
enter image description here

I’ve found similar questions being asked about this, but looks like in those situations certain frameworks (e.g. Angular) caused trouble for VsCode. My project though is just using plain vanilla JS and nothing fancy.

Does anyone know how to resolve that?

I am using the latest VsCode at the moment i.e. ver 1.89 of April 2024.

How to repress two lines from initial draw of chart, when using checkboxes to add or remove lines from a d3.js multiline chart

I have a multiline chart built with d3 that allows the user to select/deselect lines using checkboxes in the legend. I want to make two of the lines deselected by default, with the user having the ability to check them and add them in if desired.

Getting the functionality of this chart working was originally addressed in another stack overflow question.

I’m able to de-select the checkboxes. I thought that by adding the the two line groups I want deselected by default to the clickedItems array, that would remove them from the chart when it was first drawn, but that is not the case. Any idea how I can initially repress the “<18” and “56+” groups from the chart?

let timeW = 960,
  timeH = 450

let timeMargin = {
    top: 20,
    right: 300,
    bottom: 80,
    left: 60
  },
  timeWidth = timeW - timeMargin.left - timeMargin.right,
  timeHeight = timeH - timeMargin.top - timeMargin.bottom;

var x2 = d3.scaleTime().range([0, timeWidth]),
  y2 = d3.scaleLinear().range([timeHeight, 0]);

var xAxis = d3.axisBottom(x2),
  yAxis = d3.axisLeft(y2);

var line = d3.line()
  .x(function(d) {
    return x2(d.date);
  })
  .y(function(d) {
    return y2(d.value);
  });

const seriesColors = ['#ff3300', 'royalblue', 'green', 'turquoise', 'navy']

var color = d3.scaleOrdinal()
  .range(seriesColors);

const parseDate = d3.timeParse("%Y%m%d");

d3.csv("https://raw.githubusercontent.com/sprucegoose1/sample-data/main/age.csv").then(function(data) {
  console.log('data', data)
  var long_data = [];
  data.forEach(function(row) {
    row.date = parseDate(row.Date)
    let tableKeys = data.columns.slice(1);
    Object.keys(row).forEach(function(colname) {
      if (colname !== "date" && colname !== "Date") {
        long_data.push({
          "date": row["date"],
          "value": +row[colname],
          "bucket": colname
        });
      }
    });
  });

  data.sort((a, b) => a.date - b.date)

  let dataNest = d3.group(long_data, d => d.bucket)
  let tableKeys = data.columns.slice(1);

  drawChart(long_data, dataNest, tableKeys)
})

function drawChart(data, dataNest, tableKeys) {
  d3.select("#timeseries").remove()

  let timeseries = d3.select("#chart").append('svg')
    .attr('id', 'timeseries')
    .attr("width", timeWidth + timeMargin.left + timeMargin.right)
    .attr("height", timeHeight + timeMargin.top + timeMargin.bottom)

  var graph = timeseries.append('g').attr('transform', 'translate(' + timeMargin.left + ',' + timeMargin.top + ')');

  var focus = timeseries.append("g")
    .attr("class", "focus")
    .attr("transform", "translate(" + timeMargin.left + "," + timeMargin.top + ")");

  x2.domain(d3.extent(data, function(d) {
    return d.date;
  }));
  y2.domain([0, d3.max(data, function(d) {
    return d.value;
  })]);

  focus
    .selectAll("path")
    .data(dataNest)
    .enter().append("path")
    .attr('class', d => 'groups a' + d[0].replaceAll("+", "").replaceAll("<", "").replaceAll(" ", "_"))
    .attr("d", d => {
      d.line = this;
      return line(d[1]);
    })
    .style("stroke", d => color(d[0]))
    .style("stroke-width", 1)
    .style('fill', 'none')
    .attr("clip-path", "url(#clip)")

  focus.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + timeHeight + ")")
    .call(xAxis);

  focus.append("g")
    .attr("class", "axis axis--y")
    .call(yAxis);

  var gXAxis = focus.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + timeHeight + ")")
    .call(xAxis);

  var gYAxis = focus.append("g")
    .attr("class", "axis axis--y")
    .call(yAxis);

  let clickedItems = ["56+", "<18"]

  var legend = timeseries.append('g')
    .attr('class', 'legend')
    .attr("transform", "translate(" + (timeW - timeMargin.right + 10) + "," + timeMargin.top + ")")

  var legendGroups = legend
    .selectAll(".legendGroup")
    .data(dataNest, d => d[0])

  var enterGroups = legendGroups
    .enter()
    .append("g")
    .attr("class", d => "legendGroup " + d[0].replaceAll(" ", "_").replace("<", ""))
    .on("click", function(event, d) {
      console.log('d', d)

      d.clicked = !d.clicked;

      // toggle the rectangle's fill
      d3.select('rect.a' + d[0].replaceAll(" ", "_").replace("+", "").replace("<", "")).attr("fill", d.clicked ? "transparent" : d => color(d[0]));

      // hide/show the associated line
      d3.select("path.a" + d[0].replaceAll(" ", "_").replace("+", "").replace("<", "")).style("display", d.clicked ? "none" : "block");

      // hide/show the associated table row
      d3.select(".row.a" + d[0].replaceAll(" ", "_").replace("+", "").replace("<", "")).style("display", d.clicked ? "none" : "block");

      let i = d3.selectAll(".legend-rect").nodes().indexOf(this);
      d3.selectAll(".group" + i).style("display", d.clicked ? "none" : "block");

      // Logic for all empty:
      // keep track of unchecked boxes (also used in rescaling below):
      d.clicked ? clickedItems.push(d[0]) : clickedItems.splice(clickedItems.indexOf(d[0]), 1);

      // If all are empty:
      // if (clickedItems.length == tableKeys.length) {
      //     d3.selectAll(".legend-rect")
      //         .attr("fill", d => color(d[0]))
      //         .each(d => d.clicked = false);
      //     d3.selectAll(".groups")
      //         .style("display", "");
      //     clickedItems = [];
      // }

      // re-scale
      x2.domain(d3.extent(data.filter(d => clickedItems.indexOf(d.bucket) == -1), function(d) {
        return d.date;
      }));
      y2.domain([0, d3.max(data.filter(d => clickedItems.indexOf(d.bucket) == -1), function(dd) {
        return dd.value;
      })]);

      gYAxis.call(yAxis)
      gXAxis.call(xAxis)

      focus.selectAll("path.groups")
        .transition() // May want to use clip area for the line here.
        .attr("d", d => {
          return line(d[1]);
        })
      console.log('clicked items', clickedItems)

    })

  legendGroups
    .exit()
    .remove();

  enterGroups
    .append("rect")
    .attr("width", 10)
    .attr("height", 10)
    .attr("fill", d => color(d[0]))
    .attr("stroke", d => color(d[0]))
    .attr("stroke-width", 2)
    .attr('stroke-opacity', 1)
    .attr("x", 30)
    .attr("y", (d, i) => i * 20)
    .attr("class", d => "a" + d[0].replace("+", "").replace("<", "") + ' legend-rect')

  enterGroups
    .append("text")
    .attr('class', 'legend-text')
    .text(d => d[0])
    .attr("x", 45)
    .attr("y", (d, i) => 10 + i * 20)

  enterGroups
    .append("foreignObject")
    .attr("x", 15)
    .attr("y", (d, i) => i * 19)
    .attr("width", 12)
    .attr("height", 14)
    .attr("id", (d, i) => 'a' + i)
    .append("xhtml:tree")
    .html(d => d[0] == "56+" || d[0] == "<18" ? "<input type='checkbox' class='check'>" : "<input type='checkbox' checked class='check'>")
    .attr('class', 'checkcontainer')

};
#chart {
  height: 450px;
  width: 760px;
}

.check {
  width: 11px;
  height: 12px;
  filter: grayscale(1);
  margin: 0;
  margin-top: -1px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
<div id="chart"></div>

How to use Date labels as Y axis in chartsjs

Given the following chart how can I show a custom HTML label for the Y ticks?

  const yAxisLabelsLookup = {
    0: {
      label: '2024-01-01',
      color: 'red',
    },
    1: {
      label: '2024-01-02',
      color: 'blue',
    },
    2: {
      label: '2024-01-03',
      color: 'green',
    },
    3: {
      label: '2024-01-04',
      color: 'yellow',
    },
  }
  const ctx = document.getElementById('chart-container');

  const data = {
    datasets: [{
      label: 'First Dataset',
      data: [
        {
          x: 20,
          y: 0,
          r: 15
        }, {
          x: 40,
          y: 0,
          r: 10
        },
        {
          x: 20,
          y: 1,
          r: 10
        },
        {
          x: 40,
          y: 1,
          r: 10
        },
        {
          x: 25,
          y: 2,
          r: 10
        },
        {
          x: 35,
          y: 2,
          r: 10
        },
      ],
      backgroundColor: 'rgb(255, 99, 132)'
    }]
  };

  const chart = new Chart(ctx, {
    type: 'bubble',
    data: data,
    options: {
      // So we can set the height with css.
      // maintainAspectRatio: false,
      responsive: true,
      scales: {
        x: {
          type: 'time',
          // time: {
          //   displayFormats: {
          //     quarter: 'MMM YYYY'
          //   }
          // }
          position: 'top',
          ticks: {
            padding: 15,
          },
        },
        y: {
          // display: false,
          ticks: {
            padding: 25,
            callback: function (value) {
              if (value in yAxisLabelsLookup) {
                const label = yAxisLabelsLookup[value].label;
                const color = yAxisLabelsLookup[value].color;
                return `<span style="color: ${color};">${label}</span>`;
              } else {
                // Return the default numeric value if no custom label is found
                return value;
              }
              // if (value in dateLookupMap) {
              //   return dateLookupMap[value]
              // } else {
              //   return ''
              // }
            }
          }
        },
      }
    }
  });

log in page wont work even if the correct product key is entered [closed]

the log in page wont work even if the correct product key is entered

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


<head>
    <img class="log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Y50eKec01RFAX/m2AIaYTiGMoQagRBqPG/GKGKUEQQQvyHr6OJ37+QFALjGcfUwoN5ZCPH/FJpstWhf4fLpX7Wy6qz+CUZkmWSbcH64TgORqNRwCe9DOBWtjFxtzUuo2kaif9ojaZkQlYmJydPp54ls6QgC7q8SGqzBi4CZbNCC8XuIlCF0qzNfC8CZbNCC8Xu/wHNNLb1eXkmhwAAAABJRU5ErkJggg=="
        alt="Logo" width="45" height="45" style="position: absolute; top: 0; left: 0;">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Key Entry</title>
    <style>
        body {
            font-family: monospace;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            position: relative;
            /* Ensure proper positioning of elements */
        }


        .container {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);
        }


        h1 {
            text-align: center;
        }


        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }


        button {
            width: 100%;
            padding: 10px;
            background-color: #1f2127;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }


        button:hover {
            background-color: #035df7;
        }


        #content {
            display: none;
            margin-top: 20px;
        }


        /* User info container */
        #userInfo {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 5px 10px;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 4px;
            font-size: 12px;
        }
    </style>
</head>


<body>
    <!-- User info -->
    <div id="userInfo">Use Ctrl+Q to redirect to canvas! <span id="userIP"></span> | We are not responable for any
        device loss.<span id="sessionID"></span></div>


    <div class="container">
        <h1 id="heading">Enter Product Key</h1>
        <input type="text" id="productKeyInput">
        <button onclick="checkProductKey()">Submit</button>


        <div id="content">
            <!-- Your content goes here -->
            <h2>Welcome, to the cloakr repository!</h2>
            <p>Remember to never share your product key sharing your product key could result in </p>
        </div>
    </div>
    <script>
        // Function to generate session ID
        function generateSessionID() {
            let sessionID = "";
            const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            for (let i = 0; i < 12; i++) {
                sessionID += characters.charAt(Math.floor(Math.random() * characters.length));
                if (i === 3 || i === 7) {
                    sessionID += "_"; // Add underscore at specific positions
                }
            }
            return sessionID;


            // Call updateUserInfo when the page loads
            updateUserInfo();


            // Add more product keys here
            const encodedProductKeys = [
                "dGVzdA==",
                "czVlNXctcVVxLTM0YlgxLWNsb2Frcg==",
                // Add more keys encoded similarly
            ];


            function decodeProductKey(encodedKey) {
                return atob(encodedKey);
            }


            function checkProductKey() {
                const enteredKey = document.getElementById("productKeyInput").value.trim();
                const decodedKey = decodeProductKey(enteredKey);
                if (encodedProductKeys.includes(decodedKey)) {
                    document.getElementById("heading").textContent = "Product Key Verified!";
                    document.getElementById("content").style.display = "block";
                } else {
                    alert("Invalid product key. Please try again.");
                }
            }
    </script>


    <script>
            // Event listener to redirect on Ctrl+Q
            document.addEventListener("keydown", function (event) {
                // Check if Ctrl+Q is pressed
                if (event.ctrlKey && event.key === "q") {
                    // Redirect to another website
                    window.location.href = "https://npenn.instructure.com/login/ldap";
                }
            });
    </script>


    <script>

I tryed alot of things and they didnt work

Why does this custom component get placed outside of the ?

table.vue

...
        <tbody class="table-body">
            <slot></slot>
        </tbody>
...

TableCellRow.vue

<template>
    <td class="table-row-cell" :class="this.class">
        <slot></slot>
    </td>
</template>

how I tried using it:

<my-table>
                <template #default>
                    <tr>
                        <td>i am inside the tr</td> <----- this is inside the <tr>
                            <table-row-cell> <-------- this is outside of the <tr>
                                    i am outside the tr
                            </table-row-cell>
                    </tr>
                </template>
            </my-table>

and like this:

            <my-table>
                <tr>
                    <td>i am inside the tr</td>
                    <table-row-cell>
                        i am outside the tr
                    </table-row-cell>
                </tr>
            </my-table>

in this latest case, this is what I get:

<tbody class="table-body"> i am inside the tr <td class="table-row-cell"> i am outside the tr </td></tbody>

and in the first case I get this:

<tbody class="table-body"><tr><td>i am inside the tr</td></tr><td class="table-row-cell"> i am outside the tr </td></tbody>

I’ve also tried just this:

            <my-table><template #default>
                <tr>
                    <table-row-cell>
                        i am outside the tr
                    </table-row-cell>
                </tr>
            </template>
</my-table>

but I just get this:

<tbody class="table-body"><tr></tr><td class="table-row-cell"> i am outside the tr </td></tbody>

so what’s up with that? I can’t use a component inside a tag, that just has a tag in it? or like what is the issue? If I place my component inside the tag, why does it either throw the out and only render the , or either render the and put everything else below that? Like what? Why does Vue have to be SO difficult, for absolutely no reason?

I just want to put a into the slot of my custom table, and put a custom component inside that – why does it have to be so difficult? Am I tripping or something? I’m not missing a single closing tag, my components are fine, so why is this happening?

How to Target a Ref Inside a Function in React Component?

I’m working on a React component where I need to generate a PDF from a specific element referenced by a ref within a function. However, I’m encountering difficulties targeting the ref inside the function.
I’m using react-hook-form and I don’t want to use state to manage the field and therefore put the rendered content hidden in the form itself.
The main goal is to create a PDF from the element typed by the user in the form after submitting the form.

Here’s a simplified version of my component:

import { useRef } from 'react';
import generatePDF from 'react-to-pdf';

const MyComponent = () => {
  const targetRef = useRef(null);

  const defaultValues = {
    name: ''
  };
  
const methods = useForm({
    resolver: yupResolver(NewPatientSchema),
    defaultValues,
  });

  const {
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const onSubmit = handleSubmit(async (data) => {

    const content = () => {
      return (
        <div ref={targetRef}>
          Content include {data.name}
        </div>
      )
    }

    generatePDF(targetRef, { filename: 'page.pdf' });
  };

  return (
    <FormProvider methods={methods} onSubmit={onSubmit}>
      <TextField name='name' label='Name'/>
      <button onClick={onSubmit}>Generate PDF</button>
    </FormProvider>
  );
};

export default MyComponent;

So far I get Unable to get the target element., I tried also to reference to content and not the ref and I get the same error.

(I tried react-pdf/renderer it does not render the images)

Thank you in advance

Append JSON data to table after every while loop iteration using JavasScript

The ‘add_txs_fnc’ function makes an ajax request to a PHP script which adds records to a database, and returns JSON data.

The JSON is displayed in the #display_table. I want data to be appended to the table on every loop iteration (so I can see the result of every function call in real time), but they all get appended simultaneously after the while loop has finished.

I assume I need to be using something like ‘async’, ‘await’ etc, but not sure how to proceed.

<div id="display_table"></div>

<script>
$(function() {
   while (true) {
      id_lkup_fnc(function(res) {
         add_txs_fnc(function(res) {
            let data = jsonDat2Array_fnc(res);
            createTable_fnc(data);
         });
      });
   }

Changing json value order with Javascript

I need a different order of the values of my JSON string.
I use php to create a JSON string from a database query that looks like this:

$lbtbs = $DB->get_records('lbtb_eintraege');
$lbtb_json = json_encode($lbtbs, JSON_PRETTY_PRINT);

The database is read out in the “Moodle” system.
According to the documentation an array of objects is returned.

My JSON string that I submit using php looks like this:

{id: '1', date: '2024-05-05', start: '1', description: 'fdsfdsfd', standort: 'sz', …}

In Javascript I parse the JSON string with:

this.events = JSON.parse(decodeURI(this.lbtbdata));

However, I need the string to be nested differently. The date should come first, then the ID and the remaining values within the ID.
As an example:

[DATE]
 - [ID]
     - [REST DATA]

I tried it like this.

for (const date of Object.keys(this.events)) {
                    for (const id of Object.keys(this.events[date])) {
                        const event = new Event(this.events[date][id]);
                        this.events[date][id] = event;
                    }
                }

I’m still missing a few exercises when it comes to JavaScript. I would therefore be grateful for any suggestion for a solution or for a few keywords to search for!

NodeJS VM Context Script Execution Reference Error

I have a class that I am loading in to the a global vm context and I am executing a script within the shared context. Works fine when things are correct. But if I accidentally forget to define a variable when using one of the setters, I get a reference error and the application crashes.

const document = new document('users');
document.fetch('0939e8bde2f74213a0bd75bea8d82f8b').then(() => {
    document.setValue('middleName', bob); //bob is not defined
});

setValue is never executed. I have tried several ways to capture the error and no luck. I have tried added try/catch to the wrappedScriptContent. I have tried a try/catch within the async function. For now I have settle on the process.on but that doesn’t give me any details.

Here is my executeScript method as it stands.

async executeScript(script) {
    const context = vm.createContext({...this.sharedContext});
    const wrappedScriptContent = `
        (async function() {
          ${script}
        })();`;
    try {
        const scriptObject = new vm.Script(wrappedScriptContent);
        scriptObject.runInContext(context, { timeout: 5000, displayErrors: true });
        return { success: true, result: '' };
    } catch (error) {
       console.error(`Error executing script: ${error}`);
    }
}

Is there a way to handle errors, known or not known? I am looking for a way to handle errors gracefully and try to provide detailed logging.

Regex works in regex101, but not when I use it in js match

So, I’m trying to break a bunch of finnish names in to syllables to be used as data to make a name generator of sorts that makes, you guessed it, finnish inspired names out of syllables. However, for some reason, while trying to get my list of syllables, Javascript match aint working with me.

Idea is that that regex finds natural points of syllable lines in finnish (before consonant followed by a vowel and in vowel clusters which are not diftongs), but I noticed when playing with the data, that in purpose of my generator it would make a lot of sense to add exception, where doubles of the same consonant is broken off before the double consonant, not in the middle of it, as it just works better to the project. So names Mikki, Martti and Arska are usually broke in to syllables as Mik-ki, Ars-ka and Mart-ti, but I want the regex break Martti as mar-tti and Mikki and Mi-kki.

The regex monster I am usin in in display in here: https://regex101.com/r/rvXCrM/2 and it works fine in the regex101, but when I use it in my code like this:

const syllableRegex = /[bcdfghjklmnpqrstvwxz]*(?:a[aiu]?|e[eiuy]?|i[eiuy]?|o[iou]?|u[iou]?|y[iyö]?|ä[iyä]?|ö[iyö]?)(?:[bcdfghjklmnpqrstvwxz]*$|[bcdfghjklmnpqrstvwxz]?(?=(?:tt|kk|mm|nn|rr|ll|pp|ss)[aeiouyäö])|[bcdfghjklmnpqrstvwxz]+(?=[bcdfghjklmnpqrstvwxz][aeiouyäö]))?/gi;

function to_syllables(word) {
    return word.match(syllableRegex);
}

var names = [Mikki, Martti, Arska];

var syllable_charts = names.map(to_syllables);

console.log(syllable_charts);

The code does Arska and Martti right, but fails at Mikki. it specifically fails with any name, where it should cut the word between vowels and the double consonant. Can anyone tell me why and how to fix it?

If been trying different tokens and plaied around with rifferent or statements, but nothing seems to work. It is not elegant, and it is not working,what am I doing wrong?

Kendo UI grid showing no records found when reloading it’s previous grid state using setOptions

Our project has a Kendo grid where the grid databound event saves the grid state for a particular user at any give time when user applies filter or makes any changes to grid view.

Kendo grid structure is loaded in MVC as follows:

@(Html.Kendo().Grid<Entity>()
          .Name("FeedGrid")
          .HtmlAttributes(new { @class = "FeedGrid" })
          .Sortable(sortable => sortable
              .AllowUnsort(true)
              .SortMode(GridSortMode.MultipleColumn))
          .Scrollable()
          .ColumnMenu()
          .Filterable()
          .Reorderable(ro => ro.Columns(true))
          .Resizable(rs => rs.Columns(true))
          .Groupable()
          .NoRecords("<b style='text-align:center'><i>---- No records found ----</i></b>")
          .Columns(columns =>...)
          .Events(events =>
                     { events.ExcelExport("exportGridWithTemplatesContent");
    events.ColumnShow("SaveGridState");
    events.ColumnHide("SaveGridState");
    events.ColumnReorder("SaveGridState");
    events.ColumnResize("SaveGridState");
    events.ColumnMenuInit("SortFilterDropdown");
    events.DataBound("SaveGridState")};
          .DataSource(dataSource => dataSource
              .Ajax()
              .ServerOperation(false)));

The data to the above grid is passed in javascript/jquery as follows along with retrieving the saved grid state:

var dataSource = new kendo.data.DataSource({
    transport: {
        read: function (options) {
            $.ajax({
                url: GetApiUrl('Api/GetGrid'),
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(DataSourceRequestViewModel(options, currentSearchXml)),
                type: 'POST',
                cache: false,
                success: function (result) {
                    options.success(result);
                },
                error: function (result) {
                    options.error(result);
                }
            });
        }
    },
    schema: {
        data: "Data",
        total: "Total"
    }
});

setTimeout(function () {
    $("#FeedGrid").data("kendoGrid").setDataSource(dataSource);
    $("#FeedGrid").data("kendoGrid").dataSource.read();
}, 100);



var stateGrid = GetGridState("FeedGrid");
var grid = $("#FeedGrid").getKendoGrid();
stateGrid.toolbar = [{ template: kendo.template($('#FeedGrid').find(".k-grid-toolbar").html()) }];
 
if (!isNullOrEmpty(stateGrid)) {
   grid.setOptions(stateGrid);
}

Though the datasource is making the ajax call and receiving the right response, the data is not being rendered on grid in UI. It shows No records found. When I remove the setOptions it loads the data correctly. But the setoptions is an important feature and we need it, Please help me here. This looks like a bug from kendo.

I tried the following solution to wait for the grid to load completely and then use setoptions but that is loading the grid twice and is not user friendly.

Tried solution:

function getFeedGridSettings(id) {
    var isLoading = $('.k-loading-text').length;
    if (isLoading) {
        if (stateGrid == undefined) {
            stateGrid = GetGridState(id);
            stateGrid.toolbar = [{ template: kendo.template($('#' + id).find(".k-grid-toolbar").html()) }];
        }
        setTimeout(function () { getFeedGridSettings('FeedGrid'); }, 10000);
    }
    else {
        if (!isNullOrEmpty(stateGrid)) {
            var grid = $("#" + id).getKendoGrid();
            grid.setOptions(stateGrid);
        }
    }
}

var dataSource = new kendo.data.DataSource({
    transport: {
        read: function (options) {
            $.ajax({
                url: GetApiUrl('Api/GetGrid'),
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(DataSourceRequestViewModel(options, searchXml)),
                type: 'POST',
                cache: false,
                success: function (result) {
                    options.success(result);
                },
                error: function (result) {
                    options.error(result);
                }
            });
        }
    },
    schema: {
        data: "Data",
        total: "Total"
    }
});
setTimeout(function () { $("#FeedGrid").data("kendoGrid").setDataSource(dataSource) }, 100);
getFeedGridSettings('FeedGrid'); 

Please help me in finding the right solution.

Node.js Unexpected token ‘.’

I’m new in linux, js and node.js development so sorry if this question is stupid…but.

I have my first app on my local test server. When I go to the folder with the code and type npm start, everything works correctly.
BUT
I wanted to run it on the background and use systemctl to work with the app. But When I use sudo systemctl start “my app” I’m getting

Please help me :/

Unexpected token ‘.’

Stopping My Eclipse Application... eclipse.service: Deactivated successfully. Stopped My Eclipse Application. Started My Eclipse Application. [email protected] start nodemon server.js [nodemon] 3.1.0 [nodemon] to restart at any time, enter `r>
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,>
[nodemon] starting `node server.js`
/var/www/projects/eclipse/node_modules/mon>
session: options?.session,
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/load>
at Module._compile (internal/modules/c>
at Object.Module._extensions..js (inte>
at Module.load (internal/modules/cjs/l>
at Function.Module._load (internal/mod>
at Module.require (internal/modules/cj>
at require (internal/modules/cjs/helpe>
at Object.<anonymous> (/var/www/projec>
at Module._compile (internal/modules/c>
at Object.Module._extensions..js (inte>
[nodemon] app crashed - waiting for file c>

.service

[Unit]
Description=My Eclipse Application

[Service]
ExecStart=/usr/bin/npm start
WorkingDirectory=/var/www/projects/eclipse
Restart=always

[Install]
WantedBy=multi-user.target

Node.js v20.12.2.
nodemon -v3.1.0
nvm -v0.39.7

I’ve tried to update nvm, nodemon, node. Run it only like nvm start from the app folder.