Formatting CSV Data for chart.js: How to Create a JavaScript Data Structure from CSV File

I have a CSV file named data.csv with the following content:

data.csv:

time,voltage
0.0,20
0.2,1
0.3,15
0.4,2
0.5,31
0.6,11

I want to create a JavaScript data structure from this CSV data and store it in a variable. The desired data structure should look like this:

Desired Data Structure:

[
 { x: 0.0, y: 20 },
 { x: 0.2, y: 1 },
 { x: 0.3, y: 15 },
 { x: 0.4, y: 2 },
 { x: 0.5, y: 31 },
 { x: 0.6, y: 11 }
]

How can I achieve this in JavaScript?


I specifically need this data structure for creating a chart using the chart.js library. If anyone has experience or examples with parsing CSV data into a suitable format for chart.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    
    <canvas id="chart" width="1920" height="1080"></canvas>
    
    <script>
        
        

        const ctx = document.getElementById('chart').getContext('2d');
        
        

        const chart = new Chart(ctx, {
              type: 'line',
              data: {
                        datasets: [
                                      {
                                        yAxisID: 'yA',
                                        label: 'Temperature',
                                        data: [
                                              { x: 0.05, y: 12 },
                                              { x: 0.15, y: 19 },
                                              { x: 0.25, y: 3 },
                                              { x: 0.35, y: 5 },
                                              { x: 0.45, y: 2 },
                                              { x: 0.55, y: 3 },
                                              ],
                                      },
                                      {
                                        yAxisID: 'yB',
                                        label: 'Voltage',
                                        data: [
                                              { x: 0.0, y: 20 },
                                              { x: 0.2, y: 1 },
                                              { x: 0.3, y: 15 },
                                              { x: 0.4, y: 2 },
                                              { x: 0.5, y: 31 },
                                              { x: 0.6, y: 11 },
                                              ],
                                      }
                                ]
                    },
              options: {
                        responsive: true,
                  
                            scales: {
                                
                                      yA:   {
                                            type: 'linear',                                    
                                            position: 'left',
                                            ticks: { beginAtZero: true, color: 'blue' },
                                            grid: { display: false },
                                            borderWidth: 1,
                                            pointStyle: 'circle',
                                            //backgroundColor: 'blue',
                                            borderColor: 'blue',
                                            tension: 0,
                                            },
                                
                                      yB:   {
                                            type: 'linear',
                                            position: 'left',
                                            ticks: { beginAtZero: true, color: 'green' },
                                            grid: { display: false },
                                            borderWidth: 1,
                                            pointStyle: 'circle',
                                            //backgroundColor: 'green',
                                            borderColor: 'green',
                                            tension: 0,
                                            },
                                
                                      x:    { 
                                            ticks: { beginAtZero: true },
                                            type: 'linear',
                                            }
                                
                                    }
                        }
            });
     


        
    </script>
    
</body>
</html>

Mapbox satellite map is out-of-date [closed]

We’re facing an issue where the Mapbox satellite map is out-of-date.

I’m using this lat/lng as the point of interest here 13.634956, 100.591961.

If you check Google Maps, you’ll see that there is a new building here. However, on the Mapbox’s map, the building is still inprogress. We can access the Mapbox’s map with satellite style here https://docs.mapbox.com/mapbox-gl-js/example/setstyle/.

The point of interest in Google Maps

Now the same building, but on MapBox

There is really nothing I can try, I thought the issue is from my website using an old version of Mapbox’s JS SDK. But it’s not the case once I found out that on the URL https://docs.mapbox.com/mapbox-gl-js/example/setstyle/, it also has the out-of-date map data.

Is it Possible to Download Excel File from Tabulator Filling a Template?

Hello Stack Overflow Community,

I’m currently working with Tabulator, a fantastic grid library for interactive tables, and I’ve encountered a challenge that I’m hoping to get some insights on.

I’m aware that Tabulator allows for the export of table data to various formats, including Excel. However, my requirement is a bit more specific. I need to download table data into an Excel file, but instead of exporting it as a standard Excel file, I want to fill a pre-defined Excel template with this data. Essentially, the data from Tabulator should populate specific cells or ranges in an already formatted Excel template.

Here’s a brief outline of what I’m trying to achieve:

  • Pre-Existing Excel Template: I have an Excel template with specific
    formatting, formulas, and predefined headers.
  • Tabulator Table Data: My web application generates dynamic data
    displayed in a Tabulator table.
  • Desired Outcome: On triggering an export action, the data from the
    Tabulator table should be exported into the Excel template,
    populating specific areas of the template while preserving the
    original formatting and formulas.

I’m not sure if this functionality is natively supported in Tabulator or if there are known workarounds or plugins that can achieve this. My main questions are:

  • Is it possible to directly export Tabulator data into a pre-formatted Excel template?
  • If direct export is not possible, would be possible to export the data to a separate sheet where the cell values are linked to the pre-formatted Excel sheet?
  • If both of this solution are not available, what would be the best approach to achieve this functionality?

Any guidance, advice, or references to relevant documentation would be greatly appreciated. I’m open to creative solutions or alternative approaches if direct export to a template is not feasible.

Thank you in advance for your assistance!

Implementing Automated Web Interaction with Java Backend and Angular/ReactJS Frontend using playwright or any other tool

I’m currently working on a project where I need to automate a specific web interaction. The process I envision is as follows: a user clicks a button on a webpage, which triggers a script that automatically opens another webpage, logs in, and performs a specific task.

My backend is built with Java, and the frontend is developed using either Angular or ReactJS. I am seeking advice or suggestions on how to implement this functionality using these technologies. Specifically, I am interested in any frameworks, libraries, or strategies that would allow for this kind of automated web interaction directly from the user’s action (like a button click) in a web application.

Has anyone here implemented something similar or can provide guidance on how to approach this? Any insights or examples would be greatly appreciated!

Thank you in advance for your help!

At the moment, we achieve this functionality using a Jenkins server with a Playwright script. However, I’m looking for a different approach. Ideally, I would like to inject JavaScript or playwright that can automatically carry out the desired tasks without relying on the current method.

RegEx assistance for CMS custom widget

Lemme just get this out in the open, my RegEx knowledge is dire, when I need it, I tend to find solutions through Google, test them in a helper and hope for the best.

So, I have a site that uses a markdown based CMS, the CMS was formerly Netlify CMS and it is now Decap CMS. In the config.yml files I can create custom widgets to add custom “Blocks” to the CMS editor for team mates and myself. I’ve created several of these widgets, which extend the CMS to our needs. They work absolutely fine for the most part, we use Eleventy and the markdown generated by the CMS is processed.

The issue I have is related to my poor RegEx skills. When a user uses one of the custom widgets I created, what appears visually is a grey block, with the appropriate number of inputs for that particular widget. As an example, for our accordion widget there are 3 inputs:

  • The first allows a user to select the heading level of the accordion,
    between 2 & 6, this is a number
  • The second is for the accordion title (the text that will be in the
    button) and this is a string
  • The third is for the contents, the contents will be Markdown,
    which is obviously later processed by Eleventy into HTML, it can
    contain code blocks, text formatting, images and other standard
    stuff

That visible grey block is important for non-devs, as it shows it is a block and they can’t accidentally break the HTML. When a user saves a post and revisits later, in the editor what we see is the raw HTML, as opposed to the grey block with the inputs.

The reason the above is happening is React is used for the CMS, when a user revisits a post, React is parsing the contents of the editor and applying these blocks to widgets (there are default widgets such as image and code block etc), the default widgets get the block, my widgets get the raw HTML and the reason for this is my RegEx string is required for the parser to detect some specific HTML and present it as a block after a reload event.

The HTML is very basic, the accordions are progressively enhanced so don’t worry about how they appear here, they work perfectly in the browser, the HTML is as follows:

<h2 class="accordion"></h2>
<div class="accordion__panel">

</div>
  • That heading level can be any HTML heading other than 1, so 2-6
  • The heading of any level must have a class of accordion
  • Within the heading tags, allow the string of text

Then:

  • A div is present and that div must have the class of accordion__panel
  • Then there is a new line
  • Then allow any content
  • Then a new line
  • Then a closing div tag

What I have thus far, from winging it with various helpers and what not is the following:

<h[2-6].*class="accordion".*>.*</h[2-6]>n<div class="accordion__panel">n.*</div>/ms

This appears to be working OK, using RegEx tools for testing, but I’m not confident I have successfully winged my way through this, without issue and wondered if any kind folks here could give me any help on improving it or confirming it’s good?

Thanks

Electron auto-updates not working on MacOS if app is not installed in Applications directory

I am using the auto-updater module from Electron framework to implement auto updates for my Electron application on MacOS. The updates succeed only if the app is installed in Applications folder. If it is installed somewhere else, the updates do not work. I am using the implementation detailed here- https://github.com/electron/electron/issues/5020#issuecomment-477636990. The download succeeds but the app doesn’t update on relaunch.

Can someone help me with why this is happening and how to fix this.

mat-select and mat-dialog flickers on android device – Ionic 7 and angular 17

I am currently working on ionic project and used a angular framework but somehow mat-select and mat-dialog which is flickers fraction of seconds. as you can see in attachment.

Ionic 7 & Angular 17 dependecies:

"dependencies": {
    "@angular/animations": "^17.0.2",
    "@angular/cdk": "^17.0.4",
    "@angular/common": "^17.0.2",
    "@angular/compiler": "^17.0.2",
    "@angular/core": "^17.0.2",
    "@angular/forms": "^17.0.2",
    "@angular/material": "^17.0.4",
    "@angular/platform-browser": "^17.0.2",
    "@angular/platform-browser-dynamic": "^17.0.2",
    "@angular/router": "^17.0.2",
    "@capacitor/android": "5.6.0",
    "@capacitor/app": "5.0.6",
    "@capacitor/browser": "^5.1.0",
    "@capacitor/core": "5.6.0",
    "@capacitor/device": "^5.0.6",
    "@capacitor/haptics": "5.0.6",
    "@capacitor/keyboard": "5.0.7",
    "@capacitor/network": "^5.0.6",
    "@capacitor/preferences": "^5.0.6",
    "@capacitor/share": "^5.0.6",
    "@capacitor/status-bar": "5.0.6",
    "@ionic/angular": "^7.0.0",
    "chart.js": "^4.4.1",
    "chartjs-plugin-datalabels": "^2.2.0",
    "ionicons": "^7.0.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.2"
  }

global.scss

/* Basic CSS for apps built with Ionic */
@import "@ionic/angular/css/normalize.css";
@import "@ionic/angular/css/structure.css";
@import "@ionic/angular/css/typography.css";
@import "@ionic/angular/css/display.css";

/* Optional CSS utils that can be commented out */
@import './assets/fonts/icons/material-icon.scss';
@import "@ionic/angular/css/padding.css";
@import "@ionic/angular/css/float-elements.css";
@import "@ionic/angular/css/text-alignment.css";
@import "@ionic/angular/css/text-transformation.css";
@import "@ionic/angular/css/flex-utils.css";
@import "@angular/material/prebuilt-themes/indigo-pink.css";

Current Result:
Android Real Device behaviour

Have tried to set z-index for below class in global.scss

@import "@angular/material/prebuilt-themes/indigo-pink.css";


.cdk-global-overlay-wrapper,
.cdk-overlay-container {
    z-index: 99999 !important;
}

But nothing is working in real device.

Any help would be appreciated.

Djang/websocket not sending messages

i’m using django and daphne and websocket to make a chat room by following a tutorial on youtube..everything worked fine , but when i send the message it does’nt show the message in the screen….it does not show any errors in the server side ..but shows 2 warniings and one error in the browser console

im intermediate in django but completely new to web sockets

Here’s my script tag:

{% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }}
{{ request.user.username|json_script:"json-username"}}
<script>
  const roomName = JSON.parse(
    document.getElementById("json-roomname").textContent
  );
  const usrName = JSON.parse(
    document.getElementById("json-username").textContent
  );

  const chatSocket = new WebSocket(
    "ws://" + window.location.host + "/ws/" + roomName + "/"
  );

  chatSocket.onmessage = function (e) {
    console.log("onemssage");
    const data = JSON.parse(e.data);

    if (data.message) {
      let html = '<div class="p-4 bg-gray-200 rounded-xl">';
      html += '<p class="font-semibold">' + data.username + "</p>";
      html += "<p>" + data.message + "</p></div>";

      document.querySelector("#chat-messages").innerHTML += html;
    } else {
      alert("The message was empty!");
    }
  };

  chatSocket.onclose = function (e) {
    console.log("onclose", e);
  };

  document
    .querySelector("#chat-message-submit")
    .addEventListener("click", function (e) {
      e.preventDefault();
      const messageInputDom = document.querySelector("#chat-message-input");
      const message = messageInputDom.value;

      chatSocket.send(
        JSON.stringify({
          message: message,
          username: usrName,
          room: roomName,
        })
      );

      messageInputDom.value = "";

      return false;
    });
</script>

here’s my python file:

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name



        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()
    
    async def disconnect(self,close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name

        )
    
    async def recieve(self,text_data):
        data = json.loads(text_data)
        message = data['message']
        username = data['username']
        room = data['room']

        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type':'chat_message',
                'message': message,
                'username':username,
                'room':room,
            }
        )

    async def chat_message(self,event):
        message = event['message']
        username = event['username']
        room = event['room']


        await self.send(text_data=json.dumps({
            'message': message,
            'username':username,
            'room':room,
        }))

here’s routing.py:

from django.urls import path

from . import consumers

websocket_urlpatterns =[
    path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()),
]

I want the message to be sent, when hitting the send button

D3.js path styles strokeDasharray

an array with objects arrives

let data = [{
  id: 1,
  times: [7619846500000, 7619860000000,7619873600000,7619887200000],
  values: [14.725565836745528, 14.725565836745529, 14.72556583674553],
  dashtime:[7619873600000]
},{
    id: 2,
    times: [7619846400000, 7619850000000,7619853600000,7619857200000,7619860800000],
    values: [14.725565836745528, 14.725565836745529, 14.72556583674553,14.72556583674553],
    dashtime:[7619853600000]
  }];

using the dAttributeGenerator function, the result is converted to d and passed to Path

const attributes = data.map((signal, signalIndex) => {
const X = signal?.times;
const Y = signal?.values;
const I = d3.range(X?.length);

const dAttributeGenerator = d3
  .line()
  .x((i) => xScale(X[i]))
  .y((i) => (yAxisCount !== 1 ? yScales[0](Y[i]) : yScales[0](Y[i])));
 
  const d = dAttributeGenerator(I)
  return d})

  <Path
    d={d}
    fill={"none"}
    stroke={'blue'}
    strokeDasharray={"3"}
    style={{ transition: hasTransition ? "all 0.7s" : "" }}
   />

the task is that if the point by timestamp is before the value of dashtime, then it is drawn with strokeDasharray={“0”}, if the point is equal to dashtime or greater, then strokeDasharray={“3”}

expected result
enter image description here

Plotting Two Datasets in One Chart with two y-axes Using the Library chart.js

I wrote the following CODE using the chart.js library, which generates the OUTPUT displayed below. I’m seeking guidance on how to effectively control the labels on the horizontal axis.

CODE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    
    <canvas id="chart" width="1920" height="1080"></canvas>
    
    <script>
        
        const ctx = document.getElementById('chart').getContext('2d');

        const chart = new Chart(ctx, {
              type: 'line',
              data: {
                datasets: [
                  {
                    yAxisID: 'yA',
                    label: 'Data1',
                    data: [
                          { x: 0.05, y: 12 },
                          { x: 0.15, y: 19 },
                          { x: 0.25, y: 3 },
                          { x: 0.35, y: 5 },
                          { x: 0.45, y: 2 },
                          { x: 0.55, y: 3 },
                          ],
                  },
                  {
                    yAxisID: 'yB',
                    label: 'Data2',
                    data: [
                          { x: 0.1, y: 20 },
                          { x: 0.2, y: 1 },
                          { x: 0.3, y: 15 },
                          { x: 0.4, y: 2 },
                          { x: 0.5, y: 31 },
                          { x: 0.6, y: 11 },
                          ],
                  }
                ]
              },
              options: {
                        responsive: true,
                            scales: {
                                      yA: {
                                        type: 'linear',
                                        position: 'left',
                                        ticks: { beginAtZero: true, color: 'blue' },
                                        grid: { display: false }
                                      },
                                      yB: {
                                        type: 'linear',
                                        position: 'left',
                                        ticks: { beginAtZero: true, color: 'green' },
                                        grid: { display: false }
                                      },
                                      x: { ticks: { beginAtZero: true }}
                                    }
                        }
            });
        
    </script>
    
</body>
</html>

OUTPUT

enter image description here

I attempted to plot two datasets in a single Chart.js chart using the provided code. I expected both datasets to be clearly visualized on the chart.


CODE and OUTPUT using the comment from @haard:

enter image description here

Higlight text from XPointer

I’m looking for a way to highlight text segments from a kind XPointer, consisting of an XPath expression, an offset and a string length.

I’ve built a small module with XForms for indexing web page content for scholar purpose. This module allows me to save the XPointer of a selection, but now I’d like to be able to do the reverse, in order to visualize segments that have already been indexed.

Here’s a small example of what I was able to achieve (but it doesn’t work as expected):

  • Simple case, XPointer matches just text, works only once
  • Advenced case, XPointer matches mixed content, or content running over multiple paragraphs, doesn’t work at all

As you can see, I’m not a JS guy and any help would be appreciated !

Best,
Josselin

<h1>Highlight</h1>
<h2>Simple case (works once...)</h2>
<button onclick="showEntry('//p[1]', 0, 3)">Push me to highlight</button>

<p>just plain text, no mixed content</p>

<h2>advanced case (doesn't work as expected)</h2>
<button onclick="showEntry('//p[2]', 2, 35)">Push me to highlight</button>
<p>With <i>mixed</i> content and text...</p>
<p>...running over more than one paragraph</p>
function showEntry(xpath, offset, length) {
   var element = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   if (element !== null) {
      console.log(element);
      element.scrollIntoView();
      
      var str = element.innerHTML;
      str = 
        str.substr(0, offset) +
        '<span class="showEntry">' + 
        str.substr(offset, length + 1) +
        '</span>' +
        str.substr(length + 1);
      element.innerHTML = str;
   }
};

Here’s a small example of what I was able to achieve (but it doesn’t work as expected):

  • Simple case, XPointer matches just text, works only once
  • Advenced case, XPointer matches mixed content, or content running over multiple paragraphs, doesn’t work at all

NB: the solution needs to be only JS…

As you can see, I’m not a JS guy… and any help would be appreciated! Thank you!
Best,
Josselin

<h1>Highlight</h1>
<h2>Simple case (works once...)</h2>
<button onclick="showEntry('//p[1]', 0, 3)">Push me to highlight</button>

<p>just plain text, no mixed content</p>

<h2>advanced case (doesn't work as expected)</h2>
<button onclick="showEntry('//p[2]', 2, 35)">Push me to highlight</button>
<p>With <i>mixed</i> content and text...</p>
<p>...running over more than one paragraph</p>
function showEntry(xpath, offset, length) {
   var element = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   if (element !== null) {
      console.log(element);
      element.scrollIntoView();
      
      var str = element.innerHTML;
      str = 
        str.substr(0, offset) +
        '<span class="showEntry">' + 
        str.substr(offset, length + 1) +
        '</span>' +
        str.substr(length + 1);
      element.innerHTML = str;
   }
};

See on Codepen

The minimum size of the angular main component

I am using Angular 17. I was wondering if there is a simple way of setting up minimum size of the main angular component (usually called AppComponent). I would like to restrict the user from scaling down my main component to the certain size so my components still look recognizable.

Different hashes on the client

I’ve never had to use such a design on a client before, so I’m asking for help. The problem is the following, who did the md5 base64 hash comparison of the file when uploading and downloading? client + .net. Hash on the backend: 1B2M2Y8AsgTpgAmY7PhCfg==. The problem is with the client, because s3 considers the same hash I get different hashes:

.net

var md5 = MD5.Create();
md5Hash = Convert.ToBase64String(md5.ComputeHash(fileStream));

Angular

  private handleFile(event: any) {
    const files = event.target.files;
    const file: File = files[0];
    let reader = new FileReader();
    reader.onload = (e) => {
      const fileContent = e.target?.result as ArrayBuffer;
      const wordArray = CryptoJS.lib.WordArray.create(fileContent);
      const hash = CryptoJS.MD5(wordArray).toString(CryptoJS.enc.Base64);
      console.log(hash);
    };
    // reader.addEventListener(
    //   'load',
    //   () => {
    //     this.logMd5(reader.result);
    //   },
    //   false
    // );
    reader.readAsArrayBuffer(file);
  }

  private logMd5(blob) {
    const hash = CryptoJS.MD5(blob);
    const md5 = hash.toString(CryptoJS.enc.Base64);
    this.md5 = md5;
  }

Stackblitz

The file to check

Bar Chart Left to right swoop in animation

I am not able to disable the swoop in left to right animation on multiple bar chart.
I want only the growing (Down to up) animation and disable the swoop in left to right .
And I use ApexChart Library for bar chart.

enter image description here
enter image description here

I have been exploring the ApexCharts documentation and tried to modify the animation options, but I couldn’t find a way to disable this specific animation. My goal is to display the charts with an animation that only allows the bars to grow vertically. I want to completely disable the horizontal ‘swoop’ animation.