How to make a time difference discord.js?

for several days I’ve been trying to make a time difference but I can’t, to better explain to you:

I made 2 .js files, one file to take a service and it gives a role to say that the person took his service and the other file to make an end of service and it removes the role by putting in an embed the precise date, hours, minutes and seconds, just like for the service take, I managed to do that but the problem is that I would like the bot to subtract my 2 hours (the one from taking service and end of service to have the total number of hours he did during his service) but I can’t do it, if someone has an idea I’m interested !

const { Client, ApplicationCommandOptionType, PermissionFlagsBits, InteractionResponse, EmbedBuilder } = require("discord.js");
config = require('../config.json');

module.exports = {
    name: "start",
    description: `start serving `,
    run: async (client, interaction, message) => {

        var dt = new Date(Date.now())
        var now = dt.toLocaleDateString('en-En')

        var hours = (dt.getHours() < 10?"0":"") + dt.getHours()
        var minutes = (dt.getMinutes() < 10?"0":"") + dt.getMinutes()
        var seconds = (dt.getSeconds() < 10?"0":"") + dt.getSeconds()

        var day = (dt.getDate() < 10?"0":"") + dt.getDate()
        var month = (dt.getMonth()+1 < 10?"0":"") + (dt.getMonth()+1)
        var year = dt.getFullYear()

        var all = day + "/" + month + "/" + year + " • " + hours + ":" + minutes + ":" + seconds

        const service_plug = new EmbedBuilder()
        .setColor("Green")
        .setDescription(`**${interaction.member.user}** took his service !`)
        .setFooter({ text: all });

        await interaction.deferReply({ ephemeral: true });

        if (interaction.member.roles.cache.has("1067700186274603008")) return interaction.followUp({ content: `:x: You are already in service` });

        if (!interaction.guild.members.me.permissions.has(PermissionFlagsBits.Administrator)) return interaction.followUp({ content: `:x: I don't have the required permission for this command to work !` });

        interaction.member.roles.add(config.role_start)

        interaction.followUp({ content: `You took your service !`})

        interaction.guild.channels.cache.get(config.logs_start).send({ embeds: [ service_plug ] }).catch(() => {})
    }
}

Here is the code of the command to start its service, that of the end of service is exactly the same except that it removes the role of the member

How to stop timer when the ‘space’ is pressed and start if do it again?

Cant get, why it doesn’t work;
I added new boolean ‘keyPressed’ to check if the key space was pressed. When it pressed, it’s going to start the timer and, doing it again, stop the timer. But in my code this boolean doesn’t help and only one part of my ‘if’ works: i can only stop or start by pressing space

const timeDisplay = document.querySelector("#timeDisplay");
const startBtn = document.querySelector("#startBtn");
const pauseBtn = document.querySelector("#pauseBtn");
const resetBtn = document.querySelector("#resetBtn");

let startTime = 0;
let elapsedTime = 0;
let currentTime = 0;
let paused = true;
let intervalId;
let hrs = 0;
let mins = 0;
let secs = 0;
let keyPressed = false;

document.addEventListener('keydown', function(event) {
  if (event.code == 'Space') {
    if (keyPressed) {
      if (paused) {
        paused = false;
        keyPressed = true;
        startTime = Date.now() - elapsedTime;
        intervalId = setInterval(updateTime, 1000);
      }
    }
  }
});

document.addEventListener('keydown', function(event) {
  if (event.code == 'Space') {
    if (!keyPressed) {
      if (!paused) {
        paused = true;
        keyPressed = false;
        elapsedTime = Date.now() - startTime;
        clearInterval(intervalId);
      }
    }
  }
});



startBtn.addEventListener("click", () => {

  if (paused) {
    paused = false;
    keyPressed = true;
    startTime = Date.now() - elapsedTime;
    intervalId = setInterval(updateTime, 1000);
  }
});
pauseBtn.addEventListener("click", () => {
  if (!paused) {
    paused = true;
    keyPressed = false;
    elapsedTime = Date.now() - startTime;
    clearInterval(intervalId);
  }
});
resetBtn.addEventListener("click", () => {
  paused = true;
  clearInterval(intervalId);
  startTime = 0;
  elapsedTime = 0;
  currentTime = 0;
  hrs = 0;
  mins = 0;
  secs = 0;
  timeDisplay.textContent = "00:00:00";
});

function updateTime() {
  elapsedTime = Date.now() - startTime;

  secs = Math.floor((elapsedTime / 1000) % 60);
  mins = Math.floor((elapsedTime / (1000 * 60)) % 60);
  hrs = Math.floor((elapsedTime / (1000 * 60 * 60)) % 60);

  secs = pad(secs);
  mins = pad(mins);
  hrs = pad(hrs);

  timeDisplay.textContent = `${hrs}:${mins}:${secs}`;

  function pad(unit) {
    return (("0") + unit).length > 2 ? unit : "0" + unit;
  }
}
<span id="timeDisplay"></span><br />
<button type="button" id="startBtn">Start</button>
<button type="button" id="pauseBtn">Pause</button>
<button type="button" id="resetBtn">Reset</button>

there is no space between words in my js pop up

I’m trying to learn js and I created an alert for successful payment. But there is no space between the words, this issue does not occur in any other alert I made.

The result:

chrissuccssfully boughtjava/algo courseusingupi

My code:

let firstName = "chris";
const price = 99;
let courseName = "java/algo course";
let cardNum = "123456789";
let isPaid = true;
let modeOfPayment;
modeOfPayment = prompt("mode of payment");
alert(firstName + "succssfully bought" + courseName + "using" + modeOfPayment);

change event is not working properly on input in angular 4

change event is not working. I have already used the ngChange, ngModelChange but its also not working. pls help.

<input type=”text” formControlName=”amountCostUSD” currencyMask [(ngModel)]=”fundAllocationMasterObject.fundsCategoryMappingListNewProcess[fundIndex].costCategory[i].categoryAmountUSD”
  pInputText class=”form-control input_box”  placeholder=””  (focusout)=”calculateTotal_new(fundIndex,i);
checkSaveValidationFunc(fundAllocationMasterObject.fundsCategoryMappingListNewProcess[fundIndex].costCategory[i].categoryCode, fundAllocationMasterObject.fundsCategoryMappingListNewProcess[fundIndex].costCategory[i].categoryAmountUSD);
catFinPBCheck_new($event,fundIndex,i)” (change)=”catFinPBCheck_new($event,fundIndex,i)” />
<div *ngIf=”product.get(‘amountCostUSD’).hasError(‘required’) && saveButtonClicked”>
{{ErrorCodes.CATEGORY_AMOUNT_REQUIRED}}

I have already try the ngChange, ngModelChange but its also not working.

regex – leading (?!w) doesn’t work with locale characters

Context: I’m using a library (markjs.io) to mark specific words. My current solution let rgx = /(?:^|s)žolč iz žrela([s.!?,:;])/i; also marks the leading space and trailing space and separators.

I’ve come up with a solution which is very close, but the leading (?!w) allows characters to be adjacent to the word.

Current “solution” which allows adjacent characters – (?!w)[žŽ]olč iz žrela(?!w)

Example can be found here, on regex101.

Any help would be greatly appreciated.

If I can elaborate or if you find a flaw, please let me know. Thank you

Webpack – how to remove path separator?

I want to have an import of components from /source/ directory and to have an alias for that folder to be @. However, I don’t want a slash after the @, so my import would look like that:

import Component1 from '@Component1'

not

import Component1 from '@/Component1'

I tried to resolve path similarly to this thread: WebStorm and webpack alias not working without slash, but that didn’t apply to me either.

Is this possible to do?

How to use returned JSON.stringify array in C#

I have JavaScript function where I have an array and when I send that array to my C# controller, it should be in such way way that my controller should understand.

JavaScript function

function Check(obj) {
    var eArray = $('input[type="hidden"][id^="code_"]').map(function () {
        return this.getAttribute("value");
    }).get();

    $.ajax({
        data: { GUID: JSON.stringify(eArray) },
        url: "/Order/Check",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (result) {
        ...
        }
        });

My Controller

public ActionResult Check()
        {
            string guid = HttpContext.Request["GUID"];
            ......
            return Json(result, JsonRequestBehavior.AllowGet);
        }

I would like to get an array in my controller.

Upload csv for processing in PyScript

The following is my failed attempt at writing HTML/Javascript/PyScript code that allows a user to upload a csv (or excel) file, which is then available for use in PyScript (e.g., Pandas). As you might notice, I am not very experienced with Javascript.

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
        
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    
    <py-config>
        packages = ["pandas"]
    </py-config>
  </head>
  <body>
    <input type="file" id="fileinput" accept=".csv, .xlsx"/>

    <script>
        var test = "test";

        function assignFile(e) {
            // Assign file to js variable
            window.file = e.target.files[0];
            console.log("File assigned")
        }
    </script>

    <py-script>
import pandas as pd
import js
import pyodide
from js import test
js.console.log(test)

def get_file(e):
    js.console.log("Attempting file upload: " + e.target.value)

    # Assign file to a js variable
    js.assignFile(e)
    # Import variable to python
    from js import file

    display(pd.read_csv(file))

get_file_proxy = pyodide.ffi.create_proxy(get_file)

js.document.getElementById("fileinput").addEventListener("change", get_file_proxy)
    </py-script>
  </body>
</html>

Some notes to this code: I am aware that the part written in the script element could also be written in the py-script element, but decided not to. Furthermore, the line from js import file imports the variable created in Javascript, but when I try to use this variable with Pandas, it gives me the error in the console Invalid file path or buffer object type: <class 'pyodide.JsProxy'>. This is contrary to the properly functioning line from js import test. However, the specific error is unimportant to my question, which is:

What would be a simple way to allow a user to upload a csv (or xlsx) file for use in PyScript?

Reusing the already randomly generated number in another JS file – Node.js (ESM not CJS)

I need help with my project. I am creating CLI game with Node.js using ESM (not CJS).

In my randomHealth.js file, I have a function that generates a random number:

let randomHealth = () => {
  return Math.floor(Math.random() * 300 + 1)
}

export default randomHealth

In my stats.js file I need to import and display that number. However, I needs to be fixed there, because I need that same number in another file:

import random from "./random/random.js"
import randomHealth from "./random/randomHealth.js"

let stats = () => {
  console.log("STATS")

  let playerHealth = randomHealth()
  console.log("Health - " + playerHealth)
}

export default stats

I stored it in a playerHealth variable because I need to take that one generated number.

Now, I need that variable in another file, fight.js to use it.
If I call randomHealth() it’s just gonna generate a new number, and I need a number that was already generated in stats.js file.
How to get that number from stats.js to use it in fight.js ?

I tried exporting that variable and importing it in fight.js, but once I do console.log() it displays undefined. I tried many different things but none worked. It returns either undefined, either NaN either nothing. I also tried immediatelly storing it in a variable in randomHealth.js and then displaying it, but that didn’t work either. If I do console.log in randomHealth.js then I need to do it again when I want to display it in another file and a double console.log displays undefined. And if I don’t to console.log in randomHealth.js then it always regenerates a new random number and I need the number that gets displayed in stats.js to use in fight.js.

Any ideas ? This was just my idea, if there is an even better way of doing it that storing it in a varible in stats.js then by all means tell me.

Thanks in advance.

Running SQS consumer on ECS with numbers of desired count

I do the test to run 2 difference consumers (let call it Consumer-A and Consumer-B) to the same Queue then I found that when Consumer-A pulling the message, Consumer-B doesn’t pull the message and waiting for the Consumer-A to finish first and vice versa.
The process continues like this repeatedly.
So my question are:

  1. Does this normal in term of multiple SQS consumer? I found this which seem to answer this question but I’m not sure. https://aws.amazon.com/sqs/faqs/#:~:text=Do%20Amazon%20SQS%20FIFO%20queues%20support%20multiple%20consumers%3F
  2. What if we try to run the SQS consumer on ECS (example: with 3 desired count), do we get 30 messages at a time or what?

Do you have any others solutions for scaling to consume more SQS message (not using Lambda would be great)?

Unexpected decodeURI output

I send post request to my express server with body payload

handle: "new-text-collection-tech-gen"
raw:  "Нова коллекція"
title: "%D0%9D%D0%BE%D0%B2%D0%B0%20%D0%BA%D0%BE%D0%BB%D0%BB%D0%B5%D0%BA%D1%86%D1%96%D1%8F"

But i receive unexpected encoding of Cyrillic characters in body

body: {
    title: '%D0%9D%D0%BE%D0%B2%D0%B0%20%D0%BA%D0%BE%D0%BB%D0%BB%D0%B5%D0%BA%D1%86%D1%96%D1%8F',
    raw: 'PP>P2P0 P:P>P;P;P5P:QQQ',
    handle: 'new-text-collection-tech-gen'
}

And If I run decodeURI(title, 'utf-8') I expected to get back "Нова коллекція" but I get "PP>P2P0 P:P>P;P;P5P:QQQ"

I tried to use decodeURIComponent, tried not to set utf8 explicitly, tried to add app.use(express.json({ encoding: ‘utf-8’ }));

Please, help me to debug, where to look.

I use "express": "^4.18.2"

I am not sure what part of the code is relevant to provide, so just ask when having a question

How can i print a JavaScript result in Currency format and also 2 decimal poinst

Please am trying to get the result of this JavaScript in currency format, i have tried using .toFixed and Intl.NumberFormat(‘en-US’ but didnt work.

JS Fiddle Link
https://jsfiddle.net/dh8n05L1/1/

JAVASCRIPT

let abtc;
let bbtc;
let cbtc;
function btcvalue() {
    bbtc = $("#btc").val()
    $("#btcusdt").val(abtc * bbtc)
}
function btcusdtvalue() {
    cbtc = $("#btcusdt").val()
    $("#btc").val(cbtc / abtc)
}

$(document).ready(function() {
    $.get({
        url: "https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USDT",
        success: function(result) {
            
            abtc = result.USDT;
            btcvalue();
        },
        error: function() {
            console.log("error")
        }
    });
});

HTML

<input class="asset" type="text" id="btc" step=".01" name="btc" onkeyup="btcvalue()" value="3" readonly>
                                   
 <input type="text" class="equiv" value="btcusdtvalue()" id="btcusdt" readonly>
 
 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>`

Remove duplicates in for loop – vue

I have a problem that I use v-for on code and image but result is duplicate, how to fix?
enter image description here

I’m sorry if I made you misunderstand. but you can ask me

Code

 <div v-for="n in follows" :key="n.follow_artist_Id">
     <div v-if="n.artist_id == sch.artist_id && n.sch_id == sch.sch_id">
         <div class="card card-schedule mb-3">
             ...
         </div>
     </div>
 </div>`

<div class="card card-schedule mb-3">
...
</div>

how to get the required format out of json object where each key and value to be suffixed by “”

$scope.mappings = {
                     url1 : "url2",
                     url3 : "url4",.....}
var payload = {
                name : "URLS",
                 value : $scope.mappings
            }
OBTAINED FORMAT OF JSON STRINGIFIED PAYLOAD IS 
{
   "name" : "URLS",
   "value" : { "url1" : "url2",
               "url3" : "url4",..
             }
}

REQUIRED FORMAT OF VALUE
{
   "name" : "URLS",
   "value" : { /"url1" : /"url2",
               /"url3" : /"url4",..
             }
}

required: / to be suffixed to value
how could we add “/” to the json stringified object values key and value

Unable to Fit Video Into Canvas Automatically On Add?

I have a FabricJS + ReactJS project that uses a video as a background. The live example is here: https://codesandbox.io/s/empty-water-iknx5x?file=/src/App.js

When I click “Video Background”, the background seems to be only the top left of the video as shown: https://i.imgur.com/qDw45Lf.png

When I share a window using the Screenshare, only the top left of the screen is captured.

This is what is captured: https://i.imgur.com/dRqzKLr.png

This is the window: https://i.imgur.com/v77QN2t.png

Modifying the CANVAS_WIDTH and CANVAS_HEIGHT to see if the results change. It didnt.