localStorage overwrites whenever I refreshed the browser / close and there new imput

I was given a project to do for practice, the idea of the project is to create a create a form that I will create a timesheet, store in local storage and display it every data stored in a table . I’m using an array to store all the user inputs as objects and then use push method store it inside the localStorage.

Everything seems to work as I want, even when I refresh the page the localStorage is still intact. However when the user makes a new input, the localStorage gets overwritten.

this is my code

I create a function to save the data in array form inside localstorage,
I used push method


const addTask = document.querySelector("#submit");

let timeSheets =
  localStorage.getItem("timeSheets") !== null
    ? JSON.parse(localStorage.getItem("timeSheets"))
    : [];

addTask.addEventListener("click", (event) => {
  event.preventDefault();
  console.log("Btn Clicked");

  saveData();
  // showData();
});
function saveData() {
  const record = {
    // id: document.getElementById("id").value,
    task: document.getElementById("task").value,
    timeStart: document.getElementById("timestart").value,
    timeStop: document.getElementById("timestop").value,
  };

  timeSheets.push(record);
  // timeSheets.unshift(record);
  localStorage.setItem("timesheets", JSON.stringify(timeSheets));

  console.log(timeSheets);
}

My Result in the console:

[{…}]
0
: 
{id: 332, task: '1', timeStart: '11:45', timeStop: '17:45', date: '2024-05-29'}
1
: 
{id: 329, task: '1', timeStart: '11:45', timeStop: '17:45', date: '2024-05-29'}
2
: 
{id: 90, task: '1', timeStart: '11:45', timeStop: '17:45', date: '2024-05-29'}
length
: 
3

After refreshing or close the browser, and there is new input, it overwrites

[{…}]
0
: 
{id: 0, task: '3', timeStart: '10:50', timeStop: '11:50', date: '2024-06-07'}
length
: 
1
[[Prototype]]
: 
Array(0)

I expect the new input to add to the existing one

header 1 header 2
cell 1 cell 2
cell 3 cell 4
header 2
cell 2
cell 4

Highcharts legend is placed on top of caption

I have this chart:

https://jsfiddle.net/GarfieldKlon/txu215w6/

Highcharts.chart('container', {
            chart: {
                type: 'bar',
                borderWidth: 1,
            },
            title: {
                text: 'Fruit Consumption',
                align: 'left',
            },
            xAxis: {
                categories: ['Apples', 'Bananas', 'Oranges'],
            },
            yAxis: {
                title: {
                    text: 'Fruit eaten',
                },
            },
            series: [{ 
                name: 'Jane',
                data: [1, 0, 4],
            }, { 
                name: 'Marsupilami',
                data: [1, 0, 4],
            }, {
                name: 'Johnny',
                data: [5, 7, 3],
            }],
            legend: {
                enabled: true, 
                align: 'left',
                layout: 'vertical',
                symbolRadius: 0,
            },
            caption: { 
                text: '<b>The caption renders at the bottom of the chart, and is ' +
                    'included if the chart is exported.</b><br><em>Lorem ipsum dolor ' +
                    'sit amet, consectetur adipiscing elit, sed do eiusmod tempor ' +
                    'incididunt ut labore et dolore magna aliqua. Ut enim ad minim ' +
                    'veniam, quis nostrud exercitation ullamco laboris nisi ut ' +
                    'aliquip ex ea commodo consequat. Duis aute irure dolor in ' +
                    'reprehenderit in voluptate velit esse cillum dolore eu fugiat ' +
                    'nulla pariatur. Excepteur sint occaecat cupidatat non proident, ' +
                    'sunt in culpa qui officia deserunt mollit anim id est ' +
                    'laborum.</em><br><em>Lorem ipsum dolor ' +
                    'sit amet, consectetur adipiscing elit, sed do eiusmod tempor ' +
                    'incididunt ut labore et dolore magna aliqua. Ut enim ad minim ' +
                    'veniam, quis nostrud exercitation ullamco laboris nisi ut ' +
                    'aliquip ex ea commodo consequat. Duis aute irure dolor in ' +
                    'reprehenderit in voluptate velit esse cillum dolore eu fugiat ' +
                    'nulla pariatur. Excepteur sint occaecat cupidatat non proident, ' +
                    'sunt in culpa qui officia deserunt mollit anim id est ' +
                    'laborum.</em>',
            },
            credits: {
                enabled: false,
            },
        });

And the legend should be placed above the caption and both, the caption and the legend, should be aligned with the 0 grid line.
But the legend is overlapping the caption. Why? And how can I solve it?

dyld[59926]: missing symbol called

How to fix the problem? It appears when I run my nodeJS app. As I understood it is connected to m1 processor but not sure. I need to use it with arm64 architecture
I tried to delete node, nvm, node_modules and reinstall them. Not worked for me

Multiple google.visualization.events.addListener in Google Charts do not work together

I have a problem with a conflict between multiple event listeners in a Google Chart display. I have a Google Pie Chart with three event listeners, an onmuseover, an onmouseout and a ready event. The ready event allow saving the chart as a png image, while the onmouseout/onmouseover events change the background color of some divs when hovering the mouse over the chart’s slices. My problem is the following: the two onmouseover/onmouseout events work when alone, the ready event also works when alone but when all three of them are active the ready event works but the onmouseover/onmouseout do not! There is somewhere a conflict between these events and I can not figure out where. My code is below.

Also, is there a way I could sort the percentage values of the piechart slices so that the highest percentage to automatically change the background color of a div?

Thank you, Felix

google.charts.load('current', {'packages':['corechart']});

      function drawChart() {
       var SAIDFinal = parseFloat(sessionStorage.getItem('SAID_Result'));
       var SIDDFinal = parseFloat(sessionStorage.getItem('SIDD_Result'));
       var SIRDFinal = parseFloat(sessionStorage.getItem('SIRD_Result'));
       var MODFinal = parseFloat(sessionStorage.getItem('MOD_Result'));
       var MARDFinal = parseFloat(sessionStorage.getItem('MARD_Result'));
       
       var data = google.visualization.arrayToDataTable([
          ['Diabet', 'Tipul'],
          ['SAID', SAIDFinal],
          ['SIDD', SIDDFinal],
          ['SIRD',  SIRDFinal],
          ['MOD', MODFinal],
          ['MARD', MARDFinal],
        ]);
        var options = {
          pieSliceText: 'none', 
          pieHole: '0.3',  
          pieStartAngle: 270,
           chartArea: {
    left: '20',
    top: '30',
    right: '20',
    bottom: '30',
    width: '500',
    height: '500',
   },
   
   pieSliceTextStyle: {
            color: 'black'
        },
        
     slices: {
        0: {color:'#ff0000' },
        1: {color:'#d7c9bc' },
        2: {color:'lightgreen'},
        3: {color:'orange'},
        4: {color:'magenta'}, 
        /*textStyle: {color:'black'},    
      },
    
    legend: { 
          position: 'labeled', 
          /*alignment: 'center' ,
          orientation: 'vertical',*/
          textStyle: { color: 'black', fontSize: '24'}    
    },
    
        };

     options.slices[data.getSortedRows([{column: 1, desc: true}])[0]].offset = 0.1;
        

   var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    
    google.visualization.events.addListener(chart, 'ready', function () {
        piechart.innerHTML = '<img src="' + chart.getImageURI() + '">';
        console.log(piechart.innerHTML);
      });
    
    chart.draw(data, options);  
        
          google.visualization.events.addListener(chart, 'onmouseover', function(e) {
          if (data.getValue(e.row, 0) === 'SAID') {
            document.getElementById('SAIDtype').style.backgroundColor = '#ff0000';
          }
          else if (data.getValue(e.row, 0) === 'SIDD') {
            document.getElementById('SIDDtype').style.backgroundColor = '#d7c9bc';
          }
          else if (data.getValue(e.row, 0) === 'SIRD') {
            document.getElementById('SIRDtype').style.backgroundColor = 'lightgreen';
          }
          else if (data.getValue(e.row, 0) === 'MOD') {
            document.getElementById('MODtype').style.backgroundColor = 'orange';
          }
          else if (data.getValue(e.row, 0) === 'MARD') {
            document.getElementById('MARDtype').style.backgroundColor = 'magenta';
          }
        });
      
          google.visualization.events.addListener(chart, 'onmouseout', function(e) {
          if (data.getValue(e.row, 0) === 'SAID') {
            document.getElementById('SAIDtype').style.backgroundColor = '';
          }
          if (data.getValue(e.row, 0) === 'SIDD') {
            document.getElementById('SIDDtype').style.backgroundColor = '';
          }
          if (data.getValue(e.row, 0) === 'SIRD') {
            document.getElementById('SIRDtype').style.backgroundColor = '';
          }
          if (data.getValue(e.row, 0) === 'MOD') {
            document.getElementById('MODtype').style.backgroundColor = '';
          }
          if (data.getValue(e.row, 0) === 'MARD') {
            document.getElementById('MARDtype').style.backgroundColor = '';
          }
        });
        
        }
 

Convert image to buffer chunks – react native

I need to generate buffer of a chunk from an image path in react. Buffer format server is expecting is as follows:

<Buffer 64 61 74 61 3a 69 6d 61 67 65 2f 6a 70 65 67 3b 62 61 73 65 36 34 2c 2f 39 6a 2f 34 41 41 51 53 6b 5a 4a 52 67 41 42 41 51 45 41 53 41 42 49 41 41 44 ... 67141 more bytes>

But when trying to create Buffer in react native I am not getting similar Buffer format.

My codebase is

import { Buffer } from '@craftzdog/react-native-buffer';

  const data = await RNFS.read(filePath, length, uploadedSize, 'base64');
  const bufferData = Buffer.from(data, 'base64');

The format I am receiving from Buffer.from is

{ type: 'Buffer',
      data:
       [ 133,
         175,
         138,
         234,
         181,
         30,
         135,
         159,
         208,
         70,
         186,
         203,
         79,
         42,
         160,
         ... 39581 more items ] } }

How to test Quasar boot files?

My boot file connects router with Vue i18n.

src/boot/i18n.js:

import { boot } from 'quasar/wrappers'
import { createI18n } from 'vue-i18n'
import { i18nBootConfig, qDefaultLangPack } from 'src/i18n/config'
import { guessLocale } from 'src/helpers/lang'
import { Lang } from 'quasar'

export default boot(async ({ app, router, ssrContext }) => {
  const i18n = createI18n(i18nBootConfig)
  // Set i18n instance on app
  app.use(i18n)
  Lang.set(qDefaultLangPack)

  router.beforeEach(async (to, _from, next) => {
    await guessLocale({ globalI18n: i18n.global, route: to, ssrContext })
    return next()
  })
})

I wonder how can I test this connection with Vitest?

js watchmen activate the node command on a file

I’m trying to use: https://github.com/facebook/watchman

But it’s not working, I need to make sure that when a file called test2.js that is in the current path is modified then the node test2.js command is executed again.

I tried like this:

watchman -- trigger . jsfiles '**/*.js' -- node test2.js

Quello che ottengo è questo:

{
    "version": "2024.05.06.00",
    "disposition": "created",
    "triggerid": "jsfiles"
}

How do I make the command run every time the file is modified, what am I doing wrong?

How to properly use isolated-vm to execute sandboxed code in Node.js?

I am migrating from vm2 to isolated-vm for executing sandboxed code in Node.js. However, my current implementation always returns undefined for the result. Here is my code:

import ivm from 'isolated-vm';

export async function executeSandboxedCode(expression: string, params: any): Promise<any> {
  const context = {
    // populate context with necessary parameters
    ...params,
  };

  try {
    const isolate = new ivm.Isolate();
    const isolateContext = await isolate.createContext();
    
    const jail = isolateContext.global;
    await jail.set('global', jail.derefInto());

    const script = await isolate.compileScript(`
      (function(context) {
        ${expression}
      })(global.context);
    `);

    await jail.set('context', new ivm.ExternalCopy(context).copyInto());
    const result = await script.run(isolateContext);

    return result;
  } catch (error) {
    throw new Error(`Failure in process: ${error.message}`);
  }
}

What I tried:

  1. Assigned params to the global.context object.

  2. Compiled the script with the expression in a function.

  3. Used return in the expression to ensure a value is returned.

  4. Added error handling for context.

Expected:

The result from script.run(isolateContext) should contain the evaluated result based on the context parameters.

Actual:

The result always comes back as undefined.

What am I doing wrong?

Pointer lock doesn’t work on Safari during fullscreen

I’m developing a fullscreen game, where I need to programmatically enable and disable the pointer lock to let the user click on UI elements without exiting fullscreen. This seems to work fine on Chrome and Firefox, but fails in Safari.

I managed to reproduce the problem using a minimal plain HTML example:

const elem = document.getElementById("elem");
elem.addEventListener("click", (e) => {
  if (!document.fullscreenElement)
    elem.requestFullscreen();
  else
    elem.requestPointerLock();
});

document.addEventListener("pointerlockchange", (e) => {
  if (document.pointerLockElement)
    elem.innerText = "Pointer lock is now active";
  else
    elem.innerText = "Pointer lock is now inactive";
});
document.addEventListener("pointerlockerror", (e) => {
  elem.innerText = "Pointer lock has failed";
});
<div id="elem" style="width: 100px; height: 100px; background-color: red;">
  This element will go fullscreen
</div>

The first click on the element should activate the fullscreen mode, the second one should lock the pointer. On Chrome and Firefox this works properly, and “Pointer lock is now active” is displayed. On Safari, “Pointer lock has failed” is displayed instead, and neither the event or the JS console show any reason why.

However, if you modify the code to first request the pointer lock, and only then switch to fullscreen mode, everything seems to work fine in all browsers:

elem.addEventListener("click", (e) => {
  elem.requestPointerLock();
});
document.addEventListener("keydown", (e) => {
  elem.requestFullscreen();
});
// click the element to lock the cursor first, then press space to enter fullscreen

But this doesn’t achieve what I’m trying to do for my use case, as if you then release the pointer lock, it can’t be reacquired without exiting fullscreen.

I could not find any reference to what could be causing this behavior in the docs.

ReactJS – useState object loses getters when it is updated

I have a useState initialized to an object of type ExampleObject. This class has many properties (also nested) that make use of javascript’s getters and setters. I use the getters all around my code in order to access the useState’s properties:

const Component = ({data}) => {

    const [example, setExample] = useState(ExampleObject(data.p1,data.p2))

    return(
        {example.property2}
        <ChildComponent1
            example = {example}
            setExample = {setExample}
        />
        <ChildComponent2
            example = {example}
            setExample = {setExample}
        />
    )
}

export class ExampleObject {
    constructor(p1, p2) {
        this._property1 = p1;
        this._property2 = p2;
    }

    get property1(){
        return this._property1
    }

    set property1(property1){
        this._property1 = property1
    }

    get property2(){
        return this._property2
    }

    set property2(property2){
        this._property2 = property2
    }

Some of my child components update the example useState with its setter. I copy the useState’s content into another variable, update that variable and then use the setter:

const ChildComponent1 = ({example, setExample}) => {

    const [textContent, setTextContent] = useState(example.property1)

    const handleTextContent = (event) => {
        setTextContent(event.target.value)
    }

    useEffect(()=> {
        newExample = { ...example }
        newExample.property1 = textContent
        setExample(newExample)
    }, [textContent, example])

    return(
         <textarea
              value={textContent}
              onChange={handleTextContent}>
         </textarea>
    );
}

This generates a problem, the useStae is updated but its setters are lost making the whole code wrong. example.property2 in the RootComponent hands out an undefined error (should be changed to example._property) and the same goes for example.property1. I would like to keep using javascript’s getters as it is good practice to do so. Is there a way to set a useState object without losing them?

Can I define a jsdoc typedef (an object) by “spreading” existing typedefs?

Can I use the spread operator to create typedefs by combining existing typedefs?

For example- given typedefs One and Two where both are objects, how do I then create typedef Three? JSDoc seems to let me do the following, but the “spreading” doesn’t seem to be properly reflected in the generated html docs:

  /**
   * @typedef {Object} Three
   * @property {...One}
   * @property {...Two}
   */

How do you create new object typedefs using previously defined object typedefs?

I’m having an data loss issue using line Graphs in ApexCharts (JSON, JS, Electron)

ApexCharts seems to modify/remove some data, I’m not quite sure if this is a skill issue of mine, or something else.
I’m getting data from an API from my server, the APIs data is intact and seems to appear fine, the format of it is
[

[
...
{
fileName": "The Dawns Awakening.json",
    "data": {
     ...
      "2024-06-10": 2206772
    }
}
]

I’m using the variable

const JsonExample = [];

to format the data in a usable format for ApexCharts

the part of the code causing issues is below:

async function drawChart(labels, chartData, guildNames, yAxisMax) {
  const JsonExample = [];

  for (let i = 0; i < guildNames.length; i++) {
    const chartDataDict = {};
    chartDataDict.name = guildNames[i]; // Add the name field
    const reversedLabels = labels.slice().reverse();
    const data = [];
    for (let j = 0; j < reversedLabels.length; j++) {
      const date = reversedLabels[j];
      const gexp = chartData[i][chartData[i].length - j];
      data.push([date, gexp]);
    }

    chartDataDict.data = data;
    JsonExample.push(chartDataDict);
  }
  // Print the JSON object
  console.log(JsonExample);


  
  
//now to string
console.log(JSON.stringify(JsonExample));
const jsonData = JSON.stringify(JsonExample);

const seriesData = JSON.parse(jsonData).map(guild => {
  let color

    if (guild.name === "Puffy") {
      color = "#BF40BF"; // Bright Purple
  } else if (guild.name === "Lucid") {
      color = "#FFFF00"; // Piss Yellow
  } else if (guild.name === "Rebel") {
      color = "#0000FF"; // Blue
  } else if (guild.name === "Miscellaneous") {
      color = "#008000"; // Green
  } else if (guild.name === "Sailor Moon") {
      color = "#6699CC"; // Bluegrey
  } else if (guild.name === "The Abyss") {
      color = "#808080"; // Grey
  } else if (guild.name === "The Dawns Awakening") {
      color = "#FF0000"; // Red
  } else if (guild.name === "Leman") {
      color = "#FFA500"; // Orange
  } else if (guild.name === "The Blood Lust"){
      color = "#FF2301";
  } else if (guild.name === "Miscellaneous"){
      color = "#587246";
  } else {
    console.log(guild.name)
    color = "#447b40"; // default color
  }

    return {
        ...guild,
        color: color
    };
});

const options = {
    series: seriesData,
    chart: {
        height: 750,
        width: '100%',
        type: 'line',
        zoom: {
            enabled: true,
            type: 'x'
        },
        foreColor: 'white',
        animations: {
            enabled: false,
            easing: 'easeinout',
            speed: 800,
            animateGradually: {
                enabled: true,
                delay: 50
            },
            dynamicAnimation: {
                enabled: true,
                speed: 350
            },
        }
    },
    colors: seriesData.map(series => series.color),
    dataLabels: {
        enabled: false
    },
    stroke: {
        curve: 'smooth',
        width: 2
    },
    title: {
        text: 'Top Guilds',
        align: 'center',
    },
    xaxis: {
        type: 'datetime'
    },
    yaxis: {
        title: {
            text: 'Daily GEXP'
        },
        labels: {
            formatter: (val) => {
                return val.toLocaleString();
            }
        }
    }
};

var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
}

I’ve tried changing the way json is processing the data, this however just caused the guild names, and the data, to mix, causing the last guild to have the first’s data and so on.

How Can I Control the Scroll Speed When Selecting Text Near the Edge of a text box?

I’m working on a webpage where I noticed that when I select some text in a textarea and move my mouse cursor to the top or bottom edge of the textarea, it scrolls up or down automatically. However, the scrolling speed is too fast and makes it difficult to control the selection

Is there a way to reduce the scroll speed when selecting text and moving the cursor to the edge of the texarea?

body {
   height: 2000px;
   padding: 20px;
}
<textarea> Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro quidem magnam corporis itaque sit cupiditate voluptate esse. Voluptatibus ratione sit id doloribus unde dolor repellat sint. Laudantium blanditiis architecto exercitationem </textarea>

Running kiosk-website on Raspberry Pi keeps loading cached (old) videos

I have a Raspberry Pi 4 with Raspberry Pi OS installed. I want to use it as a kiosk-Terminal to display some video that will be updated with new information on a regular base. The video file is stored on a network drive that will be mounted under /mnt/Drive_P/.

It’s working well besides the fact that it keeps showing the same video after a refresh, no matter if I replace the mp4-file or even delete it. It always requires a reboot to actually load the new material!

I have the following shell-script in the autostart:

firefox file:///mnt/Drive_P/Kiosk/VideoViewer.html?"Kiosk/Videos/Test.mp4" -kiosk -new-window

And this is the code of my VideoViewer.html

<!DOCTYPE html>
<html>
<head>
    <title>VideoViewer</title>
    
    <script>
        function BodyOnLoad()
        {
            var URL = location.href;
            var Extension = URL.split("?")[1];
            
            window.setInterval(CheckVideoTimer, 10000);
            document.getElementById("VideoPlayerSourceMP4").src="/mnt/Drive_P/" + Extension;
            document.getElementById("VideoPlayer").addEventListener('ended', VideoEnded, false);
            document.getElementById("VideoPlayer").load();
        }
        
        function VideoEnded(e)
        {
            <!-- Instead of looping the video I want to reload the page so it should load the latest video file again -->
            location.reload();
        }
        
        function CheckVideoTimer()
        {
            var Vid = document.getElementById("VideoPlayer");
            
            if ((Vid.paused && (Vid.duration == Vid.currentTime)) || (Vid.readyState == 0))
            {
                <!-- there is no video-file at the given location, reload and try again -->
                location.reload();
            }
        }
    </script>
</head>

<body onload="BodyOnLoad()">
    <video id="VideoPlayer" width="100%" height="100%" autoplay preload="none">
        <source id="VideoPlayerSourceMP4" src="" type="video/mp4">
        Your browser does not support the video tag.
    </video>
</body>

I found many older threads about reloading a page without cached contents by using “location.reload(true);” but this sadly does not work any longer.

Razor Pay Not Calling CallBack URL Python Django

So basically, razorpay popup is opening, payment being success but the callback url isn’t getting called:

               var options = {
                    "key": data.razorpay_key,
                    "amount": data.amount,
                    "currency": data.currency,
                    "name": "BusinessCard4U",
                    "image": "{{websitelogo.image.url}}",
                    "description": "Payment for digital card subscription",
                    "order_id": data.razorpay_order_id,
                    "callback_url": "{% url 'PaymentSuccess' %}",
                    "handler": function (response){
                        // Handle Razorpay success callback
                    },
                    "theme": {
                        "color": "#5EB9F0"
                    },
                };

This is data i am passing… it has callback url as you can see… but neither anything is getting printed, nor it’s being called.
I tried using redirect: true variable to see if that works but that made the payment failed.

Thank You!