Decrypt file so that my code is able to run JS

Relatively new here, I encrypted all my files except the main.js file. Now I wan to decrypt the files before running my main.js. If i run main.js now it doesnt work due to the encrypted files. Is this a valid way?

Current Idea

  1. Write decryption code before running main.js

Code below is for decryption but it produces another file, I wan it so that it just read and let me access the files. Hopefully I explained clearly 🙁

const fs = require('fs');
const crypto = require('crypto');
const path = require('path');

const rootDirectory = './';
const encryptedDirectory = path.join(rootDirectory, 'Encrypted Files');
const decryptedDirectory = path.join(rootDirectory, 'Decrypted Files');
const encryptionKeyPath = path.join(rootDirectory, 'encryptionKey.txt');

// Load the encryption key from file
const encryptionKey = fs.readFileSync(encryptionKeyPath);

// Decrypt and save each file in the encrypted directory
decryptDirectory(encryptedDirectory);

function decryptDirectory(directory) {
  // Read the files and subdirectories in the directory
  const entries = fs.readdirSync(directory, { withFileTypes: true });

  // Iterate over the entries
  entries.forEach((entry) => {
    const entryPath = path.join(directory, entry.name);

    if (entry.isDirectory()) {
      // Decrypt files in subdirectories recursively
      decryptDirectory(entryPath);
    } else {
      // Read the encrypted file
      const encryptedBuffer = fs.readFileSync(entryPath);

      // Extract the IV from the encrypted file
      const iv = encryptedBuffer.slice(0, 16); // Assuming the IV is stored at the beginning

      // The rest of the buffer is the encrypted data
      const encryptedData = encryptedBuffer.slice(16);

      // Create a decipher with AES algorithm, the encryption key, and the IV
      const decipher = crypto.createDecipheriv('aes-256-cbc', encryptionKey, iv);

      // Decrypt the file
      const decryptedBuffer = Buffer.concat([decipher.update(encryptedData), decipher.final()]);

      // Create the corresponding output directory structure
      const relativePath = path.relative(encryptedDirectory, entryPath);
      const outputPath = path.join(decryptedDirectory, relativePath);

      // Ensure the output directory exists
      fs.mkdirSync(path.dirname(outputPath), { recursive: true });

      // Save the decrypted file
      fs.writeFileSync(outputPath, decryptedBuffer);
    }
  });
}

Tried running decryption code before running main.js , basically the decryption is above main.js

How to create an infinite horizontal scroll animation using Qwik framework?

I am trying to create a web page that has an infinite horizontal scroll animation using Qwik framework. I have added the CSS part, but I don’t know how to add the JavaScript part.

here is my code: https://stackblitz.com/edit/qwik-starter-v5hp1x?file=src%2Froutes%2Findex.tsx

I am expecting this type of result

you can see it on codepen: https://codepen.io/zeronicola/pen/eYZddOd

I am having a issue in WebSocket connection between client and server

Trying to make a Local Webpage were Multiple clients can chat with single Chatgpt bot.

I am running C++ Backend Implimentation through visual studio community and webpage from Vscode (Live Server).

This is my log from Chromebrowser
“WebSocket is not open yet. Message not sent. “

enter image description here

I think there might be issue with localhost

enter image description here

Here is my javascript code and c++ code,

let socket = new WebSocket("ws://localhost:7000");  

socket.addEventListener('open', (event) => {
    console.log('WebSocket connection opened. Ready state:', socket.readyState);
    sendMessage();
});

socket.addEventListener('message', (event) => {
    let chatOutput = document.getElementById('chat-output');
    chatOutput.innerHTML += '<p>' + event.data + '</p>';
});

socket.addEventListener('error', (error) => {
    console.error('WebSocket error:', error);
});

socket.addEventListener('close', (event) => {
    console.log('WebSocket connection closed. Code:', event.code, 'Reason:', event.reason);
});

function sendMessage() {
    let chatInput = document.getElementById('chat-input');
    let message = chatInput.value;

    if (socket.readyState === WebSocket.OPEN) {
        console.log('Sending message:', message);
        socket.send(message);
        chatInput.value = '';
    } else {
        console.log('WebSocket is not open yet. Message not sent.');
    }
}



#include <iostream>
#include <vector>
#include <boost/asio.hpp>
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <cpprest/uri.h>
#include <mutex> 

using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
using boost::asio::ip::tcp;

class ChatSession : public std::enable_shared_from_this<ChatSession> {
public:
    ChatSession(tcp::socket socket) : socket_(std::move(socket)) {}

    void Start() {
        std::unique_lock<std::mutex> lock(clientsMutex_); // Locking before modifying clients
        clients_.push_back(shared_from_this());
        Read();
    }

private:
    void Read() {
        auto self(shared_from_this());
        socket_.async_read_some(boost::asio::buffer(data_),
            [this, self](const boost::system::error_code& error, std::size_t length) {
                if (!error) {
                    std::wstring userMessage(data_.begin(), data_.begin() + length);

                    // Call ChatGPT API
                    std::wstring chatGPTResponse = chatWithGPT3(userMessage);

                    // Broadcast the ChatGPT response to all clients
                    Broadcast(chatGPTResponse);

                    Read(); // Continue reading.
                }
                else {
                    // Client disconnected, remove from clients vector.
                    std::unique_lock<std::mutex> lock(clientsMutex_); // Locking before modifying clients_
                    clients_.erase(std::remove(clients_.begin(), clients_.end(), self), clients_.end());
                }
            });
    }

    void Broadcast(const std::wstring& message) {
        for (auto& client : clients_) {
            if (client != shared_from_this()) {
                std::wstring messageToSend = L"ChatGPT: " + message;
                boost::asio::write(client->socket_, boost::asio::buffer(messageToSend.data(), messageToSend.size()));
            }
        }
    }

    tcp::socket socket_;
    std::array<char, 1024> data_;
    static std::vector<std::shared_ptr<ChatSession>> clients_;
    static std::mutex clientsMutex_;

    std::wstring chatWithGPT3(const std::wstring& userMessage) {
        const utility::string_t apiKey = U("Hidding My API Key"); // ChatGPT API Key

        web::http::client::http_client client(U("https://api.openai.com/v1/completions"));
        web::http::http_request request(web::http::methods::POST);

        request.headers().set_content_type(U("application/json"));
        request.headers().add(U("Authorization"), U("Bearer ") + apiKey);


        web::json::value body;
        body[U("model")] = web::json::value::string(U("davinci-002"));          
        body[U("prompt")] = web::json::value::string(userMessage);
        body[U("max_tokens")] = web::json::value(50); // Adjust as needed

        request.set_body(body);

        try {
            web::http::http_response response = client.request(request).get();
            if (response.status_code() == web::http::status_codes::OK) {
                return response.to_string();
            }
            else {
                std::cerr << "ChatGPT API error: " << response.status_code() << std::endl;
                std::cerr << "Response body: " << utility::conversions::to_utf8string(response.to_string()) << std::endl;

                return L"An error occurred while processing your request.";
            }
        }
        catch (const std::exception& e) {
            std::cerr << "Exception in ChatGPT API request: " << e.what() << std::endl;
            return L"An error occurred while processing your request.";
        }
    }
};

std::vector<std::shared_ptr<ChatSession>> ChatSession::clients_;
std::mutex ChatSession::clientsMutex_;

class ChatServer {
public:
    ChatServer(boost::asio::io_context& io_context, short port)
        : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) {
        Accept();
    }

private:
    void Accept() {
        acceptor_.async_accept(
            [this](const boost::system::error_code& error, tcp::socket socket) {
                if (!error) {
                    auto session = std::make_shared<ChatSession>(std::move(socket));
                    session->Start();
                }
                Accept();
            });
    }

    tcp::acceptor acceptor_;
};

int main() {
    try {
        boost::asio::io_context io_context;
        ChatServer server(io_context, 7000); // Port
        io_context.run();
    }
    catch (std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    return 0;
}

I tried Turning off my firewall but it made no difference.

I am expecting to be able to send message from webpage to Chatgpt.

Can you update a Vue Pinia store WITHOUT rendering data changes? Or rather, just rendering one data change?

I am using Vue3 composition with script setup. I am using a pinia store.

I have an SPA where the user gradually alters data, which is stored in a history array.
It is possible to recreate all the users’ changes by resetting the page, and running through this history array step by step.

As you run through the history array (for loop), the webpage won’t update, as JS is single thread. This recreation takes ~1-2 seconds, and so I would like a progress bar to show the progress through the ‘for’ loop. But I don’t want the rest of the page to update with every change to the store as it’s altered by going through the history array (of course, being vue, you normally do want everything to update!).

So what I want to know is; can you make changes that would normally result in a vue DOM update, but wait until a for loop has completed until updating? But whilst in the for loop, update just a progress bar, so you can see that something is happening?

I can get the progress bar to update using

await sleep(0)

where

export function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

But of course this updates the whole page, not just the progress bar.

Is this possible?

Regular function in a function is modifying the outer this context [duplicate]

Please look at the code below.
I think the arrow functions do not have their own this. so they take context from wherever they are called but regular functions should have their own this (that is the one big difference between arrow and regular functions)

function test() {
  this.name = "outermost name value";
  const test1 = () => {
    const test2 = () => {
      this.name = "test2";              // expected to modify outermost name 
    };
    test2();
    console.log(`Inside test 1 --> ${this.name}`);    // expected to print modified name = test2 (Correct)
  };
  function test3() {
    this.name = "test3";                // expected to modify outermost name
    function test4() {
      this.name = "test4";    // should not modify outermost name as inner function should have own this
    }
    test4();
    console.log(`Inside test3 --> ${this.name}`); // expected to print modified name = test3 (Incorrect)
  }

  test1(); // test2
  console.log('After test 1, outermost name is --> ', this.name); // test2 (Correct)
  test3(); // test3
  console.log('After test 3, outermost name is --> ',this.name); // expected to print test3 (Incorrect)
  return
}
test()

I have mentioned the expectation in comments.
Am I doing something wrong or is the expectation wrong?

iOS 17.0.3: Web Speech recognition does not work properly

I have iPhone 15 Pro with iOS 17.0.3 version.
Web speech recognition does not work most of the time on Safari.
Microphone turns on properly, but what you speak loud and clear on the microphone does not get transcribed into text properly.
Other versions of ios (above 16) worked fine so far.
Sometimes, it picks up what I say perfectly. But it is very rare, almost one out of ten times.

Here is what I know so far:

  • Meaning of ‘it does not work’: when you turn on the mic and speak ‘What a beautiful day today’, it just outputs ‘Relate’. Sometimes nothing at all.
  • When it does not work, it does not work no matter how many times you retry it and vice versa.
  • When you exit Safari and come back after a while, it suddenly works perfectly, picks up whatever you say accurately even on a low voice or from a distance.
  • It only occurs on iPhone 15 Pro running iOS 17.0.3, Safari browser.

What I tried:

  • checking Safari’s microphone permissions, all are OK. Site permissions are also OK
  • checking battery percentage, it is full
  • no Bluetooth devices are connected

Here is the web speech demo link: https://www.google.com/intl/en/chrome/demos/speech.html

Is it a known issue or is there anything I can do to solve this issue?
Any help is appreciated. Thanks.

Problem authenticating User seeded to MongoDB

For a MERN stack app Docker containers, I have 4 containers (one for the server, one for the client, one for a MongoDB database and another to seed the database with some predefined data from a JSON file). I do the seeding based on this answer on another post.

On my docker-compose.yml I have the following:

version: '3'
services:
  client:
    build:
      context: ./client
    stdin_open: true
    container_name: react-ui
    ports:
      - "3000:3000"
    volumes:
      - ./client:/app
    depends_on:
      - server

  server:
    build:
      context: ./server
    container_name: node-api
    restart: always
    ports:
      - "5001:5001"
    volumes:
      - ./server:/app
      - /app/node_modules
    depends_on:
      - mongo
      - mongo-seed
  
  mongo-seed:
    build: ./mongo-seed
    container_name: seed
    links:
      - mongo
    depends_on:
      - mongo

  mongo:
    image: mongo
    container_name: mongo-database
    ports:
      - "27017:27017"

As for the Dockerfile of mongo-seed:

FROM mongo:bionic

COPY init.json /init.json
CMD mongoimport                                 
    --host mongo                                
    --db xrDB                                   
    --collection users                          
    --type json                                 
    --file /init.json                           
    --jsonArray                                 
    --drop                                      
    -v                                          

And finally my init.json file:

[
  {
    "name": "New User",
    "email": "[email protected]",
    "password": "$2a$10$1sDcu9l.hr7hPk2AmCFyPuMR3P7dAoPG9iGWsFxPXE/avdrU5fHfS",
    "organization": null
    "__v": 0
  }
]

When I finally want to authenticate my user with their email and password (my_new_password_999), I always get an error when comparing the hashed password using bcrypt.compare for some bizarre reason:

async function signIn(email, password) {
  let user = await getUserByMail(email, true); // Gets the user from the DB with their password included
  
  if (user == null) { 
    throw Error('User doesn't exist.');
  }

  const isPasswordCorrect = await bcrypt.compare(password, user.password);

  if (isPasswordCorrect) {
    // does something here
  }

  throw Error('Wrong credentials');
}

Using a tool like bcrypt generator I can confirm that I am writing the correct password…so what could be wrong in here? Thanks in advance

Issue with javascript form not saving answers

I have this form that I’m trying to embed onto my website. Right now it has dummy questions. I want it to be able to store the answers to the questions, such that you can click “back” and the highlighted option is the one you chose. I also need them to save to I can then programatically redirect the user to a page depending on how many answers she got right.

Right now the answers aren’t being saved at all. It MIGHT be related to the event listeners, as I had a console.log and it was only registering the answer to the first question, but not subsequent ones. Can anyone see what’s wrong?

<style>
/* CSS Styles for the quiz - Customize as needed */

/* Styling for the quiz container */
#quizContainer {
  padding: 20px;
  border-radius: 10px;
  max-width: 600px; /* Set a maximum width */
  margin: 0 auto; /* Center the container */
}

/* Styling for the title and subtitle */
#titleContainer {
  background-color: #dfedef; /* Background color for title and subtitle */
  padding: 5px 20px; /* Added top and bottom padding */
  border-radius: 10px;
  margin-bottom: 20px;
  text-align: center; /* Center align the text */
}

/* Styling for the question number and question */
#questionContainer {
  background-color: #fcfaf7; /* Background color */
  padding: 10px; /* Added padding */
  border-radius: 10px; /* Added border radius */
  margin-bottom: 20px; /* Added margin */
}

/* Styling for the title */
h1 {
  font-size: 1.2em; /* Half the original size */
  margin-top: 0;
  margin-bottom: 0;
  color: #2d536a; /* Changed title color */
}
#age {
  font-size: 0.8em; /* 3/4 of the current size */
  font-weight: bold;
  color: #b95966; /* Color for "15-18 meses" */
  margin-top: 0;
}

/* Styling for Yes/No buttons */
input[type="radio"] {
  display: none; /* Hide default radio buttons */
}
label.btn {
  display: inline-block;
  margin: 5px;
  padding: 6px 16px; /* Adjusted padding */
  border: 1px solid #2d536a; /* Changed outline color */
  border-radius: 5px; /* Adding border radius */
  cursor: pointer;
  transition: background-color 0.3s ease, color 0.3s ease;
}
input[type="radio"]:checked+label.btn {
  background-color: #63a3ad; /* Changed background color when selected */
  color: white; /* Changed text color */
}

/* Styling for Previous/Next buttons */
#prevBtn,
#nextBtn {
  display: inline-block;
  margin-top: 45px; /* Increased margin */
  margin-right: 10px;
  padding: 6px 16px; /* Adjusted padding */
  background-color: #63a3ad; /* Changed background color */
  color: white; /* Changed text color */
  border: none; /* Removed outline */
  border-radius: 5px; /* Adding border radius */
  cursor: pointer;
  transition: background-color 0.3s ease, color 0.3s ease;
  font-size: 20px; /* Adjusting font size */
  vertical-align: middle; /* Aligns buttons vertically */
}
</style>

<div id="quizContainer">
  <div id="titleContainer">
    <h1>Hitos del lenguaje<br><span id="age">15-18 meses</span></h1>
  </div>
  <div id="questionContainer">
    <p><strong>Question 1:</strong><br>Is the sky blue?</p>
  </div>
  <form id="quizForm">
    <div>
      <input type="radio" id="yes" name="q1" value="yes">
      <label for="yes" class="btn">Yes</label>
      <input type="radio" id="no" name="q1" value="no">
      <label for="no" class="btn">No</label>
    </div>
    <button type="button" id="prevBtn">&larr;</button> <!-- Left arrow character -->
    <button type="button" id="nextBtn">&rarr;</button> <!-- Right arrow character -->
  </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  let questionNumber = 1;
  const questions = [
    "Is the sky blue?",
    "Do you like pizza?",
    "Have you traveled abroad?",
    "Do you enjoy reading?"
  ];
  const selectedAnswers = {}; // Object to store selected answers

  document.getElementById('nextBtn').addEventListener('click', function() {
    const answer = document.querySelector('input[name="q' + questionNumber + '"]:checked');
    if (answer) {
      selectedAnswers[questionNumber] = answer.value; // Save selected answer
    }

    if (questionNumber < questions.length) {
      questionNumber++;
      document.getElementById('questionContainer').innerHTML = "<p><strong>Question " + questionNumber + ":</strong><br>" + questions[questionNumber - 1] + "</p>";
      const selected = selectedAnswers[questionNumber]; // Get selected answer if exists
      const radio = document.querySelector('input[name="q' + questionNumber + '"][value="' + selected + '"]');
      if (radio) {
        radio.checked = true; // Set previously selected answer as checked
      } else {
        // If no previous answer, clear the selection
        const radios = document.querySelectorAll('input[name="q' + questionNumber + '"]');
        radios.forEach(radio => radio.checked = false);
      }

      if (questionNumber === questions.length) {
        document.getElementById('nextBtn').innerText = 'See Results';
      }
    } else {
      // Redirect to results page based on scores or selected answers
      // Use selectedAnswers object to determine the result
      // For example:
      console.log(selectedAnswers); // Display selected answers in the console
    }
  });
  
  document.getElementById('prevBtn').addEventListener('click', function() {
    if (questionNumber > 1) {
      questionNumber--;
      document.getElementById('questionContainer').innerHTML = "<p><strong>Question " + questionNumber + ":</strong><br>" + questions[questionNumber - 1] + "</p>";
      const selected = selectedAnswers[questionNumber]; // Get selected answer if exists
      const radio = document.querySelector('input[name="q' + questionNumber + '"][value="' + selected + '"]');
      if (radio) {
        radio.checked = true; // Set previously selected answer as checked
      } else {
        // If no previous answer, clear the selection
        const radios = document.querySelectorAll('input[name="q' + questionNumber + '"]');
        radios.forEach(radio => radio.checked = false);
      }

      if (questionNumber === questions.length - 1) {
        document.getElementById('nextBtn').innerText = 'Next';
      }
      if (questionNumber === 1) {
        document.getElementById('prevBtn').style.display = 'none';
      }
    }
  });
});
</script>

When I click “back”, I expect the highlighted option to be the one I selected. However, it appears the answers aren’t being saved, as the selected option is just the same for all questions.

Chales stop ssl proxying

When using Charles to grab https, with the same domain name and different interfaces, A can grab, B cannot. When turned on/off ‘stop SSL proxy’, B can grab, but A cannot.

  1. The certificate configuration is correct and can be captured by other interfaces
  2. What cannot be caught is that Charles did not respond at all

I tried to turn on or off ‘stop ssl proxy’, but only one of A and B works. May I ask why

Javascript introduction

What is different between let and const in javascript?

var and let create variables that can be reassigned another value. const creates “constant” variables that cannot be reassigned another value. developers shouldn’t use var anymore. They should use let or const instead

how to prevent the mousedown event without preventing scroll?

I need to prevent the mousedown event that happen after the touchstart event but don’t know how to do it without preventing the user from scroll when swipes the screen. The touchstart event listener cannot be removed cause if the user(s) try to touch at two points barely at the same time none of the events are triggered.

canvas.addEventListener('touchstart', function (event) {
  touchPressed = true
  if (currentScreen.name == "end") event.preventDefault()//prevents mousedown event
  userInput(
    event.targetTouches[event.targetTouches.length - 1].clientX, 
    event.targetTouches[event.targetTouches.length - 1].clientY
  )
});
canvas.addEventListener('touchend', function () {
  touchPressed = false
});
canvas.addEventListener('mousedown', function (event) {
  userInput(event.clientX, event.clientY)
});

How to remove the “frozen” state of a worksheet using ExcelJS?

I am attempting to utilize ExcelJS to remove the “frozen” state of a worksheet. My Code is as follows:

const workbook = new Workbook();
await workbook.xlsx.readFile(excel_path);
const worksheet = workbook.getWorksheet(sheet_name);

if(worksheet){
    if(worksheet?.views[0]){
        (worksheet.views as any) = [{
            state: 'normal',
            zoomScale: 100,
            zoomScaleNormal: 100,
            rightToLeft: false,
            showGridLines: true,
            showRowColHeaders: true,
            showRuler: true,
            workbookViewId: (worksheet.views[0] as any).workbookViewId,
        }];
    }
}
await workbook.xlsx.writeFile(excel_path);

However, upon saving and subsequently attempting to open the saved Excel file with Microsoft Excel, an alert is presented indicating an issue with the worksheet’s view that necessitates repair.
I read the saved file using the following code, and then get the worksheet’s view property:

const workbook = new Workbook();
await workbook.xlsx.readFile(excel_path);
const worksheet = workbook.getWorksheet(sheet_name);

if(worksheet){
    console.log(worksheet.views);
}

The result I got is:

[{
    state: 'frozen',
    zoomScale: 100,
    zoomScaleNormal: 100,
    rightToLeft: false,
    showGridLines: true,
    showRowColHeaders: true,
    showRuler: true,
    xSplit: 0,
    ySplit: 0,
    topLeftCell: "A1",
    workbookViewId: 0,
}]

Indeed, there is a problem. I would like to ask how to correctly remove the “frozen” property of a worksheet?

I have also submitted a same issue to the Issues section of the ExcelJS repository on GitHub. Appreciate your assistance. 🙂