Select2 – Set val IF selected option == “Apple”

I have a select2 drop down and would like to know the best way to SET a VALUE if the OPTION selected == ” Apple” for instance.

Here is my Select2

<select id="fruit" title="fruit" name="fruit"
                                      class="form-control select2-single">
                                  <option value="">&nbsp;</option>
                                  <option value="">Apple</option>
                                  <option value="">Lemon</option>
                              </select>

What I’d like to achieve is:

If Option “Apple” is selected, SET Value to THISVARIABLE (I get responses from an AJAX Post and would like to dynamically set the Value

“server: [object Object]” this is getting printed on the receivers screen

Building a chatApp using ws library.
Server.js

const http = require('http');
const WebSocket = require('ws'); // Import the 'ws' library

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('WebSocket servern');
});

const wss = new WebSocket.Server({ server });

// Array to store connected clients
const clients = [];

wss.on('connection', ws => {
  console.log('Client connected');

  // Add client to the list
  clients.push(ws);

  ws.on('message', message => {
    console.log(`Received: ${message}`);

    // Broadcast message to all clients except the sender
    wss.clients.forEach(client => {
        if (client !== ws && client.readyState === WebSocket.OPEN) {
          const dataToSend = JSON.stringify({ message, sender: 'server' });
          client.send(dataToSend);
        }
      });
  });

  ws.on('close', () => {
    console.log('Client disconnected');
    removeClient(ws);
  });

  function removeClient(ws) {
    const index = clients.indexOf(ws);
    if (index !== -1) {
      clients.splice(index, 1);
    }
  }
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

client.js

// client.js
let ws;

document.addEventListener('DOMContentLoaded', () => {
  ws = new WebSocket('ws://localhost:3000');
  const chatWindow = document.getElementById('chat-window');

  // Event handler for incoming messages
  ws.onmessage = event => {
    const messageData = JSON.parse(event.data);
    console.log('Received message data:', messageData); // Debugging log
    const { message, sender } = messageData;

    if (sender !== 'self') {
      console.log('Appending message:', message); // Debugging log
      appendMessage(messageData); // No need to pass chatWindow here
    }
  };
});

// Function to send a message
function sendMessage() {
  const messageInput = document.getElementById('message-input');
  const message = messageInput.value.trim();
  if (message !== '') {
    ws.send(JSON.stringify({ message }));
    messageInput.value = '';
  }
}

// Function to append a message to the chat window
function appendMessage(messageData) {
  const chatWindow = document.getElementById('chat-window'); // Access chatWindow directly
  const { message, sender } = messageData;

  console.log('Appending actual message:', message);
  const messageElement = document.createElement('div');
  messageElement.textContent = `${sender}: ${message}`; // Display sender's name with the message
  messageElement.classList.add('message-bubble');
  chatWindow.appendChild(messageElement);
  chatWindow.scrollTop = chatWindow.scrollHeight;
}

document.addEventListener('DOMContentLoaded', () => {
  const sendButton = document.getElementById('send-btn');
  sendButton.addEventListener('click', sendMessage);
});

On sending message to other sockets it is printing server: [object Object] I am not able to get that also I logged the messages on the console enter image description here

So this is the screenshot of the console. Not able to get what might be the issue. Is it in type conversion or some other element is causing issue.
For more info below is the index.html code to give a better view
Index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-Time Chat</title>
  <link rel="stylesheet" href="styles.css">
  <script src="./client.js"></script>
</head>
<body>
  <div class="container">
    <div id="chat-window" class="chat-box"></div>
    <div class="input-container">
      <input type="text" id="message-input" placeholder="Type your message...">

      <button id="send-btn" onclick="sendMessage()">Send</button>
    </div>
  </div>
 
</body>
</html>

How to create a table of contents from Strapi rich text field

I’ve searched everywhere for this but I could only find one article about it which was pretty vague.

So I’m rendering the rich text content using the BlocksRenderer component from Strapi itself. Is it possible to create a table of contents from the data gotten from strapi rich text?

This is my Blog component:

import { BlocksRenderer, type BlocksContent} from "@strapi/blocks-react-renderer";

const Blog = () => {

  const { data } = useGetBlogsByIdQuery(slug);

  const content: BlocksContent = data ? .data ? .attributes ? .content;

  return ( 
    <BlocksRenderer content = {content} />
  )
}

This is how the blog post is rendered. If I can map out the headings of each section of the content below the 'on this page' text

This is what the content data looks like

I would appreciate any tips

Why matrix.shift() is almost 25x faster than indexing in this javascript code

I noticed this behaviour while solving this leetcode problem:
https://leetcode.com/problems/search-a-2d-matrix/description/

Here is the code:

function searchMatrix(matrix, target) {
    const len = matrix.length;

    for (let i = 0; i < len; i++) {
        //const row = matrix.shift();  // if i access row using matrix.shift() the code executes in less than 100 ms. 
        const row = matrix[i]   // But if i access the row via indexing.  then it takes more than 2000ms and sometimes even gives Time limit exceeded.
        let start = 0, end = row.length - 1;

        while (start <= end) {
            const mid = start + Math.floor((end - start) / 2);

            if (row[mid] === target) return true;

            if (row[mid] < target) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
    }

    return false;
}

In this code if i access row using const row = matrix.shift(); the code executes in less than 100 ms.
but if i access the row via indexing using const row = matrix[i] . then it takes more than 2000ms and sometimes even gives Time limit exceeded.

Please help me understand why there is such a huge performance difference.

I checked Ecma script specifications here:
https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.shift
and for shift() , internally java script also uses a while loop with indexing so it should take O(n) time for each row and it should be slower than indexing.

i Tried ChatGpt and Gemini and got some info. But it dint cite any reference so it might be making things up or hallucinating. here is the answer Gemini gave:

“Here are key factors contributing to shift()’s efficiency:

Built-in Optimizations: JavaScript engines are heavily optimized for common array operations like shift(). They often implement them using low-level code that’s significantly faster than plain JavaScript loops. These optimizations can include:

In-Place Shifting: Manipulating internal pointers to elements within the same memory block, minimizing data movement and avoiding unnecessary memory reallocations.
Cache-Friendly Rearrangement: Reordering elements in a way that maximizes cache utilization, leading to faster access times for subsequent operations.
Hidden Overheads in for Loops: While for loops appear simpler, they can involve subtle overheads that shift() often avoids:

Variable Lookups: Each iteration of a for loop requires looking up loop variables and condition values, adding some overhead.
Bounds Checks: Loops often involve explicit bounds checks to ensure array access is within valid limits, potentially incurring additional costs.
Potentially Less Efficient Rearrangement: Manually rearranging elements in a for loop might not always be as cache-friendly as the optimized implementations used for shift().
Additional Considerations:

Array Size: The performance difference between shift() and indexing can become more pronounced with larger arrays, as shift()’s optimizations become more beneficial for larger data sets.
Data Types: The specific data types stored in the array can also influence performance, as optimizations might be tailored for certain types (e.g., numbers).”

how can i share a list from one js to another?

thanks for everyone who heloed me today already. i was told to use a storage to share the info and… well it didnt work.

I need to share the list that user made from list.js to dragANDdrop.js. from dragANDdrop.js i want to show this on html. well the list is not showing, i can’t get why so

here is what i tried
list.js

localStorage.setItem('lst', list);

dragANDdrop.js

list = localStorage.getItem('lst');
const html = list.map((item) => `<li>${item}</li>`).join('');
document.querySelector('ul').innerHTML = html;

the second part should display the list on the html page.

dragANDdrop.html

<section class="home-section">
    <div class="home-content">
        <i class='bx bx-menu' ></i>
        <span class="text"><h1>To do list</h1></span>
        <ul></ul>  
    </div>
</section>
<script src="list.js"></script>
<script src="dragANDdrop.js"></script>

AJAX / PHP form submit issue

I trying to upgrade a website to make it easily replicable and more database driven.

My forms use PHP / AJAX to submit to response.php within the same directory.

E.G domain.com/client1/login.php this would use JS in /js/common.js

common.js will take the variables from the form name and use domain.com/client1/response.php?action=login

The issue I am having is that despite login.php and response.php both being in client1/, the JS is trying to locate response.php at domain.com/response.php

Is there a way of forcing the JS to use the local directory or taking my php url: ‘$isteURL/response.php’,

Any help would be gratefully appreciate, racking my head here.

$siteURL is defined in the header.php above the JS file

    function submitForm3() {        
    var data = $("#reset-form").serialize();
    $.ajax({                
        type : 'POST',
        url  : '<?php echo $siteURL; ?>/response.php?action=reset',
        data : data,
        beforeSend: function(){ 
            $("#error").fadeOut();
            $("#reset_button").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...');
        },
        success : function(response){           
            if($.trim(response) === "1"){
                console.log('dddd');                                    
                $("#reset-submit").html('Email sent ...');
                setTimeout(' window.location.href = "index.php?resetStatus=1"; ',2000);
            } else {                                    
                $("#error").fadeIn(1000, function(){                        
                    $("#error").html(response).show();
                });
            }
        }
    });
    return false;
}

Why does including proj4js.js cause a 404 error re: merc.js can’t be found, even though merc.js is not mentioned anywhere in proj4js.js?

I am working on a page with a lot of code including an interactive map. (The huge majority of the code was written prior to my involvement.) Every time the page is opened, there is a 404 error in the console because projCode/merc.js cannot be found. I want to get rid of this error, but I have no idea why it is coming up at all because I cannot find any code that references a file called merc.js – except for the comments in proj4js-combined.js, which imply that merc.js used to be a separate file but its contents are now included in the ‘combined’ file.

The HTML file for the page includes the following:

<script src="~/Scripts/Maps/proj4js-combined.js"></script>
<script src="~/Scripts/Maps/proj4js-compressed.js"></script>
<script src="~/Scripts/Maps/proj4js.js"></script>
<script src="~/Scripts/Maps/proj4.js"></script>

I notice that commenting out the proj4js.js line makes the error go away, but I have no idea why. As I say, nothing in proj4js.js references “merc.js”.

Is the solution just to not include proj4js.js? Or will that cause a loss of functionality, and there is some other problem here?

How to publish to the same AWS IoT Thing topic from multiple endpoints?

I’m currently running a test on an IoT project which is utilizing AWS IOT Core service. I have an MQTT broker with a Thing set up to which I have connection policies defined and authentication access certificates generated. Using these with a policy defined ClientID, I’m able to successfully publish project’s sensors data(i.e temperature, humidity, soil pH and ambient light values) to the MQTT broker using Raspberry pi pico(RP2040) microcontroller device.
From the broker, I’ve set up DynamoDB database tables to which the received data at the broker level is consumed. Then using NodeJs APIs listener, the data is fetched for display in a NodeJs web application in realtime. All these so far works well.

However, my actual problem kicks in whenever I try to publish data(set threshold values) from the platform to the MQTT broker using the very same topic to which the RP2040 device is publishing. Immediately whenever the platform published data is received at the broker, device published data stops being received by the broker.

Here’s the API for handling platform publishing of DHT sensor threshold:

// -----------Publish to broker---------------
// DHT sensor component threshold
router.get('/dht-threshold-mqtt-publish', async (req, res) => {
  console.log("nData Publishing ---------------------------");
  try {
    const { project_id, user_id } = req.query;

    // Fetch data from MongoDB based on project_id and user_id
    const dhtSensorData = await DHTSensor.findOne({ project_id, user_id });

    if (!dhtSensorData) {// validate if data isa available
      return res.status(404).json({ success: false, message: 'DHTSensor data not found' });
    }

    // Extract the temp_threshold from the retrieved data
    const tempThreshold = dhtSensorData.temp_threshold.toString();
    const humidThreshold = dhtSensorData.humid_threshold.toString();

    console.log("Component: DHTnPublished thresholds;n -Temperature: "+tempThreshold+"n -Humidity: "+humidThreshold);

    // Construct the JSON payload
    const jsonPayload = JSON.stringify({
      user_id: user_id.toString(),
      project_id: project_id.toString(),
      dht_temperature_threshold: tempThreshold,
      dht_humidity_threshold: humidThreshold,
    });

    // call MQTT setup
    await mqttDataPublishHandler(jsonPayload, 'DHTSensor', res);

  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ success: false, message: 'Internal server error' });
  }
});

And the publishing function handler:

// MQTT broker data publish handler
async function mqttDataPublishHandler(dataPayload, targetComponent, res) {
  const mqttBrokerUrl = process.env.MQTT_BROKER_URL; // MQTT broker URL
  const topic = process.env.MQTT_PUB_TOPIC;
  const clientId = process.env.MQTT_CLIENT_ID; // Set your unique client_id
  console.log("MQTT broker url: ", mqttBrokerUrl);

  const mqttOptions = {
    clientId: clientId,
    protocol: 'mqtts', // Use 'mqtts' for MQTT over TLS/SSL
    rejectUnauthorized: true, // Set to "false" to ignore certificate validation (for testing only)
    key: fs.readFileSync(process.env.MQTT_CLIENT_KEY_PATH), // Set path to your client key
    cert: fs.readFileSync(process.env.MQTT_CLIENT_CERT_PATH), // Set path to your client certificate
    ca: fs.readFileSync(process.env.MQTT_CA_CERT_PATH), // Set path to your CA certificate
  };

  const mqttClient = mqtt.connect(mqttBrokerUrl, mqttOptions);

  let responseSent = false;

  mqttClient.on('error', (err) => {
    if (!responseSent) {
      console.error('MQTT Connection Error:', err);
      res.status(500).json({ success: false, message: 'MQTT Connection Error' });
      responseSent = true;
    }
  });

  mqttClient.on('connect', () => {
    // Publish payload to the specified MQTT topic
    mqttClient.publish(topic, dataPayload.toString(), (err) => {
      if (!responseSent) {
        if (err) {
          console.error('MQTT Publish Error:', err);
          res.status(500).json({ success: false, message: 'MQTT Publish Error' });
        } else {
          console.log(targetComponent+" threshold data published to MQTT broker.");
          // Close the MQTT connection
          mqttClient.end();
          // Respond to the client
          res.json({ success: true, data: dataPayload });
        }
        responseSent = true;
      }
    });
  });
}

Does this mean AWS IoT thing can’t support multi-device publishing to a common topic and so I should consider creating a topic under Many Things?

At initial stage of experiencing this, I thought it could be due to creation of concurrent connections to MQTT broker from different endpoints(platform API and from device firmware). I resolved this by ensuring platform connection to broker is only initiated at the time a new sensor threshold value is being set and thereafter close the connection.
However, this did not resolve the issue.`

Any assistance kindly in case you’ve come across this? Thank you.

Problem with bypass anti-bot system while deploying an application with Express.js and Puppeteer on Render.com

I’m working on a small application with Express.js using the Puppeteer web scraping library. I wanted to deploy the application on render.com, but I’m encountering errors that don’t occur locally. Specifically, the error is: “Error: No element found for selector: #login”. I’ve been suggested that it might be a bot detection system recognizing Puppeteer. I’ve also captured a screenshot with Puppeteer for confirmation.

To prevent the bot from detecting the use of Puppeteer, I’ve followed a series of steps found on forums, YouTube, and Stack Overflow. I’ve used the Puppeteer-extra library, added randomized viewport size, and changed the user-agent, but despite all, I continue to get blocked. I would like to ask if there’s another way to bypass the anti-bot system or if perhaps I might be doing something wrong.

const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");

puppeteer.use(StealthPlugin());


//this is a part of the function

console.log("Entrato in fetchData");
  const url = "https://web.spaggiari.eu/cvv/app/default/genitori_voti.php";
  const browser = await puppeteer.launch(
    { headless: "new" },
    {
      args: [
        "--disable-setuid-sandbox",
        "--no-sandbox",
        "--single-process",
        "--no-zygote",
      ],
      executablePath:
        process.env.NODE_ENV === "production"
          ? process.env.PUPPETEER_EXECUTABLE_PATH
          : puppeteer.executablePath(),
    }
  );
  const page = await browser.newPage();
  console.log("page creata");

  //Randomize viewport size
  await page.setViewport({
    width: 1920 + Math.floor(Math.random() * 100),
    height: 3000 + Math.floor(Math.random() * 100),
    deviceScaleFactor: 1,
    hasTouch: false,
    isLandscape: false,
    isMobile: false,
  });

  await newpage.setUserAgent(
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
  );
  await page.setJavaScriptEnabled(true);
  await page.setDefaultNavigationTimeout(0);

  //Skip images/styles/fonts loading for performance
  await page.setRequestInterception(true);
  page.on("request", (req) => {
    if (
      req.resourceType() == "stylesheet" ||
      req.resourceType() == "font" ||
      req.resourceType() == "image"
    ) {
      req.abort();
    } else {
      req.continue();
    }
  });

  await page.goto(url, { waitUntil: "domcontentloaded" });
  console.log("pagina caricata");
  await page.waitForTimeout(2000);

  await page.waitForSelector("#login");
  await page.type("#login", await codicePersonale);
  console.log("codice personale inserito");

  await page.waitForSelector("#password");
  await page.type("#password", await password);
  console.log("password inserita");

  await page.screenshot({
    path: "./screenshot.jpg",
  });
  console.log("screenshot fatto");

  await Promise.all([
    page.waitForNavigation({ waitUntil: "domcontentloaded" }),
    page.click(".accedi"),
  ]);

  await page.screenshot({
    path: "./screenshot2.jpg",
  });
  console.log("screenshot fatto");

Screenschot with puppeteer

Getting “Jest did not exit one second after the test run has completed” error for test script which was originally passing

I’m getting Jest did not exit one second after the test run has completed. error in my test scripts which were working before I added the port settings to app.js which were in www before. Now I can’t figure out what’s wrong but when I run npm test 4 out of 8 scripts pass and others get a port already in use error. When I try to run the failing scripts individually getting the above error. Following are my app.js and one of the failing yet earlier passed scripts.

`var express = module.exports = require(“express”);
const path = require(“path”);
var cookieParser = require(“cookie-parser”);
const http = require(“http”);
const socketIo = require(“socket.io”);
var debug = require(‘debug’)(‘tutormeister-app:server’);

var app = express();
const session = require(“express-session”);

Create HTTP server using Express app
const server = http.createServer(app);

Pass the server object to Socket.IO
const io = socketIo(server);

Set up Socket.IO in your app
app.set(“io”, io);

const socketsConnected = new Set();

io.on(‘connection’, (socket) => {
socketsConnected.add(socket.id);
io.emit(‘clients-total’, socketsConnected.size);

socket.on(‘disconnect’, () => {
socketsConnected.delete(socket.id);
io.emit(‘clients-total’, socketsConnected.size);
});

socket.on(‘message’, (data) => {
socket.broadcast.emit(‘chat-message’, data);
});

socket.on(‘feedback’, (data) => {
socket.broadcast.emit(‘feedback’, data);
});
});

var loginRouter = require(“./routes/login_router”);
var signupRouter = require(“./routes/signup_router”);
var createCourseRouter = require(“./routes/create_course_router”);
var insHomeRouter = require(“./routes/ins_home_router”);
var insViewCourseRouter = require(“./routes/ins_view_course_router”);
var accountEditRouter = require(“./routes/account_edit_router”);
var stuHomeRouter = require(“./routes/stu_home_router”);
var insStudentViewRouter = require(“./routes/ins_student_view_router”);
var studentMyCourseRouter = require(“./routes/studentMyCourse_router”);
var existingStudentCourseRouter = require(“./routes/existing_student_course_router”);
var stuCourseHomeRouter = require(“./routes/stu_course_home_router”);
var acceptStudentRouter = require(“./routes/accept_student_router”);
var communityRouter = require(“./routes/community_router”);

app.set(“views”, path.join(__dirname, “views”));
app.set(“view engine”, “ejs”);

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, “public”)));

app.use(
session({
secret: “your-secret-key”,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 3600000 },
})
);

app.use((req, res, next) => {
Helper function to determine active status
res.locals.active = (path) => (req.path === path ? “active” : “”);
next();
});

app.use((req, res, next) => {
const isLoginPage = req.path === “/login”;
const isLoginPage2 = req.path === “/”;
const isInstructorSignupPage = req.path === “/instructor-register”;
const isStudentSignupPage = req.path === “/student-register”;

const isLoggedIn = req.session && req.session.instructorId;

if (
(isLoginPage ||
isLoginPage2 ||
isInstructorSignupPage ||
isStudentSignupPage) &&
isLoggedIn
) {
Destroy the session only if the user is already logged in and accessing /login, /instructor-register, or /student-register
req.session.destroy((err) => {
if (err) {
console.error(“Error destroying session:”, err);
}
Redirect to the respective page after destroying the session
if (isLoginPage) {
res.redirect(“/login”);
else if (isInstructorSignupPage) {
res.redirect(“/instructor-register”);
else {
res.redirect(“/student-register”);
}
});
else {
Continue to the next middleware or route handler
next();
}
});

app.get(“/”, loginRouter);
app.post(“/”, loginRouter);

app.get(“/health”, loginRouter);

app.get(“/login”, loginRouter);
app.post(“/login”, loginRouter);

app.get(“/logout”, loginRouter);

app.get(“/instructor-register”, signupRouter);
app.post(“/instructor-register”, signupRouter);

app.get(“/student-register”, signupRouter);
app.post(“/student-register”, signupRouter);

app.get(“/create-course”, createCourseRouter);
app.post(“/create-course”, createCourseRouter);

app.get(“/instructor-home”, insHomeRouter);
app.post(“/instructor-home”, insHomeRouter);

app.get(“/instructor-account-edit”, accountEditRouter);
app.post(“/instructor-account-edit”, accountEditRouter);

app.get(“/student-account-edit”, accountEditRouter);
app.post(“/student-account-edit”, accountEditRouter);

app.get(“/viewCourse”, insViewCourseRouter);

app.get(“/student-home”, stuHomeRouter);
app.post(“/student-home”, stuHomeRouter);

app.get(“/studentMyCourse”, studentMyCourseRouter);
app.post(“/studentMyCourse”,studentMyCourseRouter);

app.get(“/existingStudentCourse”, existingStudentCourseRouter);
app.post(“/existingStudentCourse”,existingStudentCourseRouter);

app.get(“/instructor-student-view”, insStudentViewRouter);
app.post(“/instructor-student-view”, insStudentViewRouter);

app.get(“/student-course-home”, stuCourseHomeRouter);
app.post(“/student-course-home”, stuCourseHomeRouter);

app.get(“/acceptStudent”, acceptStudentRouter);
app.post(“/acceptStudent”, acceptStudentRouter);
app.post(“/rejectStudent”, acceptStudentRouter);

app.get(“/chat”, communityRouter);

app.set(‘port’, normalizePort(5000));

/**
Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
named pipe
return val;
}

if (port >= 0) {
port number
return port;
}

return false;
}

/**
Event listener for HTTP server “error” event.
*/

function onError(error) {
if (error.syscall !== ‘listen’) {
throw error;
}
var port = normalizePort(app.get(‘port’));
var bind = typeof port === ‘string’
? ‘Pipe ‘ + port
: ‘Port ‘ + port;

handle specific listen errors with friendly messages
switch (error.code) {
case ‘EACCES’:
console.error(bind + ‘ requires elevated privileges’);
process.exit(1);
break;
case ‘EADDRINUSE’:
console.error(bind + ‘ is already in use’);
process.exit(1);
break;
default:
throw error;
}
}

/**
Event listener for HTTP server “listening” event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === ‘string’
? ‘pipe ‘ + addr
: ‘port ‘ + addr.port;
debug(‘Listening on ‘ + bind);
}

/**
Start the HTTP server.
*/

server.listen(app.get(‘port’), “0.0.0.0”);
server.on(‘error’, onError);
server.on(‘listening’, onListening);

`
Create Course Test Script

`const supertest = require(‘supertest’);
const app = require(‘../app’);

Mocking the database connection
jest.mock(‘../common/database’);
const db = require(‘../common/database’);
const createCourseQuery = require(‘../querymanager/createCourseQuery’);
const createCourseController = require(‘../backend/create_course_controller’);
const { validationResult } = require(‘express-validator’);

describe(‘Create Course Controller’, () => {
test(‘createCourse should render “createCourse” view’, async () => {
const mockSession = {
instructorId: 1,
};
const mockReq = { session: mockSession };
const mockRes = {
render: jest.fn(),
redirect: jest.fn(),
};

await createCourseController.createCourse(mockReq, mockRes);

expect(mockRes.render).toHaveBeenCalledWith(‘createCourse’);
});

test(‘createCoursePost should redirect to “/instructor-home” on successful course creation’, async () => {
const mockSession = {
instructorId: 1,
};
const mockConnection = {
connect: jest.fn(),
query: jest.fn().mockImplementation((query, values, callback) => {
callback(null, { insertId: 1 }); // Mocking successful course insertion
}),
end: jest.fn(),
};

db.getMySQLConnection.mockReturnValueOnce(mockConnection);
jest.mock(‘express-validator’, () => ({
…jest.requireActual(‘express-validator’),
validationResult: jest.fn(() => ({ isEmpty: true })),
}));

const mockReq = {
session: mockSession,
body: {
courseName: ‘Math 101’,
subject: ‘Mathematics’,
eduLevel: ‘High School’,
level: ‘Intermediate’,
teachingStyle: ‘Interactive’,
teachingFormat: ‘Online’,
teachingMode: ‘Live’,
video: ‘https://example.com/math101’,
description: ‘Introduction to mathematics.’,
},
};
const mockRes = {
redirect: jest.fn(),
render: jest.fn(),
send: jest.fn(),
};

await createCourseController.createCoursePost(mockReq, mockRes);

expect(mockConnection.connect).toHaveBeenCalled();
expect(mockConnection.query).toHaveBeenCalledWith(
createCourseQuery.ADD_COURSE,
[
‘Math 101’,
‘Mathematics’,
‘High School’,
‘Intermediate’,
‘Interactive’,
‘Online’,
‘Live’,
‘https://example.com/math101’,
1, // instructorId
‘Introduction to mathematics.’,
],
expect.any(Function)
);
expect(mockRes.redirect).toHaveBeenCalledWith(‘/instructor-home’);
expect(mockReq.session.courseId).toBe(1);
expect(mockConnection.end).toHaveBeenCalled();
});

});

I tried –force-exit and –detectOpenHandles but nothing worked.

How to modify object parsed from a sample JSON body then use that object to append properly in JSON builder?

While trying to parse the sample JSON body and modify that object according to my preference, I’m having trouble appending it to the existing JSON body that it came from initially. The problem is that when I append it the previous object in array also changed according to the newest object that I modified.

I have tried multiple ways to append it to the existing body and trying to modify a copy of the object but ultimately results in the same problem. I think I’m missing something important and I’m quite new in JS/Groovy Script

Col fromCurr 
row 1 = EUR
row 2 = CAD
int rows = rateCurrencyList.getRowNumbers() /* not being used yet to iterate to all records */
def saveDiffRateSetJsonBody = '''[
    {
        "fromcurrency": "EUR",
        "invConvRate": "1.09",
        "convRate": "1",
        "sourceCode": "MANUAL",
        "tocurrency": "USD",
    }
]'''

def jsonData = (new JsonSlurper()).parseText(saveDiffRateSetJsonBody)
def newRate = jsonData[0]
                
for(int i = 0; i < 2 ; i++) {

    newRate.fromcurrency = rateCurrencyList.getValue("fromCurr", i + 1) /* COL NAME, ROW */
    newRate.toCurrency = "USD"
    newRate.invConvRate = 1.09
    newRate.convRate = 1
    newRate.sourceCode = "MANUAL"
    newRate.exchangeRateSetCd = "TDM_USD_RATE_SET"
    
    jsonData[i] = newRate
}

saveDiffRateSetJsonBody = (new JsonBuilder(jsonData)).toPrettyString()

println saveDiffRateSetJsonBody

Result is:

[
    {
        "fromcurrency": "CAD",
        "invConvRate": 1.09,
        "convRate": 1,
        "sourceCode": "MANUAL",
        "tocurrency": "USD",
    },
    {
        "fromcurrency": "CAD",
        "invConvRate": 1.09,
        "convRate": 1,
        "sourceCode": "MANUAL",
        "tocurrency": "USD",
    }
]

I’m expecting:

[
    {
        "fromcurrency": "EUR",
        "invConvRate": 1.09,
        "convRate": 1,
        "sourceCode": "MANUAL",
        "tocurrency": "USD",
    },
    {
        "fromcurrency": "CAD",
        "invConvRate": 1.09,
        "convRate": 1,
        "sourceCode": "MANUAL",
        "tocurrency": "USD",
    }
]

I can do this multiple more object and all the object parameters will be the same. I will add that I will be doing this to more complex Json body with multiple arrays, parameters and objects but I wanted to pick a specific array/object/parameter and modify it accordingly. So basically, I will have a source body for a default parameter and use that to create a new JSON body to use for the new request.

Uncaught ReferenceError: sendMessage is not defined at HTMLDocument.

Basically I was developing a chatApp using ws module and facing some issue on the frontend side regarding the the code not able to get a function in its scope.
Index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-Time Chat</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="container">
    <div id="chat-window" class="chat-box"></div>
    <div class="input-container">
      <input type="text" id="message-input" placeholder="Type your message...">
      <!-- Corrected onclick syntax -->
      <button id="send-btn">Send</button>
    </div>
  </div>
  <!-- Include client.js script -->
  <script src="client.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const sendButton = document.getElementById('send-btn');
      // Corrected event listener registration without invoking the function
      sendButton.addEventListener('click', sendMessage);
    });
  </script>
</body>
</html>

this is the html code I am using on the frontend
style.css

body {
    font-family: Arial, sans-serif;
    background-color: #fffdd0; /* Light yellow background */
    margin: 0;
    display: flex;
    justify-content: center; /* Aligns content horizontally */
    align-items: center; /* Aligns content vertically */
    height: 100vh; /* Full viewport height */
  }
  
  .container {
    max-width: 600px;
    width: 100%;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
  }
  
  .chat-box {
    height: 300px;
    overflow-y: scroll;
    border: 1px solid #ccc;
    padding: 10px;
    margin-bottom: 10px;
  }
  
  .input-container {
    display: flex;
  }
  
  #message-input {
    flex: 1; /* Takes remaining space */
    padding: 10px;
    border-radius: 5px;
    border: 1px solid #ccc;
    margin-right: 10px;
  }
  
  button {
    padding: 10px;
    border-radius: 5px;
    border: none;
    background-color: #007bff; /* Blue button color */
    color: #fff;
    cursor: pointer;
  }
  
  /* Message bubble styling */
  .message-bubble {
    background-color: #007bff;
    color: #fff;
    border-radius: 10px;
    padding: 10px;
    margin-bottom: 5px;
    max-width: 80%;
    word-wrap: break-word;
  }
  
  .message-container {
    display: flex;
    justify-content: flex-end; /* Aligns sent messages to the right */
  }

this is styles.css code which is used with html code for better view.
client.js

// client.js
document.addEventListener('DOMContentLoaded', () => {
  const chatWindow = document.getElementById('chat-window');
  const messageInput = document.getElementById('message-input');
  const ws = new WebSocket('ws://localhost:3000');

  // Event handler for incoming messages
  ws.onmessage = event => {
    const messageData = JSON.parse(event.data);
    const { message, sender } = messageData;

    if (sender !== 'self') {
      appendMessage(message);
    }
  };

  // Function to send a message
  function sendMessage() {
    const message = messageInput.value.trim();
    if (message !== '') {
      ws.send(JSON.stringify({ message }));
      messageInput.value = '';
    }
  }

  // Function to append a message to the chat window
  function appendMessage(message) {
    const messageElement = document.createElement('div');
    messageElement.textContent = message;
    messageElement.classList.add('message-bubble');
    chatWindow.appendChild(messageElement);
    chatWindow.scrollTop = chatWindow.scrollHeight;
  }
});

These were all components of the frontend and the error it is giving as soon as we click the send button is
Uncaught ReferenceError: sendMessage is not defined at HTMLDocument.<anonymous> ((index):24:44)

How do I select a value using the slide bar?

Can someone please help me with this project I am working on? I want to select either one of the two divs (KgDiv, LDiv) by clicking it, then use the slide bar to select a value between 0 and the maximum value of the Kilograms/ Liters paragraph, then use the Sell button to convert Kg or L to € at a rate of 1 to 1. Also the quantity (kg or l) selected using the slide var should be displayed next to the slide bar.

<div id="KgDiv">
<p id="Kilograms">Kilograms</p>
<input type="button" onClick="AddKg()" value="+400Kg"></input>
</div>
<div id="LDiv">
<p id="Liters">Liters</p>
<input type="button" onClick="AddL()" value="+340L"></input>
</div>

<input type="button" onClick="Sell()" value="Sell"></input>
<p id="Money">€ 0</p>

<input id="SlideBar" type="range" min="0" max="100" value="50"></input>
var KilogramsV=0;
var LitersV=0;
function AddKg(){
KilogramsV+=400;
document.getElementById("Kilograms").innerHTML=KilogramsV +" "+ "Kilograms";
}
function AddL(){
LitersV+=340;
document.getElementById("Liters").innerHTML=LitersV +" "+ "Liters";
}

This is what I have so far.
Thanks!

I have watched yt videos but couldn’t find anything helpful.