Render multiple ApexCharts with JS in one file

Good evening,
in order not to insert single scripts on each page, I would like to merge all the JS rendering graphics into one file.

ApexCharts uses the following code to render a single chart.

var options = {
    
    series: [3, 5],
    labels: ['Item1', 'Item2'],
    
    colors: ['#747679', '#e83323'],
    
    chart: {
        type: 'donut',
        height: 200,
        width: 200
    }
}

var chart = new ApexCharts(document.querySelector("#apexchart1"), options);
chart.render();

How can I change it?

How can I access the variable declared inside then function outside?

I want to access the input value given/already present in the input field. I am trying the below solution but I can’t access it outside the then function.

    let name
    cy.visit('/')
    cy.get('[id=username]').type("Kanye")
    cy.get('[id=username]').then((input) => {
      age = input.val()
      cy.log(name)  # Works here
    })
    cy.log(name)    #Does not work here

Can you help me modify this function? Or suggest me any alternative I can use.

How can i sort an array of objects? [duplicate]

i have the following array:

mVetor [
  { nome: 'will', idade: 18 },
  { nome: 'marcos', idade: 19 },
  { nome: 'maria', idade: 20 },
  { nome: 'bia', idade: 21 },
  { nome: 'jose', idade: 22 },
  { nome: 'clara', idade: 23 },
  { nome: 'isa', idade: 33 },
  { nome: 'pedro', idade: 38 },
  { nome: 'gabriel', idade: 19 },
  { nome: 'ana', idade: 26 }
]

And i want to know how can i organize and order the array by name(nome) and then age(idade) but i don’t know how

Print a bill using TM-T20III

I have an epson tm-t20iii printer and I want to make a program that allows me to print a bill using it.
I looked a lot about python solutions and javascript solutions, but didn’t succeed.
I don’t have any programming language preference whether it’s javascript, php, python or java, the goal is being able to make that application listen into requests, it could be an app that gets installed on a Windows machine, and listens on events coming from an electron application or python tkinter app. I just need to figure out a way to do it. (preferable USB not network)

Any ideas please ?

POST Route Is Giving CryptoJS Malformed Data Error

I’m learning Crypto.JS and Node.JS, and am currently struggling with a Malformed UTF-8 data error when accessing the login endpoint with Postman. I know that the login credentials are correct, but when I send the POST request to the endpoint, it throws me with that error. Is there a simple fix for this?

const router = require('express').Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");

router.post("/register", async (req, res) => {
    const newUser = new User({
        username: req.body.username,
        email: req.body.email,
        password: CryptoJS.AES.encrypt(req.body.password, process.env.SECRET_PASSPHRASE).toString()
    });

    try {
        const savedUser = await newUser.save();
        res.status(201).json(savedUser);
    } catch (err) {
        res.status(500).json(err);
    }
});

router.post("/login", async (req, res) => {
    try {
        const user = await User.findOne({ username: req.body.username })

        !user && res.status(401).json("Invalid username or password");

        const hashedPassword = CryptoJS.AES.decrypt(user.password, process.env.SECRET_PASSPHRASE);
        const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
        
        originalPassword !== req.body.password && res.status(401).json("Invalid username or password");

        const accessToken = jwt.sign(
        {
            id: user._id,
            isAdmin: user.isAdmin
        }, 
        process.env.ACCESS_TOKEN_SECRET,
        {expiresIn: "3d"}
        );

        const { password, ...others } = user._doc;

        res.status(200).json(others, accessToken);

    } catch(err) {
        console.log(err);
        res.status(500).json(err);
    }
});



module.exports = router;

rectangle element with image background in svg

Is there any way to put multiple images into SVG?
The best solution for me seems to be placing a RECT object that will have a photo as a backgrund but its not working.

example:

<svg width="500" height="500">
  <rect width="100" height="100" class="img1" />
  <rect width="100" height="100" class="img2" />
</svg>

and

 .img1 {
     background-image: url("../assets/panel.svg");
 }

JavaScript Add onclick functions with row number as parameter to dynamically generated rows

The Problem

Hi, I am making a table in which I have two buttons, View and Update for each row. I am generating the rows in one for loop. Since I am using innerHTML, Instead of adding the onclick listeners there, I make another for loop after the first one and add the event listeners there. The event listeners are added to all rows. However, the parameter( Row number) passed in functions for all rows is the number for the last row.
Not sure why this is happening, any clues or advice will be helpful. I will leave the relevant code and debugging results below.

The Code

Adding New Rows

table.innerHTML="";
var count=1;
querySnapshot.forEach((doc) => {
  var innerhtml='<tr id="row">.....</tr>';

  //Append the new row
  table.innerHtML=table.innerHTML+innerhtml;

  //Assign new ID to row
  document.getElementById("row").id=count.toString()+"row";
  
  //Increment Count for next row/iteration
  count=count+i;


});

Adding event Listeners for Each Rows

for(var i=1;i<count;i++){
  console.log("Adding functions for row : "+i);

  //Get/Generate ID of rows (ID was assigned with same logic) 

  var cchkid=i.toString()+"chk";
  var uupdateid=i.toString()+"update";
  console.log("Adding functions for row : "+cchkid + " "+uupdateid);

  //Add Listeners for Each button in row i

  document.getElementById(cchkid).addEventListener("click", function(){
    alert("adding check function for id : "+i);
      check(i-1);
  });
  document.getElementById(uupdateid).addEventListener("click", function(){
    alert("adding update function for id : "+i);
      update(i-1);
  });
}

Debugging by using Console Log & Inspect

Count : 3

Adding functions for row : 1
Adding functions for row : 1chk 1update
Adding functions for row : 2
Adding functions for row : 2chk 2update

Inspect
Using inspect element, I can ensure that all rows have separate id’s
Inspect Element Screenshot

So far everything looks good, However, when console logged inside the said functions, all rows give the same value for the passed parameter.

Console Log after clicking on two different rows
2 Display data for user ID: 1

This should be :

  1. Display data for user ID: 0 for first row
  2. Display data for user ID: 1 for second row and so on

I cannot figure out what’s wrong here, kindly help this newbie out. Thanks!

Fast form’s validation with server-side validation

Say for example that I’m building a web application with auth functionalities. How can I display warnings, change the colors of the input, etc. as I type? Client and server-side validation? But client-side validation would be insecure or visible to the client through the google console? Or maybe fetching an endpoint every time that I type?

JS this dynamic scoping [duplicate]

When trying to execute the following snippet, I expected the doFoo.call(obj, obj.foo) call to return "inside obj" as the dynamic scope of the previous element in the call stack has a reference to a but the call has the global context instead. What am I missing here?

function foo() {
  // debugger
  console.log(this, this.a);
}

function doFoo(fn) {
  // `fn` is just another reference to `foo`
  // debugger 
  fn()
  // <-- call-site!
}

var obj = {
  a: 'inside obj',
  foo: foo
};

var a = "oops, global"; // `a` also property on global object

doFoo(obj.foo); // "oops, global"
doFoo.call(obj, obj.foo) // "oops, global"```

Loop to get specific index values based on seed data

Ok so I have an array similar to the following.

array = [a,b,c,d,e,f,g,h,i,j,k,l];

This array is used to generate a table that I will display by distributing the array onto a grid based on the number of columns and rows that the table has. I’m trying to create a for loop that will push to an array the desired index values for new cells when adding a column to the table.

//Know Values//
selectedColumn = **A**; (2) // index of selected column
numRows = **B**;        (3) // derived from array length so 1 less than actual rows displayed
numColumns = **C**;     (2) // derived from array length so 1 less than actual columns displayed

//Mock Table Display, distributing array into rows//
index    0, 1, 2, 3
row0     a, b, c, d,    A * (X) = 2
index    4, 5, 6, 7
row1     e, f, g, h,    A * (X) = 6
index    8, 9,10,11
row2     i, j, k, l     A * (X) = 10

indexValues = [2, 6, 10]

The chart above is hopefully able to describe what I’m referring to. I would like a value for X that works for any number of columns and rows to return the correct index value. I assume X will need to be a mathematic expression involving A and C. Currently using row in a loop to determine which row is being calculated for.

  for (let row = 0; row < numRows; row++) {
    let index = (row + 1) * selectedColumn;
    indexValues.push(index);
  }

console not logging post example

view html page, where i want to add functionality to add list

 <div class="centered-content">
    <div class="task-manager-container">
        <div class="sidebar">
            <h1 class="title has-text-primary">
                Lists
            </h1>

            <div class="list-menu">
                <a class="list-menu-item">
                    <p>List 1#</p>
                </a>
                <a class="list-menu-item">
                    <p>List 2#</p>
                </a>
                <a class="list-menu-item">
                    <p>List 3#</p>
                </a>
            </div>

            <button class="button is-primary" (click)="createNewList()">+ New List</button>
        </div>
        <div class="task-list-container has-background-light">
            <h1 class="title has-text-primary">
                Tasks
            </h1>

            <div class="task">
                <p>This is something i have to do :) </p>
            </div>
            <div class="task">
                <p>This is something i have to do :) </p>
            </div>
            <div class="task complete">
                <p>This is something i have to do :) </p>
            </div>

        </div>
    </div>
</div>

this createNewList method is in task-service as:

   import { Injectable } from '@angular/core';
import { WebRequestService } from './web-request.service';

@Injectable({
  providedIn: 'root'
})
export class TaskService {

  constructor(private webReqService: WebRequestService) { }

  createList(title: string) {
    return this.webReqService.post('lists', { title });

  }
}

this is method in task-view-component.ts

import { Component, OnInit } from '@angular/core';

import { TaskService } from 'src/app/task.service';

@Component({
  selector: 'app-task-view',
  templateUrl: './task-view.component.html',
  styleUrls: ['./task-view.component.scss']
})
export class TaskViewComponent implements OnInit {

  constructor(private taskService: TaskService) { }

  ngOnInit(): void {
  }

  createNewList() {
    this.taskService.createList('Testing').subscribe( (response: any) => {
      console.log(response);
    })

  }
}

i imported httpClientModule in app.module, and the console is not logging ANYTHING (not even 404 or any error…) “Testing” which should be the body (title) of my task.
if you need any additional info to help me please say so… thank you for all of your help!

also this is in web-request-service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WebRequestService {

  readonly ROOT_URL;

  constructor( private http: HttpClient) { 
    this.ROOT_URL = 'http://localhost:3000';
  }

  get(uri: string) {
   return this.http.get(`${this.ROOT_URL}/${uri}`);
  }

  post(uri: string, payload: Object) {
    return this.http.post(`${this.ROOT_URL}/${uri}`, payload);
  }

  patch(uri: string, payload: Object) {
    return this.http.patch(`${this.ROOT_URL}/${uri}`, payload);
  }

  delete(uri: string) {
    return this.http.delete(`${this.ROOT_URL}/${uri}`);
  }
}

TypeError: member.roles.add is not a function

I’m working on a bot that needs to check some things before giving/removing a role from a user, but for some reason, the .has(), .some(), .add() and, .remove() functions don’t work.

Here’s my code:

const Permissions = require('discord.js');

function isAdmin(member) {
    return member.permissions.has(Permissions.FLAGS.ADMINISTRATOR);
}

function hasRole(member, roleID) {
    return member.roles.some(role => role.id === roleID);
}

function giveRole(member, role) {
    member.roles.add(role)
}

function removeRole(member, role) {
    member.roles.remove(role);
}

Here’s the full error that I get:

TypeError: member.roles.add is not a function
    at Object.giveRole (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTutil.js:101:30)
    at Object.buttonClicked (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTcommandsbuttonRoleexecute.js:23:14)
    at WebSocketManager.<anonymous> (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTindex.js:101:28)
    at WebSocketManager.emit (node:events:390:28)
    at WebSocketShard.onMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:300:54)
    at WebSocket.onMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibevent-target.js:199:18)
    at WebSocket.emit (node:events:390:28)
    at Receiver.receiverOnMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibwebsocket.js:1137:20)
    at Receiver.emit (node:events:390:28)
    at Receiver.dataMessage (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:528:14)
    at Receiver.getData (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:446:17)
    at Receiver.startLoop (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:148:22)
    at Receiver._write (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibreceiver.js:83:10)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Receiver.Writable.write (node:internal/streams/writable:334:10)
    at TLSSocket.socketOnData (C:UsersAdminOneDriveDocumentsGithub ProjectsdiscordBots-BOK-BOTnode_moduleswslibwebsocket.js:1231:35)
    at TLSSocket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10)
    at TLSWrap.onStreamRead (node:internal/stream_base_commons:199:23)

How to make js function delete one element from array and add another instead?

so I want to make JS function, that adds random string from my array to HTML, then remove it and add another instead of it. My code now does everything I want to, it just doesn’t remove past element and adds another one instead.

In other words – I just want a simple text slide.

MY HTML:

 <section style="height: 100vh;" class="">
      <div class="container pt-2 pb-2">
        <div class="row">
          <div class="col d-flex justify-content-center text-uppercase">
            <div>
              <h1>
                Mes teikiame
              </h1>
                <div class="scroller">
                  <span>
                  </span>
                </div>
              <h1>
                Paslaugas
              </h1>
            </div>
          </div>
        </div>
      </div>
    </section>

MY JS:

// Selecting elements
let scrollerSpan = document.querySelector('.scroller > span')
// Creating elements
let textInsideScroller = document.createElement('span')
// Class add
textInsideScroller.classList.add('text-inside-scroller')

// Function generating service name in random order for scroller
const dynamicServiceNames = () => {
    const serviceNames = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6', 'example7'];
    const randomName = serviceNames[rand(0, serviceNames.length)];
    textInsideScroller.append(randomName)
    scrollerSpan.append(textInsideScroller)    
};


// Executing my function

let i = 1;
setInterval(function()
{
    dynamicServiceNames(i++);
}, 1000)

UPDATE:
Tried to solve this issue by adding this to the function:

// Function generating service name in random order for scroller
const dynamicServiceNames = () => {
    const serviceNames = ['grožio', 'voljerų gaminimo', 'apskaitos priežiūros', 'kasinėjimo', 'metinių ataskaitų teikimo', 'deklaracijų ruošimo', 'barščių virimo'];
    const randomName = serviceNames[rand(0, serviceNames.length)];
    textInsideScroller.append(randomName)

    if (scrollerSpan.contains(textInsideScroller)){
        scrollerSpan.remove(textInsideScroller)
    }
    else{
    scrollerSpan.append(textInsideScroller)
    }
    
};

But this didn’t helped. Now the random string comes from array, but only one time — I need to refresh the page in order to get another random string….

javascript: Create variables/const for all elements in qureySelectorAll

I’m trying to querySelectorAll a bunch of things in my HTML document.
I then want to create a variable for each of them.

Individually, I would do the following to establish it, and then update it.

const workersOutput = document.getElementById('workersOutput');
workersOutput.textContent = `${workers}`;

This is really messy though when I’ll have many of these to do.

Using querySelectorAll, I can make some hybrid version, but it’s not exactly readable or easy to use.

const outputs = document.querySelectorAll('.output');
outputs[2].textContent = `${workers}`;

Couldn’t I use maybe forEach to create a variable using the ID or something along the lines of (I know that’s not how that works, but I want to get the idea across:

const outputs = document.querySelectorAll('.output');

outputs.forEach((output) => {
    const outputs[2] = document.getElementById(output.id);
});

I could also be way off on how to accomplish this the “right way”, I’m newish to coding.

Capture payment method used to pay with PayPal Checkout/Orders API

I’m using the Standard Integration of PayPal Checkout (via the Orders API), and want to capture the actual payment method – which I believe PayPal calls a “funding source” – that the customer paid with, so that I can pass this value to my server and persist it to my database.

What API object do I need to call to get this information?