How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code.
test.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title
</head>

<body>
    <script type="module" src="./test.js"></script>
</body>

</html>

test.js

import * as tf from "./node_modules/@tensorflow/tfjs";
import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter";

const MODEL_URL = './model.json';

const model = await loadGraphModel(MODEL_URL);
const cat = document.getElementById('cat');
model.execute(tf.browser.fromPixels(cat));

Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Can anyone help to solve this? Thank you

Mongoose empty subdocument array

I made this mongoose schema with a nested array of subdocuments:

const deliverySchema = new db.Schema({
   price: Number
})

const suppliersSchema = new db.Schema({
    name: String,
    deliveries: [deliverySchema]
})

exports.Suppliers = db.model('Suppliers', suppliersSchema)
const suppliers = new Suppliers({name})

await suppliers.save()

But when I try to save a document i get this error:

TypeError: Cannot read properties of undefined (reading 'length')
    at cloneArray...

If I remove the subdocument from the schema the document gets saved without issues.

Why can’t I save the document with this schema?

Create a Javascript vidiprinter

I’m using javascript on a webpage and looking for a way to create a vidiprinter effect to output text to a text area on a web page. I mean in the style of how they use to do the latest football results back in the 80’s and with an ‘*’ as the flashing cursor.

For example it would first show * flashing for a couple of seconds and then start typing out the text one letter at a time with the * flashing as it goes along.

Hope that makes sense with what I’m after. I’ve tried myself using different methods but with no success.

Send data from java to JavaScript using WebView

i’m trying to make a map java project using web view , i want to send the Longitude and Latitude from java to JavaScript .

i have used the webengine.executeScript("latitude") like this

Java

private Double longitude = 48.8588336;
private Double latitude = 2.2769956;
/*code*/
latitude= (Double) webengine.executeScript("latitude");

JavaSript

let longitude;
  let latitude;
  var map = L.map('map').setView([longitude,latitude], 13);

the Longitude and latitude didn’t send to Js.

Remove array map and handlers from render operation

I wrote this code a while ago and I came back to try and clean it by removing the map array and handlers out of the render operation but I keep getting syntax errors. How could I go about this? I’m getting the same error: Syntax error: Unexpected token, expected “,” but varying on how I try to separate it.

 if (!sales) {
    return (
      <div>
        <Spinner />
      </div>
    );
  }

 return (
    <ul>
      {sales.map((result) => {
        const {
          sale_id,
          buyer,
          seller,
          listing_price,
          listing_symbol,
          created_at_time,
        } = result;

        function HandleBuyerClick() {
          window.location = '/user/' + buyer;
        }
        function HandleSellerClick() {
          window.location = '/user/' + seller;
        }

        if (buyer !== null) {
          return (
            <Card>
              <li key={sale_id}>
                <h3>
                  <Transaction>
                    <Button onClick={HandleSellerClick}>{seller}</Button>
                  </Transaction>{' '}
                  just sold item number
                  <Transaction>
                    <Button>{sale_id}</Button>
                  </Transaction>{' '}
                  to
                  <Transaction>
                    <Button onClick={HandleBuyerClick}>{buyer}</Button>
                  </Transaction>{' '}
                  for <Transaction>{formatNumber(listing_price)}</Transaction>{' '}
                  {listing_symbol} at {parseTimestampJM(created_at_time)}
                </h3>
              </li>
            </Card>
          );
        }
      })}
    </ul>
  );

Javascript show only X amount from array.map with option to show all

I have a table row, and inside a cell I want to display values mapped from an array (yes in a single cell). I have too many values in this array, so I want to only show 3 and then have a button to show the rest if clicked. How can I go about to achieve this? Current code:

<TableCell align="right">
 {row[headCell.id].map((obj) => (
  <>
   {obj}
   <br />
  </>
 ))}
</TableCell>

intersection observer works only for the first video

I need to pause a video if it is not in view
the below code works only for the first video in list
how to make it working for all .bvideo ?

<video class='bvideo' src='a.mp4' poster='a.jpg' preload='none' controls></video>
<video class='bvideo' src='b.mp4' poster='b.jpg' preload='none' controls></video>
<video class='bvideo' src='c.mp4' poster='c.jpg' preload='none' controls></video>

let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if(!entry.isIntersecting){entry.target.pause();}
  });
});

$(document).ready(function(){
    io.observe(document.querySelector('.bvideo'));
});

automating / overriding / extending prefix in console.log for debugging

Anyone have a good solution to extending console.log so that it auto prints class name and method as a prefix? I’m using web components and use strict is turned on.

someFunction() {
  let varA = "hello"
  console.log(this.constructor.name, "someFunction", {varA})
}

Would like to automate this part: this.constructor.name, “someFunction”, …

arguments.callee.name will print the function name, but no longer works with strict mode turned on.
Extending console.log in a centralized location via:

export var log = function(){
  var args = Array.prototype.slice.call(arguments);
  args.unshift(this.constructor.name + ": ");
  console.log.apply(console, args);
}

does not work as this.constructor.name does not print the correct context and if it’s not in a web component, it doesn’t work at all.
Extending console.log in each web component defeats the purpose (or half of it).
Could fold a function that extends console.log in the build for each web component but would still have the problem of not being able to call arguments.calleee.
Using lit-element, but this is a native javascript issue.

How to Android WebView video fullscreen lock orientation

Screen orientation lock (screen.orientation.lock()) is not working in android webview.

function lockLandScape() {
    console.log(JSON.stringify(screen.orientation.lock))
    if (screen.orientation && screen.orientation.lock) {
      screen.orientation.lock('landscape');
    }
}
function unlockLandScape() {
    if (screen.orientation && screen.orientation.unlock) {
        screen.orientation.unlock()
    }
}   
function videoFullScreen(elem){
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { 
      elem.msRequestFullscreen();
    }
    elem.classList.add("fullscreen");
    lockLandScape()
}

Where elem is video element in webview.

JavaScript: How to move through my question array

I am really stuck! As a newbie, I am trying to build a guessing game for Flags of the World.
I have an array of objects which I want to shuffle. I then want to select the correct country that matches the image and add that to three answer buttons. Currently I am doing this by creating variables using a fixed index from the shuffled array for the currentFlagIndex (correct) and wrongFlagIndex (wrong) and anotherWrongIndex (also wrong).
I then want to check for a ‘correct’ or ‘wrong’ answer and then for the user to click ‘next’ which would load the next ‘correct’ country and image and two ‘incorrect’ countries from my array of objects.
I can make this all work once, as per the code below, but I am completely stuck on how to move to the ‘next’ question.
I am running this all against a 60 second timer. I have the timer counting down, but have not attempted to put a check in to ensure this is not at zero (I will do that once I know how to move my questions on).

Flags Array extract:

const flags = [
{ 
    image: 'assets/images/ad.webp',
    country: 'Andorra',
},
{ 
    image: 'assets/images/ae.webp',
    country: 'United Arab Emirates',
},
{ 
    image: 'assets/images/af.webp',
    country: 'Afghanistan',
},

Game JavaScript:

const startButton = document.getElementById('start-button');
const nextButton = document.getElementById('next-button');
const answerButtons = document.getElementById('answer-buttons');

nextButton.addEventListener('click', buildNextQuestionArray);
/**
 * Set 60 second countdown timer. Code modified from Grepper: https://www.codegrepper.com/code-examples/javascript/add+countdown+timer+to+javascript+quiz
 */
let count = 60;
let interval = setInterval(function () {
    document.getElementById('timer').innerHTML = count;
    count--;
    if (count === 0) {
        clearInterval(interval);
        document.getElementById('timer').innerHTML = 'GAME OVER'; // this is where I can add what to do once the timer ends - take to the GAME OVER score html page
    }
}, 1000);

/**
 * Function to randomly sort array modified from: https://www.codegrepper.com/code-examples/javascript/how+to+randomly+sort+an+array+javascript 
 */
function createNewFlags(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}

let newFlags = createNewFlags(flags);
console.log(newFlags[0].country);

let currentFlagIndex = 0;
console.log(newFlags[currentFlagIndex]);

let wrongFlagIndex = 12;
console.log(newFlags[wrongFlagIndex]);

let anotherWrongFlagIndex = 21;
console.log(newFlags[anotherWrongFlagIndex]);

/** 
 * Create an array of the correct answer and two wrong answers
 **/
function buildFullAnswerArray() {
    let fullAnswerArray = []; {
        fullAnswerArray.push(newFlags[currentFlagIndex].country);
        fullAnswerArray.push(newFlags[wrongFlagIndex].country);
        fullAnswerArray.push(newFlags[anotherWrongFlagIndex].country);
    }
    return fullAnswerArray
}

let allAnswers = buildFullAnswerArray();
console.log(allAnswers);

/** 
 * Shuffle the allAnswers array so that the order of the countries in the answers will be randomised
 **/
function createShuffledAnswers(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}

let finalAnswers = createShuffledAnswers(allAnswers);
console.log(finalAnswers);


    document.getElementById('flag').src = newFlags[currentFlagIndex].image;

    let answer1 = document.getElementById('answer-1');
    let answer2 = document.getElementById('answer-2');
    let answer3 = document.getElementById('answer-3');

    answer1.innerText = finalAnswers[0];
    answer2.innerText = finalAnswers[1];
    answer3.innerText = finalAnswers[2];

    answer1.addEventListener('click', checkAnswer);
    answer2.addEventListener('click', checkAnswer);
    answer3.addEventListener('click', checkAnswer);


/** 
 * Check button onclick whether correct answer or not - event listener
 * If correct - return 'CORRECT!' and change the body color to green
 * If incorrect - return 'WRONG!' and change the body color to red
 **/

function checkAnswer() {
    if (this.textContent === newFlags[currentFlagIndex].country) {
        let correct = true
        let correctAnswer = `CORRECT!`
        document.getElementById('result').innerHTML = correctAnswer;
        setStatusClass(document.body, correct);
        increaseScore();
    } else {
        let wrong = false
        let wrongAnswer = `WRONG!`
        document.getElementById('result').innerHTML = wrongAnswer;
        setStatusClass(document.body, wrong);
    }
    nextButton.classList.remove('hide');
    answerButtons.classList.add('hide');
}

/**
 * Gets the current score from the DOM and increments it by 1
 */
function increaseScore() {
    let currentScore = parseInt(document.getElementById('correct').innerText);
    document.getElementById('correct').innerText = ++currentScore;
}
/**
 * Adds a class to the body depending on whether the answer is correct or wrong. Allows the body color to be changed depending on correct or wrong answers.
 * Adapted from Web Dev Simplified YouTube Video: https://www.youtube.com/watch?v=riDzcEQbX6k
 */
function setStatusClass(element, correct) {
    clearStatusClass(element)
    if (correct) {
        element.classList.add('correct')
    } else {
        element.classList.add('wrong')
    }
}

/**
 * Resets class status on body. Used when setting the nextQuestion()
 * Adapted from Web Dev Simplified YouTube Video: https://www.youtube.com/watch?v=riDzcEQbX6k
 */
function clearStatusClass(element) {
    element.classList.remove('correct')
    element.classList.remove('wrong')
}

function resetState() {
    clearStatusClass(document.body);
    nextButton.classList.add('hide');
}

// function buildNextQuestionArray() {
//     currentFlagIndex = ++currentFlagIndex;
//     wrongFlagIndex = ++wrongFlagIndex;
//     anotherWrongFlagIndex = ++anotherWrongFlagIndex;
//     let nextQuestionArray = []; {
//         nextQuestionArray.push(newFlags[currentFlagIndex].country);
//         nextQuestionArray.push(newFlags[wrongFlagIndex].country);
//         nextQuestionArray.push(newFlags[anotherWrongFlagIndex].country);
//     }
//     return nextQuestionArray
// }

// let nextAnswers = buildNextQuestionArray();
// console.log(nextAnswers);

I have commented out the above code as it will generate a new array of three but it also causes the current correct answer to return wrong, so must be changing the variables.

I think I have a problem where I am inserting the answer text and image outside of a function, but I have tried many things here, which all return errors.

Game HTML:

 <!-- GAME AREA -->
    <div class="container">
        <div id="timer"></div>
        <div id="flag-container" class="flag"><img src="" id="flag"></div>
        <div id="answer-buttons" class="answer-box">
            <button class="btn" id="answer-1">Country 1</button>
            <button class="btn" id="answer-2">Country 2</button>
            <button class="btn" id="answer-3">Country 3</button>
        </div>
        <div id="result" class="result"></div>
        <!-- <div class="answer-box"><button class="start-btn" id="start-button">Start >></button></div> -->
        <div class="answer-box"><button class="next-btn hide" id="next-button">Next flag >></button></div>
        <div class="score">Score: <span id="correct" class="score">0</span></div>
    </div>

    <!-- SCRIPTS -->
    <script src="assets/js/flags.js"></script>
    <script src="assets/js/game.js"></script>

I have a solution where I can add two incorrect answers to my flags array, but that seems like a long-hand (there are 216 flags!) way to ‘solve’ this problem. I have all of the parts, I just need someone to help me move through the array to the next flag please!

The latest version of the full code is also deployed here: Git Hub

I am sure there is a lot wrong with my code, but any straightforward help to move me on would be much appreciated!

how to conditionally apply text to data variable based on props in VueJS

How can I conditionally apply value to the data variable based on props, the ternary operator is generating error, I would like to refer to this code:

<template>
  <div class="absolute left-3 top-1/2">
    <img
      :src="hamburgerUrl"
      style="width: 25px; cursor: pointer; transform: translateY(-50%)"
      alt="toggle menu button"
    />
  </div>
</template>

<script>
export default {
  name: "HamburgerMenu",
  props: ["white"],
  data: {
    hamburgerUrl: this.white
      ? "/gfx/hamburger-white.png"
      : "/gfx/hamburger-menu.png",
  },
};
</script>

and I get the error saying :

TypeError
Cannot read property 'white' of undefined

I have tried to validate the props and set it to not required like so:

  props: {
    white: {
      type: Boolean,
      required: false,
      default: false,
    },
  },

But it didn’t help, what am I doing wrong?
Thanks

Animate accordion plugin with auto height

I am using a very lightweight plugin which is great but I can’t get it to animate withut a fixed height.

I initally tried the usual transitions before realising they did not work with auto height

I tried modifying some JS I found but this did not work

var headers = document.querySelectorAll('.aab__accordion_head');

for (var i=0; i<headers.length; i++) {
  headers[i].addEventListener('click', toggleDisplay);
}

function toggleDisplay() {
  if (this.parentNode.classList.contains('aab__accordion_body--show')) {
    var currentlyDisplayed = document.querySelectorAll('.aab__accordion_body--show');
    for (var e=0; e<currentlyDisplayed.length; e++) {
      currentlyDisplayed[e].classList.remove('aab__accordion_body--show');
    } 
  } else {
    this.closest('.aab__accordion_body').classList.add('aab__accordion_body--show');
  }
}

I also tried a suggestion of using ScaleY like this

.wp-block-aab-accordion-block .aab__accordion_body {
    transform: scaleY(0);
    display: 
    transition: scale 300ms ease-in-out !important; 

}


.wp-block-aab-accordion-block .aab__accordion_body.aab__accordion_body--show {
    transform: scaleY(1);
    transition: scale 300ms ease-in-out !important; 
}

But this still reserves the space where it should be and doesn’t work.

I’ve tried this too but with no luck

.aab__accordion_container  {
    display: grid !important;
}

.aab__accordion_head:hover + .aab__accordion_body--show {
    display: flex !important;
    flex-direction: column !important;
}

.aab__accordion_container p {
    flex-basis: 0;
    overflow: hidden;
    transition: 1s;
}

I will actually have Gutenberg blocks in there too but I just thought i would test to see if I could get the

to show

The accordion panel is here

tinyurl.com/4afdnpkm

Any help would be appreciated

Thanks