How to give role without admin on Discord using bot with Admin?

I know this question sounds weird but I have a very strange situation. My Discord account has been disabled so I can’t access it. I created new account and joined my server but now I would like to have my Admin permissions but… how? I do not know if it is possible, but if it is possible, I would like to ask for help. There is my own bot on the server and it still works! Can anyone help me with this?

TypeError: Cannot read properties of undefined (reading ‘map’) react chart js

Hola soy nuevo en react y tengo este problema estoy llamando a una api para consumirla y al momento de querer pasar los datos al cuerpo del grafico en chart js me sucede ese error, este es mi codigo.

import React, { Component } from 'react';
import axios from 'axios';
import {Pie} from 'react-chartjs-2';
import {JPA_API_URL} from '../../../../../Constantes';
//import EscenariosServicio from '../../../../api/EscenariosServicio';

class EscenarioReporte  extends Component {
  constructor(){
    super();
    this.state = {
      chartData:{},
     // labels:[],
    }
  }

  componentDidMount() {
    this.getChartData();
  }

  getChartData() {
    axios.get(`${JPA_API_URL}/costos/escenario/lista`).then(res => {
        const coin = res.data;
        let nombre = [];
        let codigo = [];
        coin.forEach(element => {
          nombre.push(element.nombre);
          codigo.push(element.codigo);

          });

          this.setState({nombre: nombre, codigo: codigo});
          console.log(this.state.nombre);
          console.log(this.state.codigo);

       console.log(coin)
       
        this.setState({
          chartData: {
            labels:nombre,
            datasets: [
              {
               // label: "Population",
                data: codigo,
                backgroundColor: [
                  "rgba(255, 99, 132, 0.6)",
                  "rgba(54, 162, 235, 0.6)",
                  "rgba(255, 99, 132, 0.6)"
                ],
              }
            ]
          }
        });
      });
    }

  render(){

        return (
          <div className="App">
          {Object.keys(this.state.chartData).length &&
            <Pie chartData={this.state.chartData}/>
          }
          </div>
        );

    }     
}

export default EscenarioReporte;

esto tengo hasta ahora necito una ayuda por favor

My discord.js code for delayed autorole does not wrok

const { Client,  Intents } = require("discord.js");
const client = new Client({
intents: ["DIRECT_MESSAGES", "GUILDS", "GUILD_MEMBERS"],
    presence: {
        status: "online",
        activities: [{
            name: "markets",
            type: "WATCHING"
        }]
    },
});

client.on('ready', () => { 
    console.log(`Launched as a bot: ${client.user.tag}!`);
});

**client.on('guildMemberAdd', member => {
    function roleAdd() {
        member.roles.add(member.guild.roles.cache.get(process.env.SERVER_ROLE_ID));
    }
    setTimeout(roleAdd, 300000)
});**

client.login(process.env.DJS_TOKEN);

I starred the issued piece of the code. I don’t know what is wrong with this code. I used timeout in this code.

How to get multiple values using jq

I want to get multiple statuses from a select, there are about 5 options I either want to be able to get option 1 and 2 and 3 or all 5 of them but not empty ones.

What I am already doing will return 1 specific option which is optionA and If i replace this with .val() it will just get the first option in the list

  $('#myButton').on('click',function(){
      $('.filter__status').val("optionA");
      loadList();
  });

select option below

<div class="inputRow">
   <label>Status:</label>
    <select class="filter__status" id="status" name="index[filters][status]">
       <?php foreach (Options::statuses() as $status): ?>
          <option value="<?= $status ?>" <?= ($_GET['status'] === $status ? "selected" : "") ?>><?= $status ?></option>
       <?php endforeach; ?>
    </select>
</div>

How to hide a URL and token in email?

How can I hide the URL in my password reset email?

In my backend, this is how I have the URL setup:

accountService.js


async function sendPasswordResetEmail(account) {
  let message;
  const resetUrl = `https://www.example.com/accounts/reset-password?token=${account.resetToken.token}`;
  message = `<p>Please click the below link to reset your password, the link will be valid for 1 day:</p>
                   <p><a href="${resetUrl}">${resetUrl}</a></p>`;

  await sendEmail({
    to: account.email,
    subject: "Reset Password",
    html: `<h4>Reset Password Email</h4>
               ${message}`,
  });
}

When the email arrives to my inbox, the URL looks like this in the email:

https://www.example.com/accounts/reset-password?token=7a77f2273c599d2d49d1293bfb3b8a2a370528c6561189d6e229612eb51f1e0c219a3d92a20c8eda

I’d like to just show the user a link that says click here

How do I do this?

How do i copy a component which has image and text with all its format and styling in React

I have a preview component which renders dynamically:

  <div className={styles.mainPrev}>
        <nav className={styles.dp} style={{margin: `${position.top} ${position.right} ${position.bottom} ${position.left}`, width: `${avatar}px`}} >
            <img src={contact.imageAdd} alt="" style={{borderRadius: `${style}%`}} />
        </nav>
        <section>
            <h2 style={{color: `${color}`,}}>{contact.firstName}  {contact.lastName}</h2>
            <h4><span> {contact.jobTitle} </span> - <span>{contact.companyName}</span></h4>
            <p>Email: <b style={{color: `${color}`, fontFamily: `${font}`, fontSize: `${size}px`}}>{contact.email}</b></p>
            <p>Phone: <b style={{color: `${color}`, fontFamily: `${font}`, fontSize: `${size}px`}}>{contact.phone}</b></p>
            <p>Website: <b style={{color: `${color}`, fontFamily: `${font}`, fontSize: `${size}px`}}>{contact.website}</b></p>
            <p>Address: <b style={{color: `${color}`, fontFamily: `${font}`, fontSize: `${size}px`}}>{contact.address}</b></p>
                {
                    display && ( 
                        <nav className={styles.prevIcons}>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.github}`} id={social.github ? '' : styles.none}><img src={icon1} alt="" /> </a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.behance}`} id={social.behance ? '' : styles.none}><img src={icon2} alt="" /></a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.snapchat}`} id={social.snapchat ? '' : styles.none}><img src={icon3} alt="" /></a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.pinterest}`} id={social.pinterest ? '' : styles.none}><img src={icon4} alt="" /></a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.skype}`} id={social.skype ? '' : styles.none}><img src={icon5} alt="" /></a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.linkedIn}`} id={social.linkedIn ? '' : styles.none}><img src={icon6} alt="" /></a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.youtube}`} id={social.youtube ? '' : styles.none}><img src={icon7} alt="" /></a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.vimeo}`} id={social.vimeo ? '' : styles.none}>
                            <img src={icon8} alt="" />
                            </a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.twitter}`} id={social.twitter ? '' : styles.none}><img src={icon9} alt="" /></a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.facebook}`} id={social.facebook ? '' : styles.none}>
                            <Facebook  sx={{ fontSize: 25, color: '#03132C', borderRadius: '50%'}} />
                            </a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.instagram}`} id={social.instagram ? '' : styles.none}>
                            <Instagram  sx={{ fontSize: 25, color: '#03132C', }} />
                            </a>
                            <a style={{borderRadius: `${shapes}%`, background: `${color}`}} href={`https://${link.slack}`} id={social.slack ? '' : styles.none}>
                            <span className={styles.hash}>#</span>
                            </a>
                        </nav>
                    )
                }
        </section>
    </div>

I want to be able to copy to clipboard all this text and image while maintaining exactly how it appears in the browser i.e with the display flex, color, border, etc

I have tried so far with the following code:

function handleCopy(e) {
let doc = document
let text = doc.getElementById('preview')
let range, selection;

if (doc.body.createTextRange)
{
    range = doc.body.createRange();
    range.moveToElementText(text);
    range.select();
} 

else if (window.getSelection)
{
    selection = window.getSelection();        
    range = doc.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
}
document.execCommand('copy');
window.getSelection().removeAllRanges();
e.target.textContent = "Copied";
}

But this only copies the text without maintaining the styling and doesn’t also copy image (which is updated also dynamically..)

Bad Request error when trying to refresh Django login access token

Trying to refresh the access token I receive from Django every few seconds, however I am getting the error message

Request Method: POST Status Code: 400 Bad Request

I am sending my refresh token to this endpoint: “http://127.0.0.1:8000/api/token/refresh/”

This is my urls.py:

from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView)

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    # path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    path('api/register', RegisterApi.as_view()),
]

This is how I am sending my refresh token:

let updateToken = async ()=> {
        try {
            let response = await axios.post('http://127.0.0.1:8000/api/token/refresh/',JSON.stringify(authTokens.refresh))
            //update state with token
            setAuthTokens(authTokens => ({
                ...response.data
            }))
            //update user state
            const decoded = jwt_decode(response.data.access)
            setUser(user => ({
                ...decoded
            }))
            //store tokens in localStorage
            //we stringify because we can only store strings in localStorage
            localStorage.setItem('authTokens',JSON.stringify(response.data))
            }
        catch(err) {
        //if fail, something is wrong with refresh token
            console.log(err.response)
        }
    }

This is the error I am getting:

config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data:
refresh: ['This field is required.']
[[Prototype]]: Object
headers:
content-length: "39"
content-type: "application/json"
[[Prototype]]: Object
request: XMLHttpRequest
onabort: ƒ handleAbort()
onerror: ƒ handleError()
onload: null
onloadend: ƒ onloadend()
onloadstart: null
onprogress: null
onreadystatechange: null
ontimeout: ƒ handleTimeout()
readyState: 4
response: "{"refresh":["This field is required."]}"
responseText: "{"refresh":["This field is required."]}"
responseType: ""
responseURL: "http://127.0.0.1:8000/api/token/refresh/"
responseXML: null
status: 400
statusText: "Bad Request"
timeout: 0
upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
withCredentials: false
[[Prototype]]: XMLHttpRequest
status: 400
statusText: "Bad Request"
[[Prototype]]: Object

This is what i have in authTokens:

{refresh: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90e…9tIn0._aS9oDcj3Rfomodbs9qMEFmgEm4oEdOfSwGSJJKLWmg', access: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90e…20ifQ.K1YCXWoMWF7o61fGAuVm-QoehB3-jA2A_dLZ4o4uYa8'}

Uncaught TypeError: dates.map is not a function

I am a learner of React and I have some problems with my .map statement. I fetch the data from API and I keep the data using useState. But when I wanted to map the state it’s not working and it says Uncaught TypeError: dates.map is not a function. Could you please help me to write? I wanted to write in the div element.

import { useState, useEffect } from "react";

function LabelParams() {
    const url = ""

    let [dates, setDates] = useState([]);

    useEffect(() => {
        requestDate();
    }, []);


    async function requestDate() {
        const res = await fetch(url);
        const json = await res.json();
        console.log(json)
        setDates(json.dates);
    }



    return (
        <div>
            {
               dates.map() //something like this
            }
        </div>
    )
}

export default LabelParams;

how to get expected output from mongodb

im new to mongodb aggregation i im not gettign desired output
The output im getting from aggregation :-

[
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
]

but i want following output from pipeline:-

[
{key:value},
{key:value},
{key:value},
]

and lastly pipelie im running:-

const pipeline = [[
            {
              $match: {
                $expr: {
                  $in: [
                    Mongoose.Types.ObjectId(userid), '$likedBy.user'
                  ]
                }
              }
            }, {
              $lookup: {
                from: 'tweets', 
                localField: 'tweet', 
                foreignField: '_id', 
                as: 'tweet'
              }
            }, {
              $unwind: {
                path: '$tweet'
              }
            }, {
              $lookup: {
                from: 'users', 
                localField: 'tweet.user', 
                foreignField: '_id', 
                as: 'user'
              }
            }, {
              $unwind: {
                path: '$user'
              }
            }, {
              $addFields: {
                'tweet.user': '$user'
              }
            },
            {
                $addFields: {
                  'tweet.isLiked': true,
                }
              },{
                  $project:{
                      tweet:1,
                  }
              },
          ]
        ];
        const likedTweets = await TweetLike.aggregate(pipeline)

i know i can do this with javascript but i want to do with pipeline

Launch iOS app from Safari – hide alert “Safari cannot open the page because the address is invalid”

I’m working on a web page which launches an app if present on the device.
It works great for Android but I’m having trouble with the iOS version.

To launch the app I’ve used the code:

window.location = “exampleApp://”

If the app is installed, a prompt asks the user if they would like to launch the app which is great.

If the app isn’t already installed, Safari produces an alert with the message “Safari cannot open the page because the address is invalid”.

Is there a way to hide/suppress this alert?

.focus() event behavior with Javascript

I have these three tabs:

enter image description here

When a user uses the mouse and clicks on one of the tabs, (Compliance Notes in this example), the proper element on the tabbed page gets focus and is highlighted appropriately.

enter image description here

However, if the user uses the keyboard and presses the Tab key to highlight the tab they want, and then presses the Enter key to select that tab, the tabbed page gets focus. Then, via JavaScript, I set focus to the proper element on that tabbed page (by using the .focus() method on that element), and the same asp:DropDownList in the example behaves like the user not only selected the element, but clicked on it:

enter image description here

If you then either hit Enter or Tab, manually, the dropdown list closes and the element looks like it did if the user clicked on the tab versus using the keyboard:

enter image description here

So, is there a “simple” way, after I use the .focus() method, to then simulate either an Enter or Tab keystroke so the element will have focus but not have the dropdown list triggered? Or is there another way, using the .focus() method or some other approach, to prevent the dropdown list from being triggered when using the keyboard to navigate the page?

GSAP ScrollTrigger – Pin animation not working correctly

I have an element called .listing__nav which I want to pin upon scroll.

When the .listing__nav touches the top of the window, I want it to become fixed and to unpin only when the banner element comes into view.

To achieve this, I’ve tried the following:

$(function() {

  var action = gsap.set('.listing__nav', {
    position: 'fixed',
    paused: true
  });

  ScrollTrigger.create({
    trigger: '.listing__nav',
    start: 'top 0px',
    onEnter: () => action.play(),
    onLeaveBack: () => action.reverse(),
  });

  gsap.to('.listing__nav', {
    ease: 'none',
    scrollTrigger: {
      trigger: ".banner",
      scrub: 0.3,
      end: 'bottom 110%',
      markers: false,
    }
  });


});
:root {
  --black: #000000;
  --white: #FFFFFF;
  --grey: #707070;
}

header {
  background-color: var(--grey);
  padding: 30px 0;
}

.spacer {
  background-color: var(--black);
  height: 300px;
}

.listing__nav {
  padding: 80px 0 52px 0;
  border-bottom: 1px solid var(--black);
}
.listing__spacer {
  padding: 100px 0;
  height: 1000px;
  background-color: var(--black);
}

.banner {
  background-color: var(--grey);
  color: var(--white);
  padding: 60px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/ScrollTrigger.min.js"></script>

<main>
  <header>Header</header>
  <div class="spacer"></div>
  <div class="listing">
    <nav class="listing__nav">Nav</nav>
    <div class="listing__spacer">Spacer</div>
  </div>
  <div class="banner">Banner</div>
</main>

As you can see, the .listing__nav doesn’t pin where intended instead pinning at the bottom of the window, giving it glitchy behaviour.

Javascript parse and evaluate sql query in code

In Angular I have custom filter in which I build query. Filter returns array of conditions:

{
  conditionOperator: null
  filter: "sample text1"
  type: "contains"
},
{
  conditionOperator: "OR"
  filter: "sample test2"
  type: "equals"
},
{
  conditionOperator: "AND"
  filter: "sample test3"
  type: "equals"
}

Now, I need to evaluate above result from filter in TypeScript. It has only three condiditions but can be a lot of them. It’s only example.
I can parse above structure to statement:

0 OR 1 AND 2

Which structure of data I should use to write above statement and than execute it.
At the begin I have to get result from 1 AND 2 and in second step from 0 OR result (1 AND 2).
Any tree structure will be good?

How to match regex with conditions?

“Fingerprint (rear-mounted, region dependent), accelerometer, proximity, compass”

Above is the string of sensors in a device. I’m trying to match every sensor. The problem is that when I match above using /.+?,/g, The matches are:

  1. Fingerprint (rear-mounted,
  2. region dependent),
  3. accelerometer,
  4. proximity

I’m getting 4 sensors here instead of three. Because, of course, my pattern matches these. What I want to do is that when a , is preceded by (, then I want to match ), and when not preceded by (, I want to match ,

I think I need to use lookarounds here. But I can’t get them to work for me. I tried multiple regexes. It’s silly to paste them all here 🙂

I’m using JavaScript