Multi-Level Occurrence Counting in Javascript

I am trying to count the occurrences of values for multiple objects in an array in Javascript. For the following example input (original data is much larger):

input= [
   {
      Name: "James",
      Department: "Engineering",
      employeeId: 26
   },
   {
      Name: "Roger",
      Department: "Design",
      employeeId: 21
   },
   {
      Name: "John",
      Department: "Engineering",
      employeeId: 32
   },
   {
      Name: "Roger",
      Department: "Engineering",
      employeeId: 42
   },
   {
      Name: "Roger",
      Department: "Engineering",
      employeeId: 36
   }

For this I am trying to get the following output:

Output = [
{Name: 'James', Department: 'Engineering', count:1},
{Name: 'Roger', Department: 'Design', count:1},
{Name: 'John', Department: 'Engineering', count:1},
{Name: 'Roger', Department: 'Engineering', count:2},
]

I am trying to use loops and if statements given that I am new to JS. I tried implementing variations to what is provided on

https://www.geeksforgeeks.org/how-to-count-number-of-occurrences-of-repeated-names-in-an-array-of-objects-in-javascript/.

While its counting correctly, I cant seem to capture all the groupings. Any help here would be really appreciated!

Thanks!

JS Canvas Drawing Grid

I’m trying to draw a simple grid like this: Grid

I want the grid to be 17×17. So I made a function to do that:

function drawGrid() {
  let grids = 17;
  let inc = cvs.width / 17;

  let ct = 0;
  for (let c = 0; c < cvs.width; c += inc) {
    for (let r = 0; r < cvs.width; r += inc) {
      if (ct % 2 === 0) {
        ctx.fillStyle = "#aad751";
      } else {
        ctx.fillStyle = "#a1d149";
      }
      ctx.fillRect(r, c, inc, inc);
      ct++;
    }
  }
}

Basically I have a loop that counts up 17 times in the row and column direction. Each time incrementing by the exact amount. I know width = height, so I just used width for everything. Each time I just alternate each box color, and draw it. Now on small sizes my code works perfectly, but once I make my display monitor large enough for some reason the grid becomes lines:
Example of wrong behavior

Any ideas why this is doing that?

Thanks!



Firebase Cloud Messaging – Cannot receive messages through PWA (Vue + Firebase 8.10.0)

I’ve run into a snag/gap in firebase’s setup with web applications(PWA) which is not so clear in the documentation. I have an existing PWA built on Vue@^2.6.10 and am trying to plug Firebase’s cloud messaging into it using [email protected]. It’s easy enough to configure my application to receive messages from firebase when the app is active within a browser tab by using the following code in my App.vue in a created hook.

// Includes for the component
import firebase from 'firebase/app'
import 'firebase/app'
import 'firebase/messaging'

// Within the created hook
firebase.initializeApp({
  apiKey: "XXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXX",
  authDomain: "xxxx.firebaseapp.com",
  projectId: "xxxx",
  storageBucket: "xxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxxx",
  appId: "x:xxxxxxxxx:web:xxxxxxxxxxx",
  measurementId: "G-xxxxxxxxxxx"
})
const firebaseMessaging = firebase.messaging()
firebaseMessaging.getToken()
.then((token) => { console.log("Messaging Token: ", token) })
.catch((err) => { console.log("Messaging error: ", err) })
firebaseMessaging.onMessage((payload) => {
  console.log("Message in app: ", payload)
})

While the PWA is active within a browser window/tab, I am able to successfully send a curl message to my application.

curl -X POST --header "Authorization: key=XXXXXXXXXXXX" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{"to":"XXXXXXXXXXXXX","notification":{"title":"Hello","body":"World","icon":"image/mstile-150x150.png"}}'

enter image description here

However, if I try to then configure the PWA to receive notifications via the firebase service worker, this is when the documentation seems to be missing context. Below is the recommended service worker configuration from the firebase docs which I am using.

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
  apiKey: "xxxxx_xxxxxxxxxxxxxxx",
  authDomain: "xxxx.firebaseapp.com",
  projectId: "xxxx",
  storageBucket: "xxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxx",
  appId: "x:xxxx:web:xxxxxxxxxx",
  measurementId: "G-xxxxxxxxxxx"
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

For a standard website without an existing service worker, it seems like this configuration should be enough, however, since I am tying into an existing PWA with an existing service worker, it seems I need to register firebase’s configuration with the existing PWA configuration on my application. From what I’ve found thus far, the proper configuration of that tie-in is the following.

if ("serviceWorker" in navigator) {
  wb = new Workbox(`${process.env.BASE_URL}service-worker.js`)
  wb.addEventListener("controlling", () => { window.location.reload() })
  wb.register()
  wb.register("./firebase-messaging-sw.js")
  .then(function(registration) {
    console.log("Registration successful, scope is:", registration.scope);
    })
    .catch(function(err) {
      console.log("Service worker registration failed, error:"  , err );
    })
} else {
  wb = null
}

From the look of it, this does successfully register Firebase’s configuration with my existing service worker.

enter image description here

However, while the registration looks successful from the onset it’s not actually tying into the service worker. When clicking away from the PWA’s active browser tab under this configuration, the service worker does not receive a notification when performing the same curl above. From everything I can tell thus far in the docs, the PWA should be receiving the notification and firing a default browser notification for the event, however, that’s not the case. No notification is received even though the notification did send through Firebase’s API successfully given the response from their API:

{"multicast_id":3069325822032476405,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"88f73357-6a0e-416d-8417-67608437f84d"}]}%

So, I am kind of at the end of the road in terms of what documentation and threads I can find on this topic thus far. It would seem like there’s not a great example of how to do this configuration correctly when tying into an existing service worker. I very much appreciate anyone with experience on this topic providing their insight on configurations you’ve made work using firebase and service worker on PWAs.

Many thanks!

Retrieve groups-only from a replace function

I am using named groups in a replacement method, and I want to only work with that groups object, as it may have a variable number of capture groups. As an example:

function reFunc(match, p1, p2, p3, p4, offset, string, groups) {
    console.log('*****', groups);
}
"Bob Jones is the mayor of Dallas.".replace(/(?<first>w+) (?<last>w+) is the (?<position>w+) of (?<city>w+)/, reFunc);
"Bob Jones is the mayor of Dallas, Texas.".replace(/(?<first>w+) (?<last>w+) is the (?<position>w+) of (?<city>w+), (?<state>w+)/, reFunc);

Is there a way to just ignore everything except the groups in the replacement function, for example something like:

function reFunc(..., groups) {
    ...
}

I’m getting output but the numbers or letters are not being printed. Coding practice problem (JavaScript). Code and output picture included [closed]

working on a practice problem. The problem asks write a method ‘combinations’ that takes in an array of unique elements and returns a 2D array representing all possible combinations of 2 elements in of the array

Here is the expected output:
combinations([“a”,”b”,”c”]) => [[“a”,”b”], [“a”,”c”], [“b”,”c”]]

combinations ([0, 1, 2, 3]) => [[0,1], [0,2], [0,3], [1,2], [1,3], [2,3]]

Here is my code and output:
confused on why its saying array[2] for every-one. What am I missing?

Possible to get ‘regex source’ from match?

I can get the source of a regex when it’s defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*

Or:

let r2 = /el*/;
console.log(r2.source);

Is there a way to extract that if the regex isn’t defined separately? For example, something along the lines of:

let m = "Hello".match(/el*/);
console.log(m.source?);

Using match with or without global flag [duplicate]

It seems like when using match without the global flag, it returns an object:

// Chrome dev tools
console.log("Hello Hello".match(/el*/));
VM499:1 ['ell', index: 1, input: 'Hello Hello', groups: undefined]

However, if I use the g flag, regardless of whether there is one or more results, instead of returning an object, it returns an array:

console.log("Hello Hello".match(/ello$/g));
VM512:1 ['ello']

console.log("Hello Hello".match(/el*/g));
VM550:1 (2) ['ell', 'ell']

Why does javascript convert a match that uses g to an array of strings? Perhaps if you’re looking for multiple matches you should only be using matchAll ?

How to post an image using python requests? [duplicate]

So I am trying to make a post request to a certain website where the request’s data has an image, I looked at their source and they do the following:

they first ask you to input the image file using an input element

<input type="file" id="iconImageFile" accept="image/*" name="iconImageFile"/>

then they make a request and send the file

var r = new FormData;
r.append("iconImageFile", $("#iconImageFile")[0].files[0]),
$.ajax({
    url: url,
    type: "POST",
    data: r,
    cache: !1,
    contentType: !1,
    processData: !1
})

My question is how would I be able to replicate such a request using python’s requests library? I already have all of the headers needed for verification, I am just confused on how I would send this image in the request.

session.post(url,data = {
    'iconImageFile' : open('icon.png', encoding="utf8", errors='ignore')
})

Any help would be appreciated 😀

Problem with Update in Every Refresh, localStorage, useState, useEffect

I am trying to prevent my app to go into useEffect hook and implement what is inside within a 5 second period regardless of the situation the page is refreshed or not.

My code still only fires up the useEffect hook only on page refresh. It does not really care whether 5 seconds passed it fires up in every page refresh and then does not do anything for an eternity unless you refresh the page again. It acts like a useEffect hook with empty dependency array.

How can I achieve useEffect hook to run every 5 seconds regardless the page is refreshed or not? Here is my snippet.

  const localVisitTime = localStorage.getItem('localVisitTime');
  const currentTime = new Date().getTime();
  const timeDifference = currentTime - localVisitTime;

  const [ visitTime, setVisitTime ] = useState(localVisitTime);

  if (localVisitTime && timeDifference <= 5000) {
    // Do nothing, wait!
  } else {
    localStorage.setItem('localVisitTime', new Date().getTime());
    setVisitTime(localVisitTime);
  }

  useEffect(() => {

    const fetchData = async () => {
      console.log('Data fetched!');
    }

    fetchData();
  }, [visitTime]);

syntax explanation for copying object array and add new property

Can someone explain to me why this is the only version I’ve tried that works for copying state with es6 and adding another field, out of the other ways tried that are listed below? :

const values = [{key: "1", val: "one"}, {key: "2", val: "two"}];

var works = values.map(v => {
    return {
       ...v,
       extra: "stuff"
   }
})

And all of these produce these errors:

//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff"); 

// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"}) 

// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v, 
   extra: "stuff"
  }
}) 

// unexpected token 'return'
var notWorks4 = values.map(v => 
   return {
    ...v, 
    extra: "stuff"
   }
) 
// unexpected 'return'
var notWorks5 = values.map(v => return ...v, extra: "stuff");

I thought the arrow was implicit return (see first 3 attempts).

Is that first way the only syntax that can be used? If there are any others, I’d like to know as I’m trying to practice and learn multiple options.. and I want the most terse, smallest option (one line).

How do I list all servers in a discord.js v12 bot

I’m trying to make a command so when you go ;listservers it brings a list of current servers the bot is in but my code is sending servers one at a time making it really slow is there anyway I could fix this? this is my current code

    message.channel.send(`Found ${client.guilds.cache.size} serversnServer List:`)
    client.guilds.cache.forEach(guild => {
        message.channel.send(`${guild.name} | ${guild.id}`)
    })

How to format array of date

I am getting an array of dates in this format

Sat Feb 12 2022 01:00:00 GMT+0100 (West Africa Standard Time),Sun Feb 13 2022 01:00:00 GMT+0100 (West Africa Standard Time),Mon Feb 14 2022 01:00:00 GMT+0100 (West Africa Standard Time)

But i want it in a format like this

Sat, Feb 12, 2022,
Sun, Feb 13, 2022,
Mon, Feb 14, 2022

This is the code that output my date

function dateRange(startDate, endDate, steps = 1) {
  const dateArray = [];
  let currentDate = new Date(startDate);

  while (currentDate <= new Date(endDate)) {
    dateArray.push(new Date(currentDate));
    currentDate.setUTCDate(currentDate.getUTCDate() + steps);
  }

  return dateArray;
}
var currD = new Date().toISOString().slice(0,10);

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}
 const futureDate = addDays(currD, 3);

const dates = dateRange(currD, futureDate);
console.log(dates);
alert(dates)

How to load infinite scroll pages faster?

https://immutascan.io/address/0xac98d8d1bb27a94e79fbf49198210240688bb1ed

This URL has 100k+ rows that I’m trying to scrape. They go back about a month (1/10/2022 I believe) but load in badges of 7-8.

Right now I have a macro slowly scrolling down the page, which is working, but takes about 8-10 hours per day’s worth of rows.

As of now, when new rows load there are 2-3 items that load immediately and then a few that load over time. I don’t need the parts that load slowly and would like them to load faster or not at all.

Is there a way that I can prevent elements from loading to speed up the loading of additional rows?

I’m using an autohotkey script that scrolls down with the mouse-wheel and that’s been working best.

I’ve also tried a Chrome extension but that was slower.

I found a python script at one point but it wasn’t any faster than autohotkey.

vue – reference values in setup() function in html template

I am trying to setup the demo code that comes with “vee-validate” (https://vee-validate.logaretm.com/v4/examples/multistep-form-wizard)

I have some fields on the inital form page that if contain a certain value, i want to hide and show certain elements using “v-if=”true/false”.

Normally i reference a variable stored in the “data()” part of the vue file to toggle show/hide but i cannot find a way to pass a value i obtain/set in the “setup()” function of the vue project. It also will not allow me to set values in “data()” by doing “this.variable = true” like i can normally do in a function.