Generating all possible combinations of multiple arrays based on percentages

I have an array with this layout:

const arrayOfSections = [{chance: 100, items: [1,2,3,4]}, {chance: 49, items: [7,9]}, {chance: 100, items: [0,5]}];

And I am trying to find the best way in just javascript no libraries to basically find all possible combinations of the items value in each array inside arrayOfSections, while also taking into consideration the chance percentage that is in the chance key for that specific array. So for example, if there is a 49% chance for the array with the items value [7,9], it would only generate the possible combinations with only 49% of the combinations having the items inside this array.

I am currently using this function here:

    const allPossibleCases = (arraysToCombine) => {
      console.log(arraysToCombine);
      const divisors = [];

      let permsCount = 1;

      for (let i = arraysToCombine.length - 1; i >= 0; i--) {
        divisors[i] = divisors[i + 1]
          ? divisors[i + 1] * arraysToCombine[i + 1].items.length
          : 1;

        permsCount *= arraysToCombine[i].length || 1;
      }

      let totalOutputs = permsCount;

      const getCombination = (n, arrays, divisors) =>
        arrays.reduce((acc, arr, i) => {
          acc.push(arr[Math.floor(n / divisors[i]) % arr.length]);

          return acc;
        }, []);

      const combinations = [];

      for (let i = 0; i < permsCount; i++) {
        combinations.push(getCombination(i, arraysToCombine, divisors));
      }

      return combinations;
    };

To basically find all the possible combinations based on just

const arraysToCombine = [[1,2,3,4], [7,9], [0,5]]

and its working fine but im having a really hard time figuring out how I could do this while also taking into consideration the chance percentages.

Hopefully this isnt too sloppy of a post and I appreciate any help lol.

Is it possible to verify nodemon.json is being read correctly?

I’m trying to use a simple regular expression as follows:

{
  "verbose": false,  
  "ignore": [
    ".git",
    "bundle.*"
  ]
}

However, it appears the nodemon restarts when bundle.js is updated.

I have seen the form *.js where the filename is a catchall, but I wanted the extension to be a catch all as follows bundle.*.

I would like to use nodemon.json to configure my nodemon. I found this SO Q/A but it did not help.

Problem with Request URL in production in React

I am working on the React App project, In env file – I have declared

REACT_APP_URL = 'http://localhost:8080/'

and using axios to make HTTP request

and here is my code

export const ADMIN_URL = process.env.REACT_APP_URL;
export const api = axios.create({
  baseURL: ADMIN_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

But when I deployed I could see frontend url and backend url in the request url

example : "http://localhost:3000/login'http://localhost:8080/'/logged

How to show data in a select/option based on input picker plugin choice using jQuery, ajax and PHP?

I need to get data from database and display it in a select/option based on input value of a chosen choice of an input picker plugin. I have this code in invoice.php:

  <div class="form-group">
     <input type="text" class="form-control form-control-sm" id="items" name="items" value="">
  </div>
  <div class="form-group">
       <select class="form-select form-select-sm" id="uom" name="uom">
             </select>
      </div>

 <script>
 var myData = JSON.parse(
 $.ajax({
 method: "GET",
 url: "parsers/items_select.php",
 async: false
 }).responseText);

 $(document).ready(function () {
  $('input#items').inputpicker({
   data: myData,
   fields:['itemNo','title'],
   fieldText:'itemNo',
   fieldValue:'id',
   headShow: true,
   filterOpen: true,
   autoOpen: true
   });
   });
</script>

and this is items_select.php:

<?php
require_once '../init.php';
$data = [];
$q = ((isset($_GET['q']) && $_GET['q'] != '')?sanitize($_GET['q']):'');
$item_select = $db->query("SELECT id, itemNo, title FROM products");
while($item = mysqli_fetch_assoc($item_select)){
$data[] = $item;
}
echo json_encode($data);
?>

The input picker plugin works 100% fine.
Now I have did it perfectly if I use a regular select/option rather than input picker. Here is my code in invoice.php:

<?php
$itemQuery = $db->query("SELECT * FROM products ORDER BY title DESC");
?>
            <div class="form-group">
              <select class="form-select form-select-sm" id="items" name="items">
                <option value=""<?=(($items == '')?' selected':'');?>></option>
                <?php while($item = mysqli_fetch_assoc($itemQuery)): ?>
                  <option value="<?=$item['id'];?>"<?=(($items == $item['id'])?' selected':'');?>><?=$item['uom'];?></option>
                <?php endwhile; ?>
              </select>                    
            </div>

<script>
 function get_child_options(selected){
   if(typeof selected === 'undefined'){
     var selected = '';
   }

   var itemsID = jQuery('#items').val();
   jQuery.ajax({
     url: 'parsers/uom_select.php',
     type: 'POST',
     data: {itemsID : itemsID, selected: selected},
     success: function(data){
       jQuery('#uom').html(data);
     },
     error: function(){alert("Something went wrong with the child options.")},
   });
 }
 jQuery('select[name="items"]').change(function(){
   get_child_options();
 });

 jQuery('document').ready(function(){
   get_child_options('<?=$uom;?>');
 });
 </script>

and in uom_select.php:

<?php
require_once '../init.php';
$itemsID = (int)$_POST['itemsID'];
$selected = sanitize($_POST['selected']);
$item_childQuery = $db->prepare("SELECT * FROM products WHERE id = ? ORDER BY uom");
$item_childQuery->bind_param('i', $itemsID);
$item_childQuery->execute();
$result = $item_childQuery->get_result();
ob_start(); ?>
   <option value=""></option>
   <?php while($item_child = mysqli_fetch_assoc($result)): ?>
     <option value="<?=$item_child['id'];?>"<?=(($selected == $item_child['id'])?' selected':'');?>><?=$item_child['uom'];?></option>
   <?php endwhile; ?>
 <?php echo ob_get_clean();?>

But the above code will not work on input picker plugin, since it is not a select/option element and it displays data in divs and table. What is the solution?

Function in useEffect continues to fire after component unmounts [duplicate]

I’m learning React and having trouble with component lifecycle, or some kind of memory leak. In the code below I’ve using [this codepen][1] in React, and it works, until my Preloader unmounts, and I continually get error below.

Is this a place for a cleanup function? How do I stop animate() from firing after the Preloader has been removed from the dom?

Error

"Uncaught TypeError: text2.current is null
setMorph Preloader.jsx:47
doMorph Preloader.jsx:42
animate Preloader.jsx:83"

In Parent Component

  const { initialLoad, setInitialLoad } = useGlobalState();

    useEffect(() => {
        if (initialLoad) {
          setTimeout(() => {
          setInitialLoad(false);
        }, 4600);
        }
      }, [initialLoad]);
    
    return (
        <div className='browser-wrapper'>
            {initialLoad &&
            <Preloader initialLoad={initialLoad} />
            }
           ...
    )

Preloader Component

const Preloader = ({ initialLoad }) => {
    const text1 = useRef(null)
    const text2 = useRef(null)

    // Insert Text String and Morph tuning adjusments
    const morphTime = .68;
    const cooldownTime = 0.12;
    let textIndex = texts.length - 1;
    let time = new Date();
    let morph = 0;
    let cooldown = cooldownTime;
    text1.current = texts[textIndex % texts.length];
    text2.current = texts[(textIndex + 1) % texts.length];

    function doMorph() {
        morph -= cooldown;
        cooldown = 0;

        let fraction = morph / morphTime;

        if (fraction > 1) {
            cooldown = cooldownTime;
            fraction = 1;
        }
        setMorph(fraction);
    }

    // A lot of the magic happens here, this is what applies the blur filter to the text.
    function setMorph(fraction) {
        text2.current.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
        text2.current.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;

        fraction = 1 - fraction;
        text1.current.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
        text1.current.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;

        text1.current.textContent = texts[textIndex % texts.length];
        text2.current.textContent = texts[(textIndex + 1) % texts.length];
    }

    function doCooldown() {
        morph = 0;

        text2.current.style.filter = "";
        text2.current.style.opacity = "100%";

        text1.current.style.filter = "";
        text1.current.style.opacity = "0%";
    }

    // Animation loop, which is called every frame.
    function animate() {
        requestAnimationFrame(animate);
        let newTime = new Date();
        let shouldIncrementIndex = cooldown > 0;
        let dt = (newTime - time) / 1000;
        time = newTime;

        cooldown -= dt;

        if (cooldown <= 0) {
            if (shouldIncrementIndex) {
                textIndex++;
            }

            doMorph();
        } else {
            doCooldown();
        }
    }

    useEffect(() => {
        if (text2.current !== null || undefined) {
        animate();
        } else {
            console.log('current text.2 is ' + text2.current)
        }
    }, [text2.current])
    

    return ( --- JSX follows
    ```


  [1]: https://codepen.io/Valgo/pen/PowZaNY?ref=devawesome.io

Why is the Kendo UI (AngularJS) affected by an NGX update?

I work on an enterprise application that has a mix of AngularJS (v1) and NGX (v2+) pages. We employ Kendo UI to construct Grids for list pages in the app.

Recently, we updated the the NGX portion of our application to Angular 12 via these update steps. After doing so however, the “items per page” text that usually appears at the bottom of the Kendo Grid next to the page size drop down disappeared from grids that are on AngularJS pages.

I’ve tried reverting the i18n migration step in the Angular upgrade guide which changes message IDs (“items per page” is one of the messages in messages.xlf) but this didn’t help.

I also tried modifying the $scope‘s gridOptions that set the messages on the grid based on these docs i.e.

pageable: {
   .
   .
   .
   messages: {
      itemsPerPage: "items per page"
   }
}

but this also didn’t work.

What’s interesting is that if I modify the display or empty properties in messages, I do actually end up seeing a change. It’s itemsPerPage (among other properties) whose updates can’t be seen on the front-end. This might be a symptom of the same issue.

Anyone have ideas as to why this might be happening? Are there any incompatibility issues with certain versions of @progress/kendo-angular-<package_name> with version 12 of Angular?

Adobe Animate HTML5/JavaScript Canvas – Symbol disappears when adding as a child

In an Adobe Animate HTML5/JavaScript Canvas movie, I have a draggable Movie Clip symbol being added to another Movie Clip symbol on hitBox.hitTest.

function onMouseUp(evt){
    var item = evt.currentTarget;
    item.drag = false;
    var pt = item.localToLocal(item.dot.x, item.dot.y, item.LFLensHolder.hitBox);
    if(item.LFLensHolder.hitBox.hitTest(pt.x, pt.y) ){
        item.x = item.LFLensHolder.x;
        item.y = item.LFLensHolder.y;
        item.lensParentLeft.addChild(item);
        console.log(item.parent);
    }   
}

In this instance, the item symbol instance name is ConcaveSphereLens…

However, the draggable item disappears on hitBox.hitTest, that is, when the drggable item snaps to position, it just disappears. Very odd.

Looking at browser console on hitTest with console.log(item.parent); I can see that the draggable item has a parent of lensParentLeft which it should have.

I can also see that the draggable item, now a child of lensParentLeft has properties which indicate it is on stage and visible.

I’m not sure what is going wrong. Any ideas?

enter image description here

and the properties in console for the dragged child item…

enter image description here

Trouble with JavaScript Timer

I am having trouble creating a JavaScript timer using. I have tried to implement things from other stack overflow questions and haven’t had any success.

When I click the play button, “0-8:0-46” is displayed instead of the actual timer. And it does not count down.

Link to codepen: https://codepen.io/Jamece/pen/jOazYvQ

My Code thus far is below. I am trying to troubleshoot the sessionTimer function right now.

const minTime = 1;
const maxTime = 60;
class Application extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      breakLength: 5,
      sessionLength: 25,
      started: false,
      mode: "Session"
    };
    this.breakIncrement = this.breakIncrement.bind(this);
    this.breakDecrement = this.breakDecrement.bind(this);
    this.sessionIncrement = this.sessionIncrement.bind(this);
    this.sessionDecrement = this.sessionDecrement.bind(this);
    this.beginTimer = this.beginTimer.bind(this);
    this.sessionTimer = this.sessionTimer.bind(this);
    this.breakTimer = this.breakTimer.bind(this);
    this.pauseTimer = this.pauseTimer.bind(this);
  }

  breakIncrement() {
    if (!this.state.started) {
      if (this.state.breakLength !== maxTime) {
        this.setState((state) => ({
          breakLength: state.breakLength + 1
        }));
      }
    }
  }

  breakDecrement() {
    if (!this.state.started) {
      if (this.state.breakLength !== minTime) {
        this.setState((state) => ({
          breakLength: state.breakLength - 1
        }));
      }
    }
  }

  sessionIncrement() {
    if (!this.state.started) {
      if (this.state.sessionLength !== maxTime) {
        this.setState((state) => ({
          sessionLength: state.sessionLength + 1
        }));
      }
    }
  }

  sessionDecrement() {
    if (!this.state.started) {
      if (this.state.sessionLength !== minTime) {
        this.setState((state) => ({
          sessionLength: state.sessionLength - 1
        }));
      }
    }
  }

  beginTimer() {
    this.setState({ started: !this.state.started });
    if (this.state.started) {
      if (this.state.mode == "Session") {
        this.sessionTimer();
      } else {
        this.breakTimer();
      }
    } else {
      this.pauseTimer();
    }
  }
  sessionTimer() {
    var start = new Date().getTime();
    const sessionTime = setTimeout(() => {
      const distance = this.state.sessionLength - start;
      var minutes = Math.floor(distance / (1000 * 60) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60 * 60)) / 1000);
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      const sessionClock = (document.getElementById("time-left").innerHTML =
        minutes + ":" + seconds);

      if (distance <= 0) {
        clearTimeout(sessionTime);
      }
    }, 1000);
  }

  breakTimer() {}

  pauseTimer() {}

  render() {
    let pausePlayStyle = this.state.started
      ? "fa-solid fa-pause"
      : "fa-solid fa-play";
    return (
      <div className="container-fluid px-0">
        <div className="main d-flex justify-content-center align-items-center">
          <div className="d-flex flex-column align-items-center">
            <div className="heading">25 + 5 Clock</div>
            <div className="d-flex">
              <div className="d-flex flex-column break align-items-center">
                <div id="break-label" className="mb-3 h3">
                  Break Length
                </div>
                <div className="d-flex flex-row">
                  <button
                    className="btn btn-top"
                    id="break-increment"
                    onClick={this.breakIncrement}
                  >
                    <i class="fa-solid fa-arrow-up"></i>
                  </button>
                  <div className="mx-3 h3" id="break-length">
                    {this.state.breakLength}
                  </div>
                  <button
                    className="btn btn-top"
                    id="break-decrement"
                    onClick={this.breakDecrement}
                  >
                    <i class="fa-solid fa-arrow-down"></i>
                  </button>
                </div>
              </div>
              <div className="d-flex flex-column align-items-center session">
                <div id="session-label" className="mb-3 h3">
                  Session Length
                </div>
                <div className="d-flex flex-row">
                  <button
                    className="btn btn-top"
                    id="session-increment"
                    onClick={this.sessionIncrement}
                  >
                    <i class="fa-solid fa-arrow-up"></i>
                  </button>
                  <div className="h3 mx-3" id="session-length">
                    {this.state.sessionLength}
                  </div>
                  <button
                    className="btn btn-top"
                    id="session-decrement"
                    onClick={this.sessionDecrement}
                  >
                    <i class="fa-solid fa-arrow-down"></i>
                  </button>
                </div>
              </div>
            </div>
            <div className="d-flex flex-column align-items-center timer-border">
              <div className="h2 mb-3 session" id="timer-label">
                {this.state.mode}
              </div>
              <div className="display-1 timer mb-4" id="time-left"></div>
              <div className="d-flex flex-row">
                <button
                  className="btn btn-bottom"
                  id="start_stop"
                  onClick={this.sessionTimer}
                >
                  <i className={pausePlayStyle}></i>
                </button>
                <button className="btn btn-bottom" id="reset">
                  <i className="fa-solid fa-rotate"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
ReactDOM.render(<Application />, document.getElementById("root"));

javascripts puppeteer: How do I get the new elements generated by the dom when interacting with the page?

With the puppeteer library, I click on a div in the dom, and a modal appears with a list of divs, and then I try to click on one of the divs I need from that modal, but the “page” variable doesn’t find the div

I click on the div element as follows and then when the modal appears I try to select the div I need.

 const browser = await puppeteer.launch({headless: false});
 const page = await browser.newPage();
 await page.setDefaultNavigationTimeout(0);

  
 await page.goto(`https://www.page.com`);

 await page.evaluate(() => {
     document.querySelector('div.css-bt1pje').click();
 })

 await page.waitForTimeout(10000);

 await page.evaluate(() => {
     document.querySelector('[data-title=content]').click();
 })/* here it stays thinking and never finds the element

How can I launch a single process of puppeteer.launch() and just send pages to it in Node?

The following code runs on every one of my requests and I’m afraid that it’s trying to launch the browser every time and causing server issues on Heroku. I want to launch puppeteer like a Singleton instance where I only launch it once and then after that my requests will just trigger browser.newPage(). I’m not experienced in JS to resolve this.

 (async () => {
      const browser = await puppeteer.launch({ headless: true});
      const page = await browser.newPage();    

      await page.on('response', interceptedResponse =>{
        let status = interceptedResponse.status();
        interceptedResponse.text()
          .then((text) => {          
            handleResponse(text)
            browser.close();
          })
          .catch(err => {
            console.error(`interceptedResponse error: ${err}`)
            browser.close();
          });
      });

      await page.goto(url);
    })();

How can I use manifest.mix.js to generate a service worker for offline?

I’m using laravel-mix-workbox to bundle and create a service worker. The service worker is running as expected, but there is apparently no precache files because it doesn’t work offline (no content when offline after a reload).

Stack: Laravel 8, Vue 2, Workbox 6, Laravel-mix 6

// webpack.mix.js
const mix = require('laravel-mix');
require('laravel-mix-workbox');

mix.js('resources/js/app.js', 'public/js')
    .vue()
    .sass('resources/sass/app.scss', 'public/css')
    .sourceMaps(false)
    .generateSW()

here’s what I tried:

// app.js
if ('serviceWorker' in navigator) {
    const wb = new Workbox('/service-worker.js')

    wb.addEventListener('install', (event) => {
        event.waitUntil(caches.open('v1').then(cache => {
            return cache.addAll([
                '/',
                '/index.html',
                '/favicon.ico',
                '/img/app_bar_text.jpg',
 //             (etc...)
            ])
        }))
    })

    wb.addEventListener('fetch', event => {
        event.respondWith(caches.match(event.request).then(response => {
            if (response)
                return response;
            return fetch(event.request)
        }))
    })

    window.addEventListener('load', async () => {
        await wb.register('service-worker.js')
    })
}

But, the generated service worker does not include any files I specify and no content when offline.

Do I have to explicitly list every offline file? Should this list of cached files (urls) go in app.js or webpack.mix.js? If webpack.mix.js, then how?

express post method and body.req does not work

I am trying to get “POST” method form data from HTML form using app.post method but I can catch anything to req.body. What am I doing wrong?

My html form –

                <div id="input-area">
                    <textarea id="title" name="title" rows="1" cols="75" placeholder="Title" onkeyup="instance.tweaker()"></textarea>
                    <textarea rows="10" type="text" cols="75" placeholder="Description" name="description"></textarea>
                    <div id="calender"><input id="dater" type="date" value=""></div>
                    <button type="submit" value="Submit"  id="buton">Add Task</button>
                </div>
                </form>
<script src="backend2.js" defer></script>

my js code

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.listen(3308,() =>{
    console.log('My server is running');
})

const jsonParser = bodyParser.json();

//

const urlencodedParser = bodyParser.urlencoded({ extended: false })

app.post('/success.html', urlencodedParser , function (req, res) {
    console.log(req.body.title);
})

Problem with launch.json file: Visual Studios Code -> Firefox for localhost not working

So I want to launch my JavaScript code from VS-Code to Firefox but cant figure out how to setup the launch.json file.

Terminal:
Terminal view when I run: npm run dev

Debug URL option:
When I hover over “local: http://localhost:3000/”

Error:
Error message that pops up when I try “Debug URL”

launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "firefox",
            "request": "attach",
            "name": "Attach"
        },
        {
            "type": "firefox",
            "request": "launch",
            "reAttach": true,            
            "name": "Launch Firefox against localhost",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceFolder}",
            "program": "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
        },

        {
            "type": "firefox",
            "request": "launch",
            "reAttach": true,
            "reloadOnAttach": true,
            "name": "Launch index.html",
            "file": "${workspaceFolder}/index.html"
        },
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\Project 3 Three.js\main.js"
        }
    ]
}

Script to play music on button click and disable button after specified time

I’m trying to use the onClick function to make a button play an audio file and then disable after a specified length of time (to line up with the end of the audio file). Basically I’m trying to set up a Mission Impossible-esque thing where, when the button is clicked, the audio file plays and at the end of the recording the button disables (the message “self-destructing”). I can get the file to play but I can’t figure out how to get the button to disable using the script code. This is what I’ve got so far. I tried both document.getElementById("briefingButton").this.disabled="true" and document.getElementById("briefingButton").style.display="none" and neither works.

<p id="briefingButton"><input type="button" value="Click for briefing" onclick="playMusic(); disableButton()" />


<script>
function playMusic(){
  var music = new Audio('/Users/devonhunt/Documents/ADVENTURE WEDDING/Mission briefings/dom mk1.mp3');
  music.play();
  }

setTimeout(function disableButton() {
  document.getElementById("briefingButton").this.disabled="true";
}, 1080)

</script></p>