SHA256 from scratch in Javascript

recently I’m trying to code SHA256 but from scratch in JavaScript.
However, I am getting an incorrect output when I input the string “abc”.
Here’s my code:

const k = [
   "01000010100010100010111110011000", // K[0]
   "01110001001101110100010010010001", // K[1]
   "10110101110000001111101111001111", // K[2]
   "11101001101101011101101110100101", // K[3]
   "00111001010101101100001001011011", // K[4]
   "01011001111100010001000111110001", // K[5]
   "10010010001111111000001010100100", // K[6]
   "10101011000111000101111011010101", // K[7]
   "11011000000001111010101010011000", // K[8]
   "00010010100000110101101100000001", // K[9]
   "00100100001100011000010110111110", // K[10]
   "01010101000011000111110111000011", // K[11]
   "01110010101111100101110101110100", // K[12]
   "10000000110111101011000111111110", // K[13]
   "10011011110111000000011010100111", // K[14]
   "11000001100110111111000101110100", // K[15]
   "11100100100110110110100111000001", // K[16]
   "11101111101111100100011110000110", // K[17]
   "00001111110000011001110111000110", // K[18]
   "00100100000011001010000111001100", // K[19]
   "00101101111010010010110001101111", // K[20]
   "01001010011101001000010010101010", // K[21]
   "01011100101100001010100111011100", // K[22]
   "01110110111110011000100011011010", // K[23]
   "10011000001111100101000101010010", // K[24]
   "10101000001100011100011001101101", // K[25]
   "10110000000000110010011111001000", // K[26]
   "10111111010110010111111111000111", // K[27]
   "11000110111000000000101111110011", // K[28]
   "11010101101001111001000101000111", // K[29]
   "00000110110010100110001101010001", // K[30]
   "00010100001010010010100101100111", // K[31]
   "00100111101101110000101010000101", // K[32]
   "00101110000110110010000100111000", // K[33]
   "01001101001011000110110111111100", // K[34]
   "01010011001110000000110100010011", // K[35]
   "01100101000010100111001101010100", // K[36]
   "01110110011010100000101010111011", // K[37]
   "10000001110000101100100100101110", // K[38]
   "10010010011100100010110010000101", // K[39]
   "10100010101111111110100010100001", // K[40]
   "10101000000110100110011001001011", // K[41]
   "11000010010010111000101101110000", // K[42]
   "11000111011011000101000110100011", // K[43]
   "11010001100100101110100000011001", // K[44]
   "11010110100110010000011000100100", // K[45]
   "11110100000011100011010110000101", // K[46]
   "00010000011010101010000001110000", // K[47]
   "00011001101001001100000100010110", // K[48]
   "00011110001101110110110000001000", // K[49]
   "00100111010010000111011101001100", // K[50]
   "00110100101100001011110010110101", // K[51]
   "00111001000111000000110010110011", // K[52]
   "01001110110110001010101001001010", // K[53]
   "01011011100111001100101001001111", // K[54]
   "01101000001011100110111111110011", // K[55]
   "01110100100011111000001011101110", // K[56]
   "01111000101001010110001101101111", // K[57]
   "10000100110010000111100000010100", // K[58]
   "10001100110001110000001000001000", // K[59]
   "10010000101111101111111111111010", // K[60]
   "10100100010100000110110011101011", // K[61]
   "10111110111110011010001111110111", // K[62]
   "11000111110111011011111011100010"  // K[63]
];
function RotR(data, n){
   n %= data.length;
   return data.slice(-n) + data.slice(0, -n);
}
function ShR(data, n){
   return '0'.repeat(n) + data.slice(0, -n);
}
function and(data1, data2){
   let result = "";
   for (let i = 0; i < data1.length; i++) result += data1[i]=='0' || data2[i]=='0' ? '0' : '1';
   return result;
}
function or(data1, data2){
   let result = "";
   for (let i = 0; i < data1.length; i++) result += data1[i]=='1' || data2[i]=='1' ? '1' : '0';
   return result;
}
function not(data){
   return data.split('').map(char => char == '0' ? '1' : '0').join('');
}
function xor(...data) {
   let result = data[0];
   for (let i = 1; i < data.length; i++){
      let result_temp = "";
      for (let j = 0; j < result.length; j++) result_temp += result[j] === data[i][j] ? '0' : '1';
      result = result_temp;
   }
   return result;
}
function add(data1, data2){
   let result = "";
   let carry = 0
   for (let i = data1.length-1; i >= 0; i--) {
      const bit1 = parseInt(data1[i], 10);
      const bit2 = parseInt(data2[i], 10);
      const sum = bit1 + bit2 + carry;
      result = (sum % 2) + result;
      carry = Math.floor(sum / 2);
   }
   return result.slice(-32);
}
function Ch(x, y, z) {
   return xor(and(x, y), and(not(x), z));
}
function Maj(x, y, z) {
   return xor(and(x, y), and(x, z), and(y, z));
}
function E0(x){
   return xor(RotR(x,2), RotR(x,13), RotR(x,22));
}
function E1(x){
   return xor(RotR(x,6), RotR(x,11), RotR(x,25));
}
function o0(x){
   return xor(RotR(x,7), RotR(x,18), ShR(x,3));
}
function o1(x){
   return xor(RotR(x,17), RotR(x,19), ShR(x,10));
}
function bin(data) {
   return String(data).split('')
   .map(char => char.charCodeAt(0).toString(2).padStart(8, '0')).join('');
}
function pad(data){
   let len = data.length;
   data+='1'
   while ((data.length + 64) % 512 !== 0) data+='0';
   let lengthInBits = '0'.repeat(64 - (len.toString(2)).length) + len.toString(2);
   return data + lengthInBits;
}
function decompose(data){
   // first 16
   let m = [];
   for (let i = 0; i < data.length; i+=32){
      let w = data.slice(i, i + 32);
      m.push(w);
   }
   // rest 48
   for (let i = 16; i < 64; i++)
      m[i] = add(add(o1(m[i-2]), m[i-7]), add(o0(m[i-15]), m[i-16]));
      console.log()
   return m;
}
function hash(data){
   var H_value = [
      "01101010000010011110011001100111",  // H0
      "10111011011001111010111010000101",  // H1
      "00111100011011101111001101110010",  // H2
      "10100101010011111111010100111010",  // H3
      "01010001000011100101001001111111",  // H4
      "10011011000001010110100010001100",  // H5
      "00011111100000111101100110101011",  // H6
      "01011011111000001100110100011001"   // H7
   ];
   let [a, b, c, d, e, f, g, h] = H_value;
   for (let i = 0; i < 64; i++) {
      let t1 = add(add(add(add(h, E1(e)), Ch(e, f, g)), k[i]), data[i]);
      let t2 = add(E0(a), Maj(a, b, c));
      h = g;
      g = f;
      f = e;
      e = add(d, t1);
      d = c
      c = b;
      b = a;
      a = add(t1, t2);
   }
   H_value[0] = add(H_value[0], a);
   H_value[1] = add(H_value[1], b);
   H_value[2] = add(H_value[2], c);
   H_value[3] = add(H_value[3], d);
   H_value[4] = add(H_value[4], e);
   H_value[5] = add(H_value[5], f);
   H_value[6] = add(H_value[6], g);
   H_value[7] = add(H_value[7], h);
   return H_value;
}
function hex(data){
   return data.map(h => parseInt(h, 2).toString(16).padStart(8, '0')).join(' ');
}
function sha256(input) {
   // convert input into binary
   let binary = bin(input);
   // padding
   let padding = pad(binary);
   // block decomposition
   let m = decompose(padding);
   // hash computation
   let h = hash(m);
   // convert to hexadecimal
   let result = hex(h);
   return result;
}

document.getElementById('text-input').addEventListener('input', function() {
   const inputText = document.getElementById('text-input').value;
   var sha256_output = sha256(inputText);
   const outputBox = document.getElementById('output-box');
   outputBox.value = sha256_output;
});

when I input “abc” the expected output should be:

ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

but the actual output was:

bbe45caf8f01cfea414140de5dae2223b16fa79396177a9cb410ff61f20015ad

I’ve gone through my implementation step-by-step, checking the functions for binary operations, padding, and block decomposition. I verified the constants (K values) and initial hash values (H values).
Upon reviewing my code, I’ve noticed that the H_value[0] and H_value[4] differ from the expected values, while the other H_values are consistent.
I’m trying to figure this out for a week but still got no clue.
Can you guys help me?

WebAssembly exported function: Cannot read properties of undefined

I’m trying to run lightningcss on a WebWorker module for my JavaScript application.

I imported it as a module as follows:

import * as lightningcss from './index.mjs';

and tried using the function as below:

let code = lightningcss.transform({
    code: bufferedTextInput,
    minify: true,
    sourceMap: false
});

However, on running the script in my browser, I encountered the following error:

index.mjs:41 Uncaught TypeError: Cannot read properties of undefined (reading 'transform')
    at Module.transform (index.mjs:41:15)
    at wasm-worker.js:9:29

I tried troubleshooting on the web but to no avail. How would I go about fixing this problem?

play the video or audio autoplay with no muted

I want to create a web page that can display courseware. There is a short video on the first side of this courseware page for introduction, but I found no matter what i do that I can not make the video autoplay with no muted(only can autoplay with muted, but this is not i want), Is there any way to solve this question?

Here is more information about browser restrictions on autoplay
more info

Try to modifying the browser configuration can automatically play, but this only applies to one’s own computer
chrome://flags/#autoplay-policy

actually this problem occurred in a big electron project. i have try on some simple html, none of them worked

Cursor cannot focus in certain areas within a contentEditable element

When inserting an HTML tag with styles into a contentEditable element, in some cases, the cursor cannot focus behind the inserted tag。 The specific steps are as follows:

  1. Insert some characters.
  2. Insert a tag.
  3. Press enter.
  4. Insert more characters.
    enter image description here

However, if I skip the first step, the cursor can focus normally behind the tag
enter image description here

Why does this happen? How can I make the cursor position itself behind the tag and continue typing in the first case?

https://codesandbox.io/p/sandbox/elastic-nova-72hmw4?file=%2Fsrc%2FApp.js%3A65%2C32-65%2C54

Is it possible to position the cursor as expected?

Extracting info from JSON response

I’m trying to get the last value of “TMiles” in the following JSON.

[{
  "__type": "MileageReport:http://pcmiler.alk.com/APIs/v1.0",
  "RouteID": null,
  "ReportLines": [{
    "Stop": {
      "Address": {
        "StreetAddress": "Apple Park Way",
        "City": "Cupertino",
        "State": "CA",
        "Zip": "95014",
        "County": "Santa Clara",
        "Country": "United States",
        "SPLC": null,
        "CountryPostalFilter": 0,
        "AbbreviationFormat": 0,
        "StateName": "California",
        "StateAbbreviation": "CA",
        "CountryAbbreviation": "US"
      },
      "Coords": {
        "Lat": "37.334866",
        "Lon": "-122.014282"
      },
      "Region": 4,
      "Label": "",
      "PlaceName": "",
      "TimeZone": "PDT",
      "Errors": [],
      "SpeedLimitInfo": null,
      "ConfidenceLevel": "Exact",
      "DistanceFromRoad": 0,
      "CrossStreet": null,
      "TimeZoneOffset": "GMT-7:00",
      "TimeZoneAbbreviation": "PDT",
      "IsDST": true
    },
    "LMiles": "0.000",
    "TMiles": "0.000",
    "LCostMile": "0.00",
    "TCostMile": "0.00",
    "LHours": "0:00",
    "THours": "0:00",
    "LTolls": "0.00",
    "TTolls": "0.00",
    "LEstghg": "0.0",
    "TEstghg": "0.0",
    "EtaEtd": null
  }, {
    "Stop": {
      "Address": {
        "StreetAddress": "22-26 West 34th Street",
        "City": "New York",
        "State": "NY",
        "Zip": "10001",
        "County": "New York",
        "Country": "United States",
        "SPLC": null,
        "CountryPostalFilter": 0,
        "AbbreviationFormat": 0,
        "StateName": "New York",
        "StateAbbreviation": "NY",
        "CountryAbbreviation": "US"
      },
      "Coords": {
        "Lat": "40.748462",
        "Lon": "-73.984770"
      },
      "Region": 4,
      "Label": "",
      "PlaceName": "",
      "TimeZone": "EDT",
      "Errors": [],
      "SpeedLimitInfo": null,
      "ConfidenceLevel": "Exact",
      "DistanceFromRoad": 0.003,
      "CrossStreet": null,
      "TimeZoneOffset": "GMT-4:00",
      "TimeZoneAbbreviation": "EDT",
      "IsDST": true
    },
    "LMiles": "2945.142",
    "TMiles": "2945.142",
    "LCostMile": "5690.99",
    "TCostMile": "5690.99",
    "LHours": "55:44",
    "THours": "55:44",
    "LTolls": "284.55",
    "TTolls": "284.55",
    "LEstghg": "9788.0",
    "TEstghg": "9788.0",
    "EtaEtd": null
  }],
  "TrafficDataUsed": false
}]

I’ve tried using multiple methods but to no avail. Here’s one i tried:

dataM = 'supplied json
var lastTMiles = dataM[0].ReportLines[dataM[0].ReportLines.length - 1].TMiles;

Here is my error:

Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at reqhttpM.onreadystatechange (mileage-finder.asp:280:60)

I’m not quite sure what to do here. Looking forward to responses. Thank you

Stripe Embedded Checkout Page Not Loading for First time on some devices

I am having a issue in my flask website. I have implemented Stripe Embedded Checkout into the website. But somehow on new devices when they hit checkout Stripe Checkout page doesn’t load just keeps showing loading and times out but if they attempt it second time it works just fine.

Is it a stripe issue or something which can be solved by making changes to flask file.

I havenot tried anything.

p5 sketch freezing every 2ish seconds

My p5.js sketch is freezing for a couple of frames every 2-3 seconds. I know p5 is not performant, but I feel like my sketch is optimized enough to not warrant this.

I think it may have to do with how the particles are handled when driving, so I used a particle pool, but that had no effect on performance. Here is my code

game.js:

const canvasSize = 400;
let car;

function setup() {
    frameRate(60);
    angleMode(RADIANS);
    createCanvas(canvasSize, canvasSize);
    noStroke();
    car = new Car(200, 200);     
}

function draw() {
    background(100, 100, 100);

    car.drawCar();
    car.drawGroundMarks();
    car.updatePoints();

    let turnDirection = 0;
    if (keyIsDown(LEFT_ARROW) || keyIsDown(65)) {
        turnDirection = -1;  // Turn left
    }

    if (keyIsDown(RIGHT_ARROW) || keyIsDown(68)) {
        turnDirection = 1;   // Turn right
    }

    car.rotateCar(turnDirection);

    if (keyIsDown(UP_ARROW) || keyIsDown(87)) {
        car.accelerateCar(1);
    }

    if (keyIsDown(DOWN_ARROW) || keyIsDown(83)) {
        car.accelerateCar(-1);
    }
}

car.js:

class Car {
    constructor(x, y, width = 40, height = 20, rotation = 0, speed = 0.05) {
        this.carX = x;
        this.carY = y;
        this.carW = width;  
        this.carH = height;
        this.carSpeed = speed;
        this.carRotation = rotation;
        this.maxSpeed = 9;
        this.carAcceleration = createVector(0, 0);
        this.carVelocity = createVector(0, 0);
        this.carPoints = [];
        this.color = [255, 0, 0];
        this.maxTurnSpeed = radians(20);  
        this.turnSpeed = 0;              
        this.turnAcceleration = radians(1);
        this.friction = 0.98;  // Friction to slow down car

        this.groundMarks = [];
        this.particlePool = new ParticlePool(); // Create the particle pool

    }

    drawCar() {
        // Draw the car body

        if (this.carPoints.length == 0)
            return;

        fill(...this.color);
        beginShape();
        this.carPoints.forEach(point => vertex(point.x, point.y));
        endShape(CLOSE);

        //fill(0, 0, 0);
        //ellipse(this.carPoints[0].x, this.carPoints[0].y, 5, 5); //back left wheel
        //ellipse(this.carPoints[3].x, this.carPoints[3].y, 5, 5); //back right wheel
        //ellipse(this.carPoints[2].x, this.carPoints[2].y, 5, 5); //front right wheel
        //ellipse(this.carPoints[1].x, this.carPoints[1].y, 5, 5); //front left wheel
        
        let windshieldLeftPoint = createVector((this.carPoints[0].x*.25 + this.carPoints[1].x*.75), (this.carPoints[0].y*.25 + this.carPoints[1].y*.75));
        let windshieldRightPoint = createVector((this.carPoints[3].x*.25 + this.carPoints[2].x*.75), (this.carPoints[3].y*.25 + this.carPoints[2].y*.75));
        fill(180, 180, 255);
        beginShape();
        vertex(this.carPoints[2].x, this.carPoints[2].y);
        vertex(this.carPoints[1].x, this.carPoints[1].y);
        vertex(windshieldLeftPoint.x, windshieldLeftPoint.y);
        vertex(windshieldRightPoint.x, windshieldRightPoint.y);
        endShape();

    }

    drawGroundMarks() {
        // Draw active particles
        this.groundMarks.forEach((mark) => {
            mark.draw();
        });

        // Remove dead particles and return them to the pool
        this.groundMarks = this.groundMarks.filter((mark) => {
            if (mark.dead) {
                this.particlePool.release(mark); // Return dead particles to the pool
                return false;
            }
            return true;
        });

        //console.log(this.groundMarks.length);
    }

    updatePoints() {
        this.carVelocity.add(this.carAcceleration);
        this.carVelocity.limit(this.maxSpeed);
        
        // Apply friction to gradually slow down the car when no acceleration
        this.carVelocity.mult(this.friction);

        this.carX += this.carVelocity.x;
        this.carY += this.carVelocity.y;
        this.carAcceleration.mult(0); // Reset acceleration after each frame

        let halfW = this.carW / 2;
        let halfH = this.carH / 2;

        let p1 = createVector(-halfW, -halfH); 
        let p2 = createVector(halfW, -halfH);  
        let p3 = createVector(halfW, halfH);   
        let p4 = createVector(-halfW, halfH);  

        this.carPoints = [p1, p2, p3, p4];

        this.carPoints.forEach(point => {
            let x = point.x;
            let y = point.y;
            let cosA = cos(this.carRotation);
            let sinA = sin(this.carRotation);
            let rotatedPoint = createVector(x * cosA - y * sinA, x * sinA + y * cosA);
            let translatedPoint = rotatedPoint.add(createVector(this.carX, this.carY));
            point.set(translatedPoint.x, translatedPoint.y);
        });
    }

    accelerateCar(direction) {
        let forwardVelocityX = this.carSpeed * direction * cos(this.carRotation);
        let forwardVelocityY = this.carSpeed * direction * sin(this.carRotation);
        this.carAcceleration.add(createVector(forwardVelocityX, forwardVelocityY));
        
        // Get recycled particles from the pool instead of creating new ones
        if (frameCount % 5 !== 0)
            return;
        
        this.groundMarks.push(this.particlePool.get(this.carPoints[0].x, this.carPoints[0].y));
        this.groundMarks.push(this.particlePool.get(this.carPoints[3].x, this.carPoints[3].y));
    }

    rotateCar(direction) {
        if (direction !== 0) {
            this.turnSpeed += this.turnAcceleration * direction;
            this.turnSpeed = constrain(this.turnSpeed, -this.maxTurnSpeed, this.maxTurnSpeed);
        } else {
            this.turnSpeed *= 0.9;
        }

        // If the car is moving, allow rotation, else stop turning
        if (this.carVelocity.mag() > 0.1) {
            this.carRotation += this.turnSpeed * (this.carVelocity.mag() / this.maxSpeed); // More natural turning at speed
        }
    }
}

drift particle.js

class driftParticle {
    constructor(x, y) {
        this.reset(x, y);
    }

    reset(x, y) {
        this.x = x;
        this.y = y;
        this.timeAlive = 0;
        this.alpha = 255;
        this.dead = false; // Reset dead flag
    }

    draw() {
        if (this.dead) return;
        
        this.alpha = 255 - this.timeAlive * 2;
        if (this.alpha <= 0) {
            this.dead = true;
        }
        fill(50, 50, 50, this.alpha);
        ellipse(this.x, this.y, 3, 3);
        this.timeAlive++;
    }
}

particle pool.js

class ParticlePool {
    constructor() {
        this.pool = [];
    }

    get(x, y) {
        let particle;
        if (this.pool.length > 0) {
            particle = this.pool.pop(); // Reuse an old particle if available
            particle.reset(x, y); // Reset its position and state
        } else {
            particle = new driftParticle(x, y); // Create a new one if none available
        }
        return particle;
    }

    release(particle) {
        this.pool.push(particle); // Return particle to the pool for reuse
    }
}

How to move a child element from one parent to another parent, and place it in a specific location on mobile resize?

Lets say I have this HTML:

<div class="wrapper">
    <div id="wrapperItems" class="container">
        <div class="row belowContent">
            <div class="favoriteContainer"></div>
            <div class="bottomExcerpt">
                <p>HTML links are hyperlinks. You can click on a link and jump to another document.</p>
             </div>
        </div>
    </div>
</div>

  
<div class="wrapperTwo">
    <div id="wrapperItemsTwo" class="container">
        <div class="row belowContent">
            <div class="picture">
                <div class="symbol"></div>
             </div>
             <div class="smallhyperlinks">
                <h2 class="hidden">H2 Text</h2>
             </div>
        </div>
    </div>
</div>

On mobile ONLY, I want to move bottomExcerpt from wrapper and place it in wrapperTwo after smallhyperlinks and before picture.

So basically the structure of wrapperTwo on mobile(580) will be smallhyperlinks -> bottomExcerpt -> picture.

How can I do this using jQuery?

I tried the following, but it doesn’t work properly:

$(window).resize(function () {
    if ($(window).width() < 580) {
        $('.wrapperTwo .picture').insertAfter('.wrapperTwo .smallhyperlinks');
        $('.smallhyperlinks h2').removeClass('hidden');
        if ($('.wrapper .bottomExcerpt').length > 0) {
            $('.wrapper .bottomExcerpt').insertAfter('.wrapperTwo .smallhyperlinks');
        }
    } 
    else 
    {
        $('.wrapperTwo .smallhyperlinks').insertAfter('.wrapperTwo .picture');
        $('.smallhyperlinks h2').addClass('hidden'); 
    }
});

For some reason, bottomExcerpt is showing up below picture, but I want it to show between smallhyperlinks and picture. How can I fix this issue?

discord bot using javascript+websocket – error code 4003 after sending heartbeat payload

so basically im trying to make a discord bot, pretty much from scratch or “writing a custom implementation”, as discord dev calls it. I’m using Websocket and node-js to make the whole thing, however I’m now stuck at the point that initiates the heartbeat with discords api, because the connection keeps terminating due to the error status code 4003 “Not Authenticated”.

This is what is logged when the connection closes:

Terminating Connection: 4003 Not authenticated. CloseEvent {Symbol(kTarget): WebSocket, Symbol(kType): ‘close’, Symbol(kCode): 4003, Symbol(kReason): ‘Not authenticated.’, Symbol(kWasClean): true}

And finally this is my code:
{ Thank you 🙂 }

import dotenv from "dotenv";
import Websocket from "ws";
import {fetchData} from "./index.js";

const version = "v=10";
const encoding = "encoding=json";
const opcode = {
    Dispatch:"0", 
    Heartbeat:"1", 
    Identify:"2", 
    Presence_Update:"3", 
    Voice_State_Update:"4", 
    Resume:"6", 
    Reconnect:"7", 
    Req_Guild_Members:"8", 
    Invalid_Session:"9", 
    Hello:"10", 
    Heartbeat_ACK:"11"}

fetchData("/gateway/bot", {method: "GET", redirect: "follow"}) // function imported from another js file, simply gets discords wss url
    .then((url) => {
        console.log(url);
        const newurl = url+`/?${version}&${encoding}`;
        const client = new Client(newurl);
    });

class Client {
    constructor(url) {
        this.url = url;
        this.client = new Websocket(url);
        this.identified = false
        this.client.onopen = (event) => {
            console.log("Connection Established! State:", this.client.readyState); 
        };
        this.client.onclose = (event) => {
            console.log("Terminating Connection:", event.code, event.reason, event)
        };
        this.client.addEventListener("message", (event) => {
            console.log("Message Received")
            this.handle_event(event)
        })

    }

    handle_event(event) {
        let data = this.parse(event.data);
        console.log(data);
        if(data.op == opcode.Hello || opcode.Heartbeat_ACK) {
            let interval = data.heartbeat_interval;
            let jitter = Math.random();
            let heartbeatInterval = interval * jitter;
            setTimeout(() => {
                console.log("Handled message event, data:", data, "interval:", heartbeatInterval)
                this.send_event(this.payloads(opcode.Heartbeat));
            }, heartbeatInterval
        )
        }
    }

    send_event(payload) {
        if(!this.identified) {
            this.client.send(this.payloads(opcode.Identify, {
                "token":process.env.DISCORD_TOKEN, 
                "intents":515, 
                "properties": {
                    "os":"windows", 
                    "browser":"chrome", 
                    "device":"chrome"}}
                ))
            console.log("identified with:", this.payloads(opcode.Identify, {
                "token":process.env.DISCORD_TOKEN, 
                "intents":515, 
                "properties": {
                    "os":"windows", 
                    "browser":"chrome", 
                    "device":"chrome"}}
                ))
            this.identified = true
        }
        if(this.identified) {
            console.log("sending payload:", payload)
            this.client.send(payload)
        }
    }

    parse(data) {
        let dataObject = {};
        JSON.parse(data, (key, value) => {
            dataObject[key] = value;
        });
        return dataObject;
    }

    payloads(op=null, d=null, s=null, t=null) {
        let payload = {
            "op": op,
            "d": d,
            "s": s,
            "t": t
        }
        return JSON.stringify(payload)
    }

}


I’ve tried sending the identify payload along with the heartbeat payload and even tried identifying before sending the heartbeat, but both return the same error.

On the pros and cons of multiple nesting in React component development

I’ve developed a React application for a book library based on what I learned in my university classes. The application manages a list of books, allowing users to view, rate, and delete books. I’ve structured my components as follows:

  • App.js (main component)
    • BookTable (renders the table of books)
      • BookTableRow (renders each row in the table)
        • StarRating (handles the star rating for each book)
          • Star (individual star component)

(App.js)

import './App.css';
import React, { useState, useEffect } from 'react';
import {books as bks} from './services/bookObject';
import BookTable from './components/bookTable';

function App() {
  const [books, updateBooks] = useState(bks);

  const initProcess = () => {
    const booksCurrent = books.map(book => ({
      ...book,
      rating: 0
    }));
    updateBooks(booksCurrent);
  };

  // execute only one time at first render
  useEffect(() => {
    initProcess();
  }, []);

  const handleDelete = (id) => {
    const booksCurrent = books.filter(book => book._id != id);
    updateBooks(booksCurrent);
  };

  const handleRating = (id, rating) => {
    const booksCurrent = books.map(book => {
      if (book._id === id) {
        book.rating = rating;
      }
      return book;
    });
    updateBooks(booksCurrent);

    console.log(books);
  }

  return (
    <div className="App">
      <h1>My Book Library</h1>
      <p>Showing {books.length} books</p>
      <BookTable
      books={books}
      handleDelete={handleDelete}
      handleRating={handleRating}/>
    </div>
  );
}

export default App;

(components/bookTable.jsx)

import React, { Component } from 'react';
import BookTableRow from './bookTableRow';


const BookTable = ({books, handleDelete = f => f, handleRating = f => f}) => {
    if (books.length === 0) {
        return (<p>There is no book infromation</p>);
    }
    return (
        <div className='books'>
            <table className="table">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Author</th>
                        <th>Number In Stock</th>
                        <th>Price</th>
                        <th>Year</th>
                        <th>Review</th>
                        <th>Action(s)</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        books.map((book, index) => (
                            <BookTableRow 
                            book={book}
                            onDelete={handleDelete}
                            onRating={handleRating}
                            />
                        ))
                    }
                </tbody>
            </table>
        </div>
    );
}

export default BookTable;

(components/bookTableRow.jsx)

import * as React from 'react';
import { Component } from 'react';

import StarRating from './starRating';

const BookTableRow = ({book, onDelete = f => f, onRating = f => f}) => {
    return (
        <tr>
            <td>{book._id}</td>
            <td>{book.title}</td>
            <td>{book.category.name}</td>
            <td>{book.author}</td>
            <td>{book.numberInStock}</td>
            <td>{book.price}</td>
            <td>{book.publishYear}</td>
            <td>
                <StarRating
                starCount={5}
                book={book}
                onRating={onRating}
            /></td>
            <td>
                <button className="btn btn-danger" onClick={() => onDelete(book._id)}>Delete</button>
            </td>
        </tr>
    );
}

export default BookTableRow;

(components/starRating.jsx)

import React, { Component, useState } from 'react';
import { FaStar } from 'react-icons/fa';

import { createArray } from '../services/createArray';
import Star from './star';

const StarRating = ({starCount, book, onRating = f => f}) => {

    return (
        <div>
            {
                createArray(starCount).map((n, i) => (
                    <Star 
                    book={book}
                    index={i}
                    isSelected={i < book.rating+1}
                    onClick={onRating}
                    />
                ))
            }
            <p> {book.rating+1} of {starCount} stars</p>
        </div>
    );
}
 
export default StarRating;

(components/star.jsx)

import React, { useState } from 'react';
import { FaStar } from 'react-icons/fa';

const Star = ({book, index, isSelected, onClick = f => f}) => {
    return (
        <div>
            <FaStar color={isSelected?"red": "gray"} onClick={() => onClick(book._id, index)}/>
        </div>
    );
}
 
export default Star;

services/bookObject.js

books = [
  (the list of book object)
]

export function getBooks() {
    return books;
}

(services/createArray.js)

import React, { Component } from 'react';

export const createArray = (length) => {
    return ([...Array(length)]);
}

My questions are:

  1. Is this level of component nesting (App > BookTable > BookTableRow > StarRating > Star) considered good practice in professional React development?
  2. Are there any potential issues or drawbacks with this approach?
  3. How might experienced React developers structure this differently, if at all?
  4. Are there any general guidelines for deciding when to create a new component versus keeping functionality in a parent component?

I’m looking to understand best practices in React component structuring as I transition from academic projects to professional development. Any insights or suggestions for improvement would be greatly appreciated.

Dynamic select option and checkbox

enter image description here

based on this picture i have project status select option and phase. just assume that statusId for completed == 1. in the recent code, i have a function that make if all checkbox checked, then the statusId changed. same as if only one of checkbox checked and none of it checked.

I WANT to make the select option to be connected function with phase checkbox. if the statusId go to completed then all checkbox will be checked and the progress will be 100%. but now if i create the function, it error and make my page lagging. i try ask chatGPT but still not working.


    <script>
        // Document ready event: ensures that the DOM is fully loaded before executing the script
        $(document).ready(function () {

            // Function to fetch and update phases based on the selected service ID
            function fetchAndUpdatePhases(serviceId) {
                if (serviceId) {
                    // If serviceId exists, make an AJAX request to fetch the phases
                    $.ajax({
                        type: 'POST',
                        url: 'get_phases.php',
                        data: { idserv: serviceId }, // Send service ID to server
                        success: function (html) {
                            // On success, update the phase list with the received HTML
                            $('#phases-list').html(html);
                        },
                        error: function (xhr, status, error) {
                            // Log errors if the request fails
                            console.error("Failed to fetch phases:", error);
                        }
                    });
                } else {
                    // If no serviceId, clear the phases list and reset the progress bar and percentage
                    $('#phases-list').html('');
                }
            }

            // When a department is selected or changed
            $('#iddept').change(function () {
                var deptId = $(this).val(); // Get selected department ID
                if (deptId) {
                    // If department ID exists, fetch associated services via AJAX
                    $.ajax({
                        type: 'POST',
                        url: 'get_services.php',
                        data: { iddept: deptId }, // Send department ID to server
                        success: function (html) {
                            // On success, populate the service dropdown with the returned HTML
                            $('#idserv').html(html);
                            // Clear phases since the department has changed
                            fetchAndUpdatePhases(null);
                        },
                        error: function (xhr, status, error) {
                            // Log errors if the request fails
                            console.error("Failed to fetch services:", error);
                        }
                    });
                } else {
                    // If no department is selected, reset the service dropdown and clear phases
                    $('#idserv').html('<option selected disabled>Select a service</option>');
                    fetchAndUpdatePhases(null);
                }
            });

            // When a service is selected, fetch its phases
            $('#idserv').change(function () {
                var serviceId = $(this).val();
                // Reset progress bar, percentage, and colors when service is changed
                $('#percentage').text('--%');
                $('#progress-bar').attr('stroke-dasharray', '0 100');
                $('#total_percentage').val(0);

                // Reset color to red (0% progress)
                var resetColor = `rgb(255, 0, 0)`;
                $('#progress-bar').css('stroke', resetColor);
                $('#percentage').css('color', resetColor);
                $('#prog').css('color', resetColor);
                $('#circle').css('color', `rgba(255, 0, 0, 0.4)`);
                fetchAndUpdatePhases(serviceId);
            });

            // Event listener for phase checkboxes
            $(document).on('change', '.phase-checkbox', function () {
                var selectedPhases = [];
                
                // Collect all checked phases
                $('.phase-checkbox:checked').each(function () {
                    selectedPhases.push($(this).val());
                });

                if (selectedPhases.length > 0) {
                    // If there are selected phases, calculate the percentage via AJAX
                    $.ajax({
                        type: 'POST',
                        url: 'get_percentage.php',
                        data: { phases: selectedPhases.join(',') }, // Send the selected phases as a comma-separated string
                        success: function (response) {
                            var data = JSON.parse(response);
                            var percentage = data.percentage; // Get the calculated percentage

                            // Update the percentage text and input value
                            $('#percentage').text(percentage + '%');
                            $('#total_percentage').val(percentage);
                            
                            // Calculate and update the progress bar based on the percentage
                            var strokeValue = (percentage / 100) * 75; // Max is 75 for full progress
                            $('#progress-bar').attr('stroke-dasharray', strokeValue + ' 100');

                            // Dynamically calculate color for the progress bar (red to green transition)
                            var red = Math.max(255 - (percentage * 2.55), 0); // Red decreases as percentage increases
                            var green = Math.min(percentage * 2.55, 255); // Green increases as percentage increases
                            var color = `rgb(${red}, ${green}, 0)`; // Combine red and green for a smooth transition
                            
                            // Apply the color transition to relevant elements
                            $('#progress-bar').css('stroke', color);
                            $('#percentage').css('color', color);
                            $('#prog').css('color', color);
                            $('#circle').css('color', `rgba(${red}, ${green}, 0, 0.4)`); 

                            // If percentage is 100%, mark status as completed and disable status change
                            if (percentage === 100) {
                                $('#idstatus').val('1').trigger('change'); // Completed status
                                $('#idstatus').prop('disabled', true);
                            } else {
                                $('#idstatus').val('3').trigger('change'); // In-progress status
                                $('#idstatus').prop('disabled', false);
                            }
                        },
                        error: function (xhr, status, error) {
                            // Log errors if the request fails
                            console.error("Failed to fetch percentage:", error);
                        }
                    });
                } else {
                    // If no phases are selected, reset the progress bar and percentage
                    $('#percentage').text('--%');
                    $('#progress-bar').attr('stroke-dasharray', '0 100');
                    $('#total_percentage').val(0);

                    // Reset color to red (0% progress)
                    var resetColor = `rgb(255, 0, 0)`;
                    $('#progress-bar').css('stroke', resetColor);
                    $('#percentage').css('color', resetColor);
                    $('#prog').css('color', resetColor);
                    $('#circle').css('color', `rgba(255, 0, 0, 0.4)`);
                    
                    // Reset the status to default (in-progress)
                    $('#idstatus').val('2').trigger('change');
                }
            });

            // Submit form with selected phases as a hidden input value
            $('#signUpForm').on('submit', function () {
                var selectedPhases = [];
                
                // Collect all checked phases before submission
                $('.phase-checkbox:checked').each(function () {
                    selectedPhases.push($(this).val());
                });
                $('#selected_phases').val(selectedPhases.join(',')); // Set the hidden field value
                
                this.submit(); // Submit the form
            });
        });

        // Additional document ready function for handling status change and completion date checks
        $(document).ready(function () {

            // Function to handle status change and toggle the completion date field
            function handleStatusChange(statusId) {
                if (statusId === '1') {
                    // Show the completion date input and make it required
                    $('#completion-date').removeClass('hidden');
                    $('#completion-date').find('input').attr('required', 'required');
                    checkCompletionDate();
                } else {
                    // Hide the completion date input and remove required attribute
                    $('#completion-date').addClass('hidden');
                    $('#completion-date').find('input').removeAttr('required').val('');
                    $('#overdue-label').addClass('hidden');
                }
            }

            // Function to check if the completion date is overdue
            function checkCompletionDate() {
                var completionDateStr = $('#completion_date').val();
                var endDateStr = $('#endd').val(); // Get the project's end date

                if (completionDateStr && endDateStr) {
                    var completionDate = new Date(completionDateStr);
                    var endDate = new Date(endDateStr);

                    // Show overdue label if completion date is after the end date
                    if (completionDate > endDate) {
                        $('#overdue-label').removeClass('hidden');
                    } else {
                        $('#overdue-label').addClass('hidden');
                    }
                }
            }

            // Initial setup for the status change handling when the page loads
            var initialStatusId = $('#idstatus').val();
            handleStatusChange(initialStatusId);

            // Event listener for status change
            $('#idstatus').change(function () {
                var statusId = $(this).val();

                if (statusId === '1') {
                    $('.phase-checkbox').prop('checked', true);  // Check all checkboxes
                } else{
                    $('.phase-checkbox').prop('checked', false).trigger('change');
                }
                handleStatusChange(statusId);
            });

            // Event listener for completion date change
            $('#completion_date').change(function () {
                checkCompletionDate();
            });
        });
    </script>

Difference between Arrow function and normal function in JavaScript [duplicate]

I’m a newbie trying to learn JavaScript. Can I know what is the difference between the arrow function and normal function.

Normal function:
function example(){}

Arrow function:
const example = () => {}

There is also this thing called Empty Arrow Function example(() => {});, that I don’t understand. Please help me.

I tried doing my own research and ask chatGPT about it. I don’t clearly understand. I expect to have a simple explanation with example if possible.

How do I parse a value from a data attribute in Cypress?

I have an input field:

<input type="range" id="amtRange" value="0" min="280" max="1400">

I want to get the value of the min attribute and see if it is less than another pre-existing value, eg:

The amount in the min attribute (280) should be less than the number in the ‘amt’ variable.

I can get the value as a string as such:

cy.get('#amtRange').invoke('attr', 'min');

But cannot figure out how to pass it as an integer. I have tried the following:

const amt = 286;
let minAmt = cy.get('#amtRange').invoke('attr', 'min');
minAmt = parseInt(minAmt);
minAmt.should('be.lessThan', amt);

But this produces the error: TypeError: minAmt.should is not a function.

I have also tried:

const amt = 286;
cy.get('#amtRange').then(($amtInput) => {
    let minAmt = parseInt($amtInput.invoke('attr', 'min'));
    minAmt.should('be.lessThan', amt);
});

But this produces the error: $amtInput.invoke is not a function.

Would anyone know how I can achieve this?

Replace special character only between square brackets by regex and asp classic

I need replace special character only between square brackets [ ] by Regex and asp classic if may

StrPost :
“Hello [Good morning] and [good day] , this year is [2024] and israel killed ( 20000 ) childrens and [20000 womans] in Gaza and Palestine and Lebanon only in 12 months, it is not Good news”

i need Only Replace word “good” to “bad” and number “2” to “3” in between square brackets [ ] , i should not change another word or number outside square brackets

Output :
“Hello [bad morning] and [bad day] , this year is [3034] and israel killed ( 20000 ) childrens and [30000 womans] in Gaza and Palestine and Lebanon only in 12 months, it is not Good news”

i try this code but replace all content in [square brackets] to number 3 and is not good for me , i need change some of number and character between square brackets, not all words

`<%
Function RemoveSpace( strText )
Dim RegEx

Set RegEx = New RegExp

RegEx.Pattern = "[.*?]"
RegEx.Global = True

RemoveSpace = RegEx.replace(strText,”3″)

End Function

StrPost_excerpt = RemoveSpace(StrPost)

response.write StrPost_excerpt
%>`