Get Typescript type hierarchy as a string

type Emotion="Excited"|"Disappointed"|"Other"
interface Response{
  summary:Summary
  glossary: Map<string,string[]>
}
interface Summary { 
title:string,
  desc:string,
emotions:Emotion[]
}
hierarchy:string='type Emotion="Excited"|"Disappointed"|"Other";interface Response{  summary:Summary;  glossary: Map<string,string[]>;};interface Summary { title:string;  desc:string;emotions:Emotion[];}'

In the above code, can I generate the hierarchy string programmatically.

I am calling LLMS(llama/GPT4) and getting the response as JSON. I send the type hierarchy to ensure type compliance in my response JSON. Currently, I copy paste my Typescript types into the request manually. Is there anyway to obtain the type hierarchy, including all the enums, types and interfaces, as a string programmatically? I would be ok to get is as part of webpack build phase too.

Print an external page without opening it not working in Firefox

I’m trying to print a PDF document without opening it. I found a guide on MDN that explains how this can be done. In Chrome everything works well, but in Firefox an error occurs (see below).

Partitioned cookie or storage access was provided to
“http://localhost:3000/api/documents/5bf1c493-b8ce-4f82-9ee0-def28065c645/visualization”
because it is loaded in the third-party context and dynamic state
partitioning is enabled.

enter image description here

Storage tab screenshot:

enter image description here

What am I doing wrong?

Error while passing an array of IDs of Items to be deleted to the backend using Axios.delete()

I am trying to delete several Items from a database(mongoose) at once by selecting them and clicking a delete button. I have managed to get from the the database the IDs of each element in the list. I am collecting the IDs of the selected items in the list and storing them in an array called isCHecked but the problem is when I click to delete them at once, I get a AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST' error. I feel the Id is not effectively passed to the backend, please where am I getting it wrong?

here is just the code snippets. Thank you

const StockItems = () => {
    const [stockItemsList, setStockItemsList] = useState([])
    const [showCheckBox, setShowCheckBox] = useState(false)
    const [isCHecked, setIsChecked] = useState([])

    const handlecheckbox=(e)=>{
        const {value, checked} = e.target
        console.log(value)
        if(checked){
           setIsChecked([...isCHecked, value])
        }else
          setIsChecked(isCHecked.filter((e)=> e!==value))

    }

    const deleteAll = async()=>{
        console.log(isCHecked)
         await Axios.delete('http://localhost:3500/newItems', {isCHecked}).then((response) => {
            console.log(response.status)
            console.log(response.data)
        })
        .catch((e) => console.log('something went wrong :(', e));
        //setDeleteMessage(response.data.deleteMessage)
    }
}

//controller code (Backend)
const NewItemsData = require('../models/NewItemsData')
const asyncHandler = require('express-async-handler')

const deleteNewItems = asyncHandler(async (req, res) => { 
    const id = req.body
    console.log(id) // this shows undefined in the console

    if(!id) {
       return res.status(400).json({message: 'Items Id is required'})
    }
    const items = await NewItemsData.findById({_id: {$in: id}}).exec()

    if(!items){
       return res.status(400).json({message: 'Items does not exist'})
    }

     await items.deleteMany()
   // const reply = `Username ${result.username} with ID ${result._id} deleted`
    res.json({message: 'Items has been deleted'})
})

module.exports = {
    deleteNewItems,  
}

//Server
app.use('/newItems', require('./routes/newItemsRoutes'))// a line just to show how my route is mounted in the server

//Routes
const express = require('express')
const router = express.Router()
const newItemsController = require('../contollers/newItemsController')

router.route('/')
      .get(newItemsController.getAllNewItems)
      .post(newItemsController.createNewItems)
      .patch(newItemsController.updateNewItems)
      .delete(newItemsController.deleteNewItems)

Send data to ddatabase by using ajax and php in symfony

  1. twig file:
{% extends 'base.html.twig' %}

{% block content %}
    <!DOCTYPE html>
    <html>
    <head>
        <!-- Dodaj link do jQuery -->
        <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> 
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    </head>
        <h1>Projekcik dla septema</h1>


        <form method="POST" action="{{ path('post') }}" id="postForm">
            Wiadomość:<br>
            <textarea name="wiadomosc" id="wiadomosc" required></textarea><br>
            <input type="submit" value="wyślij" onclick="ajaks(event)">
        </form>
<div id="tableContainer">
    <table style='border: 1px solid black'>
        <tr style='border: 1px solid black'>
            <th>id</th>
            <th>wiadomość</th>
            <th>godzina</th>
            <th>nazwa użytkownika</th>
        </tr>
        
        {% for post in posts %}
            <tr style='border: 1px solid black'>
                <td>{{ post.id }}</td>
                <td>{{ post.text }}</td>
                <td>{{ post.time|date('Y-m-d H:i:s') }}</td>
                <td>{{ post.getUserId().getUsername() }}</td>
            </tr>
        {% endfor %}
    </table>
</div>

    <form method="post" action="{{ path('logout') }}">
        <input type="submit" value="wyloguj">
    </form>

  
    <script>
function ajaks(event){
    event.preventDefault();
let post = {
  text: $("#wiadomosc").val(),
  time: new Date().toISOString(),
  user_id: 1
};
console.log(post);
$.ajax({
  url: "{{ path('post') }}",
  type: "POST",
  data: {
      'post': JSON.stringify(post)
  },
  success: function(response) {
    console.log(response);
  }
});
  } 
</script>
      <script> 
    $(document).ready(function() {
    
        setInterval(refreshTable, 2000);
    });

    function refreshTable() {
        $.ajax({
            url: "{{ path('showTable') }}",  
            type: "GET",
            success: function(data) {
                $('#tableContainer').html(data);
            }
            });
            }
    </script>
</body>
</html>
{% endblock %}
  1. controler:
<?php
// src/Controller/PostController.php


namespace AppPostController;
use AppUserEntityUser;
use AppPostEntityPost;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use AppPostServiceCreatePost;
use SymfonyComponentHttpFoundationSessionSessionInterface;

class PostController extends AbstractController
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    #[Route('/post', name: 'post')]
    public function createPost(Request $request, CreatePost $createPost, SessionInterface $session): Response
    {
        if($session->get('online') === 'false'){
            return $this->render('user/register.html.twig', ['posts' => '']);
        }
    
        $userId = $session->get('user_id');
        $user = $this->entityManager->getRepository(User::class)->find($userId);
       
        if ($user) {
            $data = json_decode($request->getContent(), true);
            $post = $data['post'] ?? null;
            $post = json_decode($post, true); 

            if ($post === null) {
                die('post is null');
            }
         
            var_dump($request->getContent());
    
            if (!isset($post['text'])) {
                die('text is not set in post');
            }
    
            $createPost->create($post['text'], $user);
        }     
    
        return $this->redirectToRoute('show');
    }
    

    

    #[Route('/showTable', name: 'showTable')]
    public function showTable(SessionInterface $session): Response
    {

        if($session->get('online') === 'false'){
        return new Response('');
        }

        $posts = $this->entityManager->getRepository(Post::class)->findAll();

        return $this->render('post/table.html.twig', ['posts' => $posts]);
    }
    
    #[Route('/show', name: 'show')]
    public function showPost(Request $request, CreatePost $createPost,SessionInterface $session): Response
    {
        if($session->get('online') === 'false'){
            return $this->render('user/register.html.twig', ['posts' => '']);
        }
        $posts = $this->entityManager->getRepository(Post::class)->findAll();
     
        return $this->render('post/index.html.twig', ['posts' => $posts]);
    }   

}

i have problem with sending data to database. when i try to send object to my route i got infomation (post is null) but when i wrote my object in twig file before sending everything works. can somebody say what im doing wrong? i tried everything. other functions in my code work without problem. Before when i useed only php to send data everything worked. when i had only web reolading – that worked too.

Not using useEffect Dependencies causing state to not change

I have a question about useEffect and useCallback.

I have react code that will request and load data when you scroll to the bottom of the screen

export default function ImagePage() 
 {

  const [artData, setArtData] = 
  useState([])
  const [isLoading, setIsLoading] = 
  useState(false)
  const [index, setIndex] = 
  useState(2)

  const url = "https://api.artic.edu/api/v1/artworks?page=1&limit=5"

  const fetchData = useCallback(async () => { <---CALLBACK HERE
    if (isLoading) return

    setIsLoading(true)

    axios.get(`https://api.artic.edu/api/v1/artworks?page=${index}&limit=5`)
      .then((res) => {
       setArtData(((prevItems) => [... new Set ([...prevItems, ...res.data.data])]))
       setIndex((prevIndex) => prevIndex + 1) <---CHANGING INDEX 
       setIsLoading(false)
     })
      .catch((err) => {console.log(err)})
     }, [index, isLoading])

  useEffect(() => {
   setIsLoading(true)
   axios.get(url)
    .then((res) => {
      setArtData(res.data.data)
      setIsLoading(false)
      console.log("use effect loaded")
    })
   .catch((err) => {
     console.log(err)})
  }, [])

  useEffect(() => {  <---USE EFFECT IN QUESTION
    const handleScroll = () => {
      const {scrollTop, clientHeight, scrollHeight} = document.querySelector('#image-page-container')
      if (scrollTop + clientHeight >= scrollHeight - clientHeight) {
        console.log("Fetching data")
        console.log(index)
        fetchData()
      }
    }

    document.querySelector('#image-page-container').addEventListener("scroll", handleScroll)

    return () => {
      document.querySelector('#image-page-container').removeEventListener('scroll', handleScroll)
      }
    }, [fetchData]) <--- If i remove "fetchData" the state "index" won't get updated 

My question is…
As you see at the bottom of the code, the final useEffect() is using the fetchData callback as a dependency. If I remove the dependency, the code works fine however the index state does not get updated.
Can anyone shed light of this curious occurance?

What I know
I know the useEffect dependencies are used to decided when the effect is run (if state of dependency changes). However I’m not yet sure how a callBack can change states. This hole in my knowledge may be where the answer to the strange reaction is.

how to resize points in d3.js icosahedron

so i found codepen with the perfect d3 drag rotate animation except that i need points to be smaller.
I don’t understand how do I customize them? I tried to fix size of points by adding a stroke but nothing seems to be working

I use d3.js v5

https://codepen.io/pr0da/pen/OmzKNq

here is CSS styles:

.point {
  fill: #000;
  stroke: #fff;
}

.edge {
  fill: none;
  stroke: #000;
  stroke-opacity: .4;
}

.face {
  fill: #eee;
  fill-rule: nonzero;
}

and d3 script

/**
 * Resources: 
 * https://bl.ocks.org/ivyywang/7c94cb5a3accd9913263
 * https://bl.ocks.org/mbostock/3055104
 * 
 */


var width = 960, height = 500;
var sens = 0.25;
var velocity = [0.18, 0.06];

var projection = d3.geoOrthographic().scale(240);

var path = d3.geoPath().projection({
  stream: function(out) {
    return {
      point: function(x, y) {
        var p = projection([x, y]);
        out.point(p[0], p[1]);
      },
      lineStart: function() {
        out.lineStart();
      },
      lineEnd: function() {
        out.lineEnd();
      },
      polygonStart: function() {
        out.polygonStart();
      },
      polygonEnd: function() {
        out.polygonEnd();
      }
    };
  }
});

var svg = d3
  .select("#root")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var face = svg
  .selectAll(".face")
  .data(icosahedron_faces)
  .enter()
  .append("path")
  .attr("class", "face");

const points = icosahedron_points();
console.log(JSON.stringify(points));
var edge = svg.append("path").datum(icosahedron_edges).attr("class", "edge");

var point = svg.append("path").datum({
  type: "MultiPoint", coordinates: points
}).attr("class", "point");

var dragging = false;
var drag = d3.drag()
  .subject(function() { var r = projection.rotate(); return {x: r[0] / sens, y: -r[1] / sens}; })
  .on("start", () => {
    dragging = true;
  })
  .on("end", () => {
    dragging = false;
  })
  .on("drag", function() {
    var rotate = projection.rotate();
    projection.rotate([d3.event.x * sens, -d3.event.y * sens, rotate[2]]);
    refresh();
  });
svg.call(drag);

d3.timer(function(elapsed) {
  if(!dragging) {
    const r = projection.rotate();
    projection.rotate([r[0] + velocity[0], r[1] + velocity[1]]);
    refresh();
  }
});

function refresh() {
  point.attr("d", path);
  edge.attr("d", path);
  face.attr("d", path);
}

function icosahedron_points() {
  var points = [], y = Math.atan2(1, 2) * 180 / Math.PI;
  points.push([0, -90]);
  for (var x = 0; x < 360; x += 36) {
    points.push([x, -y], [(x += 36), y]);
  }
  points.push([0, 90]);
  return points;
}

function icosahedron_edges() {
  var edges = [], y = Math.atan2(1, 2) * 180 / Math.PI;
  for (var x = 0; x < 360; x += 72) {
    edges.push([[x + 0, -90], [x + 0, -y]]);
    edges.push([[x + 0, -y], [x + 72, -y]]);
    edges.push([[x + 36, y], [x - 36, y]]);
    edges.push([[x + 36, y], [x + 0, -y]]);
    edges.push([[x - 36, y], [x + 0, -y]]);
    edges.push([[x + 36, 90], [x + 36, y]]);
  }
  console.log(JSON.stringify(edges));
  return { type: "MultiLineString", coordinates: edges };
}

function icosahedron_faces() {
  var faces = [], y = Math.atan2(1, 2) * 180 / Math.PI;
  for (var x = 0; x < 360; x += 72) {
    faces.push([[[x + 0, -90], [x + 0, -y], [x + 72, -y], [x + 0, -90]]]);
    faces.push([[[x + 0, -y], [x + 72, -y], [x + 36, y], [x + 0, -y]]]);
    faces.push([[[x + 36, y], [x + 0, -y], [x - 36, y], [x + 36, y]]]);
    faces.push([[[x - 36, 90], [x - 36, y], [x + 36, y], [x + 36, 90]]]);
  }
  return faces.map(function(face) {
    return { type: "Polygon", coordinates: face };
  });
  ///
}

React function doesn’t construct correct array

I’m experiencing some weird behavior in my code.

I have the following function:

const generateDefaultDataForModel = (data: any) => {
        const numBlocks = data && Object.keys(data).length > 0 ? data[Object.keys(data)[0]].length : 3;
        console.log("numBlocks", numBlocks);

        const defaultWeight = 1 / Object.keys(originalWeights).length;
        console.log("defaultWeight", defaultWeight);

        const defaultData = Array.from({ length: numBlocks }, () => [defaultWeight, true]);
        console.log("defaultData", defaultData);

        const test = Array.from({ length: numBlocks }, () => [defaultWeight, true]);    
        console.log("test", test);

        return test;
    };

Basically the idea is that it creates some default data for me to use. When I run this via an onClick event I can see the console outputs which in the first one (numBlocks) gives me 3. defaultWeight gives me 0.9. However, when I try to create defaultData I jsut get an array like: [[0, true], [0, true], [0, true]].

However, in the next line with test I do the exact same thing, but t hat output is: [[0.9, true], [0.9, true], [0.9, true]]

At first I thought I had a reused variable name, but no. Even if I change the name defaultData to something weird, same thing happens. If I then comment out the defaultData line, then test doesn’t output the correct data any more.

Even if I hardcode the value of numBlocks and defaultWeight I get the same issue.

I have no idea what is going on. It seems like it should be so simple, but it’s giving me a bit of a head scratch right now.

What am I doing wrong here?

Upload a file to temporary folder with a Yesod application: encoding issue

I’m trying to do a Yesod web app allowing to upload a file and to save it in the temporary folder. I’m using Base64 encoding/decoding. When I upload a text file with this content:

copie carte d'identité
téléphone
autocertfication fiscale
signature

then the content of the file I get in the temporary folder is:

u«Zµìmþ™ZŠvÚ±î¸copie carte d'identité
téléphone
autocertfication fiscale
signature

The input file is UTF8-encoded.

Here is how I handle the file upload with JavaScript:

$("#file").on("change", function() {
    let file = this.files[0];
    let fileReader = new FileReader(); 
    fileReader.readAsDataURL(file);
    fileReader.onload = function() {
        let base64 = fileReader.result;
        $.ajax({
            contentType: "application/json",
            processData: false,
            url: "@{FileR}",
            type: "PUT",
            data: JSON.stringify({
                _filename: file.name, 
                _base64: base64
            }),
            success: function(result) {
                // not important
            },
            dataType: "text"
        });
    }; 
    fileReader.onerror = function() {
        alert(fileReader.error);
    }; 
});

In Haskell, I have:

import qualified Data.ByteString as B
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as BC
import System.IO.Temp ( getCanonicalTemporaryDirectory )

base64ToFile :: String -> FilePath -> IO FilePath
base64ToFile b64string fileName = do
    let bstring = B64.decodeLenient (BC.pack b64string)
    tmpDir <- getCanonicalTemporaryDirectory
    let filePath = tmpDir ++ "/" ++ fileName
    B.writeFile filePath bstring 
    return filePath

data File = File {
    _filename :: String,
    _base64   :: String
} deriving (Show, Generic)

instance FromJSON File

b64FileToFile :: File -> IO FilePath
b64FileToFile file = base64ToFile (_base64 file) (_filename file)

putFileR :: Handler String
putFileR = do
    file <- requireCheckJsonBody :: Handler File
    liftIO $ b64FileToFile file 

I don’t know where is the source of the issue, whether this is in the JavaScript step or in the Haskell step. I want to be able to upload a text file, a CSV file, a XLSX file, or an image file.

cut and paste a image file and upload it on form submit

I have code whereby I cut and paste an image in a div and it will upload the the image and store the file in a directory. I tried to change my code to upload the cut and paste file data on submit.

readastext seems to store the data in the hidden field. it also transfers the data on submit to the php file processor but no file is being created in the target directory. What am I doing wrong?

$(document).ready(function() {
  $('#pasteTarget').on('paste', function(e) {
    e.preventDefault();
    var data = e.originalEvent;
    
    if (data.clipboardData && data.clipboardData.items) {
      var items = data.clipboardData.items;
      for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          var file = items[i].getAsFile();
          var reader = new FileReader();
          reader.onload = function() {
            $("<input>").attr("type", "hidden").attr("name", "file[]").appendTo("form").val(reader.result);
          };
          reader.readAsText(file);
        }
      }
    }
  });
  
  $('#subfile').on('click', function(e) {
    var form = $('form')[0];
    var data = new FormData(form);
    
    $.ajax({
      type: "POST",
      url: 'postfileuploader.php',
      data: data,
      contentType: false,
      processData: false,
      cache: false,
      success: function(result) {
        console.log(result);
      },
      error: function(error) {
        console.log(error);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div style="width: 200px; height: 200px; background: grey" id="pasteTarget">
    Click and paste here.
  </div>
  <button type="button" name="sub" id="subfile" class="btn btn-primary">Create Tasks</button>
</form>

How to select HTML elements with document.getSelection() in JavaScript,

let selection =document.getSelection();
let cloned = selection.getRangeAt(0);
for(let i =0; i <selection.rangeCount; i++) { cloned.append(selection.getRangeAt(i).cloneContents());}

Whenever, I tried to select multiple Html elements, it gives me whole body as selection.

    const handleFormatBlock = (action: any): any => {
        const iframeDoc = _editorRef.current.contentWindow.document;
        const selection = iframeDoc.getSelection();
        if (!(selection && selection.rangeCount > 0)) {
            return;
        }
        const range = selection.getRangeAt(0);
        const fragment = document.createDocumentFragment();
        let returnFragment;
        console.log(range);
        // For multiple selection
        if (range.commonAncestorContainer.childNodes.length > 1) {
            console.log('multiple selection');
            const nodes = Array.from(range.commonAncestorContainer.children);
            const cloneNodes = Array.from(range.cloneContents().children);
            const selectedNodes = nodes.filter((node: any) => cloneNodes.some((cloneNode: any) => node.textContent === cloneNode.textContent));
            console.log(selectedNodes, 'selected nodes');
            selectedNodes.forEach((node: any) => {
                console.log(node);
            });
            range.deleteContents();
            range.insertNode(returnFragment)
        }

JS and / or expression [closed]

prompt('Enter:') == '1' || == '2' ? alert('One or two') : alert('Wrong');

I can’t get the results I want. Look at this expression and find the errors. The output from user input must be processed in a ternary operator.//

Javascript – Remplir formulaire – Problème avec select event “change” [closed]

Automatisation du Remplissage de Formulaire : Le script permet de remplir automatiquement un formulaire web en lisant les données d’un fichier CSV. Il est particulièrement utile pour les tâches répétitives où de nombreuses données doivent être saisies manuellement dans un formulaire.
Structure et Fonctions du Code
Initialisation et Gestion des Événements

Chargement du Document : Le script attend que le document complet soit chargé (DOMContentLoaded).
Sélection de Fichier CSV : L’utilisateur peut sélectionner un fichier CSV via un champ de type input. Le nom du fichier sélectionné est affiché.
Chargement des Données CSV : Un bouton permet de charger et de lire le contenu du fichier CSV sélectionné.
Traitement des Données CSV

Lecture et Division des Données : Les données du fichier CSV sont divisées en lignes et colonnes.
Affichage des Données : Les données sont affichées dans une table HTML avec des en-têtes de colonnes et des boutons “Remplir” pour chaque ligne.
Remplissage Automatique du Formulaire

Bouton Remplir : Chaque ligne de la table a un bouton “Remplir” qui, lorsqu’il est cliqué, déclenche le remplissage automatique du formulaire associé avec les données de cette ligne.
Fonction fillMultipleInputsWithXPath : Cette fonction utilise l’API chrome.tabs pour exécuter des scripts dans l’onglet actif, ce qui permet de cibler les éléments du formulaire via XPath et de remplir leurs valeurs.
Fonction de Remplissage

fillInput : Une fonction dédiée pour remplir chaque élément du formulaire. Elle cible les éléments en fonction de leur XPath, met à jour leur valeur et déclenche un événement “change” pour s’assurer que tous les gestionnaires d’événements JavaScript liés sont exécutés.
Points Techniques Clés
Utilisation de l’API Chrome :
Le script exploite les capacités des extensions Chrome pour interagir avec les contenus des onglets.
Manipulation du DOM : Le script manipule le DOM pour afficher les données et gérer les interactions utilisateur.
Gestion des Événements : Les événements “change” sont déclenchés pour garantir la compatibilité avec la logique JavaScript existante du formulaire.
Sélecteurs XPath : Le script utilise des XPath pour identifier de manière précise les éléments du formulaire à remplir.

    document.getElementById('csvFile').addEventListener('change', function() {
        let fileName = this.files[0].name;
        document.getElementById('fileNameLabel').textContent = fileName;
    });

    document.getElementById('loadCSV').addEventListener('click', function() {
        const csvFileInput = document.getElementById('csvFile');
        const file = csvFileInput.files[0];

        if (file) {
            const reader = new FileReader();

            reader.onload = function(event) {
                const csvData = event.target.result;
                storeCSVInArrays(csvData);
            };
            reader.readAsText(file, 'UTF-8');
        } else {
            alert('Veuillez sélectionner un fichier CSV.');
        }
    });
});

function storeCSVInArrays(data) {
    const rows = data.split('n');
    const table = document.getElementById('csvDataTable');
    const thead = table.querySelector('thead');
    const tbody = table.querySelector('tbody');

    thead.innerHTML = ''; // Clear previous headers
    tbody.innerHTML = ''; // Clear previous data rows

    // Add column headers (only the first 12)
    const headers = rows[0].split(',').slice(0, 12);
    const trHead = document.createElement('tr');

    const actionTh = document.createElement('th');
    actionTh.textContent = "Action";
    trHead.appendChild(actionTh);

    headers.forEach(header => {
        const th = document.createElement('th');
        th.textContent = header;
        trHead.appendChild(th);
    });
    thead.appendChild(trHead);

    for (let i = 1; i < rows.length; i++) {
        const columns = rows[i].split(',').slice(0, 12);
        const tr = document.createElement('tr');

        const actionTd = document.createElement('td');
        const fillButton = document.createElement('button');
        fillButton.className = "button is-small is-primary";
        fillButton.textContent = "Remplir";
        fillButton.addEventListener('click', function() {
            const xpaths = [
                "/html/body/div/div/div/div[4]/div/form[1]/fieldset/div/div/div/div/div/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div/select",
                "/html/body/div/div/div/div[4]/div/form[1]/fieldset/div/div/div/div/div/div[1]/div[2]/div[1]/div[1]/div[2]/div[2]/div/input",
                "/html/body/div/div/div/div[4]/div/form[1]/fieldset/div/div/div/div/div/div[1]/div[2]/div[1]/div[1]/div[3]/div[2]/div/input",
                "/html/body/div/div/div/div[4]/div/form[1]/fieldset/div/div/div/div/div/div[1]/div[2]/div[1]/div[1]/div[4]/div[2]/div/input",
                "/html/body/div/div/div/div[4]/div/form[1]/fieldset/div/div/div/div/div/div[1]/div[2]/div[1]/div[2]/div[1]/div[2]/div/input",
                "/html/body/div/div/div/div[4]/div/form[1]/fieldset/div/div/div/div/div/div[1]/div[2]/div[1]/div[2]/div[2]/div[2]/div/select",
                "/html/body/div/div/div/div[4]/div/form[1]/fieldset/div/div/div/div/div/div[1]/div[2]/div[1]/div[2]/div[3]/div/div[2]/div/input"
            ];
            fillMultipleInputsWithXPath(xpaths, headers, columns);
        });
        actionTd.appendChild(fillButton);
        tr.appendChild(actionTd);

        columns.forEach(column => {
            const td = document.createElement('td');
            td.textContent = column;
            tr.appendChild(td);
        });
        tbody.appendChild(tr);
    }
}

function fillMultipleInputsWithXPath(xpaths, headers, dataColumns) {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        let tabId = tabs[0].id;
        for (let i = 0; i < xpaths.length; i++) {
            chrome.scripting.executeScript({
                target: { tabId: tabId },
                func: fillInput,
                args: [xpaths[i], headers[i], dataColumns[i]]
            });
        }
    });
}


function fillInput(xpath, header, data) {
    const element = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    if (element) {
        element.value = data; // Mise à jour de la valeur

        // Déclencher un événement "change"
        if ('createEvent' in document) {
            var evt = document.createEvent('HTMLEvents');
            evt.initEvent('change', false, true);
            element.dispatchEvent(evt);
        } else {
            element.fireEvent('onchange');
        }
    }
}

Le formulaire se rempli correctement mais quand je clique sur le bouton valider, les 2 champs select se vide et on me demande de les remplir, c’est comme si l’évènement “change” n’avait pas été prit en compte, c’est dans la fonction fillInput que tout se passe.

Is it possible to get higher-level information from DeviceMotionEvent?

total noobie on the topic, and not very good in physics, so have mercy.

I’m looking to use DeviceMotionEvent’s acceleration and rotationRate info to control events appearing on the phone’s screen in a browser environment.

For example: make the screen go red when the phone is suddenly stopped (decelerated).

How would I use the acceleration data to do that? are there libraries that simplify the job of de-fluttering the data and firing events base on thresholds (like the one above)?

I’ve googled around but there seems not to be much on the topic.