How to read Blob synchronously in Javascript?

I’m writing a chrome extension to intercept WebSocket traffic, by hooking the function WebSocket.send, like:

var _send = WSObject.send
WSObject.send = function (data) {
    arguments[0] = my_hook_function(data)
    _send.apply(this, arguments)
}

function my_hook_function(data) {
    // how to read the data here synchronously?
    return data
}

The my_hook_function should be synchronous. The type of data is Blob, I can’t find a synchronous API for reading the Blob. Google says there is FileReaderSync but I tried in console and this class does not exist.

How to solve it?

Nextjs: static class / use function

I want to create tools class/function in nextjs

I have 2 ways for this.

With static class:

class Tools {
    static titleCase(value: string) {
        return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
    }
}

export default Tools

With use function:

export default function Tools(){
    function titleCase(value: string) {
        return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
    }

    return { titleCase }
}

And here is my question:

1- Which is better?

2- What is difference between these?

how to access object data within object

I have this:

const paymentIntents = await stripe.paymentIntents.list({
    stripeAccount: stripe_account
});

and it returns:

object: 'list',
  data: [
    {
      id: 'pi_...',
      object: 'payment_intent',
      amount: 2500,

now I have two problems. 1. I need to access amount. and 2. there is going to be dozens of records being returned, so I need to loop through all the results and actually add up the amounts. here’s what I’ve tried so far:

console.log(paymentIntents.amount)
console.log(paymentIntents.data.amount)

neither of those worked. and i wouldn’t even know how to loop thorugh all those results. How can i do this?

Best way to update all documents in a collection in mongo?

Basically, I want to check a schedule field in every document, and if Date.now() falls within the bounds of the schedule, I want to set isActive to true.

{

schedule: {
    start: (Date object),
    end: (Date object)
},
isActive: false

}

That in itself is simple, but my issue is that this collection can potentially have hundreds of thousands of documents. I also need this to run every 30 minutes using cron.

Is there any way to efficiently do this without totally locking up my application and/or database every 30 minutes for however long it takes?

Do I need to call save() on each document individually or is there a way I can save all of them at once?

Requesting guidance on user profiles and personal MongoDB collections

I am working with Node/express/javascript/mongoDB.

   My application is one where users log in, POST key/value pairs to a REST api, and the saved data is to be shared with other users of their choice.
    As of now I have the server & front end communicating so users can POST data to a local mongodb. My next step is new users/logins, which I will approach with Passport and a local strategy.
Where I need guidance:
    Let’s say I have 20 users logged in, they all add their own list of items to the db in varying quantities, 10 entries give or take. HOW do I enable their document collections to stay private to their user profile in the overall database AND then be shared with select people to view as in a private group? (is namespacing involved here?)
    I would appreciate advice on if I am proceeding in the right direction and some opinions of popular approach to this kind of thing.
In a nutshell: user logs in, makes a list of things (saved to mongodb), user invites X amount of friends to view their list.

TypeError Next.js GetStaticProps

I have the following error in my Next.js project

error - pagespost[slug].js (30:38) @ getStaticProps
TypeError: (0 , _services__WEBPACK_IMPORTED_MODULE_2__.getPostDetails) is not a function

Can anyone help me to solve this?

export async function getStaticProps({ params }) {
    const data = await getPostDetails(params.slug);
    return {
        props: {
            post: data,
        },
    };
}

export async function getStaticPaths() {
    const posts = await getPosts();
    return {
        paths: posts.map(({ node: { slug } }) => ({ params: { slug } })),
        fallback: false,
    };
}

Rendering performance problem with Phaser 3

I’m new to Phaser 3 and seem to have a huge performance problem. I’m making a Wordle clone game that renders a grid and fills it in with colors and letters as users progress in the game. Each item in the game is either something I created using this.add.text or this.add.graphics

When the game starts, the scene is able to render in less than 3ms

By the end of the game, the scene takes more than 45ms

What am I doing wrong and why is it so slow? How can I improve the performance?
enter image description here

enter image description here

BootstrapVue b-table not storing selected rows when changing pages using b-pagination

I have the following b-table and b-pagination in my template:

<b-table
  bordered
  hover
  responsive
  :items="items"
  :fields="fields"
  :sort-by.sync="sortBy"
  :sort-desc.sync="sortDesc"
  sort-icon-left
  :filter="searchFilter"
  @filtered="onFiltered"
  :filter-included-fields="filterOn"
  :per-page="perPage"
  :current-page="currentPage"
  class="table1"
  ref="table1"
  selectable
  @row-selected="selectedRow"
  :tbody-tr-class="styleRow"
>
  <template #cell(selected)="{ rowSelected }">
      <template v-if="rowSelected">
          <span class="sr-only">Selected</span>
      </template>
      <template v-else>
          <span class="sr-only">Not selected</span>
      </template>
  </template>
</b-table>

<b-pagination
  v-model="currentPage"
  :total-rows="totalRows"
  :per-page="perPage"
  align="center"
  limit="15"
></b-pagination>

In my Vue app, I have the following functions for when the user selects a row:

export default {
  data() {
    return {
      items: [],
      sortBy: 'build',
      sortDesc: true,
      searchFilter: '',
      perPage: 11,
      currentPage: 10,
      totalRows: 1,
      fields: [],
      defaultFields: [],
      fieldNames: [],
      filterOn: [],
      selectedInfo: { item: {}, value: {}, field: {} },
      selected: [],
    };
  },
  methods: {
    styleRow(item) {
      if (item.selected) {
        return ['b-table-row-selected', 'table-secondary'];
      }
      return [];
    },
    selectedRow(items) {
      this.selected = items;
    }
  },
};

Here’s the problem: let’s say the user selects a few rows on page 1 of the table, then goes to page 2, and then goes back to page 1. The previously clicked rows are no longer selected. How do I fix this? How do I prevent pagination from resetting the selected rows?

discord.js autorole from custom status

I have an idea but unfortunately, I don’t know how to make this, or if this is possible.

I want that my discord bot gives a role on my server for a specific keyword in the custom status. The role should be removed if the custom status gets removed or changed.

My question is: If it’s possible how can I make a feature like that in the latest discord.js?

JavaScript: Filter out keys from array of objects

This is what my current object looks like.
My question is how to parse this object such that it will return the expected output (without index 0,1,2…) I want a Javascript array of objects, without the key value.

 "contacts": {
  "0": {
    "firstName": "James",
    "lastName": "April",
    "emails": [
      {
        "emailType": "WORK",
        "address": ""
      },
      {
        "emailType": "PERSONAL",
        "address": ""
      }
    ],
    "relationship": "boyfriend",
    "phones": [
      {
        "phoneType": "HOME",
        "phoneNumber": "(456) 888-9999"
      },
      {
        "phoneType": "CELL",
        "phoneNumber": "(789) 123-4567"
      },
    ],
    "callSequence": 0,
    "note": null
  },
  "1": {
    "firstName": "Joe",
    "lastName": "Kimmel",
    "emails": [
      {
        "emailType": "WORK",
        "address": ""
      },
      {
        "emailType": "PERSONAL",
        "address": ""
      }
    ],
    "relationship": "ex-husband",
    "phones": [
      {
        "phoneType": "HOME",
        "phoneNumber": ""
      },
      {
        "phoneType": "CELL",
        "phoneNumber": "(111) 111-1111"
      },
      {
        "phoneType": "WORK",
        "phoneNumber": ""
      }
    ],
    "callSequence": 0,
    "note": null
  },
  "2": {
    "firstName": "Test",
    "lastName": "",
    "emails": [
      {
        "emailType": "WORK",
        "address": "[email protected]"
      },
      {
        "emailType": "PERSONAL",
        "address": "[email protected]"
      }
    ],
    "relationship": "BROTHER-IN-LAW",
    "phones": [
      {
        "phoneType": "HOME",
        "phoneNumber": ""
      },
      {
        "phoneType": "CELL",
        "phoneNumber": ""
      },
      {
        "phoneType": "WORK",
        "phoneNumber": ""
      }
    ],
    "callSequence": 0
  }
}

}

Expected Result
Wihout the indexes 0,1,2 and should be inside an array. So I want the output as array of objects

   "contacts": [{
   {
    "firstName": "James",
    "lastName": "April",
    "emails": [
      {
        "emailType": "WORK",
        "address": ""
      },
      {
        "emailType": "PERSONAL",
        "address": ""
      }
    ],
    "relationship": "boyfriend",
    "phones": [
      {
        "phoneType": "HOME",
        "phoneNumber": "(456) 888-9999"
      },
      {
        "phoneType": "CELL",
        "phoneNumber": "(789) 123-4567"
      },
    ],
    "callSequence": 0,
    "note": null
  },
   {
    "firstName": "Joe",
    "lastName": "Kimmel",
    "emails": [
      {
        "emailType": "WORK",
        "address": ""
      },
      {
        "emailType": "PERSONAL",
        "address": ""
      }
    ],
    "relationship": "ex-husband",
    "phones": [
      {
        "phoneType": "HOME",
        "phoneNumber": ""
      },
      {
        "phoneType": "CELL",
        "phoneNumber": "(111) 111-1111"
      },
      {
        "phoneType": "WORK",
        "phoneNumber": ""
      }
    ],
    "callSequence": 0,
    "note": null
  }]

set focus on iframe contents to allow sound

this is an extension to another question i’ve asked

i want to embed a game on a website and i want it to automaticaly focus on the iframe. but whenever i try anything like iframe.contentWindow.focus() it focuses on the iframe but the iframe doesnt have any sound

the code for the game was written in a special program so the code is all jumbled and hard to comprehend. though i did find a script that can test the audio. what i want is for this to return true.

testAudio(){
  playTestAudio();return _yb1&&g_WebAudioContext&&g_WebAudioContext.state!==_fa1._ga1
}
function playTestAudio() {
  if(_yb1||_zb1)return;
  _zb1=true;
  var _lb1=new Audio(_X91);
  _lb1.controls=false;
  _lb1.autoplay=true;
  _lb1.preload="none";
  document.body.appendChild(_lb1);
  try{
    var _Bb1=_lb1.play();
    if(_Bb1!==undefined) {
      _Bb1.then(function() {
        debug("WebAudio autoplay test passed.");
        _yb1=true;
        _zb1=false;
        _Cb1();
        document.body.removeChild(_lb1)
      }).catch(function(error) {
        console.log("WebAudio autoplay test failed: ",error);
        document.body.removeChild(_lb1);
        _zb1=false;
        _Db1()
      })
    }else {
      console.log("WebAudio autoplay test failed: Playback promise invalid.");
      document.body.removeChild(_lb1);
      _zb1=false;
      _Db1()
    }
  }
  catch(_wC){debug("WebAudio autoplay test failed with exception: "+_wC);
  document.body.removeChild(_lb1);_zb1=false;_Db1()}
}

this is the location of the script file if needed
lacation.scripts.net

Don’t know how to write a specific regular expression

I have a string like this:

“56×74 x567 x7 7889 x97x89xx”.

I need to leave everything except the letter x, which has a left empty space involved. It has to be done by the Match method.
I was trying to do it, but it has not worked at all.
Please, help me.
The result should look like this:

“56×745677 788997x89xx”.

Having a varible in regex?

Hi I have the following code

    const containsAtLeastDigits = (digits, password) => {
  
  const regex = new RegExp(/(?=.{6}).*/g);

  if (regex.test(password)) {
    console.log("yes");
    return false;
  } else {
    console.log("no");
  }
};

containsAtLeastDigits(6, "abcdefg");

Here I have to pass the parameter digits where {6} is defined in regex as interpolation like this ${digits}. Can someone please explain if this is possible to do? I saw a few answers in StackOverflow itself but they are not working.

Using react-select with multiple inputs

I have multiple react-select inputs, each have their own separate options array. The issue i’m having is I’m now sure how to properly store the output of each select input.

I want to use this select output to POST to my backend but i’m unsure how to do it all with a single handler function.

This is what I have so far, i have 2 paragraphs to just output the appropriate result from the select fields but i can’t seem to get it working.

This is the codesandbox i have:

https://codesandbox.io/s/busy-yonath-rlj9e?file=/src/App.js

Setting React state Asynchronous – React useState hook

I am trying to update 1 quote inside of an array of “quotes”

const [quotes, setQuotes] = useState([]);
const [quoteToUpdate, setQuoteToUpdate] = useState(initialValues);

When I click on a switch (checkbox) I set quoteToUpdate with the quoteToUpdate with the selected quote data, and update the switch from true to false or vice versa.

const onCheckboxChange = async (e, selectedQuote) => {
  setQuoteToUpdate({...selectedQuote, [e.target.name]: e.target.checked});
};

The Problem I’m having is, right after I update the quoteUpdate, I need to send the updated object to the backend to update. But since React state is sync, the quoteToUpdate does not get updated instantly but instead queues up.

What I’ve tried:
I’ve tried putting the onSubmit() function inside a useEffect but it’s clearly not working.

useEffect(() => {
  onSubmit(quoteToUpdate);
}, [quoteToUpdate])

onSubmit looks like this:

const onSubmit = (quoteToUpdate) => {
    axiosWithAuth().put('/quotes/' + quoteToUpdate.id, quoteToUpdate)
      .then((res) => {
        const updatedQuote = res.data;
        setQuotes(quotes.map(quote => (
          quote.id === updatedQuote.id ? {...quote, 'is_complete': updatedQuote.is_complete} : quote
          ))
        );

        const alertContent = `quote updated successfully.`;

        halfmoon.stickyAlerts = document.getElementsByClassName("sticky-alerts")[0]
        halfmoon.initStickyAlert({
        content: alertContent, alertType: "alert-success", title: "Successfully updated"
      })
    }).catch(error => {
      console.log(error.message);
    });
}