Wont delete a document in mongodb (using moongoose) when a user leaves a discord server

Wont delete a document in mongodb (using moongoose) when a user leaves a discord server.

So i made this code where when a user joins i get his info and save it to a new document in mongodb.when he leaves the discord server i want to delete that user who left his info document but i cannot do it for somereason here is my code:
member join:

const test = require('../schmeas/GuildSchema.js');

module.exports = {
  name: Events.GuildMemberAdd,
  once: false,
  async execute(member) {
    const welcomeChannel = member.guild.channels.cache.get('1111700932858761278');
    const welcomeMessage = `Welcome, ${member}! Enjoy your time here.`;

    welcomeChannel.send(welcomeMessage);

    try {
   let forn = new test({   
        User:  member.user.username,
        Guild: member.guild.id,
        id: member.id });
        await forn.save()
        .then(s => console.log(`saved : ${s}`))
          .catch(error => {
    console.log('Error saving document:', error);
  });


     
    } catch (error) {
      console.error('Error saving new member data:', error);
    }
  },
};```


member leave.js:
```const { Events } = require('discord.js');
const test = require('../schmeas/GuildSchema.js');

module.exports = {
  name: Events.GuildMemberRemove,
  once: false,
  async execute(member) {
    let channelwel = await member.guild.channels.cache.get('1111700932858761278');
    let thing = `User ${member.user.tag} left. Bye!`;

    try {
      const data = await test.findOne({
        User: member.user.id,
        Guild: member.guild.id,
        id: member.user.id
      }) 
      console.log(data)

     
        const deleted = await test.deleteOne({
            User: member.user.id,
            Guild: member.guild.id,
            id: member.user.id
          })
          .then(s => console.log(`delete ${s}`))
          .catch(e => console.log(e));
           console.log(deleted.deletedCount)    
      
    
    } catch (error) {
      console.error('Error occurred during deletion:', error);
    }

    channelwel.send(thing);
  },
};``` 

any help will be appreciated

Recreating JavaScript Google Calendar API authentication in Vue

Google has provided this document to explain how to migrate from GAPI to GIS, but being new to Vue, I’m struggling with figuring out how to divide JavaScript into the appropriate blocks. https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#server-side-web-apps

Below is my attempt, that I took from the GIS only section of the migration doc, but I receive an error of Uncaught TypeError: Cannot read properties of undefined (reading 'requestAccessToken')

<template>
    <h1>Google Identity Services Authorization Token model</h1>
    <button @click="getToken()">Get access token</button><br><br>
    <button @click="loadCalendar()">Load Calendar</button><br><br>
    <button @click="revokeToken()">Revoke token</button>

</template>

<script>
    var client
    var access_token

    
    export default {
        
        methods:{
            initClient() {
                client = google.accounts.oauth2.initTokenClient({
                client_id: '...',
                scope: 'https://www.googleapis.com/auth/calendar.readonly 
                        https://www.googleapis.com/auth/contacts.readonly',
                callback: (tokenResponse) => {
                    access_token = tokenResponse.access_token;
                },
                });
            },
            getToken() {
                client.requestAccessToken();
            },
            revokeToken() {
                google.accounts.oauth2.revoke(access_token, () => {console.log('access token revoked')});
            },
            loadCalendar() {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', 'https://www.googleapis.com/calendar/v3/calendars/primary/events');
                xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
                xhr.send();
            }
    }
    }
</script>

In the index.html file I have placed:

<script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>

Can anyone help me fix this please?

How can I make the background image on my div fit to the screen?

I have tried many things, One of the things I tried is putting background-size: cover on the CSS of my div that have the background-img.

Here is my HTML code

.container-fluid-layanan {
  background-size: cover;
  height: 100%;
  width: 100%;
  border: none;
  outline: none;
  background-image: url('../img/dropdown-bg.svg');
}

.container-fluid-layanan {
  box-sizing: border-box;
  z-index: 5;
  display: none;
  left: 0;
  padding: 0px 0px;
  position: absolute;
  width: 100%;
  background-color: white;
  height: 252px;
  box-shadow: 0px 20px 25px rgba(0, 0, 0, 0.1), 0px 10px 10px rgba(0, 0, 0, 0.04);
}
<div class="dropdown-header" id="drophead">
  <div class="container-fluid-layanan" id="drop-layanan">
    <hr/>
  </div>
</div>

and this is what it looks like with the code that I used.

What causes a promise using the first call variable value

I’m developing a AMQPClient class to abstract RPC calls, works perfectly on the first call, but when calling again the correlationId has the value of the first call.

async RPC<T>(queue: string, message: string): Promise<T> {
    if (!this.channel) {
      throw new Error('Channel not initialized')
    }

    const replyTo = `${queue}.reply`
    await this.channel.assertQueue(replyTo)
    await this.channel.assertQueue(queue)

    return new Promise<T>((resolve) => {
      const correlationId = Math.random().toString(36).slice(2)
      console.log('generated correlationId: ', correlationId)
      const onMessage = (message: ConsumeMessage | null) => {
        console.log(
          correlationId,
          message?.properties.correlationId,
          correlationId === message?.properties.correlationId
        )
        if (message && message.properties.correlationId === correlationId) {
          resolve(JSON.parse(message.content.toString()))
          this.channel?.removeListener('message', onMessage)
        }
      }

      this.channel?.consume(replyTo, onMessage, { noAck: true })
      this.channel?.sendToQueue(queue, Buffer.from(message), {
        correlationId,
        replyTo
      })
    })
  }

Output:

generated correlationId:  lwfvgqym5ya
lwfvgqym5ya lwfvgqym5ya true

generated correlationId:  1m09k9jk2xm
lwfvgqym5ya 1m09k9jk2xm false

The correlationId printed on the second time matches the correlationId from the first call that was already resolved. The second call was made after the first one resolved.

I already tried moving the const correlationId = Math.random().toString(36).slice(2) outside the new Promise(...).
I also tried to pass a anon function to the consume callback calling the onMessage funcion, no success.

this.channel?.consume(replyTo, (msg) => onMessage(msg), { noAck: true })

I also tried to pass the correlationId as parameter, none above works. Always the second call uses the last value of correlationId inside de onMessage function.

Full code:

import client, { Channel, Connection, ConsumeMessage } from 'amqplib'

class AMQPClient {
  private channel?: Channel

  constructor(private readonly amqpUrl: string) {
    client.connect(this.amqpUrl).then((connection) => {
      connection.createChannel().then((channel) => {
        this.channel = channel
      })

      process.on('SIGINT', () => this.close(connection))
      process.on('SIGTERM', () => this.close(connection))
    })
  }

  async RPC<T>(queue: string, message: string): Promise<T> {
    if (!this.channel) {
      throw new Error('Channel not initialized')
    }

    const replyTo = `${queue}.reply`
    await this.channel.assertQueue(replyTo)
    await this.channel.assertQueue(queue)

    return new Promise<T>((resolve) => {
      const correlationId = Math.random().toString(36).slice(2)
      console.log('generated correlationId: ', correlationId)
      const onMessage = (message: ConsumeMessage | null) => {
        console.log(
          correlationId,
          message?.properties.correlationId,
          correlationId === message?.properties.correlationId
        )
        if (message && message.properties.correlationId === correlationId) {
          resolve(JSON.parse(message.content.toString()))
          this.channel?.removeListener('message', onMessage)
        }
      }

      this.channel?.consume(replyTo, (msg) => onMessage(msg), { noAck: true })
      this.channel?.sendToQueue(queue, Buffer.from(message), {
        correlationId,
        replyTo
      })
    })
  }

  close(connection: Connection) {
    connection.close()
    process.exit(0)
  }
}

const amqpClient = new AMQPClient(process.env.AMQP_URL || 'amqp://localhost')
export { amqpClient, AMQPClient }

Call:

this.amqpClient.RPC<MerchantStatus>(
  'getMerchantStatus',
  JSON.stringify({ merchantId: 'test' })
)

number of threads/worker spawned

I am trying to work with a worker but I am getting the system crashed so I believe the issue is because multiple event handlers are spawning threads without waiting for others to get killed.

Is there any way I can check how many threads are spawned at the moment so that i can check and debug the system?

I really appreciate any help you can provide.

How can I get the API key for Upwork?

Can someone please tell me how to get the access of API KEY for Upwork?

I tried but requesting an access to API but somehow I lost don’t know where to go now?
Help for anyone will be highly appreciated as I want this things done very quickly .

Adding text to dynamically created div not working

I am trying to show the value of a variable(fundProvider[j]) present in my Javascript, when I hover over an element which is created dynamically using JS.

I am trying document.getElement(s)ById/ClassName but it is not working.

Here is the relevant part of my JS code:

for (var j=0; j<listLength; j++) 
{
 componentList = rebalanceDates[j].split("-");
 getYear - Number(componentList[0]);
 getMonth - Number(componentList[1])-1;
 getDate - Number(componentList[2]);
 if (i - first_day.getDay() +1 === getDate && year === getYear && month === getMonth ) 
{
 day.classList.add('rebal-date')
 day.innerHTML = i - first_day.getDay() + 1
 day.innerHTML +- '<div class="tooltiptext" id="myText"></div>
                   <span></span>
                   <span></span>
                   <span></span>
                   <span></span>'
 document.getElementById("myText").innerHTML = fundProvider[j]; //tried innerTEXT and appending child node but none worked.
 }
}

I am getting the below error:
Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’) at…

How to access the files uploaded in react

I’m trying to create an upload button using material UI that would allow users to upload many files and then save their path into an array to use later. I’m having trouble understanding where the files get stored once they are uploaded.

I have the following component for an upload button:
Upload.js

export default function Upload ({onUpload}) {
return (
    <div >
        <input
            style={{ display: 'none' }}
            id="upload-raw-files"
            multiple
            type="file"
            onChange={onUpload}
        />
        <label htmlFor="upload-raw-files">
            <Button 
            variant="contained"
            component="span"
            size="large"
            className="Upload"
            startIcon={<UploadIcon />}
            sx={{
                
                width: '130px',
                height: '40px',
                background: '#5985F7',
                border: '3px solid #5985F7',
            }}
            >
            Upload
            </Button>
        </label>
        
    </div>
) }

This makes the filesystem pop up and we can pick multiple files, but I’m struggling to find a way to retrieve the files selected.
In the parent I call this component like this:

import Upload from './Upload.js'
const Form = () => {
    const [filepath, setFilepath] = useState([])

    const handleUpload = (event) => {
        setFilepath(event.target.files)
        console.log(filepath)
    }
    <Upload onUpload={handleUpload}/>
}

However this is not printing anything to the console, so I’m confused how I am supposed to have access to the files selected. Any help would be appreciated!

How to fix Next.JS’ ununderstandable setting of classes

So here I have a little scroller component:

export default function Scroller({children, scrollSpeed="10", className, ...props}){


    const period = 1000 / scrollSpeed
    const generated = 'scroller-' + pureGen(10)

    console.log(generated)

    return (
        <>
            <style jsx>
                {`
                .scroller {
                    width: calc(100vw - .5rem) !important;
                    margin-left: calc(-1 * var(--page-padding));
                    overflow-x: scroll;
                    overflow-y: hidden;
                    display: flex;
                    padding: 1rem 0;
                    gap: 2rem;
                    scroll-behavior: auto;
                }

                .scroller::-webkit-scrollbar {
                    display: none;
                } 
                `}
            </style>
            <div className={`scroller ${className} ${generated}`} {...props}>
                {children}
            </div>
        </>
    )
}

The pureGen() function generated a random ID, which is then console logged.
The value console logged into the browser is: scroller-i934CUja5Y (In a test)
However the real value is: enter image description here
which is completely different.

What in the world is going on?
I’ve never seen anything like this before.
I’ve tried searching for the same problem everywhere but only useless replies appeared.

html2canvas file makes images distorted when they are cropped

I want to upload an image, then crop it, and then preview it on my website, it works, but when I use html2canvas to download the canvas, the cropped image gets distorted.

CSS:

#uploadedImage{
    position: absolute;
    height: 344px;
    width: 191px;
    object-fit: cover;
    object-position: center;
    margin-bottom: -50px;
}

JavaScript:

const myElement = document.getElementById('frameContainer');
function imageDownload() {
  myElement.style.borderRadius = 0;
  html2canvas(myElement).then(canvas => {
  const link = document.createElement('a');
  link.download = 'image.jpg';
  link.href = canvas.toDataURL('image/jpg');
  document.body.appendChild(link);
  link.click();
  }).catch(error => {
  console.error('Error:', error);
  });
}

Input file – Show file name

I have this input file, where I attach files, whose objective is that when editing the information below the input file, it shows the name of the file that was previously registered. In the console it shows me the name but I can’t get it to be displayed where I want it to be.

Attached what I have of code:

var p = '@Model.ArchivoCSF.NombreArchivo';
var c = '@Model.ArchivoCSF.Contenido';

if (p != null) {
  $(this).next('a').text(p);
  t = "application/pdf";
  $(this).next('a').prop("href", URL.createObjectURL(new Blob([c], {
    type: t
  })));
  $(this).next('a').css('display', 'block');
  $("#deleteFile").css('display', 'block');
  console.log(p);
}

$('#file1').change(function() {
  var file = $('#file1')[0].files[0];
  $(this).next('a').text(file.name);
  $(this).next('a').prop("href", URL.createObjectURL(file));
  $(this).next('a').css('display', 'block');
  $("#deleteFile").css('display', 'block');
});

$("#deleteFile").click(function(e) {
  $('#file').val(null);
  $(this).prev('a').text(null);
  $(this).css("display", "none");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="mb-2">
  <label class="form-label">Adjuntar CSF</label>
  <label for="file1" class="form-control custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Seleccione un archivo</label>
  <input type="file" id="file1" asp-for="CSF" class="form-control" style="display:none" />
  <a href="" target="_blank" style="display:none; overflow:auto;">file</a>
  <span class="fa fa-times" id="deleteFile" style="display:none; padding: 1px 3px; float:right" href="#"></span>
  <br />
</div>

Image:

enter image description here

Which would appreciate any comments and/or reference.
Thank you.

Other Solutions for Applying Dynamic Slides in Keen Slider Only When Resizing the Window

I’m using Vue 3 and the Quasar framework to create a dynamic carousel. Every time I switch to the next slide, I send an API request to retrieve data for three books, which I then add to the books[] array. I’m using v-for to render the carousel slides using Keen Slider.

I came across a post on Stack Overflow (link: Angular / Keen-Slider: Slider just work in modal when resize window) where they suggested triggering the resize event (window.dispatchEvent(new Event(‘resize’));) to make it work. I implemented this approach, and it worked for me. I have set it to resize every second.

However, I encountered another issue. When I add a large number of slides to the books[] array at once, the carousel stops resizing. Strangely, if I manually navigate to the next slide one by one, it works fine.

I’m wondering if there are alternative ways to make the carousel dynamic and handle a large number of slides.

Additionally, I tried using other libraries such as Swiper. Unfortunately, I found that its slideNext function is broken and cannot be used. Do you have any other recommendations?

Yup validation schema for fields in multiple grid rows

In my React app, I have a JSON definition for grid rows as below

"gridItemsModel": [
    {
    "fields": [{
        "id": "nestedFld1",
        "mandatory": true,
        "value": "Nested Row 1 Column 1"
    }, {
        "id": "nestedFld2",
        "mandatory": true,
        "value": "Nested Row 1 Column 2"
    }]
    }, {
    "fields": [{
        "id": "nestedFld1",
        "mandatory": true,
        "value": "Nested Row 2 Column 1"
    }, {
        "id": "nestedFld2",
        "mandatory": true,
        "value": "Nested Row 2 Column 2"
    }]
}]

Now, I want to define Yup validation schema for this model. i.e. nestedFld1 would have same rules for both Row1 and Row2 and similarly nestedFld2 would have same rules for both Row1 and Row2.

Is it possible to define a Yup validation schema given that my id “nestedFld1” would be common for both row1 and row2 ?