getEngineFactories() returns an empty list

I need to execute JS code in Java (JDK 18). To do this, I want to use the ScriptEngine class with the engine “Nashorn” (or any other capable of executing Javascript) using the constructor new ScriptEngineManager().getEngineByName(“nashorn”).

The problem is that this code returns null, the same happens for the name “js”. Then I decided to go through the list of all possible engines with new ScriptEngineManager().getEngineFactories(), but it returns…an empty list. After a little digging, I also found out that Nashorn seems to have been removed from JDK15, so another question: what to use?

Remove all routes from a map with mapbox

I have code with a structure similar to this one that I put in Codepen and I want to create a function to remove all the routes drawn on the map. But I can’t remove the route in blue, which is the last one tested by mapbox.

codepen: https://codepen.io/lucasthaynan/pen/ZEqGYqM

Script done but unable to remove the route in blue:


function removeRoutes(map) {

  if (map.getSource("theRoute")) {
    map.removeLayer("theRoute");
    map.removeSource("theRoute");
  }
  if (map.getSource("theBox")) {
    map.removeLayer("theBox");
    map.removeSource("theBox");
  }
  if (map.getSource("clearances")) {
    map.removeLayer("clearances");
    map.removeSource("clearances");
  }
  if (map.getSource("route")) {
    map.removeLayer("route");
    map.removeSource("route");
  }
  if (map.getSource("load")) {
    map.removeLayer("load");
    map.removeSource("load");
  }

}

Javascript Giving Random Number Of Input Text Length

I cant seem to get my js code properly functioning. I looped through
the elements that are in a list and printed out their text length (elements are inputs)
and it just gave me the same random numbers (4, 5, 8)

function OnCreation() {
  let X = {
    User: document.getElementsByClassName("Username").value,
    Gmail: document.getElementsByClassName("Gmail").value,
    Password: document.getElementsByClassName("Password").value
  }
  for (var Y in X) {
    console.log(Y.length)
  }
}

send message to iframe from main page in localhost

I am trying to send a message between two files that are in the same folder in localhost, main.php and iframe.php, but the iframe does not listen to it, I have tried to use many target origin like this:

mainpage.php

const iframe = document.querySelector('.iframe');
        
iframe.contentWindow.postMessage("message sent from localhost/mainpage.php","http://localhost/iframe.php");

and inside the iframe.php to listen to the message i use

window.onmessage = function(event) {

    alert(event.data);
}

How to update interval time with external variable using jQuery

I have created this script in JS that when a button is pressed, an audio file is played repeatedly. For context, the audio file is some ‘beep’ and is used as sort of an alarm. The speed at which the beep must be played is depending on a setting which can be found on a page called ‘sound.php’.

Now this script is working partly. Whenever the sound-producing page is loaded up, and the ‘Play’ button is pressed, the beeping starts and it is audible at the correct frequency.

However, when the time interval on sound.php is changed in real time, the frequency of the beeping does not change with it.

I believe that the script as it is now, will retrieve the interval from sound.php every 1000ms but something is not right and I cannot get it to work.

$(document).ready(function () {
    ajax_call = function() {
        $.ajax({
            type: "GET",
            url: "sound.php",
            dataType: "html",              
            success: function (response) {
                soundValue = response;
            }
        });
    };
    var interval = 1000; //refresh every second
    setInterval(ajax_call, interval);
});
    
function play() {
  const intervalTime = soundValue; // Interval time in milliseconds
  const interval = setInterval(function() {
    var audio = new Audio('beep.mp3');
    audio.play();
  }, intervalTime);
  
  setTimeout(function() {
    clearInterval(interval);
  }, 900000);
}

What am I missing here? Small thing or a major flaw that I’m not overseeing? Any help is much appreciated.

How to set Authorization header in jest testing?

I have this testing code that it’s not returning what i want, and it’s sending me 401 Authorization error, am i doing something wrong? I’m new at testing. I already tried passing the raw authentication token, but still the same error.

This is the error:

GET /products › should return a list of products                                                  
                                                                                                  
expect(received).toBe(expected) // Object.is equality

Expected: 200
Received: 401

  22 |       .get("/product")
  23 |       .set("Authorization", `Bearer ${token}`);
> 24 |     expect(res.status).toBe(200);
     |                        ^
  25 |     expect(Array.isArray(res.body)).toBe(true);
  26 |   });
  27 | });

  at __tests__/controllers/product.test.ts:24:24
  at fulfilled (__tests__/controllers/product.test.ts:5:58)
import request from "supertest";
import { Request, Response } from "express";
import { app } from "../../src/app";
import { connect, disconnect } from "../../src/database/db";
import Product from "../../src/models/Product";
import Category from "../../src/models/Category";
import jwt from "jsonwebtoken";
import { login } from "../../src/controllers/auth"

beforeAll(async () => {
  await connect();
});

afterAll(async () => {
  await disconnect();
});

describe("GET /products", () => {
  it("should return a list of products", async () => {
    const token = jwt.sign({ role: "admin" }, "CARDAPIOJWTPASS");
    const res = await request(app)
      .get("/product")
      .set("Authorization", `Bearer ${token}`);
    expect(res.status).toBe(200);
    expect(Array.isArray(res.body)).toBe(true);
  });
});

Biggest value in bar chart does not appear

I have a bar chart that I have scripted and am loading values in through my json file. All values appear through labels except for my highest value (60). What can I do to get my 60 label to appear in my chart?

html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>CS50C Week11</title>
  </head>
  <body>
    <div style="margin-top: 50px; padding:auto">
        <canvas id="myCanvas" width="500" height="500" ></canvas>
      </div>
    <script src="script.js"></script>
  </body>
</html>

data.json

[25, 30, 40, 50, 35, 20, 45, 60, 55, 50]

script.js

try {
  // Load data from JSON file
  fetch('data.json')
    .then(response => response.json())
    .then(data => {
      // Initialize canvas element
      const canvas = document.getElementById('myCanvas');
      if (!canvas) {
        throw new Error('Canvas element not found');
      }
      const ctx = canvas.getContext('2d');

      // Set chart properties
      let chartWidth = 500;
      let chartHeight = 500;
      const barSpacing = 10;
      const barWidth = (chartWidth - (data.length - 1) * barSpacing) / data.length;
      const maxValue = Math.max(...data);
      const labelFont = '16px Arial';
      const valueFont = '12px Arial';
      const labelColor = '#333';
      const valueColor = '#999';

      // Draw bars and labels
        data.forEach((value, index) => {
        const x = index * (barWidth + barSpacing);
        const y = chartHeight - (value / maxValue) * chartHeight;
        const height = (value / maxValue) * chartHeight;

        // Draw bar
        ctx.fillStyle = '#66a';
        ctx.fillRect(x, y, barWidth, height);

        // Draw label
        ctx.font = labelFont;
        ctx.fillStyle = labelColor;
        ctx.textAlign = 'center';
        ctx.fillText(` ${index + 1}`, x + barWidth / 2, chartHeight + 20);

        // Draw value
        ctx.font = valueFont;
        ctx.fillStyle = valueColor;
        ctx.textAlign = 'center';
        ctx.fillText(value, x + barWidth / 2, y - 10);


      });
    })
    .catch(error => console.log(error.message));
} catch (error) {
  console.log(error.message);
}


I have tried adding this if condition in my Draw Label section of my JS

 ctx.textAlign = 'center';              
if (index === data.length - 1) {
        // Adjust x-coordinate for last bar label
        x += barWidth / 2;
      }

so that way it only manipulates x under that condition, but doing so makes my bar furthest to the right disappear (in addition to my 60 bar already being gone)

Ccapture.js and poor webm video quality

I created a simple script to test Ccapture.
It works well but the webm export is of a very poor quality (the edge of the shapes are very pixellated), even though the options are set to “quality: 100”.

I exaggerated the contrast (green background and red shapes) so that the quality shows.

Can someone tell me how I can improve the result?

Thanks.

<!DOCTYPE html>
<html>
<head>
</head>

<body>
    <canvas id="myCanvas" width="960" height="540" style="border:1px solid black"></canvas>
    <button onclick="startRecording()">Start</button>
    <button onclick="stopRecording()">Stop</button>

    <script>
        function startRecording() {
            t = 0;
            capturer.start();
            animation();
        }
    
        function stopRecording() {
            capturer.stop();
            capturer.save();
        }
    
        const canvas = document.getElementById("myCanvas");
        const ctx = canvas.getContext("2d");
        let t = 0;
        let  duration = 120;
        let  startSize = 100; 
        let  startX = (canvas.width - startSize) / 2;
        let  startY = (canvas.height - startSize) / 2;
        let  endSize = startSize * Math.sqrt(2);
        let  endX = (canvas.width - endSize) / 2;
        let  endY = (canvas.height - endSize) / 2;
        
        function animation(){
            const size = startSize + (endSize - startSize) * t / duration;
            const x = startX + (endX - startX) * t / duration;
            const y = startY + (endY - startY) * t / duration;
        
            ctx.fillStyle = "green";
        
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        
            ctx.beginPath();
        
            if (t < duration / 2) { 
                ctx.fillStyle = "red";
                ctx.rect(x, y, size, size);
            } else { 
                ctx.fillStyle = "red";
                ctx.arc(x + size / 2, y + size / 2, size / 2, 0, Math.PI * 2);
            }
            ctx.fill();
        
            if (capturer && capturer.capture) {
                capturer.capture(canvas);
            }
        
            if (t < duration) {
                requestAnimationFrame(animation);
                t++;
            } else if (capturer && capturer.save) {
                capturer.stop();
                capturer.save();
            }
        }
    </script>

    <script src="https://www.clicktorelease.com/code/conway3d_ccapture/js/CCapture.all.min.js"></script>

    <script>
        var capturer = new CCapture( { 
            format: 'webm',
            framerate: 60,
            name: 'visualization',  
            quality: 100,
            verbose: true
        } );
    </script>

</body>

</html>

PS: I kept it all in one file so people can easily copy paste and test this.
If you want me to separate the html from the js, just ask.

Thank you.

I developed a webview application with Flutter and I’m having a cache problem

I am developing an application with flutter, I used flutter_webview in the application, there is no problem, but after a little navigation between large pages, I noticed that some pages are not loading, I think the cache memory is filling up. When I refresh, I can only access the page (reload), so is there a method for this, this way the application becomes unusable, how can I solve this problem thanks

Problems with classes in Tailwind when mapping

I have an API that pulls all data from a table into one. The issue is that I have a Header Component with links, and to make it more flexible and dynamic, I want to separate the pages that have the same category as the link and map them into objects, filtering them. All the mapping goes very smoothly, however when I try to apply the Tailwind classes to them, in case the link they redirect to is the current one, for some reason it adds several commas at the end of the classes “,,,,”.

I’m using NextJS App Directory and Tailwind. Here is the code I used in the Header:

<li
          className={`h-full flex flex-col justify-center group items-center cursor-pointer text-[17px] text-[gray] hover:text-[hsl(var(--theme-color-light))] px-2 border-4 border-transparent ${pages
            .filter((p) => p.category === "8")
            .map((p) =>
              pathname === "/paginas/" + p.url
                ? "font-bold text-[hsl(var(--theme-color))] border-t-[hsl(var(--theme-color))]"
                : ""
            )}`}
        >
          HABBLETXD
          <ul className="absolute rounded-[0.3rem] shadow-[0px_0px_20px_hsla(0,0%,0%,0.25)] top-[65px] opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-all before:content-[''] before:w-0 before:h-0 before:absolute before:border-[7.5px] before:border-transparent before:border-b-[hsl(var(--theme-color))] before:top-[-15px] before:left-[calc(50%-10px)]">
            <div className="h-full w-full flex flex-col rounded-[0.3rem] overflow-hidden">
              {pages
                .filter((p) => p.category === "8")
                .map((item) => (
                  <a
                    className="px-4 py-[0.9rem] h-full w-full bg-white flex justify-center items-center text-base font-bold text-[hsl(var(--theme-color))] transition-all hover:bg-[hsl(var(--theme-color))] hover:text-white"
                    style={{ textShadow: "0px 0px 5px hsla(0, 0%, 0%, 0.25)" }}
                    key={item.name}
                    href={`/paginas/${item.url}`}
                  >
                    {item.name}
                  </a>
                ))}
            </div>
          </ul>
        </li>

The data I used in this code I set in states. In addition, I used hooks from NextJS itself, such as usePathname (pathname).

Here’s the print of how the code results:

How to reset `top`, `left`, `transition` attributes using a css class?

The below is meant for simulating a drag and drop effect. I’m manually changing the styles both on mousedown and mouseup events using Object.assign(target.style, ...). If I replace the assigment statements with .dragging class that contains the mousedown styles, followed by removing that class on mouseup, the associated left and top attributes set in mouseup stay after removing the .dragging class.

Here’s the working version:

(function() {
    let targets = document.querySelectorAll('.draggable');
    let offsetX;
    let offsetY;
    targets.forEach((target) => {
        target.isMouseDown = false;
        target.initialOffsetLeft = target.offsetLeft;
        target.initialOffsetTop = target.offsetTop;
        target.addEventListener('mousedown', (e) => {
            if (e.buttons === 1) {
                Object.assign(target.style, {
                    transition: null,
                    zIndex: 10000,
                    position: 'relative'
                });
                target.isMouseDown = true;
                offsetX = target.initialOffsetLeft + e.offsetX;
                offsetY = target.initialOffsetTop + e.offsetY;
            }
        });
        document.addEventListener('mouseup', (e) => {
            e.preventDefault();
            target.isMouseDown = false;
            Object.assign(target.style, {
                transition: 'all 0.5s ease',
                zIndex: null,
                left:  '0',
                top: '0'
            });
        });
        document.addEventListener('mousemove', (e) => {
            e.preventDefault();
            if (target.isMouseDown) {
                target.style.left = e.pageX - offsetX + 'px';
                target.style.top = e.pageY - offsetY + 'px';
            }
        });
    });
})();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Roboto', sans-serif
}

.draggable {
  display: flex;
  padding: 10px 12px;
  margin-top: 0px;
  margin-left: 0px;
  margin-bottom: 11px;
  border-radius: 5px;
  margin-right: 5px;
  background-color: #000000;
  cursor: grab;
  flex-grow: 1;
  color: #ffffff;
  border: 1px solid #6c757d;
}

.my-card-group {
  margin-top: 30px;
  background-color: #000000;
  margin-right: 2%;
  margin-left: 2%;
  border: 1px solid #6c757d;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="card group">
  <div class="my-card-group">
    <div class="card-body">
      <div class="draggable">
        Lorem ipsum dolor sit amet 1
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 2
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 3
      </div>
    </div>
  </div>
</div>

Here’s what I do to replace the Object.assign(...) statements with .dragging class:

(function() {
    let targets = document.querySelectorAll('.draggable');
    let offsetX;
    let offsetY;
    targets.forEach((target) => {
        target.isMouseDown = false;
        target.initialOffsetLeft = target.offsetLeft;
        target.initialOffsetTop = target.offsetTop;
        target.addEventListener('mousedown', (e) => {
            if (e.buttons === 1) {
                target.classList.add('dragging')  // replaced with this
                target.isMouseDown = true;
                offsetX = target.initialOffsetLeft + e.offsetX;
                offsetY = target.initialOffsetTop + e.offsetY;
            }
        });
        document.addEventListener('mouseup', (e) => {
            e.preventDefault();
            target.isMouseDown = false;
            target.classList.remove('dragging') // replaced with this
        });
        document.addEventListener('mousemove', (e) => {
            e.preventDefault();
            if (target.isMouseDown) {
                target.style.left = e.pageX - offsetX + 'px';
                target.style.top = e.pageY - offsetY + 'px';
            }
        });
    });
})();
 

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif
}

.draggable {
    display: flex;
    padding: 10px 12px;
    border-radius: 5px;
    margin: 0 5px 11px 0;
    background-color: #000000;
    cursor: grab;
    flex-grow: 1;
    color: #ffffff;
    border: 1px solid #6c757d;
    transition: all 0.5s ease; /*added this*/
    z-index: unset; /*added this*/
    left: 0; /*added this*/
    top: 0 /*added this*/
}

.dragging { /*added this*/
    z-index: 10000;
    position: relative;
    transition: all 0s;
}

.my-card-group {
    margin-top: 30px;
    background-color: #000000;
    margin-right: 2%;
    margin-left: 2%;
    border: 1px solid #6c757d;
}
 
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="card group">
  <div class="my-card-group">
    <div class="card-body">
      <div class="draggable">
        Lorem ipsum dolor sit amet 1
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 2
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 3
      </div>
    </div>
  </div>
</div>

This breaks how the dragging works because left and top as well as transition attributes persist after .dragging is removed, and the next time any of the .draggable is dragged, it starts where its previous drag ended and with a transition delay set by .dragging. Is there a way to achieve the initial behavior using a similar approach?

How to show a message if the search doesn’t match the result?

I am using node js and templates of ejs in my application, and I am trying to show a message in case the search field doesn’t match any result, I expected it will show me “Line does not exist.”, but it shows the search results instead as shown in the screenshot below:

enter image description here

I tried to modify the condition in the if statement <% } else if(oneresult != ''){ %> in different ways but it doesn’t work. Below is the code:

<%- include('partials/header') -%>

<div class="container mt-5 w-50">
  <h2 class="mb-4">Search a Line</h2>

  <form action="/line" method="GET">
    <input
      type="text"
      name="line"
      class="form-control"
      placeholder="Enter a Line"
    />

    <button type="submit" class="btn btn-danger btn-block mt-3">
      Search in Database
    </button>
  </form>

  <% if(oneresult) { %>
  <h4 class="text-danger my-4">Search Results:</h4>
  <table class="table table-bordered" width="100%" cellspacing="0">
    <thead>
      <tr>
        <th>ID</th>
        <th>Line</th>
        <th>Date</th>
      </tr>
    </thead>

    <tbody>
      <% oneresult.forEach( oneresult=>{ %>
      <tr>
        <td><%= oneresult.id %></td>
        <td><%= oneresult.result %></td>
        <td><%= oneresult.date %></td>
      </tr>
      <% }) %>
    </tbody>
  </table>
  <% } else if(oneresult != ''){ %>

  <div class="alert alert-danger mt-4">Line does not exist.</div>

  <% } %>
</div>

<%- include('partials/footer') -%>

Any suggestions, please?