How can I display Plop generators based on choice?

I’m trying to configure Plop so that when the command is run, a sort of menu is first displayed prompting to select what group of generators you’d want to run. For example, you have generators for frontend files and generators for backend files. When you run plop, you should first be prompted with what group of generators you want to proceed with, then from that choice, the correspoding generators will be revealed to pick from.

Here’s what I have so far:

const controllerGenerator = require('./generators/server/controller');

module.exports = function (plop) {
  plop.setGenerator('menu', {
    description: 'Choose between client and server generators',
    prompts: [
      {
        type: 'list',
        name: 'workspace',
        message: 'Choose your workspace generator: ',
        choices: ['Client', 'Server'],
      },
    ],
    actions: (data) => {
      if (data.workspace === 'Client') {
        return [];
      } else if (data.workspace === 'Server') {
        return [controllerGenerator(plop)];
      }
    },
  });
};

I get this error when I run plop and select the server option

> plop

? Choose your workspace generator: Server
 - [ERROR] Cannot read properties of undefined (reading 'type')

Here is my controller generator:

module.exports = function (plop) {
  plop.setGenerator('controller', {
    description: 'generate controller',
    prompts: [
      {
        type: 'input',
        name: 'name',
        message: 'controller name: ',
      },
    ],
    actions: [
      {
        type: 'add',
        path: 'apps/server/src/controllers/{{kebabCase name}}-controller.js',
        templateFile: './templates/server/controller.js.hbs',
      },
    ],
  });
};

I’m assuming this has to do with the actions part of the controller generator, but I’m not sure as to what would make it not work. I’ve tried using the plop.load() function, but it just creates a no action error. Not sure how else to proceed to achieve my desired effect, which is that if I had selected the server option, then there would be the various server related generators displayed (ex: controller, router, etc.). Something like below:

> plop

? Choose your workspace generator:  Server

- controller generator
- router generator
...

and when you chose the specified generator (ex: controller generator), you would then be prompted to provide the details for it, like the name for example.

Is this feasible with plop?

Error output when trying to add data to the database using ajax in opencart

This is the error that appears
Warning: Undefined array key “name” in C:OSPanelhomehikmetpubliccatalogcontrollerdemotest.php on line 13Warning: Undefined array key “tel” in C:OSPanelhomehikmetpubliccatalogcontrollerdemotest.php on line 14{“success”:0}

HTML

<form action="/" method="post" class="main-hero-form">
                <div class="form-row">
                  <input class="form-control" type="text" name="name" placeholder="Ваше имя" autocomplete="name" required="" id="name">
                  <input class="form-control" type="tel" name="tel" placeholder="Телефон" autocomplete="phone" required="" id="tel">
                  <input class="d-none" type="text" name="service" value="Тепловые центры на жидком и газовом топливе с автономной работой">
                </div>
                <input type="submit"value="Запросить стоимость, условия и времени поставки" class="main-hero-form-send">
                <p class="main-hero-text">В течении <span>15 минут</span> вы получите звонок от нашего менеджера, который предоставит подробную консультацию.</p>
              </form>

jQuery

$(document).ready(function() {
    $('.main-hero-form-send').on('click', function() { //активация функции при нажатии на кнопку с class='main-hero-form-send'
        $.ajax({
            url: 'index.php?route=demo/test&language=ru-ru', 
            type: 'post',
            dataType: 'json', // нужно ли указывать именно json?
            data: {'name': $('#name').val(), 'tel': $('#tel').val()}, // записываем в массив данные из инпута
            success: function(data){
                if (data.success){
                    alert('Заметка добавлена');
                } else {  
                    alert('Ошибка записи'); 
                }
            }
        });
    });
});

PHP

$json = array();

        $name = $this->request->post['name']; // получаем обе эти переменные из посланных в аяксе через POST данных
        $tel = $this->request->post['tel'];
    
        try {
            $this->db->query("INSERT INTO " . DB_PREFIX . "customer (firstname, telephone) VALUES ($name, $tel)");
            $json['success'] = 1; // все успешно
        } catch (Exception $e) {
            $json['success'] = 0; // не получилось
        }
        $this->response->addHeader('Content-Type: application/json'); // формируем и отправляем данные в формате json (как и было указано в аяксе )
        $this->response->setOutput(json_encode($json));

Automated Flask Interface Querying After Form Submission

I’m creating a basic Flask app to showcase my silly mini projects that I’ve done for fun in python (originally created for CLI). One of these is a program to visualize John Conway’s Game Of Life (GOL). If you don’t know what that is, you don’t need to, just know that it’s a continuously changing binary matrix.

After the user submits a form that specifies an integer for the size of the grid and a float between 0 and 1 to auto-generate the density of living cells in the initial state, I want the grid to display below the form and switch to its next state every 0.1 seconds (without refreshing the page).

I have a fairly decent knowledge of Vanilla Python and HTML, but I’m new to Flask and know nothing about JavaScript. I ChatGPTed a little JS that I thought would work, but nothing displays below the form after it is submitted. As a side note, if possible, I’d like to not start querying Flask until after the form is submitted, which ChatGPT’s JS does not do. Here’s the code relevant to the GOL piece of the app:

In app.py:

import game_of_life
from markupsafe import Markup

game = None
@app.route("/create_GOL", methods=['post'])
def create_game():
    density, size = request.form['density'], request.form['size']
    global game
    # initializes game in GameOfLife class
    game = game_of_life.GameOfLife(int(size), float(density))
    return render_template("index.html")

@app.route("/next_state", methods=['get'])
def next_state():
    # runs method to update "game" to the next state in-place
    game.find_next_state()
    # returns the HTML-friendly version of the matrix
    return Markup('<br>'.join(''.join(('  ', '██')[j] for j in i) for i in game.m))

In index.html:

<form action="create_GOL", method="post">
    <label for="density">Density (0-1): </label>
    <input type="number" name="density", step="any", min=0, max=1>
    <label for="size">Size: </label>
    <input type="number" name="size", min=1, max=100>
    <input type="submit" value="Submit">
</form><br>
<div id="game-state"></div>
<script>
    function updateGameState() {
        fetch('/next_state')
            .then(response => response.json())
            .then(data => document.getElementById('game-state').innerText = data.state)
    }
    setInterval(updateGameState, 100);
</script>

How should I modify my code to:
1. Actually display something
2. Not waste queries on nothing until the form is actually submitted

Or, should I use a different approach?

Substitute synchronous (Webpack) bundled ESM client code on the server side (Node) based on feature flag

Given:

moduleA.mjs,
moduleA_FeatureFlag1.mjs,
moduleA_FeatureFlag2.mjs,

Where:
no modules expose an async export

I’d like to substitute moduleA.mjs from my node server at runtime (or at least at pod startup time) based on a feature flag stored in an environment variable. For example, I would switch moduleA.mjs for moduleA_FeatureFlag1.mjs on the server side if environment variable GLOBAL_FEATURE_FLAGS=FeatureFlag1

In webpack, you can easily do this if you have async code by using a const module = await import(<name of module>); in your code base.

However, the idea here is to allow developers to quickly and arbitrarily substitute new feature flag specific code in the application by copying existing modules (which might have synchronous interfaces) and renaming the copy with the feature flag (maintaining the same exports obviously). I don’t want people to have to add redirection logic in the existing modules to do this. The whole idea here is to keep the existing, tested logic unchanged so there are fewer opportunities to introduce regressions in the non-feature flag code.

This copying and renaming happens before the code is webpack bundled for production, so I could use webpack to do this. I just don’t know how (without using async import();).

Because this is going to be happening all the time (there may be dozens of feature flags at a time), it will be too much ceremony to separate the code into its own bundled library for every feature flag – unless there is some way to make this transparent to the developer by automating the process at bundle time.

Also, this is a large code base (i.e. slow to build) and there may be any number of these files with feature flag substitutions, so building every possible combination of them is probably a bad idea.

How to make the webpage look 3-Dimentional using eye and head tracking

If you have ever owned or had a friend that let you use there 3DS, you probably have tried the 3D feature that looks so good, you just feel like you could jump right into the game and meet Mario, Link, Kirby, or your Mii. I want to build a web page in a very specific way so that you can switch between 2D (the original) and 3D. What I am doing is that I have an embed element viewing the webpage, and a video element getting my camera feedback.

My question is, does any one know how to track the user’s head position and rotation, and the eye position? I want to send an animationRequest to the document so it will scan the video, and update an object variable of the user’s head and eyes, then run some code (which I can figure out) to update the screen so it looks 3D.

Here is my web page:

<body style="margin: 0;">
    <embed src="game/index.html" style="width: 100vw; height: 100vh; position: absolute;"></embed>
    <video id="webcam" style="display: none;"></video>
</body>
<script>
    
    const webcam = document.getElementById("webcam");

    if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices
        .getUserMedia({ video: true })
        .then((stream) => {
        webcam.srcObject = stream;
        })
        .catch((error) => {
        console.error("Error accessing webcam:", error);
        });
    } else {
    console.error("getUserMedia not supported in this browser.");
    }
</script>

How to save information from an async request and use it in another async request after an event is triggered?

Part of a game I am making requires a query to gpt-4o asking whether two people have met. An inital person is provided and the user has to input the name of someone who they think has met the initial person. After the guess is submitted through an input field, a promise containing the text “true” or “false” is returned.

Depending on the response, I need to update some values contained in “gameState” and pass them into another query to gpt-4o.

However, since the response is a promise, I cannot update global variables using the response. As of now, “gameState” is initialized inside the async function. “gameState” is changed when the function is run, but when I input a different name it resets and “count” does not increase.

How do I use the information from the promise to update variables, wait until another input is submitted, then pass those updated variables along with the new input into another query?

import './App.css';
import React, { useState, useRef } from 'react';


const { OpenAI } = require('openai');
const openai = new OpenAI({ apiKey: '[myKey}');



function App() {
  const inputRef = useRef();

 let people = ["Donald Trump", "Taylor Swift"];

  const handleSubmit = (event) => {
    play(inputRef.current.value, people[0], people[1]);
    event.preventDefault();
  }

 async function play(guess, p1, p2) {
  let gameState = {
    currentPerson: p1,
    count: 0
   
  }
    const completion = await openai.chat.completions.create({
      messages: [
        { 
          role: "system",
          content: "respond with true or false in lower case depening on if these people have met" 
        },
        {
          role: "user",
          content: `${gameState.currentPerson}, ${guess}`
        
        },
        
      ],
        model: "gpt-4o",
    }); 

    if(completion.choices[0].message.content === "true" && guess === p2) {
      console.log("You Win!");
      gameState.count++;
      console.log(gameState);

    } else if(completion.choices[0].message.content === "true") {
      console.log("Correct");
      gameState.count++;
      gameState.currentPerson = guess;
      console.log(gameState);

    } else {
      console.log("Wrong");

    }
    
  }

  return ( 
    
    <form onSubmit={handleSubmit} >
      <label >
        Name:
        <input name="guessInput" type="text" ref={inputRef} />
      </label>
      <button type="submit">
        Submit
      </button>
    </form>

    
  );
}

export default App;

I have tried changing the input event handler into an async function and making the API call there but it resulted in an error.

Dynamically change color of Spotfire Calculated Values within an html table

In a Spotfire Text area I have calculated values set in a table that tracks a monthly score.

These are custom calculations.

the first row has the goals

The second row has actual scores.

Both goals and actuals are roll up of multiple different depts that contribute both to the score and the goal that I need to be able to drill down and make a report off of.

I am looking for a way for the actuals to dynamically change color in comparison to the goals.

Month Jan Feb
Goal 25.22 75.78
Score 66.12 30.87

in this example. The score for Jan should be red and the score for Feb would be green.

The Spotfire calculated values do not allow for dynamic colors that do not compare it to itself.

I have tried assigning the calculated values in HTML and Referencing them as variables.

I have tried an if statement with duplicates of the value. One in Red and one in green to show up if a third had a difference greater than zero.

have also tried assigning the caluclated values to javascript and having them returned recolored. but I cannot get it to reference or return

<!DOCTYPE html>
<html>
<head>
    <style>
        .value {
            font-size: 24px;
            font-weight: bold;
        }
        .red {
            color: red;
        }
        .green {
            color: green;
        }
        .black {
            color: black;
        }
    </style>
   </head>
   <body>
    <div id="value1" class="value" hidden><spotfireControl id="12345"></spotfireControl></div>
    <div id="value2" class="value" hidden><spotfireControl id="67890"></spotfireControl></div>
    <script>
        function updateValues() {
            // Fetch Spotfire values from controls
            var value1 = parseFloat(document.querySelector('[spotfireControl][id="12345"]').innerText)|| 0;
            var value2 = parseFloat(document.querySelector('[spotfireControl][id="67890"]').innerText)|| 0;

            var value1Element = document.getElementById('value1');
            var value2Element = document.getElementById('value2');

            // Function to update color based on the value comparison
            function updateColor(element, value) {
                if (isNaN(value) || value === '') {
                    element.className = 'value black';
                } else if (value > 0) {
                    element.className = 'value green';
                } else if (value < 0) {
                    element.className = 'value red';
                }
            }

            // Update both values
            updateColor(value1Element, value1);
            updateColor(value2Element, value2);
        }

        // Run the function to update values and colors
        updateValues();
    </script>
</body>
</html>

Why does the ENTER key release the wait?

The button executes the “resolve” function and releases the wait, as expected.
But then the ENTER key releases the wait also. What’s going on?

<html>
  <head>
    <title> Q:await </title>
    <meta charset="utf-8">
    <script>
  "use strict";
  let fnresolve, n=0; // globals
window.onload = function() {
  zlog('Hit the button, then the ENTER key');
  zlog();
  Main();
}
async function Main() {
  do {
    zlog('before wait', ++n);    
    let pMain = new Promise((res) => { fnresolve = res; } ); // save the res function
    await pMain;
    zlog('after wait', n); zlog('');    
  } while (1);
}
function zlog() {
  document.getElementById('zlog').innerHTML += (Object.values(arguments).join(', ')) + '</br />';
}
    </script>
  </head>
  <body>
  <button onclick='fnresolve();'> fnresolve </button>
  <div id='zlog'></div>  
  </body>
</html>

PapaParse incorrectly handles empty rows, so that it affects headers?

const csvString2 = "a;brn1;2rn3;4rn";
const csvArray2 = Papa.parse(csvString2, { header: true }).data;
console.log("csvArray2", csvArray2);

const csvString3 = "a;brn1;2rn3;4";
const csvArray3 = Papa.parse(csvString3, { header: true }).data;
console.log("csvArray3", csvArray3);

gives

csvArray2 [ { 'a;b': '1;2' }, { 'a;b': '3;4' }, { 'a;b': '' } ]
csvArray3 [ { a: '1', b: '2' }, { a: '3', b: '4' } ]

skipEmptyLines: true
would solve the problem, but why the empty rows affects headers ?

Surely there is an easier way to do this? HTML, CSS, JS

I’m creating some animated lines that run from one side of the page to the other, while they are doing this they change in size, there are currently 5 animated lines and I may add more, but i also want them all to move across the screen at different intervals, change size at different intervals and if possible at random, so the animation never truly repeats itself.

Currently I can only think to write a a really long block of code for each line and it wouldn’t be at random I would have to set left and width so it seems random, but it would evidently just be a pre programmed sequence that would keep repeating itself.

Surely this can be done with less code in JS and actually at random be randomly generated?

Currently I have the below keyframes:

@keyframes slider {
    0%  {width: 75%; left: 10%;}
    5%  {width: 66%; left: 18%;}
    10% {width: 60%; left: 26%;}
    15% {width: 31%; left: 34%;}
    20% {width: 26%; left: 38%;}
    25% {width: 20%; left: 44%;}
    30% {width: 10%; left: 52%;}
    35% {width: 8%; left: 71%;}
    40% {width: 7%; left: 82%;}
    45% {width: 5%; left: 89%;}
    50% {width: 0%; left: 94%;}
    55% {width: 12%; left: 79%;}
    60% {width: 21%; left: 72%;}
    65% {width: 35%; left: 59%;}
    70% {width: 38%; left: 51%;}
    75% {width: 47%; left: 41%;}
    80% {width: 53%; left: 33%;}
    85% {width: 70%; left: 19%;}
    90% {width: 84%; left: 11%;}
    95% {width: 89%; left: 6%;}
    100%{width: 100%; left: 0%;}
}

Now I can link this to the elements I require as per below:

.animation :nth-child(1) {
    top: 10%;
    animation: slider 3s infinite;
}

if it helps you get a picture of what im doing, the div is styled as below:

.an {
    height: 10px;
    position: absolute;
    background-color: #09a07a;
    top: 0;
}

This means i have to write one of those repeating code blocks for each child element. I’m not asking you to code the whole thing for me, but just some guidance as to what i should look at when approaching a JS block that will:

Randomly make the element targeted move from one side of the screen to the other, while growing and shrinking in width randomly, this will be applied to each element randomly to save having a code block for each element, but also save writing such a large keyframe.

copy to clipboard and transform svg

I need some help on improving my copy to clipboard script
I want when i click on copy svg and transform to other (svg) on success
And then reset for accessibility of copying again

This is the svg i want to transform to after clicking the copy svg

<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
    <path fill="black" d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10s10-4.5 10-10S17.5 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8s8 3.59 8 8s-3.59 8-8 8m4.59-12.42L10 14.17l-2.59-2.58L6 13l4 4l8-8z" />
</svg>
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.12/clipboard.min.js"></script>
    </head>
    <body>
        <span id="copythis">Hello</span>
        <span class="copy" type="button" data-clipboard-target="#copythis">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 16 16">
                <path
                    fill="currentColor"
                    d="M4 4.085V10.5a2.5 2.5 0 0 0 2.336 2.495L6.5 13h4.414A1.5 1.5 0 0 1 9.5 14H6a3 3 0 0 1-3-3V5.5a1.5 1.5 0 0 1 1-1.415ZM11.5 2A1.5 1.5 0 0 1 13 3.5v7a1.5 1.5 0 0 1-1.5 1.5h-5A1.5 1.5 0 0 1 5 10.5v-7A1.5 1.5 0 0 1 6.5 2h5Zm0 1h-5a.5.5 0 0 0-.5.5v7a.5.5 0 0 0 .5.5h5a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.5-.5Z"
                />
            </svg>
        </span>

        <script>
            var copyCode = new Clipboard(".copy");

            copyCode.on("success", function (event) {
                event.clearSelection();
            });
        </script>
    </body>
</html>

Node Js sort Manipulate

Node.js Sort and Manipulate
In the JavaScript file, you have a program that performs a GET request on the route https://coderbyte.com/api/challenges/json/wizard-list and then sort the object keys alphabetically. However, the sorting should be case-insensitive, and the original data structure should be preserved (e.g., arrays should remain arrays, objects should remain objects).

Next, remove any duplicate objects from arrays. Two objects are considered duplicates if they have the same keys and values in the same order. Although JavaScript objects don’t inherently maintain key order, key order should be considered for this challenge (using something like a Set). Only the first occurrence should be preserved when an array contains duplicate objects.

Finally, remove any object properties with all values set to an empty string, null, or undefined, and console log an array of the modified objects as a string.

Example Input:

[{“name”:”John”,”age”:30,”city”:”New York”,”country”:”USA”,”Hobbies”:[“reading”,”swimming”,”hiking”,”swimming”],”occupation”:”programmer”,”favorite_foods”:{“Breakfast”:”pancakes”,”Lunch”:””,”dinner”:”pasta”,”Snack”:””},”gear”:{“type”:””,”material”:””,”color”:null},”affiliations”:[“”,””,””],”friends”:[{“name”:”Jane”,”age”:28,”city”:”New York”,”country”:”USA”,”occupation”:null},{“name”:”Tom”,”age”:32,”city”:”London”,”country”:”UK”,”occupation”:”teacher”},{“name”:”Jane”,”age”:28,”city”:”New York”,”country”:”USA”,”occupation”:null}]}]

Example Output:

[{“age”:30,”city”:”New York”,”country”:”USA”,”favorite_foods”:{“Breakfast”:”pancakes”,”dinner”:”pasta”},”friends”:[{“age”:28,”city”:”New York”,”country”:”USA”,”name”:”Jane”},{“age”:32,”city”:”London”,”country”:”UK”,”name”:”Tom”,”occupation”:”teacher”}],”gear”:{},”Hobbies”:[“reading”,”swimming”,”hiking”],”name”:”John”,”occupation”:”programmer”}]

code is running but output is incorrect

How to Change the Hover Background Color of a Dropdown Option in Angular? [duplicate]

I’ve been struggling to find the perfect solution to change the hover background color of a dropdown option in an Angular form. By default, the dropdown options display a blue background on hover, but I need to change that color to pink.
dropdown image on hover of options

Here is the HTML structure of my form:

<div class="form-group">
  <label for="supportHierarchy">Support Hierarchy</label>
  <select id="supportHierarchy" [(ngModel)]="flag.supportHierarchy" name="supportHierarchy" class="form-control custom-select">
    <option class="custom-option" [value]="'Yes'">Yes</option>
    <option class="custom-option" [value]="'No'">No</option>
  </select>
</div>

And here is the CSS I’ve been trying:

option:hover,
option:checked,
option:active,
option:focus {
  background: linear-gradient(#5a0c6f, #5a0c6f);
}

.custom-option:hover,
.custom-option:checked,
.custom-option:active,
.custom-option:focus {
  background: linear-gradient(#5a0c6f, #5a0c6f);
}

.custom-option:hover {
  background-color: red !important;
}

Issues:
The above CSS only works if the dropdown is already open (for example, if I set the size attribute on the element to force the dropdown to stay open).
The hover effect does not seem to apply when the dropdown is closed, which is the main issue I need to solve.
I’ve tried various approaches and scoured multiple solutions online, but none seem to work for my requirement.

References:
Changing hover background color with javascript
How to change the background color of a select option on hover

Question:
How can I effectively change the background color of the dropdown options on hover, so that it displays the desired color (pink) when the dropdown is open and being interacted with? Any help or alternative approach would be appreciated!

How can I prevent Navigate forward?

I currently have a beforeunload event handler which exists when a form is dirty. it correctly blocks page a “Refresh” and navigating “Back”, but navigate “Forward” is not prevented.

window.addEventListener('beforeunload', (event) => {
    event.preventDefault();
})

This can happen if a user navigates back and starts filling out a form, I need to warn them that their data is not saved will be lost if they navigate forward again.

I thought about using popstate but that wont work either https://stackoverflow.com/a/32432366/10917416

Is there another event fired when Navigating forward?