How do i give a user a role with ‘/’ command with discord.js v14

I was trying to give myself a role when executing a “/” command, and ive tryed many solutions from stackoverflow but none of them work for discord.js v14. Im pretty new to js.

tryed:

const guild = interaction.guild
const role = guild.roles.cache.find(role => role.name === 'Admin');
var dcuser = interaction.user.id
dcuser.roles.add(role)

Got:

TypeError: Cannot read properties of undefined (reading ‘add’)

How can I use react-quill to provide a user to create a template that can also be previewed

I’m looking at an npm library called react-quill but unsure how to achieve the same functionality over at HTML Code editor with preview

I need to be able to allow the user enter HTML code that then renders this code within a preview window.

I am new to react-quill and not sure how to achieve this as I would like to provide the user with a toolbar of HTML code options like h1, h2, span etc.

I have tried this code over in codesandbox but it is appearing as a rich text editor with no preview window. I actually want it to appear as a HTML Editor with rendered preview.

I’m also not sure if react-quill can achieve this or if I should be looking at another library?

How to format pipe delimited data returning from API into a table format in Javascript

Integrate Chatgpt API in project. Now it is returning data in piped format.

Suppose question: ‘top 10 ODI cricket players in table’

Returning :

Sure, here are the top 10 ODI cricket players based on ICC rankings as of August 2021:

| Rank | Player Name         | Team            | Rating |
|------|-------------------|----------------|--------|
| 1    | Babar Azam         | Pakistan        | 873    |
| 2    | Virat Kohli        | India           | 844    |
| 3    | Rohit Sharma       | India           | 813    |
| 4    | Ross Taylor        | New Zealand     | 801    |
| 5    | Aaron Finch        | Australia       | 779    |
| 6    | Jonny Bairstow     | England         | 775    |
| 7    | Fakhar Zaman       | Pakistan        | 768    |
| 8    | Francois du Plessis| South Africa   | 754    |
| 9    | David Warner       | Australia       | 753    |
| 10   | Quinton de Kock    | South Africa   | 747    | 

any idea how I can convert this to

Sure, here are the top 10 ODI cricket players based on ICC rankings as of August 2021:

Rank Player Name Team Rating
1 Babar Azam Pakistan 873
2 Virat Kohli India 844
3 Rohit Sharma India 813
4 Ross Taylor New Zealand 801
5 Aaron Finch Australia 779
6 Jonny Bairstow England 775
7 Fakhar Zaman Pakistan 768
8 Francois du Plessis South Africa 754
9 David Warner Australia 753
10 Quinton de Kock South Africa 747

Please Help. Thanks In advance.

How to use Fetch api to post text/plain

I try to use Fetch() API to post text/plain

fetch('/test', {
    method: 'post',
    headers: {
      'Content-Type': 'text/plain'
    },
    body: "this is a test"
  })
 .then(response => response.text())
 .then(body => {
    console.log(body)
 })

This is the router that deal with the request

router.post('/test',(req,res)=>{
    console.log(req.body)
    res.send('OK')
})

However, the output of console.log(req.body) is {}.

I think the problem is the code after body:. I don’t know what is the right way to post text/plain data.

How to setup unit tests for Nuxt3?

I created a new Nuxt3 app via npx nuxi init <project-name> and want to add unit tests. Based on the docs for testing I called npm install -D @nuxt/test-utils vitest and started with ./pages/foo.spec.ts

import { describe, it, expect } from "vitest";
import { setup } from "@nuxt/test-utils";

describe("Suite", async () => {
  await setup();

  it("passes", () => {
    expect(true).toBeTruthy();
  });
});

When calling vitest --run I get the following error

TypeError: Cannot read properties of undefined (reading 'on')
 ❯ setupVitest ../../node_modules/@nuxt/test-utils/dist/index.mjs:138:10
    137|     setTestContext(void 0);
    138|   };
    139|   const afterAll = async () => {
       |     ^
    140|     if (ctx.serverProcess) {
    141|       setTestContext(ctx);
 ❯ Module.setup ../../node_modules/@nuxt/test-utils/dist/index.mjs:197:3
 ❯ pages/foo.spec.ts:5:3

I also thought about calling nuxt test instead but get this error

Listening http://[::]:38515
[error] ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
[error]
[error]  FAIL  pages/foo.spec.ts [ pages/foo.spec.ts ]
[error] Error: No test suite found in file /home/.../pages/foo.spec.ts

Maybe my setup is wrong. I wasn’t able to find information about

  • Where to put the tests?
  • How to call the tests via npm scripts?

Regex matching for multiple html tags

I am trying to find a regex that matches if all tags in a piece of HTML are empty, regardless of attributes and if there are nested tags.

My code essentially looks like this:

const emptyHtmlTagRegex = new RegExp(/<[^/>][^>]*></[^>]+>/);

if (emptyHtmlTagRegex.test(this.htmlContent)) {
  // Output placeholder
};

And I’d like to get a match when this.htmlContent is for example:

<ul><li class="class-name"></li></ul>
<p></p>

But not match if this.htmlContent is:

<p>nomatch</p><ul><li></li><ul><p></p>

The regex does not match the entire string so the test method reports false positives if there are trailing empty tags: Regex 101 sample

I’ve also tried to use this.htmlContent.replace(regex,'') and look for empty strings but that failed because of compatibility issues with the testing framework I use.

Server responded with a status of 500 (Internal Server Error) – MVC C#

I’m getting the Internal Server Error when I tried to get the details by sending ajax request from the Jquery Datatable to the Controller. Even in the controller the code works fine and the result too. But I’m getting this error in both “HTTPGET” and “HTTPPOST” request.

This is my code.

`
Employee.cshtml

Dependencies

    <script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/DataTables/DataTables-1.13.4/js/jquery.dataTables.js" defer="defer"></script>
<script src="~/Scripts/DataTables/DataTables-1.13.4/js/dataTables.bootstrap.js" defer="defer"></script>

    <script type="text/javascript">
    $(document).ready(function () {
        debugger;
        $('#empTable').DataTable({
            "columnDefs": [
                { "searchable": true,  targets: "_all" },
                { "className": "text-center custom-middle-align", targets: "_all" }
            ],
            "processing": true,
            "serverSide": true,
            "ajax":
            {
                "url": "/Employee/GetEmployeeDetails",
                "type": "POST",
                "dataType": "json",
                "dataSrc": function (response) {
                    debugger;
                    resultObj = $.parseJSON(response.data)
                    return resultObj.data;
                },
                "error": function (jqXhr, textStatus, errorMessage) { // error callback 
                    console.log('Error: ' + errorMessage + '    request.statusText:' + jqXhr.statusText);
                }
            }
        });

    });
</script>

Employee.cs

[HttpPost]
    public JsonResult GetEmployeeDetails()
    {
        connection();
        SqlCommand cmd = new SqlCommand("GetEmployeeDetails", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);

        //Note I have tried both SqlDataAdapter and SqlDataReader
        //SqlDataAdapter da = new SqlDataAdapter();
        //da.Fill(dt);

        con.Close();
        return Json(dt);
    }

URL is updating but page is not redirecting in react

Here in my project I am trying to redirect to checkout page by clicking on cart icon. The url is getting updated but it’s not redirecting to the new page

version of react-router-dom: “5.2.0”,
version of react 18.2.0
App.js

import React from 'react';
import './App.css';
import Header from './Header';
import Home from './Home';

import { BrowserRouter as Router, Switch, Route }
from 'react-router-dom';
import Checkout from './Checkout';
// import {Link}  from "react-router-dom";


function App() {
  return (
    <Router>
    <div className="app">
    <Header />
      <Switch>
      <Route exact path="/checkout">
      <Checkout />
      </Route>
        <Route exact path="/">
        <Home />
      
      </Route>
      
      </Switch>
    </div>
    </Router>
  );
}

export default App;


Here is my Header.js file

import React from 'react'
import './Header.css'
import SearchIcon from '@mui/icons-material/Search';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import { BrowserRouter, Link } from 'react-router-dom';
import { useStateValue } from './StateProvider';



function Header() {
  const [{basket},dispatch]=useStateValue();
  return (
    <div className='header'>
      <Link exact to='/'>
      <img className='header__logo' src="assets/logo.png"></img>
      </Link>
      
        <div className='header__search'>
            <input className='header__searchInput' type='text'/>
            <SearchIcon className='header__searchIcon'/>
            </div>
        <div className='header__nav'>
            <div className='header__option'>
              <span className='header__optionLineOne'>Hello Guest</span>
              <span className='header__optionLineTwo'>Sign In</span>
            </div>
            <div className='header__option'>
            <span className='header__optionLineOne'>Returns</span>
              <span className='header__optionLineTwo'>& Orders</span>
            </div>
            <div className='header__option'>
            <span className='header__optionLineOne'>Your</span>
              <span className='header__optionLineTwo'>Prime</span>
              </div>
             
              <Link to="/checkout">
              <div className='header__optionBasket'>
            <ShoppingCartIcon />
            <span className='header__optionLineOne header__basketCount'>
              {basket?.length}
            </span>
          </div>
          </Link>
          
         
        </div>
    </div>
  );
}

export default Header

Previously there is no exact but after some browsing in stack overflow I added exact but still no use

Route exact path="/checkout">
      <Checkout />
      </Route>
        <Route exact path="/">
        <Home />
      
      </Route>

In class some function is undefined

I created the class with some functions, but its not working well. In the running time it is showing the this.pickRandomName is undefined. When I call it this.createBot.

class HostBotManager {
 this.xmpp.on('online', async (address) => {
        // Makes itself available
        console.log('online as ', address.toString())

        // Let the action begin!
        // for (var i=0; i<this.instanceCount; i++) {
          // this.createBot()
          this.runBetween(0, 1000, this.instanceCount);
        // }

      })

    // no need to listen for stanzas
  }
  
  // Load list of possible bot names from file
  loadNames(filename) {
    let data = fs.readFileSync(filename, 'utf-8')
    return data.split(/r?n/)
  }
  
  pickRandomName() {
    console.log("what is this ", this)
    if (!this.names) return unnamed
    
    let nameIndex = Math.floor(Math.random() * this.names.length)
    let prefix = this.names[nameIndex]
    
    let suffix = Math.random().toString(36).substr(2)
    
    return `${this.botPrefix}${prefix}-${suffix}`
  }
  
  runBetween(start, end, instanceCount) {
    const delay = (end - start) / instanceCount;
    console.log("delay time ", delay)
    for (let i = 0; i < instanceCount; i++) {
      setTimeout(this.createBot, start + i * delay);
    }
  } 

  async createBot() {
    console.info("create bot has called!", this)
    // don't do this if we're winding down
    if (this.windingDown) return

    // Randomly create the bot
    let bot = {}
    
    // Choose a name
    let name = this.pickRandomName()
    bot.jid = jid(`${name}@${this.domain}`)

    // Choose a table
    let suffix = Date.now().toString(36)
    bot.table = jid(`${name}-${suffix}@${this.tableService}`)
    
    console.log(`Sending ${bot.jid} to ${bot.table}`)

    // Create the room
    this.xmpp.send(stanza(`
      <presence from="${bot.jid}" to="${bot.table}">
        <game var="http://hool.org/protocol/mug/hool">
          <item role="kibitzer"/>
        </game>
      </presence>
    `))

    this.activeBots.push(bot)

    // invite player bots
    for (let seat of ['N', 'E', 'S', 'W']) {
      this.xmpp.send(stanza(`
        <message from="${bot.jid}" to="${bot.table}">
          <game xmlns="http://jabber.org/protocol/mug#user">
            <invite to="${this.botService}"/>
            <item role="${seat}"/>
          </game>
        </message>
      `))

      await wait()
    }
  }

If I call a this.createBot() straightly from the for loop its working fine. But if I call it via this.runBetween its showing some error with this.pickRandomname is not a function.

This is the error

 let name = this.pickRandomName()
                    ^

TypeError: this.pickRandomName is not a function
    at Timeout.createBot [as _onTimeout] (C:bk-hoolbot-testhobotindex.js:140:21)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)

Google Ads Script – getConversionRate() method always return 0 value

I’m using google ads script to pull some data to sheet. my goal is to get conversion Rate for each campaign.

this is my code

   var campaignIterator = AdsApp.campaigns().get();
   while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();
     const stats = campaign.getStatsFor('LAST_MONTH');
     
     console.log(campaign.getName()+ ', '+stats.getImpressions()+', '+stats.getConversionRate())
     
  }

it always return 0 as Conversion Rate. but it should be 9.09 according to my data set.

I tried logging stats object too, seems the field related to ConversionRate is not even there.

output of console.log(stats)

{ metrics: 
   { clicks: '11',
     videoViews: '0',
     conversions: 1,
     costMicros: '10520000',
     ctr: 0.125,
     averageCpc: 956363.6363636364,
     averageCpm: 119545454.54545455,
     impressions: '88' } }

this what I see from the ad report front end
enter image description here

this is the API guide I’m using
https://developers.google.com/google-ads/scripts/docs/reference/adsapp/adsapp_stats#getConversionRate_0

what am I doing wrong here ?

Aligning linechart with grouped-barchart using chart.js

The linechart datapoints are coming at the center of each label of grouped-barchart.

The input data will all be lists.

Plug-ins required to render the chart are “npm install chart.js”, “npm install chartjs-plugin-datalabels –save”

The code which I used is:

function draw_grouped_barchart(
  labels_data,
  billable_data,
  non_billable_data,
  total_data,
  bench_data
) {
  const max_y = Math.max(...total_data) * 1.25;
  var barChartData = {
    labels: labels_data,
    datasets: [
      {
        label: "HC",
        backgroundColor: "#64218f",
        borderColor: "#64218f",
        borderWidth: 1,
        data: total_data,
        order: 2,
      },
      {
        label: "Billable",
        backgroundColor: "#a83b8f",
        borderColor: "#a83b8f",
        borderWidth: 1,
        data: billable_data,
        order: 2,
      },
      {
        label: "Non Billable",
        backgroundColor: "#ed8394",
        borderColor: "#ed8394",
        borderWidth: 1,
        data: non_billable_data,
        order: 2,
      },
      {
        label: "Bench",
        backgroundColor: "#f8c7aa",
        borderColor: "#f8c7aa",
        borderWidth: 1,
        data: bench_data,
        order: 2,
      },
      {
        label: "Linear (HC)",
        data: total_data,
        fill: false,
        borderColor: "rgb(75, 192, 192)",
        tension: 0.1,
        type: "line",
        order: 1,
      },
    ],
  };
  var chartOptions = {
    responsive: true,
    plugins: {
      datalabels: {
        anchor: "end",
        align: "top",
        formatter: (value, context) =>
          context.datasetIndex !== 4 ? value : "",
        color: "#000000",
        font: {
          weight: "bold",
          size: 10,
        },
      },
      legend: {
        onClick: () => {
          return "";
        },
        position: "bottom",
        labels: {
          color: "#000000",
          font: {
            size: 10,
          },
          usePointStyle: true,
          generateLabels: (chart) => {
            let pointStyle = [];
            chart.data.datasets.forEach((dataset) => {
              if (dataset.type === "line") {
                pointStyle.push("line");
              } else {
                pointStyle.push("rect");
              }
            });
            return chart.data.datasets.map((dataset, index) => ({
              text: dataset.label,
              fillStyle: dataset.backgroundColor,
              strokeStyle: dataset.borderColor,
              pointStyle: pointStyle[index],
            }));
          },
        },
      },
      title: {
        display: false,
        text: "Allocations Projections (in FTE)",
      },
    },
    scales: {
      y: {
        display: false,
        beginAtZero: true,
        max: max_y,
      },
      x: {
        display: true,
        grid: {
          display: false,
        },
        ticks: {
          color: "#000000",
          font: {
            size: 10, //this change the font size
          },
        },
        border: {
          color: "#000000",
          width: 2,
          z: 1,
        },
      },
    },
  };
  Chart.register(ChartDataLabels);
  $("#canvas").remove();
  $("#mycanvas").append(
    '<canvas class="w-100" id="canvas" height="350"></canvas>'
  );
  var ctx = document.getElementById("canvas").getContext("2d");
  window.myBar = new Chart(ctx, {
    type: "bar",
    data: barChartData,
    options: chartOptions,
  });
}
 

I have tried giving offset & transform. It didn’t work.

enter image description here

I want HC to be inline with linear HC.

Navigate fullcalendar months using arrow keys on kayboard

In v3 of fullcalendar i could navigate months using a JavaScript switch statement with the following:

$('#calendar').fullCalendar('next');
$('#calendar').fullCalendar('prev');

I’ve now migrated to fullCalendar v6.15 and the js switch statement no longer works.

I have tried:

calendar.prev();
calendar.next();

Which won’t work, any suggestions in the right direction appreciated.

View Images From a URL

When one sends a URL in a message on a chat app or paste a URL on a note taking app, you will often see an image from that URL as well as some text — often the H1 or title tag of that URL.

Is this possible to do on the web in JavaScript or some other way?

I have been looking through blogs, articles, and videos and can’t see anything on this specifically. I am a noob and don’t know where to start

Alternative to for loops? [closed]

<div id="1" brand="BMW" price="1000"></div>
<div id="2" brand="LEXUS" price="2000"></div>
<div id="3" brand="MERCEDES" price="3000"></div>
<div id="4" brand="VW" price="4000"></div>

<div id="5" brand="TESLA" price="5000"></div>

for (i=1;i<=5;i++) {

var brand = $('#'+i).attr('brand');
var price = $('#'+i).attr('price');

 if (brand = 'LEXUS') {

 for (b=1;b<=10;b++){
 //code for doing things on specific model
 }
}

 if (price = "4000") {
  for (c=1;c<=20;c++) {
  //code for doing things on specific price
  }
 }

}

On the original code I have more than 5 nested loops on many places and I am looking for a proper way to replace this. If possible to not use loops at all.

I have tried array object and mapping doesn’t really helped me much as I still need to use for loops to get data from specific div id. I want to possibly use zero loops for this approach.