get difference with previous date

I have the following JSON , how do i get difference between the previous date for num_followers for each website ?

like for website yqq on 15-02-2022 I need to get the difference between the num_followers from 14-02-2022 and update num_followers with difference value

[
    {
        "date": "2022-02-15",
        "websites": [
            {
                "website_name": "yqq",
                "num_followers": "454421"
            },
            {
                "website_name": "soundcloud",
                "num_followers": "757127"
            },
            {
                "website_name": "twitter",
                "num_followers": "21779161"
            },
            {
                "website_name": "soundcloud",
                "num_followers": "757054"
            },
            {
                "website_name": "triller",
                "num_followers": "5196"
            },
        ]
    },
    {
        "date": "2022-02-14",
        "websites": [
            {
                "website_name": "yqq",
                "num_followers": "123058219"
            },
            {
                "website_name": "triller",
                "num_followers": "5195"
            },
            {
                "website_name": "tiktok",
                "num_followers": "17100000"
            },
            {
                "website_name": "instagram",
                "num_followers": "123059626"
            },
            {
                "website_name": "tiktok",
                "num_followers": "17100000"
            },
            {
                "website_name": "tiktok",
                "num_followers": "17100000"
            },
            {
                "website_name": "soundcloud",
                "num_followers": "756956"
            },
        ]
    
    }
]

Relative import of CJS module from an eval’ed Worker in Node?

I am creating a worker from a source string like so:

import { Worker } from "worker_threads"

const w = new Worker(mySourceCode, {eval: true})

This works fine in most cases.

However, suppose I have a CommonJS module (ESM isn’t supported in eval’ed workers) that I want to import into the worker scope. Since the worker doesn’t have a source file on the disk, there is no way I can think of to make a relative import work. This is the error message I get if I try to relative import from the path of the source file of the parent thread:

node:internal/event_target:916
  process.nextTick(() => { throw err; });
                           ^
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module './c.js'
Require stack:
- /mnt/c/ME/[worker eval]
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at [worker eval]:3:20
    at Script.runInThisContext (node:vm:129:12)
    at Object.runInThisContext (node:vm:305:38)
    at node:internal/process/execution:76:19
    at [worker eval]-wrapper:6:22
    at evalScript (node:internal/process/execution:75:60)
Emitted 'error' event on Worker instance at:
    at Worker.[kOnErrorMessage] (node:internal/worker:289:10)
    at Worker.[kOnMessage] (node:internal/worker:300:37)
    at MessagePort.<anonymous> (node:internal/worker:201:57)
    at MessagePort.[nodejs.internal.kHybridDispatch] (node:internal/event_target:647:20)
    at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/mnt/c/Users/ME/[worker eval]' ]
}

Node.js v17.5.0

How can I relative import a module from a Worker?

Como gerar um erro no readFile do modulo fs? How to generate a error on readFile fs module?

Ola! Como eu conseguiria gerar um erro de leitura do arquivo, pra poder testar minha condicao de erro da linha 8?

Hi! How would I be able to generate an error reading the file, so I can test my error condition on line 8?

1  const fs = require('fs/promises');
2  
3  const TALKERS_FILE = './talker.json';
4  
5  module.exports = async (_req, res) => {
6   try {
7     const talkersFile = await fs.readFile(TALKERS_FILE, 'utf-8', (err, data) => {
8       if (err) return new Error('Ops! I cant read required file... sorry =(');
9       return (data);
10    });
11    return res.status(200).json(JSON.parse(talkersFile));
12  } catch (err) {
13    console.log(err);
14  }
15 };

talker.json =

 [   
     {
        "name": "Henrique Albuquerque",
        "age": 62,
        "id": 1,
        "talk": {
          "watchedAt": "23/10/2020",
          "rate": 5
        }
     }
  ]

Exit Intent in Mobile using java scrpt

I want to modify the popup plugin, where the popup doesn’t work on mobile devices.
And this is the code that calls the exit intent popup


  $(document).on('mouseleave', function (e) {

    if (e.clientY > 20) {
      return;
    }

    $('.fel-modal-parent-wrapper').each(function () {

      var $this = $(this);
      var tmp_id = $this.attr('id');
      var popup_id = tmp_id.replace('-overlay', '');
      var trigger_on = $this.data('trigger-on');
      var exit_intent = $this.data('exit-intent');

      if ('automatic' == trigger_on) {
        if (
          'yes' == exit_intent
          && FelModalPopup_canShow(popup_id)
        ) {
          FelModalPopup_show(popup_id);
        }
      }
    });
  });

Why is the findIndex method showing second occurance too?

Basically the idea is that my code chooses a random element from an array. That element is the arr[i].answer and is placed at the end of that array. Then i want to make the first occurrence of that answer as an *. I used the findIndex method as i thought that the first occurrence of my answer will become the * however both first occurrence and the last element have become an asterix.

Here is the code

arr.forEach(element => {
              arr[i].answer = arr[i].sequence[rndElement];
              arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;

              function isFirst(element, index, array) {
                return element === arr[i].answer;
                }

                let index = arr[i].sequence.findIndex(isFirst);
                arr[i].sequence[index] = "*";

              
          });

Above is the necessary code, below is all the code for reference

const arr = [];
    const input = document.getElementById('answer').value;
    const rndElement = Math.floor(Math.random() * 6);


    function displaySeq() {
        var i = 0;
        while (arr.length < 21) {
            const rndInt = Math.floor(Math.random() * 50);
            const iterator = Math.floor(Math.random() * (8 - 3 + 1)) + 3;
          arr[i] = {
              sequence: [rndInt],
              answer: 7,
              guess: []
          };

          let j = iterator;
          while (arr[i].sequence.length < 7) {
              arr[i].sequence.push(rndInt + j);
              j+=iterator;
          }

        arr.forEach(element => {
              arr[i].answer = arr[i].sequence[rndElement];
              arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;

              function isFirst(element, index, array) {
                return element === arr[i].answer;
                }

                let index = arr[i].sequence.findIndex(isFirst);
                arr[i].sequence[index] = "*";

              
          });
          i++;

       }  
        console.log(arr);
    }

Insert a Javascript Animation in a Vue app?

I want to put this raining pixels animation in my Vue app:
https://codepen.io/kme211/pen/pRzRpJ

I tried just copying the HTML, CSS and JS in their respective tags, thus template, style and script.
However, when I insert the JS in my IDE and refresh the page it turns blank.

How can I insert this animation in my Vue app? I need it as a background for my homepage.

<template>
<div class="bloks"></div>

<section>
  <p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi porta aliquet scelerisque. Donec accumsan magna vel felis volutpat dapibus. In eleifend molestie ipsum vitae fringilla. Fusce at euismod velit. Pellentesque ut lacus sed justo faucibus euismod vel id dui. Nulla ac dictum turpis. Fusce congue enim vel egestas sollicitudin. Etiam nec mi ultricies orci tincidunt pretium eu non urna.
  </p>
</section>

<section>
  <p>
  Sed eget ligula congue, dignissim nibh rutrum, congue nisl. Curabitur vehicula malesuada nulla a fringilla. Nullam nisl felis, mollis ac pellentesque et, tempus at dolor. Etiam quis purus at neque faucibus elementum sed nec sem. Integer dapibus dolor sed egestas vehicula. Mauris fringilla eleifend iaculis. Suspendisse gravida urna ac interdum fringilla. Maecenas sagittis mollis imperdiet. Aenean venenatis metus tortor, ac consequat urna faucibus eget. Pellentesque at mi malesuada, ornare eros vel, iaculis libero. Cras lacinia, nisl in volutpat volutpat, magna magna sagittis urna, ut posuere ante ligula ac lorem. Praesent iaculis ipsum et dui fermentum, non eleifend neque faucibus. Vestibulum quis urna eget eros maximus gravida.
  </p>
</section>

<section>
  <p>
  Ut commodo arcu eu leo consectetur faucibus. Donec egestas ligula id commodo vehicula. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam mauris nulla, gravida id ex id, egestas eleifend sem. Phasellus sit amet scelerisque nunc. Aenean laoreet iaculis malesuada. Cras et volutpat augue, eget convallis turpis. Donec accumsan lobortis dapibus. Proin scelerisque, nulla id fringilla laoreet, felis justo sollicitudin odio, eget efficitur sem metus in libero.
  </p>
</section>
</template>
<style>
:root {
  --blokColor: #495664;
}

html {
  box-sizing: border-box;
  background: #333C4A;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 18px;
  color: white;
  height: 100%;
  width: 100%;
}

*, *:before, *:after {
  box-sizing: inherit;
}

section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

p {
  padding: 2em;
  max-width: 600px;
  background: rgba(0, 0, 0, 0.4)
}

.bloks {
  width: 100%;
  height: 100%;
  z-index: -5;
  position: fixed;
  overflow: hidden;
}

.blok {
  height: 25px;
  width: 25px;
  background: #495664; // Fallback for browsers w/o CSS variable support
  background: var(--blokColor);
  position: absolute;
  transition: background 1.5s;
}

@keyframes blok {
  100% { top: 100vh; opacity: 0;  }
}
</style>
<script>
const numberOfBloks = 9,
      w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0],
      x = w.innerWidth || e.clientWidth || g.clientWidth,
      y = w.innerHeight|| e.clientHeight|| g.clientHeight,
      bloksContainer = d.querySelector('.bloks'),
      blokColors = ['#495664', '#379956', '#F70C9B'], // Color for each section
      sections = Array.from(document.querySelectorAll('section'));

function injectCssAndMarkup() {
  const head = d.head || d.getElementsByTagName('head')[0],
        style = d.createElement('style'),
        leftValues = getLeftValues(numberOfBloks, x),
        topValues = getRandomValues(numberOfBloks, 200),
        delayValues = getRandomValues(numberOfBloks, 15);
  
  style.type = 'text/css';
  const css = getBlokCSS(numberOfBloks, y, leftValues, topValues, delayValues);
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  head.appendChild(style);
  bloksContainer.innerHTML = getBlokMarkup(numberOfBloks);
}

function getBlokMarkup(blokNum) {
  let bloks = [];
  for(let i = 0; i < numberOfBloks; i++) {
    bloks.push(`<div class="blok blok${i+1}"></div>`);
  }
  return bloks.join('n');
}

function getRandomValues(blokNum, maxVal) {
  let values = [];
  for(let i = 0; i < blokNum; i++) {
    values.push(Math.floor((maxVal / blokNum) * (i)));
  }
  return values.sort(function() { return 0.5 - Math.random() });
}

function getLeftValues(blokNum, screenWidth) {
  let values = [];
  for(let i = 0; i < blokNum; i++) {
    values.push(Math.floor((screenWidth / blokNum) * (i + 0.5)));
  }
  return values;
}

function getBlokCSS(blokNum, screenHeight, left, top, delay) {
  let css = [];
  for(let i = 0; i < blokNum; i++) {
    let duration = (screenHeight - (-top[i]))/50;
    css.push(`
      .blok${i+1} {
        left: ${left[i]}px;
        top: -${top[i]}px;
        animation-delay: ${delay[i]}s;
        animation: blok ${duration}s infinite;
        animation-timing-function: linear;
      }
    `);
  }
  return css.join('n');
}

// https://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

var handleScroll = debounce(function() {
    console.log(`scrollTop: ${document.body.scrollTop}`)
  const scrollTop = document.body.scrollTop;
  sections.forEach((section, i) => {
    console.log(`section ${i} | offsetTop: ${section.offsetTop}`)
    if(scrollTop >= (section.offsetTop-100)) {
      document.documentElement.style.setProperty('--blokColor', blokColors[i]);
    }
  })
}, 250);


document.addEventListener('scroll', handleScroll);
injectCssAndMarkup();
</script>

How do I update the repository of a Heroku app?

I am trying to update a repo on Heroku due to finding an error in my index.js file. After using heroku logs --tail, I noticed that:
Heroku Screenshot

I misspelled “config”, so I fixed the file. I tried to wipe the old repo using heroku git:remote -a <appname>, followed by git add ., git commit --am, and git commit push master to create a new one. However, opening the app begets the same error. How am I to update the repo so that the update to index.js is read?

I also followed the instructions of this Stackoverflow question, but nothing seemed to change. Thanks to any help in advance.

Don’t show contents of HTML page until firebase auth status is known

I am building a small site using plain HTML and javascript, and I am using Firebase for authentication. When users go to a certain page, I would like to redirect them to another page if they are signed in. This is the code I am using to achieve that (all scripts are placed in the <head>):

   <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
   <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-auth.js"></script>

   <script>
      const firebaseConfig = {
         // ...
      };

      firebase.initializeApp(firebaseConfig);

      firebase.auth().onAuthStateChanged((user) => {
         window.location.href = "/feed";
      });
   </script>

This redirects the user properly, but the user briefly sees the page meant for non-authenticated users during the time it takes for Firebase to fetch the auth state and for the onAuthStateChanged callback to be fired. Is there a way I can prevent rendering of the HTML page until onAuthStateChanged is called?

javascript fetch declares that response.json() is not a function [duplicate]

I have a simple function that sends json to a server in order to follow a user. Let me know if there’s an easier way, but this is the best way I’ve found that allows me to use a csrf token. Everytime the function runs it says “Uncaught TypeError: response.json is not a function”. I have no idea why…

Here is my function below:

function follow_user(user_id) {
    const fields = {
        csrf_token: {
            input: document.getElementById('csrf_token'),
            error: document.getElementById('csrf_token-error')
        }
    };
    const response = fetch('/_follow_user/'+user_id, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            csrf_token: fields.csrf_token.input.value
        })
    });
    console.log(response.json())
    if (response.ok) {
        if (response.text=="followed") {
            document.getElementById('follow_button').innerHTML="Unfollow";
        } else if (response.text=="unfollowed") {
            document.getElementById('follow_button').innerHTML="Follow";
        }
    } else {
        //This is the part that it declares is not a function. console.log shows response as going through, but response.ok also fails...
        const errors = response.json();
        Object.keys(errors).forEach((key) => {
           fields[key].input.classList.add('is-invalid');
           fields[key].error.innerHTML = errors[key][0];
        });
        jFlash('Follow Failed');
    }
}

SyntaxError: await is only valid in async function (in DiscordJS) [duplicate]

So, I am super new to this, and I’ve been trying to connect my Discord bot to a MySQL Database. I will need to do so in the future. So, because I’m still learning, I downloaded a pre-made bot off of GitHub (Link). And when I tried to execute the code, I got:

/home/zodiac/Documents/DiscordJS-MySQL-master/app.js:47
    if (message.guild && !message.member) await message.guild.fetch.members(message.author);
                                          ^^^^^


SyntaxError: await is only valid in async function

The part of the code it is referring to (Line number 6):

let prefix = row[0].value;
    let args = message.content.slice(prefix.length).trim().split(/ +/g);
    let command = args.shift().toLowerCase();

    if (!message.content.startsWith(prefix)) return;
    if (message.guild && !message.member) await message.guild.fetch.members(message.author);

    let member = message.guild.member(message.mentions.users.first() || args[0]);

I know this isn’t my code, but I would really like to see it working.

Awaiting a reply

How do I resolve this object promise? [duplicate]

I’m initializing a LeagueAPI object that returns a dictionary when a function is called on it. However, when I try to write the returned data to my HTML file, it displays an [object Promise] instead of the data. Here is the code:

LeagueAPI = new LeagueAPI('********', Region.NA);

LeagueAPI.initialize()
    .then().catch(console.error)


document.write(LeagueAPI.getFeaturedGames())

I’ve tried a few implementations of this, but I often run into a CORS error policy. What would be the correct implementation to write the returned data to the HTML file?

How to write JavaScript constructors without strong typing [duplicate]

In strongly typed languages, like C# or Java, I can distinguish constructor signatures by argument types.

class Cars {

    Cars(string x, string y) {};
    Cars(string x, int y) {};

}

But without strong typing in JavaScript, I can only do this, which obviously will not work:

class Cars {

    Cars(x, y) {};
    Cars(x, y) {};

}

Am I limited to only the number of constructor arguments to distinguish them? Is there some way to create JS constructors that have the same number of args, but of different “types”?

How do I make constructors that know that it should be looking for an string y in the first constructor, but int y in the second?

Fixed background and content attachment

Hey guys I have a fixed background attachment for scrolling uptill two pages of the content after that i want the second page to be fixed and make the third page with a different background to come up covering the second page. How can I make the content of the second page fixed when it comes at the top? So that scroll effect can be appliedm