Why the command “npm start” doesn’t work on my Electron framework project?

I’ve made a simple notes app using HTML, CSS and Javascript, and now i want to turn it into a desktop application, i’m using the Electron framework to achieve it, but for some reason i can’t launch the application for testing purposes.

i typed “npm start” on the code editor terminal to launch the application, but instead it outputs the following log:

> [email protected] start
> electron .

[17011:0428/235408.856171:ERROR:bus.cc(407)] Failed to connect to the bus: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory
[17011:0428/235408.946582:ERROR:ozone_platform_x11.cc(244)] Missing X server or $DISPLAY
[17011:0428/235408.946601:ERROR:env.cc(258)] The platform failed to initialize.  Exiting.
/workspaces/Notes-App/node_modules/electron/dist/electron exited with signal SIGSEGV

Additional information (if useful).
the main.js file is on the root directory of the project, and the HTML, CSS and Javascript of the website is on a folder called “src” on the root directory, as this screenshot shows:

enter image description here

Main.js code:

const { app, BrowserWindow } = require('electron');

function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
    });

    win.loadFile('src/index.html');
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
})

script.js code (the code that saves the notes app text on browser):

var textarea = document.querySelector('textarea');

textarea.addEventListener("input", function () {
    var textWritten = textarea.value;
    localStorage.setItem("written", textWritten);
});

var written = localStorage.getItem("written");

if (written) {
    textarea.value = written;
}

loading json file takes too long in rails 7

I have a JSON file with about a million entry, and when I load it in javascript like this:

<script>
var $select = $('#country');
$.getJSON("helpers/countries.json", function (data) {
  console.log(data.length);

  for (var i = 0; i < data.length; i++) {
   var value = data[i].name;
    var $option = $("<option/>").attr("value", value).text(value);
    $select.append($option);   
    }
});

</script>

It takes about 30 seconds to show the list of countries in the dropdown menu.

I have put the file in /public/helpers/countries.json on a server running ruby on rails.

I don’t want to use online APIs, I’d rather use local json file.

Function is not triggering event in node-pty terminal class

I’m using node-pty & I have a socket.io server, and I’m trying to run a terminal for the client to communicate with. It mostly works, except for one issue where the onData listener doesn’t fire when writing to my terminal.

terminal.ts

import { spawn, IPty } from "node-pty"
import { Socket } from "socket.io"
import os from "os"

export class Pty {
  socket: Socket
  ptyProcess: IPty
  shell: string

  constructor(socket: Socket, id: string) {
    this.socket = socket
    this.shell = os.platform() === "win32" ? "cmd.exe" : "bash"

    this.ptyProcess = spawn(this.shell, [], {
      name: "xterm",
      cols: 100,
      cwd: `/temp`,
    })

    this.ptyProcess.onData((data) => {
      console.log("onData", data)
      this.send(data)
    })

    this.write("hello")
  }

  write(data: string) {
    console.log("writing data", data)
    this.ptyProcess.write(data)
  }

  send(data: string) {
    this.socket.emit("terminalResponse", {
      data: Buffer.from(data, "utf-8"),
    })
  }
}

sockets.ts (very simplified)

const terminals: { [id: string]: Pty } = {}

io.on("connection", async (socket) => {
  const data = socket.data as {
    userId: string
    id: string
  }

  socket.on("createTerminal", ({ id }: { id: string }) => {
    terminals[id] = new Pty(socket, id)
  })

  socket.on("terminalData", ({ id, data }: { id: number; data: string }) => {
    if (!terminals[id]) {
      console.log("terminal not found")
      return
    }

    terminals[id].write(data)
  })
})

In the constructor of terminal.ts, I run this.write("hello") and it works as expected (triggers onData and emits the terminalResponse socket event).

In the sockets.ts file, the createTerminal listener works properly. The terminalData listener calls the write function on a terminal but it doesn’t execute the onData function.

Why is the behaviour different, and what’s causing it?

User Click only passing once in JavaScript along with other behavior

I’m experiencing unexpected behavior with HTML, CSS, and JS… I’m building an interface where it receives a number in each input, but the “pisca” class, which does the magic of receiving one element per input and passes it to the next waiting for the user’s click, is only being passed once, which means that I can input a number in the first input and in the second several numbers, and the other inputs become inaccessible. I believe that if I put the code here, it will be too long and complex, so I decided to deploy it on CodePen where you can see the source code and better understand my problem: https://codepen.io/pen?template=ZEZZGYV

(in JS) I tried to change the logic by declaring the “pisca” variable at the beginning of the function to solve it, but it didn’t work.

function urnaEletronica() {
  this.pisca = document.querySelector(".pisca");
  this.contador = document.querySelector(".contador");
  this.digito = document.querySelector(".digitos-tela");

  this.inicia = () => {
    this.capturaCliques();
    this.atualizaTimer();
  };

  let minutos = 99;
  let segundos = 0;
  let timerInterval;

  this.atualizaTimer = () => {
    timerInterval = setInterval(() => {
      if (segundos === 0) {
        segundos = 59;
        minutos--;
      }
      if (minutos === 0 && segundos === 0) {
        this.contador.innerHTML = `${(minutos = 0)}:${segundos
          .toString()
          .padStart(2, "0")}`;
        clearInterval(timerInterval);
        console.log("Tempo esgotado!");
        return (window.location.href = "resultados.html");
      }
      this.contador.innerHTML = `${minutos}:${segundos
        .toString()
        .padStart(2, "0")}`;
      segundos--;
    }, 1000);
  };

  this.capturaCliques = () => {
    document.addEventListener("click", (event) => {
      const el = event.target;

      if (el.classList.contains("numeros")) this.adicionaTela(el);
    });
  };

  this.adicionaTela = (el) => {
    /*let somNumeros = new Audio();
    somNumeros.src = "audios/numeros.mp3";
    somNumeros.play();*/
    this.pisca.innerText += el.innerText;
    this.digito.classList.remove("pisca");
    this.digito.nextElementSibling.classList.add("pisca");
    this.pisca = document.querySelector(".pisca");
  };
}
urna = new urnaEletronica();
urna.inicia();

Aid! I have a couple of doubts with frontend and I am a beginner

Hello programmer/developer friends (maybe for some the answer to my next question is a bit obvious, but I am a beginner in front-end development).

Recently I was practicing ❝Link to relative page❞ in HTML to link some data like ❝contact❞ or ❝about us❞ when clicking on a text), and I came across the following questions:

When making a new folder to empty the corresponding information, do I have to apply CSS and JavaScript as if it were the main folder?

Would that procedure be done with each and every additional folder I create?

Finally, will it be necessary for each of these folders to have a Back-End or would the Back-End already be something generalized?

I hope you can answer me, I hope I have explained myself well (PS: My native language is not English, so I am using a translator) ;D

I am trying to expand my knowledge a little more and remove doubts, I hope you can help me on my path as a developer.

Create aggrid cell editor in specific path in dom

i am using Angular 16 and AgGrid 30.

i want the cell editor to be created on different path, currently its created in body at bottom div element with this class: ag-theme-material ag-popup, and inside is the editor, but i want it to be somewhere else, for example body > div.dialog

cant find that in documentation, any help is apprechiated.

enter image description here

Thanks

I have a variable that I want the program to continuously check its value

I have a variable that I want the program to continuously check its value. the code goes something like this:

var score = 1

if (player touches the star) 
{
    player moves to bottom of screen
score = score + 1
}

if (score == 2)
{
   a bunch of images.x = 1300
`your text`}

this is obviously not the real code (i use javascript with phaser library) but i hope that you get the idea

i tried changing the place in the code where if (score == 2) { a lot of images move off screen} but it did not work. I even put the places where the images .x properties were mentioned inside if (score > 2) if statements but it did not move the images no matter what. I think that the only way to fix this is to constantly check the score variable.

Update Stocks after Orders – Next.js, MongoDB

I cannot implement the logic to update my product stocks at my Back interface after an order placed via my website (Customer).

I would simply like that after an order for products made via the Site, the stocks of the products ordered decrease by the quantity ordered.

Here are the relative files present in my code:

** Models / Order :

import {model, models, Schema} from "mongoose";

const OrderSchema = new Schema({
  line_items:Object,
  name:String,
  email:String,
  city:String,
  zip:String,
  address:String,
  country:String,
  paid:Boolean,
}, {
  timestamps: true,
});

export const Order = models?.Order || model('Order', OrderSchema);


** Model / Product :

import mongoose, {model, Schema, models} from "mongoose";

const ProductSchema = new Schema({
  title: {type:String, required:true},
  description: {type:String, required:true},
  price: {type: Number, required: true},
  details: {type:String},
  brand: {type:String},
  stock: {type:Number},
  sizes: {type:String},
  gender: {type:String},
  images: [{type: String}],
  category: {type:mongoose.Types.ObjectId, ref:'Category'},
});

export const Product = models.Product || model('Product', ProductSchema);

Api / Order :


import { mongooseConnect } from "@/lib/mongoose";
import { Order } from "@/models/Order";
import { Product } from "@/models/Product"; // Importez le modèle de produit



export default async function handler(req, res) {
  await mongooseConnect();

  // Ajoutez votre logique pour enregistrer une nouvelle commande
  if (req.method === 'POST') {
    const { line_items } = req.body;

    try {
      
      const newOrder = await Order.create(req.body);

     
      for (const item of line_items) {
        const { product_id, quantity } = item;

   
        const product = await Product.findById(product_id);

    
        product.stock -= quantity;

      
        await product.save();
      }

      res.status(201).json(newOrder);
    } catch (error) {
      console.error("Error creating order:", error);
      res.status(500).json({ error: "Internal server error" });
    }
  } else {

    const orders = await Order.find().sort({ createdAt: -1 });
    res.status(200).json(orders);
  }
}

Api/ Products :

import { mongooseConnect } from '@/lib/mongoose';
import { Product } from '@/models/Product';

export default async function handle(req, res) {
  const { method } = req;

  await mongooseConnect();

  if (method === 'POST') {
    const { title, description, price, images, category,details, brand, gender, sizes, stock } = req.body;

    const productDoc = await Product.create({
      title,
      description,
      price,
      images,
      category,
      details,
      brand, gender, sizes, stock
    })

    res.json(productDoc);
  }

  if (method === 'GET') {
    if (req.query?.id) {
      res.json(await Product.findOne({ _id: req.query.id }));
    } else {

      res.json(await Product.find());
    }
  }

  if (method === 'PUT') {
    const { title, description, price, _id, images, category,details, brand, gender, sizes, stock } = req.body;
    await Product.updateOne({ _id }, {
      title, description, price, images, category,details, brand, gender, sizes, stock
    });
    res.json(true);
  }

  if (method === 'DELETE') {
    if (req.query?.id) {
      await Product.deleteOne({_id:req.query?.id});
      res.json(true)
    }
  }
}

Database :

enter image description here
enter image description here

I tried to do this but nothing is updated, neither in the Database nor at the interface level :

import { mongooseConnect } from '@/lib/mongoose';
import { Product } from '@/models/Product';

export default async function handle(req, res) {
  const { method } = req;

  await mongooseConnect();

  if (method === 'POST') {
    const { line_items } = req.body;

    try {
   
      const newOrder = await Order.create(req.body);

      for (const item of line_items) {
        const { product_id, quantity } = item;


        await Product.updateOne(
          { _id: product_id },
          { $inc: { stock: -quantity } } 
        );
      }

      
      res.status(201).json(newOrder);
    } catch (error) {
      console.error("Error creating order:", error);
      res.status(500).json({ error: "Internal server error" });
    }
  }

  // Autres routes GET, PUT, DELETE...
}

Sending byte array to Speech-To-Text API (Azure)

i am recording voice on browser and sending it to my API, which is going to send data to Speech-To-Text Api (Azure).
I am keep getting NoMach from the API.

Here is my browser code:


let languageCode = "da-DK";
let mediaRecorder;
let audioChunks = [];
let isRecording = false;


function startRecording() {
    var constraints = {
        audio: {
            sampleRate: 16000,
            channelCount: 1
        }
    };

    navigator.mediaDevices.getUserMedia(constraints)
        .then(function (stream) {
            mediaRecorder = new MediaRecorder(stream);
            mediaRecorder.ondataavailable = function (e) {
                audioChunks.push(e.data);
            }
            mediaRecorder.onstop = function () {
                const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                const reader = new FileReader();
                reader.onload = function () {
                    const audioBytes = new Uint8Array(reader.result);
                    var base64String = btoa(String.fromCharCode.apply(null, audioBytes));

                    voiceToText(languageCode, base64String);

                };
                reader.readAsArrayBuffer(audioBlob);
            }
            mediaRecorder.start();
            recordButton.disabled = true;
            stopButton.disabled = false;
            playButton.disabled = true;
        })
        .catch(function (err) {
            console.error('Error recording audio: ' + err);
        });
}

function voiceToText(myLanguageCode, wavData) {
    $.ajax({
        type: "POST",
        url: "https://localhost:7058/api/Conversation/postVoiceToString",
        contentType: "application/json", // Set Content-Type header
        data: JSON.stringify({ // Stringify the data
            LanguageCode: myLanguageCode,
            WAV: wavData
        }),
        success: function (result) {
            console.log(result);
        },
        error: function (req, status, error) {
            console.log(status);
        }
    });
}

I know my API works, and when i send test data with voiceToText(languageCode, base64String); in js then it’s also works. but when i record the data and then send, then it says NoMach.

What options are there in Tailwind CSS for applying styles to the custom classes of a pre-built component?

I have a text editor in a MERN project where I am trying to change the z-index (and color eventually) of parts of its UI and cannot find a method to do so that makes me happy.

There is an obvious solution, accessing the classes with their selector in your stylesheet:

@layer utilities {
    .tox.tox-silver-sink.tox-tinymce-aux {
        z-index: 100000 !important;
    }
}

To me though, having the styles in a different file and using traditional CSS kind of defeats the main purpose of using Tailwind.

Are there any options out there to avoid that issue and keep all the styles to the className of the component?

i think i understand the problem i just can’t get it to wrok, i’m sure it’s managing dependencies

web-1  | yarn run v1.22.19
web-1  | $ vite
web-1  | /app/node_modules/rollup/dist/native.js:59
web-1  | throw new Error(
web-1  |       ^
web-1  | 
web-1  | Error: Cannot find module @rollup/rollup-linux-x64-gnu. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.
web-1  |     at requireWithFriendlyError (/app/node_modules/rollup/dist/native.js:59:9)
web-1  |     at Object.<anonymous> (/app/node_modules/rollup/dist/native.js:68:76)
web-1  |     ... 3 lines matching cause stack trace ...
web-1  |     at Module._load (node:internal/modules/cjs/loader:1081:12)
web-1  |     at cjsLoader (node:internal/modules/esm/translators:344:17)
web-1  |     at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:284:7)
web-1  |     at ModuleJob.run (node:internal/modules/esm/module_job:235:25)
web-1  |     at async ModuleLoader.import (node:internal/modules/esm/loader:461:24) {
web-1  |   [cause]: Error: Cannot find module '@rollup/rollup-linux-x64-gnu'
web-1  |   Require stack:
web-1  |   - /app/node_modules/rollup/dist/native.js
web-1  |       at Module._resolveFilename (node:internal/modules/cjs/loader:1202:15)
web-1  |       at Module._load (node:internal/modules/cjs/loader:1027:27)
web-1  |       at Module.require (node:internal/modules/cjs/loader:1290:19)
web-1  |       at require (node:internal/modules/helpers:188:18)
web-1  |       at requireWithFriendlyError (/app/node_modules/rollup/dist/native.js:41:10)
web-1  |       at Object.<anonymous> (/app/node_modules/rollup/dist/native.js:68:76)
web-1  |       at Module._compile (node:internal/modules/cjs/loader:1455:14)
web-1  |       at Module._extensions..js (node:internal/modules/cjs/loader:1534:10)
web-1  |       at Module.load (node:internal/modules/cjs/loader:1265:32)
web-1  |       at Module._load (node:internal/modules/cjs/loader:1081:12) {
web-1  |     code: 'MODULE_NOT_FOUND',
web-1  |     requireStack: [ '/app/node_modules/rollup/dist/native.js' ]
web-1  |   }
web-1  | }
web-1  | 
web-1  | Node.js v22.0.0`your text`
web-1  | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
web-1  | error Command failed with exit code 1.

so this the error i tried all i can find online but nothing work. i did try to add npm i or yarn add in my docker file but it didn’t change anything i keep getting the same problem

Passing WebSocket request from Sveltekit to Elysiajs

I have a backend server written with elysiajs, and I have integrated it with sveltekit app.
The problem is that the rest routes work as expected but the ws ones don’t because sveltekit do not support ws nativly, how could I intercept the ws request coming to the sveltekit app and pass them to elysia?

I have tried to write a vite plug in to transform the request, but that didn’t work

No response from javascript frida

I’m currently trying frida and using https://github.com/httptoolkit/frida-interception-and-unpinning/ as a tutorial, but unfortunately frida isn’t working. Im using a Samsung Galaxy S9 (https://www.devicespecifications.com/de/model-cpu/066948b6) so a rooted physical device.

frida version: 16.2.1, I have also tried frida 15.2.2, client and server of course.

C:Users###Downloadsplatform-tools-latest-windowsplatform-tools>frida --debug -U -f tech.httptoolkit.pinning_demo -l frida_multiple_unpinning.js
     ____
    / _  |   Frida 16.2.1 - A world-class dynamic instrumentation toolkit
   | (_| |
    > _  |   Commands:
   /_/ |_|       help      -> Displays the help system
   . . . .       object?   -> Display information about 'object'
   . . . .       exit/quit -> Exit
   . . . .
   . . . .   More info at https://frida.re/docs/home/
   . . . .
   . . . .   Connected to SM G960F (id=2252a1780a037ece)
Spawning `tech.httptoolkit.pinning_demo`...

also Objection is an tool for injecting code but also no response:

C:Users###>objection --gadget tech.httptoolkit.pinning_demo explore
Using USB device SM G960F

How to prevent internal navigation if user had unsaved changes in form in react

I am working on a reactjs web project where I am using react-router-dom version 5 and 6 and I wanted to show a confirmation dialog to user when user tries to navigate to other page using Link or navigate of react-router

<Link></Link>
const navigate=useNavigate()
navigate('/some-route')
  1. The beforeUnload only works if user tries to reload the page or
    close the tab or browser.
  2. useBlocker hook works only in react-router
    version 6.
  3. usePrompt hook works only in react-router version 5.

Please suggest a generic way that can be used for both react-router version 5 and 6.

Query DynamoDB with array of numbers that is not the pk or sk in NodeJs?

This is my API request body (Array of numbers):

{
        "userIds": [10,11,12, 20]
}

Where the usersIds in DB is a number type and it’s not the primary or secondary keys.
I need to query DynamoDB and get the details of these users in NodeJs please.

I tried:

const keys: { userIds: number }[] = userIds.map(id => ({ userID: id }))
        const params: BatchGetCommandInput = {
           RequestItems: {
            [this.tableName]: {
                Keys: keys,
                ProjectionExpression: projectionExpression
            }
           }
        };
return ResultAsync.fromPromise(this.dynamoDocumentClient.batchGet(params),

I think that batchGet needs the keys to be passed so doesn’t work in this case!