Problem at getting the memberCount of every guilds + excepting the bots in the guilds (Discord.js)

Making a bot in Discord.js, and i wanna see how many users the are in the servers that the bot is in(excepting the bots of the servers)

I’ve been trying for weeks but when i wanna get the value, it gives me something else..

Here’s my code:

var AllUsers = 0
client.on('ready', () => {
    client.guilds.cache.forEach( guild => {
        var memners = 0
        mems = mems + guild.memberCount
        var Bcount = 0
        Bcount = Bcount + guild.members.cache.filter(member => !member.user.bot).size
        var users = mems - Bcount
        AllUsers = AllUsers + users
    })
    console.log(`the bot is ready and dealing with ${AllUsers} users`)
}

In this code i’m actually excepting the count of the bots from the memberCount itself, but my problem is that it just doesn’t work! the code guild.members.cache.filter(*member* => !member.user.bot).size doesn’t work! it doesn’t give me an error..

It actually gives me this(i made some console.logs for that):

in my Bots server: 
members: 5    
Bcount: 1  
users: 4   
AllUsers: 4
---------  
in Code server:      
members: 4    
Bcount: 1  
users: 3   
AllUsers: 7
---------  
in Games server:  
members: 3    
Bcount: 1
users: 2
AllUsers: 9
---------

Its like the value of the Bcount is “1” while it’s not!

I’ve tried the: guild.members.cache.filter(member => member.user.bot).size instead of: guild.members.cache.filter(member => !member.user.bot).size and this time the value of the Bcount was “0“.

It’s really ridiculous! cause all those three servers have 2 bots in it but it gave me 1 and 0!

Please if you know how to solve this problem help me.

thank you.

How to override scroll functions in a window?

How do you override scroll functions of a browser in JavaScript?

Functions which I was able to find are scroll, scrollBy and scrollTo (from the window object).
But, if I try to override them using the standard procedure, like any other function, for example, by executing the following code window.scroll = function(parameter){} it does not have any effect on the browser.
So, if I try to scroll the page after executing the above code (for all 3 methods), the window still scrolls.

Are there any other functions which browser uses to scroll? If so, which function should I override to get a custom scrolling behaviour?

I am using Google Chrome (latest version), of course.

How would you handle JSON string parsing with user sent data? (NodeJS ws)

I’m doing a chat app on a platform called NeosVR and there is no way to handle JSON objects on it. To send my message / user data, i’m sending a string from the client that is built as something like this (if it helps):

{“user”:”…”, “message”:”…”}

I then parse it to JSON on the server side (NodeJS) with JSON.parse(), but as the user string is not handled propperly (can contain characters like ‘”‘ or escape characters), the JSON parsing sometimes fails.
Examples of failed parsing:

{“user”:”santette”, “message”:”””}

{“user”:”santette”, “message”:” “}

How would you parse something like this ? (I need to keep all the escape characters as a normal character and ‘”‘ too, because it’s a chat app…).
Thank you for your help 🙂

Twilio Programmable Chat – not able to run the quickstart project

I was trying to run twilio quickstart code for programmable chat, but I was getting the below error.

Logging in…
There was an error creating the chat client:
Error: Fetch resource from “Client/v1/Configuration” failed.
Please check your .env file.

configurations seems proper in Twilio Server Starter Kit Environment Setup.

enter image description here

enter image description here

Browser JS: How to extract aac audio data from a mp4 file?

Using browser javascript, i need to load mp4-files containing AAC audio data, and extract this audio data for later use.

There is an mdat block in the mp4 file that (to my understanding) holds the embedded aac data, but just extracting the contents of that mdata block does not seem to give me valid aac data.

So, what is the simplest way to – in the browser – get embedded aac audio data out of a mp4 conatiner file?

Vue 2 – Dragover a child element pass the event to the parent depending of what we drag

I’m making a template editor with Vuejs and I don’t know how to make this:

I got one parent component that is a rowComponent and inside it got one child that is a container and inside that one, I got 2 text components.

rowComponent

________________container

_________________________textComponent

rowComponent and textComponent will both have a @mouseover and @drop.
rowComponent is listening mouseover because we can drop other rows on it and thats working great.

I need to put too a @mouseover and @drop on the child component (text) because I want to drop some other elements (like others texts) BUT I DON’T want to dragover and drop rows on it.

So when I’m overing childs (text) with a row block element, I want to propage the event to the parent so if I drop in the child a ROW block, it’s the @dragover (and drop) of the parent that is triggered. But I don’t know who to do that.

Of course, if I take a TEXT block, the child will accept the dragover and drop on himself

dragStart element :

       <v-list-item v-for="item in rowContainers" :key="item.title">
          <v-list-item-content
            draggable
            @dragstart="dragStart($event, item)"
            :id="item.id"
            class="d-flex justify-center mb-2"
            style="border: 1px solid black"
          >
            {{ item.name }}
          </v-list-item-content>
        </v-list-item>



  dragStart(event, item) {
   console.log('dragging : ')
   console.log(item)
   event.dataTransfer.setData('item', item)
 },

Row Component (parent):

<template>
  <div
    @dragover="dragOver"
    @dragleave="dragleave"
    @drop="handleDropRow"
    @mouseover="isHovering = true"
    @mouseout="isHovering = false"
    @click.stop="selectRow"
    class="blueprint-row"
    :class="{
      'blueprint-row-hovering': isHovering,
      'blueprint-row-selected': isSelected,
      'blueprint-row-drag-row-hover-top': dragHoverRowOnTop,
      'blueprint-row-drag-row-hover-bot': dragHoverRowOnBot,
    }"
  >
    <!-- Container block  -->

    <component
      :is="block.component"
      :block="block"
      :blockId="block.id"
      :rowIndex="index"
    ></component>
  </div>
</template>

<script>
import SingleContainer from "./containers/SingleContainer.vue";
import { mapGetters, mapActions } from "vuex";

export default {
  props: ["rowId", "block", "index"],
  components: {
    SingleContainer,
  },
  data() {
    return {
      isHovering: false,
      dragHoverRowOnTop: false,
      dragHoverRowOnBot: false,
    };
  },
  mounted() {
    console.log("mounted");
  },
  computed: {
    ...mapGetters("templateEditor", ["blockSelected"]),
    isSelected() {
      return this.blockSelected.id === this.block.id;
    },
  },
  methods: {
    ...mapActions("templateEditor", ["setSelectedBlock"]),
    selectRow() {
      console.log("click on row " + this.block.id);
      this.setSelectedBlock({ type: "row", id: this.block.id });
    },
    dragOver(e) {
      e.preventDefault()
      console.log(e.target)
       const offset = this.getOffsetPosition(e);
        console.log(offset)

        // const target_index = this.getDataIndexById(e.target.id);
        if (offset < 0) {
          this.dragHoverRowOnTop = true
          this.dragHoverRowOnBot = false
        } else {
          this.dragHoverRowOnBot = true
          this.dragHoverRowOnTop = false
        }
    },
    dragleave() {
      this.dragHoverRowOnTop = false
      this.dragHoverRowOnBot = false
    },
    handleDropRow(e) {
      console.log("drop");
      console.log(e);
    },
    getOffsetPosition(e) {
      const box = e.target.getBoundingClientRect();
      const offset = e.clientY - box.top - box.height / 2;
      return offset;
    },
  },
};
</script>

container :

<template>
  <div :style="computeRowStyle" >
    <!-- has no children -->
    <div
      v-if="!block.children.length"
      :class="{ 'dragcontent-hovering': dragContentOvering }"
    >
      <div
        class="d-flex justify-center align-center items-center empty-content"
      >
        Pas de contenu ici. Glissez un nouvel élément depuis "contenu".
        {{ blockId }}
      </div>
    </div>
    <!-- has children -->
    <div v-else style="width: 900px;" class="d-flex flex-column">

      <div
        v-for="(child, index) in block.children"
        :key="index"
      >
                <TextTitle v-if="child.type === 'text-title'" :data="child" :rowIndex="rowIndex" :index="index" />
      </div>
    </div>
  </div>
</template>

child (text):

<template>
  <div
    style="width: 100%"
    :style="computeRowStyle"
    :class="{ 'content-hovering': isHovering, 'content-selected': isSelected }"
    @mouseover.stop="isHovering = true"
    @mouseout="isHovering = false"
    @dragover="dragOver"
    @dragleave="dragleave"
    @click.stop="selectContent"
  >
    <span contenteditable @input="update">{{ data.content }}</span>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  props: ["data", "rowIndex", "index"],
  data() {
    return {
      isHovering: false,
    };
  },
  computed: {
    ...mapGetters("templateEditor", ["blockSelected"]),
    isSelected() {
      return this.blockSelected.id === this.data.id;
    },
    computeRowStyle() {
      const rowStyle = {
        textAlign: this.data.elementStyle.textAlign,
      };

      return rowStyle;
    },
  },
  methods: {
    ...mapActions("templateEditor", ["setSelectedBlock", "updateTextValue"]),
    selectContent() {
      console.log("click on content " + this.data.id);
      this.setSelectedBlock({ type: "text-title", id: this.data.id });
    },
    update(e) {
      console.log(e.target.textContent);
      // this.data.content = e.target.textContent
      this.updateTextValue({
        index: this.index,
        rowIndex: this.rowIndex,
        value: e.target.textContent,
      });
    },
    dragOver(e) {
        e.preventDefault()
        console.log(e.dataTransfer)
        
    //   e.preventDefault();
    //   const offset = this.getOffsetPosition(e);
    //   console.log(offset);

      // const target_index = this.getDataIndexById(e.target.id);
    //   if (offset < 0) {
    //     this.dragHoverRowOnTop = true;
    //     this.dragHoverRowOnBot = false;
    //   } else {
    //     this.dragHoverRowOnBot = true;
    //     this.dragHoverRowOnTop = false;
    //   }
    },
    getOffsetPosition(e) {
      const box = e.target.getBoundingClientRect();
      const offset = e.clientY - box.top - box.height / 2;
      return offset;
    },
  },
};
</script>

Typescript and Array.map with thisArg results in an error

In Javascript, I can pass a thisArg into the Array.map function as a second argument. Here is a minimal example.

const a = [1,2,3,4,5,6];
a.map(function(e) { this.sum += e; return this.sum; }, {sum: 0});

The result is the array [1, 3, 6, 10, 15, 21]. When I try the same in Typescript, I get the following error.

'this' implicitly has type 'any' because it does not have a type annotation. ts(2683)

How can I annotate the code so that this inside the callback has the correct type?

I have tried giving everything a type annotation like this,

const a: number[] = [1,2,3,4,5,6];
const S: {sum: number} = {sum: 0};
a.map(function(e: number): number { this.sum += e; return this.sum; }, S);

But this doesn’t get rid of the error because none of these annotations specifies the type of this explicitly.

LightGallery + SwiperJs multiple dynamic galleries

I am using Lightgallery in combination with Swiper.js. LightGallery opens once clicking on a slide from a Swiper carousel. My issue is that I am displaying multiple galleries (multiple carousels) on the same page, and my setup apparently sees all of them as one long gallery. How can I fix this? I guess I should create dynamic IDs and call them via dynamicEl, but I’m very new to javascript and have no clue how to do that.

Here’s my PHP setup within a foreach loop

<?php foreach($pages->children()->listed() as $project ): ?>
<li id="<?= $project->slug() ?>" class="card">
      <div class="card-carousel-container">
          <div class="swiper swiperGrid">
            <ul class="swiper-wrapper">

                <?php foreach($project->images()->sortBy('sort') as $image ): ?>
                    <li class="swiper-slide">
                      <a class="lightgallery-open">
                        <img src="<?= $image->url() ?>" data-src="<?= $image->url() ?>" alt="<?= $project->info()->text() ?>">
                      </a>
                    </li>
                <?php endforeach ?>

            </ul>
          </div>
    </div>
  </li>
<?php endforeach ?>

and here’s my javascript setup:

const gsBgImgSelector = ".swiperGrid .swiper-slide img";

const dynamicEl = [...document.querySelectorAll(gsBgImgSelector)].map(
  (sliderImg) => {
    return {
      src: sliderImg.src,
      thumb: sliderImg.src,
      subHtml: sliderImg.alt,
    };
  }
);

console.log(dynamicEl);

const dynamicGallery = document.querySelector(".swiperGrid");

const popup = lightGallery(dynamicGallery, {
  plugins: [lgHash, lgVideo],
  selector: '.swiper-slide:not(.swiper-slide-duplicate) > div',
  dynamic: true,
  loop: true,
  autoplayVideoOnSlide: true,
  dynamicEl,
});

console.debug(popup);

dynamicGallery.addEventListener("click", () => {
  popup.openGallery(0);
});

[...document.querySelectorAll(".swiper-slide")].map((slide, idx) => {
  slide.addEventListener("click", () => {
    popup.openGallery(idx);
  });
});

Could you please help me to solve this? Thank you very much all!

How to prevent http calls to “http://www.w3.org”

Background of the issue :
I have developed a custom plugin that reads string or text information in defined manner and represents that information in graphical format i.e. flowchart. I am using mermaid javascript library for this purpose. Below is link to mermaid website and javascript library I am using
Mermaid website – https://mermaid-js.github.io/mermaid/#/flowchart
Mermaid library – https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js
This custom plugin is developed using java and deployed on Rational Team Concert server (IBM tool for project management). This plugin returns html response to user when invoked with specific url. HTML response is the flowchart of all the workflows contained in the project. In the HTML response I am calling mermaid functions which are responsible for converting text information into SVG which is rendered as flowcharts on web page.

Actual Issue
Whenever I invoke this plugin I get Exception: java.net.UnknownHostException: www.w3.org exception. It is when html response is returned to the user inside html code mermaid functions are called to convert text into flowchart. There are occurrences of www.w3.org in the mermaid library I am using. I believe at the time of returning html response RTC server is trying to reach to www.w3.org but because there is not internet on the server this exception is thrown.

Please help me with how to solve this issue.

foreach hover over change the text color – Javascript

I have 4 divs (colored box) and each div represent a different color.
When a user hovers over one of the colored boxes the text to display (“Hello world”) should change to the color that is being hovered over – this is how it looks like .
I wrote the code for each color, but it seems worng because I’m copying the code many times for each color.
How can I make this code shorter and more efficient?

html:

<body>
<h1 id="change_heading">Hello World</h1>
SELECTED COLOR <span class="selected">None!</span>
<section>
    <div class="brown"></div>
    <div class="green"></div>
    <div class="blue"></div>
    <div class="yellow"></div>
</section>
<script src="script.js"></script>

css:

 div {
        width: 50px;
        height: 50px;
        display: inline-block;
    }
    .brown {
        background-color: brown;
    }

    .green {
        background-color: green;
    }

    .blue {
        background-color: blue;
    }
    .yellow {
        background-color: yellow;
    }

javascript:

document.addEventListener('DOMContentLoaded', function () {

const textToChange=document.getElementById('change_heading');

const brownColor=document.querySelector('.brown');
const greenColor=document.querySelector('.green');
const blueColor=document.querySelector('.blue');

brownColor.addEventListener('mouseover', function(){
    textToChange.classList.add('brown');
});

brownColor.addEventListener('mouseout', function(){
    textToChange.classList.remove('brown');
});

greenColor.addEventListener('mouseover', function(){
    textToChange.classList.add('green');
});

greenColor.addEventListener('mouseout', function(){
    textToChange.classList.remove('green');
});

blueColor.addEventListener('mouseover', function(){
    textToChange.classList.add('blue');
});

blueColor.addEventListener('mouseout', function(){
    textToChange.classList.remove('blue');
});

});

Is there a way to know or calculate only the Attachments size before or after sending the email using Nodemailer?

In our application we are attaching PDF, at some random scenario the attachment is getting corrupted. So we decided to check if the attachment size is same as before and after the attachment is attached, and validate for the same.

I couldn’t find any information regarding how the messageSize is calculated or a way to know the attachment size from the callback of transporter.sendMail().

We observed the changes in size by manipulating the attributes does not have any repeatable patter that we can take advantage off.

var mailOptions = {
  from: "<some email>",
  to: "<some email>",
  subject: "S",
  text: "",
  attachments: [
    {
      filename: "a.pdf",
      path: "./sample.pdf",
    },
  ],
};

const getFileSize = () => {
  const fileSize = fs.statSync(mailOptions.attachments[0].path);
  return fileSize.size;
};

const calTotalSize = () => {
  let total = 165;

  if (mailOptions?.from?.length > 0) {
    total = total + mailOptions.from.length;
  }
  if (mailOptions?.to?.length > 0) {
    total = total + mailOptions.to.length;
  }
  if (mailOptions?.subject?.length > 0) {
    total = total + mailOptions.subject.length + 11;
  }
  if (mailOptions?.text?.length > 0) {
    total = total + mailOptions.text.length + 50;
  }
  if (mailOptions?.attachments?.length > 0) {
    if (mailOptions.attachments?.filename?.length > 0) {
      total = total + mailOptions.attachments[0].filename.length;
    }
    if (mailOptions.attachments?.path?.length > 0) {
      total = total + mailOptions.attachments[0].path.length;
    }
    total = total + getFileSize();
  }

  return total;
};

transporter.sendMail(mailOptions, function (error, info) {
  if (error) {
    console.log(error);
  } else {
    console.log(getFileSize(), "calculate original pdf size");
    console.log(calTotalSize(), "calculate total size");
    console.log(info.messageSize, "Email size");
  }
});

Thank you.

Best MVC architecture to build rest API with Express JS [closed]

I practice to build a simple rest api using express js. It’s running well but i’m not really sure this follow the MVC architecture.

please give me a feedback to improve my code.

here’s my code

server.js
running my server from here:

const express = require('express');
const cors = require('cors');
const { getAllNotes, postNewNote, updateNoteById, deleteNoteById, notFoundError, getNoteByTitle } = require('./controllers/controllers.js');
const app = express();
const port = 3001;

app.use(express.json());
app.use(cors());

app.get('/', (req, res) => {
    res.send({
        response: req.query.tes
    });
});

app.route('/notes')
    .get(getAllNotes)
    .post(postNewNote)
    .put(updateNoteById)
    .delete(deleteNoteById);

app.route('/notes/:title')
    .get(getNoteByTitle);

app.route('*')
    .all(notFoundError);

app.listen(port, () => console.log(`app listening on http://localhost:${port}`));

and here’s my db connection code.

db.js

const mysql = require('mysql');

const conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'daily_task'
});

conn.connect( err => {
    if (err) throw err;
    console.log('Success connected to db');
});

module.exports = conn;

controller.js

const { nanoid } = require('nanoid');
const sql = require('../db/db.js');

const getAllNotes = (req, res, next) => {
    const getAllQuery = 'SELECT * FROM notes';

    sql.query(getAllQuery, (err, result) => {
        if (err) {
            res.send({
                status: 'ERROR',
                error: 'Failed to GET notes'
            });
            next(err);
        } else {
            res.send({ 
                notes: result
            });
        }
    });
};

const getNoteByTitle = (req, res, next) => {
    const getNoteByIdQuery = `SELECT * FROM notes WHERE title LIKE '%${req.params.title}%'`;

    sql.query(getNoteByIdQuery, (err, result) => {
        if (err) {
            res.send({
                status: 'ERROR',
                error: 'Failed to GET note'
            });
            next(err);
        } else {
            res.send({
                notes: result
            });
        }
    });
};

const postNewNote = (req, res, next) => {
    const id = nanoid(16);
    const postNoteQuery = `INSERT INTO notes (id, title, note) VALUES ('${id}', '${req.body.title}', '${req.body.note}')`;
    sql.query(postNoteQuery, (err) => {
        if (err) {
            res.send({
                status: 'ERROR',
                error: 'Failed to POST notes'
            });
            next(err);
        } else {
            res.send({
                id: req.body.id,
                title: req.body.title,
                note: req.body.note,
                status: 'ADDED',
            });
        }
    });
};

const updateNoteById = (req, res, next) => {
    const updateNoteByIdQuery = `UPDATE notes SET title = '${req.body.title}', note = '${req.body.note}' WHERE id = '${req.body.id}'`;
    sql.query(updateNoteByIdQuery, (err) => {
        if (err) {
            res.send({
                status: 'ERROR',
                error: 'Failed to UPDATE notes'
            });
            next(err);
        } else {
            res.send({
                id: req.body.id,
                title: req.body.title,
                note: req.body.note,
                status: 'UPDATED'
            });
        }
    });
};

const deleteNoteById = (req, res, next) => {
    const deleteNoteByIdQuery = `DELETE FROM notes WHERE id = '${req.body.id}'`;
    sql.query(deleteNoteByIdQuery, (err) => {
        if (err) {
            res.send({
                status: 'ERROR',
                error: 'Failed to DELETE notes'
            });
            next(err);
        } else {            
            res.send({
                id: req.body.id,
                status: 'DELETED'
            });
        }
    });
};

const notFoundError = (req, res) => {
    res.status(404).send({
        response: 'Not Found'
    });
};

module.exports = {
    getAllNotes,
    getNoteByTitle,
    postNewNote,
    updateNoteById,
    deleteNoteById,
    notFoundError
};

please give me some review for my first build rest api with express js. any input and feedback would be appreciated.

Destroy ChartJS rendered with Symfony

i have a little problem with my Symfony/ChartJS Application.

So if i create a Chart with JS like var myChart = new Chart.. and so on, i can easily destroy the Chart with myChart.destory(); because i can address the ChartObject.

My Problem:
The first Chart i Render with my SymfonyController. So i render the chart in my Controller with

return $this->render('category.html.twig', [
         'chart' => $chart]);

In Twig i assign an ID to the Chart {{ render_chart(chart, {'id': 'my-chart'}) }}.
But i dont really know how i can adress the whole Chartobject in Js. So how i can destroy the Chart i created with my Symfonycontroller? Anyone have a suggestion?

Thank you in advance!

access to dynamic query params in nextjs

i have a project with nextjs and i have a route like this => /categories/224?brand[0]=6.
i want when ever this query changed forExample /categories/224?brand[0]=8 my useEffect run again
this is my useEffect

    const router = useRouter();

useEffect(()=>{
  console.log('hey there');
},[])

i don’t want my useEffect run when ever whole router.query change i just it runs when ever router.query.brand[0] changed.