Can i fire Magento2 MirasvitGtm events on page load?

I have installed MirasvitGtm module for GA4, and
I Had checkout MagePlaza module , there was events such as begin_checkout , add_shiping_data and so on , which are fired on checkout page , but i had an upgrade to new Hyva Theme checkout module , and the events are not firing , so any idea where to look ?

tried to look the events firing on mirasvitGtm module itself and in checkout observers files

Draw a static 3D cube using WebGL

I just started learning WebGL and I am trying to draw a simple 3d cube. I followed a tutorial that showed how to draw a rotating cube, but I can’t figure out how to make it static, but still be able to see that it’s 3d. I know that I have to introduce the rotation matrix somewhere in my code, but I have tried multiple times and I don’t know how to do that. I could really use some help, thank you! Also, I can use the gl-matrix and webgl-utils.js libraries, along with some helper functions in order to initialize WebGL/load shaders, but I am not allowed to use Three.js.

This is my code:

var vertexShaderText = [
    'precision mediump float;', 
    '',
    'attribute vec3 vertPosition;', 
    'attribute vec3 vertColor;',
    'varying vec3 fragColor;',
    'uniform mat4 mWorld;',
    'uniform mat4 mView;',
    'uniform mat4 mProj;',
    '',
    'void main()',
    '{',
    'fragColor = vertColor;',
    'gl_Position = mProj * mView * mWorld * vec4(vertPosition, 1.0);',
    '}'
].join('n');

var fragmentShaderText = [
    'precision mediump float;',
    '',
    'varying vec3 fragColor;',
    'void main()',
    '{',
    'gl_FragColor = vec4(fragColor, 1.0);', 
    '}'
].join('n');

var InitDemo = function() {
    console.log("working");

    var canvas = document.getElementById('game-surface');
    var gl = canvas.getContext('webgl');

    if (!gl) {
        console.log('WebGL not supported, falling back on experimental-webgl')
        gl = canvas.getContext('experimental-webgl');
    }

    if (!gl) {
        alert('Your browser does not support WebGL')
    }

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    gl.viewport(0, 0, window.innerWidth, window.innerHeight);

    gl.clearColor(0.75, 0.85, 0.8, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.CULL_FACE);
    gl.frontFace(gl.CCW);
    gl.cullFace(gl.BACK);

    var vertexShader = gl.createShader(gl.VERTEX_SHADER);
    var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);

    gl.shaderSource(vertexShader, vertexShaderText);
    gl.shaderSource(fragmentShader, fragmentShaderText);

    gl.compileShader(vertexShader);
    if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
        console.error('ERROR compiling vertex shader!', gl.getShaderInfoLog(vertexShader));
        return;
    }
    gl.compileShader(fragmentShader);
    if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
        console.error('ERROR compiling fragment shader!', gl.getShaderInfoLog(fragmentShader));
        return;
    }

    var program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);

    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        console.error('ERROR linking program', gl.getProgramInfoLog(program));
        return;
    }
    gl.validateProgram(program);
    if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)) {
        console.error('ERROR validating program', gl.getProgramInfoLog(program));
        return;
    }

    var boxVertices = [
        // Top
        -1.0, 1.0, -1.0, 0.5, 0.5, 0.5, -1.0, 1.0, 1.0, 0.5, 0.5, 0.5,
        1.0, 1.0, 1.0, 0.5, 0.5, 0.5,
        1.0, 1.0, -1.0, 0.5, 0.5, 0.5,

        // Left
        -1.0, 1.0, 1.0, 0.75, 0.25, 0.5, -1.0, -1.0, 1.0, 0.75, 0.25, 0.5, -1.0, -1.0, -1.0, 0.75, 0.25, 0.5, -1.0, 1.0, -1.0, 0.75, 0.25, 0.5,

        // Right
        1.0, 1.0, 1.0, 0.25, 0.25, 0.75,
        1.0, -1.0, 1.0, 0.25, 0.25, 0.75,
        1.0, -1.0, -1.0, 0.25, 0.25, 0.75,
        1.0, 1.0, -1.0, 0.25, 0.25, 0.75,

        // Front
        1.0, 1.0, 1.0, 1.0, 0.0, 0.15,
        1.0, -1.0, 1.0, 1.0, 0.0, 0.15, -1.0, -1.0, 1.0, 1.0, 0.0, 0.15, -1.0, 1.0, 1.0, 1.0, 0.0, 0.15,

        // Back
        1.0, 1.0, -1.0, 0.0, 1.0, 0.15,
        1.0, -1.0, -1.0, 0.0, 1.0, 0.15, -1.0, -1.0, -1.0, 0.0, 1.0, 0.15, -1.0, 1.0, -1.0, 0.0, 1.0, 0.15,

        // Bottom
        -1.0, -1.0, -1.0, 0.5, 0.5, 1.0, -1.0, -1.0, 1.0, 0.5, 0.5, 1.0,
        1.0, -1.0, 1.0, 0.5, 0.5, 1.0,
        1.0, -1.0, -1.0, 0.5, 0.5, 1.0,
    ];

    var boxIndices = [
        // Top
        0, 1, 2, 
        0, 2, 3,

        // Left
        5, 4, 6,
        6, 4, 7,

        // Right
        8, 9, 10,
        8, 10, 11,

        // Front
        13, 12, 14,
        15, 14, 12,

        // Back
        16, 17, 18,
        16, 18, 19,

        // Bottom
        21, 20, 22,
        22, 20, 23
    ];

    var boxVertexBufferObject = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, boxVertexBufferObject);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(boxVertices), gl.STATIC_DRAW);

    var boxIndexBufferObject = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boxIndexBufferObject);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(boxIndices), gl.STATIC_DRAW);

    var positionAttribLocation = gl.getAttribLocation(program, 'vertPosition');

    var colorAttribLocation = gl.getAttribLocation(program, 'vertColor');

    gl.vertexAttribPointer(
        positionAttribLocation, 
        3,
        gl.FLOAT, 
        gl.FALSE, 
        6 * Float32Array.BYTES_PER_ELEMENT, 
        0 // offset from the beginning of a single vertex to this attribute
    );

    gl.vertexAttribPointer(
        colorAttribLocation, 
        3, 
        gl.FLOAT, 
        gl.FALSE,
        6 * Float32Array.BYTES_PER_ELEMENT, 
        3 * Float32Array.BYTES_PER_ELEMENT 
    );

    gl.enableVertexAttribArray(positionAttribLocation);

    gl.enableVertexAttribArray(colorAttribLocation);

    gl.useProgram(program);

    var matWorldUniformLocation = gl.getUniformLocation(program, 'mWorld');
    var matViewUniformLocation = gl.getUniformLocation(program, 'mView');
    var matProjUniformLocation = gl.getUniformLocation(program, 'mProj');

    var worldMatrix = new Float32Array(16);
    var viewMatrix = new Float32Array(16);
    var projMatrix = new Float32Array(16);
    glMatrix.mat4.identity(worldMatrix);
    glMatrix.mat4.lookAt(viewMatrix, [0, 0, -8], [0, 0, 0], [0, 1, 0]);
    glMatrix.mat4.perspective(projMatrix, glMatrix.glMatrix.toRadian(45), canvas.width / canvas.height, 0.1, 1000.0);

    gl.uniformMatrix4fv(matWorldUniformLocation, gl.FALSE, worldMatrix);
    gl.uniformMatrix4fv(matViewUniformLocation, gl.FALSE, viewMatrix);
    gl.uniformMatrix4fv(matProjUniformLocation, gl.FALSE, projMatrix);

    var angle = 0;
    var identityMatrix = new Float32Array(16);
    glMatrix.mat4.identity(identityMatrix);
   
    gl.clearColor(0.75, 0.85, 0.8, 1.0);
    gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);

    gl.drawElements(gl.TRIANGLES, boxIndices.length, gl.UNSIGNED_SHORT, 0);
}

Why I can’t open the Textfield when button iss clicked?

So I’m getting the choice.toggle so if it is a Yes it should be open, but the textarea is not opening, yet the handleClick says its open.

enter image description here

  const handleClick = (choice) => {
    console.log(choice.toggle)
    if (choice.toggle === 'Yes') {
      console.log('Open')
      setIsOpen(!isOpen);
    }
  };


<label className="toggle-button"  onClick={() => handleClick(choice)}>
                    <input className="toggle-button__state" type="radio" name="choice" value={choice.question_choices} onChange={handleChange} />
                    <span className="toggle-button__text">{choice.toggle}</span>
                  </label>
                  {isOpen && choice.toggle === 'Yes' &&
                    <input type="text" style={{height: '200px', width: '200px'}} name="text-field" />
                  }

Adding a number using a checkboxes

i have made a menu around 20 items and i want to add their price by checkboxes on the web ?
i dont know how to manage this ?
how to merge their name and price together?

var valueList = document.getElementById ('valueList');
var text = '<span> You have selected : </span>';
var listArray = [];

var checkboxes = document.querySelectorAll('.checkbox');

for (var checkbox of checkboxes ) {
  checkbox.addEventListener('click',function (){
  if(this.checked == true) {
    listArray.push(this.value);
    valueList.innerHTML = text + listArray.join(" / " );
  }
  else {
    listArray = listArray.filter(e => e !== this.value);
    valueList.innerHTML = text + listArray.join(' / ');
  }
})

Onclick function deleting all HTML elements

<!DOCTYPE html>

<html>
<head>
</head>

  <button id="someid" onclick="open()">Open A Booster Pack</button>
  <button id="somid" onclick="view()">View Garage</button>
<body>
  <p id="demo"></p>
</body>
<script>
  function open(){
  itms = ['2014 Nissan 350z', '2019 VW golf GTI ', '1995 Mazda 323 Protoge', '1990 BMW 8-series', '1990 ford mustang svt cobra', '1990 mazda rx7', '1990 nissan skyline gt-r'];
itm = itms[Math.floor(Math.random()*itms.length)];
    console.log(itm)
}
  function view(){
    document.getElementById("demo").innerHTML = ""+itm+""
  }
</script>
</html>

I have no idea why all the elements dissapear, even the DOCTYPE declaration vanishes when either button is clicked, for those who want to know I am trying to make a car collection card game website.

TypeScript error with object properties possibly undefined despite checking for undefined values using Object.values()

I have an interface MentionItem with id and value properties, both of which are required to be strings. However, TypeScript is giving me an error that these properties are possibly string | undefined.

When I manually check that id and value are not undefined, TypeScript is happy. However, when I use Object.values(dataset).includes(undefined) to check for undefined values, TypeScript still complains.

Why is TypeScript giving me this error, and how can I fix it?

Here’s my code:
  interface MentionItem {
    id: string;
    value: string;
  }

  getItemData = (): MentionItem => {
    const dataset = (this.mentionList.childNodes[this.itemIndex] as HTMLElement).dataset;

    if(Object.values(dataset).includes(undefined)) {
      throw new Error("Incomplete dataset")
    }

    return {
      id: dataset.id,
      value: dataset.value,
    };
  };
And here is the TS Error:

Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322)

I am trying to understand why this gives me an error, since it should achieve the same thing, please correct me if I am wrong:

The check that satisfies TypeScript

if(dataset.id === undefined || dataset.value === undefined) {
  throw new Error("Incomplete dataset")
}

The check that upsets TypeScript

if(Object.values(dataset).includes(undefined)) {
  throw new Error("Incomplete dataset")
}

NextJS too many redis clients – How to handle with one client?

Introduction

Hey 🙂

I created a next app for a discord web-dashboard and use redis as my database.


The main Problem

Every time I make an axios request to one of my docs in the api folder, where a redis client is needed, a new redis client connects to my database.


What did I try already?

I tried it with .quit() after my requests and I tried to add redis into the SessionProvider. But there I had the problem, that the redis property was undefined on the browsers console/clientsided. On my IDE console/serversided, it wasn’t undefined.

I wanted to paste the redis property through the SessionProvider but I got the error “Module not found: dns” every time when I hadn’t previously queried whether typeof window was undefined when creating the redis client.


My questions

  1. Why does this not work with .quit()?
  2. Is there a better/easier way to prevent connecting many redis clients to my db?
  3. How do you handle this?

Thanks for answers and sorry when I messed up things, I am new in next and I wanna learn 🙂


Code

My _app.js:

import '@/styles/globals.css'
import '@/styles/custom.css'

import { SessionProvider } from "next-auth/react"

export default function App({
  Component, pageProps: { session, ...pageProps }
}) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps}/>
    </SessionProvider>
  )
}

My connection.js:

import getConfig from 'next/config';
const { serverRuntimeConfig } = getConfig();
const { REDIS_HOST, REDIS_PORT, REDIS_PASSWORD } = serverRuntimeConfig;

let redis = null;

if (!redis) {
    const Redis = require('ioredis');
    redis = new Redis({
        host: REDIS_HOST,
        port: REDIS_PORT,
        password: REDIS_PASSWORD
    });
}

export default redis

addItemToBlacklist.js from API Folder:

import client from '../../database/connection'


const addToBlacklist = async (nick) => {
  client.rpush(['blacklist', nick]).then(() => {
    client.quit();
  });
};

export default async function handler(req, res) {
  console.log(req.query.addnick)
  const nick = req.query.addnick;
  await addToBlacklist(nick);
  res.status(200).json({ status: "OK" });
}

The Axios request from my BlacklistCard.js:

const addNick = (props) => {
        axios.post("/api/addItemToBlacklist?addnick=" + props)
    }

SvelteKit & Firebase Auth, Two output files share the same path but have different contents?

I keep getting the error whenever I import import { createUserWithEmailAndPassword } from "firebase/auth";

Two output files share the same path but have different contents: node_modules.vitedeps_temp_0b51b981firebase_auth.js

I’ve checked all my imports and there are no duplicates, I also checked for capitalization and found no abnormalities. Does anyone else have this issue?

I’ll include all my code related to firebase below:

firebase.js

import { initializeApp } from "firebase/app";

import { collection, doc, getFirestore } from "firebase/firestore/lite";


const firebaseConfig = {
  (deleted)
};


const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const userDoc = (userId) => doc(db, "users", userId);
export {
    auth,
}

login.svelte

<script>
    import { createEventDispatcher } from 'svelte';
    let email, password;
    const dispatcher = createEventDispatcher()
    function login() {
        dispatcher('login', {
            email,
            password
        })
    }
</script>

auth/+page.svelte

<script>
    import Login from "../../utilities/login.svelte";
    import { signInWithEmailAndPassword } from "firebase/auth";
    import { auth, userDoc } from "../../firebase";
    import { goto } from "$app/navigation";
    import { setDoc } from "firebase/firestore/lite";
    export let errors;


    async function signIn(event) {
        try {
            let user = await signInWithEmailAndPassword(auth, event.detail.email, event.detail.password)
            await setDoc(userDoc(auth.currentUser.uid), { username: user.user.displayName, email: user.user.email })
            await goto("/admin")
        } catch (error) {
            console.log("Error signing in: ", error)
        }
    }
</script>

EDIT: I feel like I should mention none of these are in the same folder.

How to dynamically import a module or a resource using webpack?

I’m writing a single page web application that is built using webpack, but dynamic import of resources just doesn’t work in webpack because it replaces the original relative path in the generated code with “./”.

For example:
I have a few *.html files in the “./resources” subfolder and want to import them dynamically.
So I do something like this:

const s = "file_name";
import( `./resources/${s}.html` ).then( (file)=>console.log( file.default ) );

Pretty simple and nearly exactly as it’s described in webpack’s documentation.
But when the code is executed, I just get a runtime error:

Uncaught (in promise) Error: Cannot find module ‘./file_name.html’

As you can see, the module’s path disappeared and has been replaced with “./”.
And when I see webpacks’s “–stats-modules-space” output I see the next:

modules by path ./src/resources/ 320 bytes
     ./src/resources/ lazy ^./file_name.*.html$ namespace object 160 bytes [built] 
[code generated]

The imported resource is processed and included into the bundle, but the path to the resource is replaced with “./”
And if I change the code to:

import( `./resources/file_name.html` ).then( (file)=>console.log( file.default ) );

Everything works as expected.

Why does webpack replace the real path with “./” and how can dynamic import be used in practice? The documentation and examples there seem pretty clear and simple regarding this.

Added:
If there is no file extension specified and the imported files are not resources but JS-modules (the files themselves have a “.js” extensions) then everything works as expected.
I mean that everything is OK if the file is “./resources/file_name.js” and the code is:

const s = "file_name";
import( `./resources/${s}` ).then( (file)=>console.log( file.default ) );

Everything is perfect. And yes, I have correct rules for “.html” files being imported and it doesn’t work if I specify asset type with resource queries or even with the good old loader (“raw-loader!…”).

Added:
As I already investigated, the relative dynamic import works only for “real” js-modules and seems broken for any resources.
Now I am a bit worried that I can’t find any bug report for that.

Opencv in Javascript

I am working on making a quick project that counts reps of a bicep curl in mediapipe and opencv. I finished making it in python but I also want to make the Javascript equivalent of it. I looked at some documentation but there isn’t much stuff on how to do certain things, like display text, make rectangles, and more. I am also new to javascript so I need some help understanding the syntax of it

Here is my python code that I want to replicate in js:

import cv2
import mediapipe as mp
import numpy as np
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose

# Video feed
cap = cv2.VideoCapture(0)

# Counter 
counter = 0
stage = None
prev_left_shoulder = None
prev_right_shoulder = None
shoulder_moving = False

def calculate_angles(a, b, c):
    a = np.array(a)
    b = np.array(b)
    c = np.array(c)

    radians = np.arctan2(c[1] - b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0])
    angle = np.abs(radians * 180.0/np.pi)
    
    if angle > 180.0:
        angle = 360-angle
    
    return angle


# Change confidence to be tighter on user's form
with mp_pose.Pose(min_detection_confidence=0.8, min_tracking_confidence=0.6) as pose:
    while cap.isOpened():
        ret, frame = cap.read()

        # Recolor to RGB
        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        image.flags.writeable = False # Improves Performance

        # Detection
        results = pose.process(image)

        # Recolor back to BGR
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Improves Performance

        # Extract Landmarks
        try:
            landmarks = results.pose_landmarks.landmark

            #Checking if shoulder moves
            left_shoulder = [landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y]
            right_shoulder = [landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].y]
            if prev_left_shoulder is not None and prev_right_shoulder is not None:
                left_dx = left_shoulder[0] - prev_left_shoulder[0]
                left_dy = left_shoulder[1] - prev_left_shoulder[1]
                right_dx = right_shoulder[0] - prev_right_shoulder[0]
                right_dy = right_shoulder[1] - prev_right_shoulder[1]
                if abs(left_dx) > 0.05 or abs(left_dy) > 0.05 or abs(right_dx) > 0.05 or abs(right_dy) > 0.05:
                    shoulder_moving = True
                    
            prev_left_shoulder = left_shoulder
            prev_right_shoulder = right_shoulder

            # Bicep Curl
            left_shoulder = [landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y]
            left_elbow = [landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y]
            left_wrist = [landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y]
            left_hip = [landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].x, landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].y]
            left_distance = np.sqrt((left_elbow[0] - left_hip[0])**2 + (left_elbow[1] - left_hip[1])**2)
            angle_left = calculate_angles(left_shoulder, left_elbow, left_wrist)
            cv2.putText(image, str(round(angle_left)), tuple(np.multiply(left_elbow, [1280, 720]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)

            right_shoulder = [landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value].y]
            right_elbow = [landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value].y]
            right_wrist = [landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value].y]
            right_hip = [landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].x, landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value].y]
            right_distance = np.sqrt((right_elbow[0] - right_hip[0])**2 + (right_elbow[1] - right_hip[1])**2)
            angle_right = calculate_angles(right_shoulder, right_elbow, right_wrist)
            cv2.putText(image, str(round(angle_right)), tuple(np.multiply(right_elbow, [1280, 720]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
            # cv2.putText(image, str(right_distance), tuple(np.multiply(right_elbow, [1280, 720]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)

            # Curling logic
            if not shoulder_moving:
                if left_distance < 0.4 and right_distance < 0.4:
                    if angle_left > 150 and angle_right > 150:
                        stage = "extended"
                    elif angle_left < 165 and angle_right < 165 and stage == "compressed":
                        cv2.rectangle(image, (0, 650), (1280, 720), (255, 255, 255), -1)
                        text = "Extend arms fully"
                        cv2.putText(image, text, (50, 700), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)

                    if (angle_left < 25 and stage == "extended") and (angle_right < 25 and stage == "extended"):
                        stage = "compressed"
                        counter += 1
                    elif angle_left > 25 and angle_right > 25 and stage == "extended":
                        cv2.rectangle(image, (0, 650), (1280, 720), (255, 255, 255), -1)
                        text = "Contract arms fully"
                        cv2.putText(image, text, (40, 700), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)
                else:
                    cv2.rectangle(image, (0, 650), (1280, 720), (0, 0, 0), -1)
                    text = "Elbows should be tucked"
                    cv2.putText(image, text, (40, 700), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
            else:
                shoulder_moving = False

        except Exception as err:
            pass


        # Counter text
        cv2.rectangle(image, (0, 0), (225, 73), (51, 68, 255), -1)
        cv2.putText(image, "REPS: ", (15, 12), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
        cv2.putText(image, str(counter), (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 0), 2, cv2.LINE_AA)

        # Rendering connections
        mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,
            mp_drawing.DrawingSpec(color=(56, 55, 54), thickness=2, circle_radius=2),
            mp_drawing.DrawingSpec(color=(51, 68, 255), thickness=2, circle_radius=2)
        )

        cv2.imshow('Cam', image)

        if cv2.waitKey(10) & 0xFF == ord("q"):
            break

    cap.release()
    cv2.destroyAllWindows()

here is the javascript I have written so far:

const video5 = document.getElementsByClassName('input_video5')[0];
const out5 = document.getElementsByClassName('output5')[0];
const controlsElement5 = document.getElementsByClassName('control5')[0];
const canvasCtx5 = out5.getContext('2d');

const fpsControl = new FPS();

const spinner = document.querySelector('.loading');
spinner.ontransitionend = () => {
  spinner.style.display = 'none';
};

function zColor(data) {
  const z = clamp(data.from.z + 0.5, 0, 1);
  return `rgba(0, ${255 * z}, ${255 * (1 - z)}, 1)`;
}

function onResultsPose(results) {
  document.body.classList.add('loaded');
  fpsControl.tick();

  canvasCtx5.save();
  canvasCtx5.clearRect(0, 0, out5.width, out5.height);
  canvasCtx5.drawImage(
      results.image, 0, 0, out5.width, out5.height);
  drawConnectors(
      canvasCtx5, results.poseLandmarks, POSE_CONNECTIONS, {
        color: (data) => {
          const x0 = out5.width * data.from.x;
          const y0 = out5.height * data.from.y;
          const x1 = out5.width * data.to.x;
          const y1 = out5.height * data.to.y;

          const z0 = clamp(data.from.z + 0.5, 0, 1);
          const z1 = clamp(data.to.z + 0.5, 0, 1);

          const gradient = canvasCtx5.createLinearGradient(x0, y0, x1, y1);
          gradient.addColorStop(
              0, `rgba(0, ${255 * z0}, ${255 * (1 - z0)}, 1)`);
          gradient.addColorStop(
              1.0, `rgba(0, ${255 * z1}, ${255 * (1 - z1)}, 1)`);
          return gradient;
        }
      });
  drawLandmarks(
      canvasCtx5,
      Object.values(POSE_LANDMARKS_LEFT)
          .map(index => results.poseLandmarks[index]),
      {color: zColor, fillColor: '#FF0000'});
  drawLandmarks(
      canvasCtx5,
      Object.values(POSE_LANDMARKS_RIGHT)
          .map(index => results.poseLandmarks[index]),
      {color: zColor, fillColor: '#00FF00'});
  drawLandmarks(
      canvasCtx5,
      Object.values(POSE_LANDMARKS_NEUTRAL)
          .map(index => results.poseLandmarks[index]),
      {color: zColor, fillColor: '#AAAAAA'});
  canvasCtx5.restore();
}

const pose = new Pose({locateFile: (file) => {
  return `https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/${file}`;
}});
pose.onResults(onResultsPose);

const camera = new Camera(video5, {
  onFrame: async () => {
    await pose.send({image: video5});
  },
  width: 480,
  height: 480
});
camera.start();

new ControlPanel(controlsElement5, {
      selfieMode: true,
      upperBodyOnly: false,
      smoothLandmarks: true,
      minDetectionConfidence: 0.5,
      minTrackingConfidence: 0.5
    })
    .add([
      new StaticText({title: 'MediaPipe Pose'}),
      fpsControl,
      new Toggle({title: 'Selfie Mode', field: 'selfieMode'}),
      new Toggle({title: 'Upper-body Only', field: 'upperBodyOnly'}),
      new Toggle({title: 'Smooth Landmarks', field: 'smoothLandmarks'}),
      new Slider({
        title: 'Min Detection Confidence',
        field: 'minDetectionConfidence',
        range: [0, 1],
        step: 0.01
      }),
      new Slider({
        title: 'Min Tracking Confidence',
        field: 'minTrackingConfidence',
        range: [0, 1],
        step: 0.01
      }),
    ])
    .on(options => {
      video5.classList.toggle('selfie', options.selfieMode);
      pose.setOptions(options);
    });

How can I make the js equivalent of the python code i had, with the rectangles, text, and logic.

Expo + Firebase how activate AppCheck

I am building an App with Expo + Firebase sdk and want to implement AppCheck now. How can i implement it into the App? How can I create an AppChestCustomProvider for IOS(DeviceCheck) and Android(Play Integrity)? How do i get the tokenFromServer and expireTimeMillis for both?
Is there maybe a complete different approach to this issue?

import { initializeAppCheck, ReCaptchaV3Provider, CustomProvider } from "firebase/app-check"


    const appCheckCustomProvider = new CustomProvider({
     getToken: () => {
    return new Promise((resolve, _reject) => {
      // TODO: Logic to exchange proof of authenticity for an App Check token and
      // expiration time.

      // ...

      const appCheckToken = {
        token: tokenFromServer,
        expireTimeMillis: expirationFromServer * 1000
      };

      resolve(appCheckToken);
    });
  }
});

// Pass your reCAPTCHA v3 site key (public key) to activate(). Make sure this
// key is the counterpart to the secret key you set in the Firebase console.
const appCheck = initializeAppCheck(app, {
  provider: appCheckCustomProvider,

  // for web: new ReCaptchaV3Provider('6LdOHjAlAAAAAAuELCh4n53HGv01THoZVFEJTGO5'),
  // Optional argument. If true, the SDK automatically refreshes App Check
  // tokens as needed.
  isTokenAutoRefreshEnabled: true
});

React native contextual buttons

I have created a react native application that connects to a node js server and I have a screen that makes a request to the server in useEffect and stores them in useState and then maps them and lists all the games on the screen. My question is how to either make the games listed clickable or have a button next to them that could then run a fetch call to the server with a token but more importantly the name of the game. Or another example is a list of friend requests, how would I go about creating a button for each request that allows the user to send a request to the server with that friend name? I’m just looking to be nudged in the right direction because I feel extremely lost on how to approach this problem

My React app gives me an error every time about my index.js file, how would i fix this error? [error provided below]

import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

This is the code in my index.js file, I’ve asked chatgpt and looked at other options but the different variations of code still give me the same error with my syntax

“SyntaxError: The requested module ‘/preview/src/index.js?t=1679787723635’ does not provide an export named ‘default'”