Node JS – Recieve UDP String Used for Live Timing – Issues with Parsing Data

I have a simulator game that outputs Live Timing results via a UDP String. In Node JS I spun up a UDP client to receive data from the game. I’m getting what I need from the game but I’m having a hard time parsing the data so that I can use to update a webpage in real time. The string comes in as a big string with smaller strings separated by n.

This race had one racer in it, me. This is what is received by the Node JS Client.

MSG
0
EVENT
RACE
LiveResults Test
Forest Raceway
1256.0
OPEN

ENTRY
123
Racer Name
KTM 250 SX-F 2023
OEM 250 SX-F '23
MX2 OEM
FF011000010134CF9F


SESSION
RACE2
INPROGRESS
L 2

WEATHER
CLEAR
0.0

BESTLAP
906
82443
82443
1
36201
60607
15.2

LASTLAP
906
82443
82443
1
36201
60607
15.2

I’ve tried using RegEx and using split to try and extract the data I need. I just can’t seem to go get it to work. What would be the most efficient way to do this? There will be about 30 racers per server so I’m assuming there will be 30 racers under the ENTRY section each racer contains 6 lines. (Race #, Racer Name, Bike, Bike Model, Class and GUID)

I want to be able to extract all details about the racer and their LASTLAP time.

React – Using useState to push object of arrays to an array

I’m new to react and I want to keep track of array, as it changes. I’m using useState and I want to add array of objects into another array. I can accomplish this with push() but based on react documentation, this is mutating the array, which is not the right way. How could I accomplish this using array spread ..., slice() and etc?

Code

const [images, setImages] = useState(data.images)
const [object, setObject] = useState([])

const removeImage = (image) => {
    object.push(images)
    setImages(images.filter(i => i.id != image.id))
  }

Result

Array [ (5) […] ]
Array [ (5) […], (4) […] ]
Array(3) [ (5) […], (4) […], (3) […] ]
Array(4) [ (5) […], (4) […], (3) […], (2) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]

CocoaPods could not find compatible versions for pod “FBLazyVector”

While running command “pod install” it show me this:

[!] CocoaPods could not find compatible versions for pod "FBLazyVector": In Podfile: FBLazyVector (from ../node_modules/react-native/Libraries/FBLazyVector`)

Specs satisfying the FBLazyVector (from ../node_modules/react-native/Libraries/FBLazyVector) dependency were found, but they required a higher minimum deployment target.`

I’m trying to install pods in react native project but getting error and I want to resolve this error.

Pending Transcations not being Processed

On my node I tried to submit multiple transactions and didnt know that the account had to be unlocked

So I done so using

geth unlock "myaddress"

I now have 4 pending transactions that show the error “This txn hash was found in our secondary node and should be picked up by our indexer in a short while” on etherscan.

How do I clear these transactions and how do I prevent these from happening again.

As a side note heres one of the transaction hashes 0xa25a5dbb57e1186f09c2c2bb629284f9a846eacca595a993b0467b594d1e9157.

how to store a redux state that contain data from express cookie so when we reload page the state still there and not reset?

Issue with Persisting User Login Sessions in Express.js and React

I’m encountering an issue with persisting user login sessions in my Express.js and React application. Here’s a brief overview of the problem and the relevant code snippets:

Problem:

After successfully logging in, the user’s authentication state is stored in Redux state (isAuthenticated: true). However, upon reloading the page, the user is required to log in again.

Code Snippets:

  1. Express.js Route for Login:
const { email, password } = req.body;
try {
  const user = await User.findOne({ email });
  if (user) {
    // Logic here
    // Send cookie with user token
    sendCookie(user, 200, res);
    return; // Return after sending the response
  }
}
  1. Function to Send Cookie:
const jwt = require("jsonwebtoken");

const sendCookie = (user = {}, statusCode, res) => {
  const expiresInSeconds = parseInt(process.env.COOKIE_EXPIRE) * 24 * 60 * 60;

  // Sign the token using the user object
  const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
    expiresIn: expiresInSeconds,
  });

  const options = {
    expires: new Date(Date.now() + process.env.COOKIE_EXPIRE * 24 * 60 * 60 * 1000),
    httpOnly: false,
    secure: true,
    sameSite: 'None',
  };

  res.status(statusCode).cookie("token", token, options).json({
    success: true,
    user,
  });
};

module.exports = sendCookie;
  1. Redux Reducer:
case LOGIN_USER_SUCCESS:
  return {
    ...state,
    loading: false,
    isAuthenticated: true,
    user: action.payload,
    error: null,
  };

Additional Information:

I attempted to store the cookie in the browser’s cookie storage and access it upon reload to set isLoggedIn to true. However, when I deployed the app on Vercel, I couldn’t access the cookie from the cookie storage. It seems that the cookie is only sent in the network panel, even though I’ve set httpOnly to false. I suspect that Vercel might be hiding the cookie to prevent XSS attacks.

Request:

I’m seeking guidance on how to resolve this issue and ensure that user login sessions persist across reloads in my application. Any insights or suggestions would be greatly appreciated.

Displaying the 4 first numbers, and adding a whitespace that is offset AND making the rest of the numbers a Personsökare?

200 *20 + 5 /7 -200+5

I want to transform this, I want to take the first 4 numbers, which are 3805 and making them visible there just as they are. Then, taking the dot(.) and making it a satellit for the phone which is the remaining numbers!

I have tried making a game earlier, need help with this one though because it’s a dangerous game! The name of my game is Alascae.com

How play a sound when get a push notification [duplicate]

I’m currently using Firebase Cloud Messaging JS API for this purpose, and everything is working very well. However, I’m trying to play a notification sound when a new notification arrives.

I’m aware that I can’t play a sound directly from JavaScript due to autoplay restrictions. I tried a small hack by requesting permission to access the microphone to trigger the automatic sound playback permission, but I’m not satisfied with the final result.

I see that applications like Slack, WhatsApp, and others are able to play a sound after requesting notification permissions. Do you have any ideas on the best way to achieve this goal?

I’m leaving the fragment where I perform my ‘trick’ to request permission to the microphone and thus activate automatic sound playback.

        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            // Solicitar permiso para acceder al audio
            navigator.mediaDevices.getUserMedia({ audio: true })
                .then(function (stream) {
                    // El usuario ha otorgado permisos para acceder al audio
                    console.log('Permisos de reproducción de audio concedidos')

                    // Reproducir el sonido automáticamente
                    const audioElement = new Audio(`${mediaPath}/sounds/level-up-191997.mp3`)

                    audioElement.play();
                })
                .catch(function (error) {
                    // El usuario ha denegado el permiso para acceder al audio
                    console.error('Permisos de reproducción de audio denegados:', error)
                });
        } else {
            console.error('getUserMedia no está disponible en este navegador')
        }

Get caret position and selection range of any input type without using selectionStart and selectionEnd

According to the WHATWG forms spec selectionStart property applies only to inputs of types text, search, URL, tel, and password. This useful solution to get the caret position and the selection range does not work with input elements with type email, number, month, number and week, despite all of these looking somewhat like normal text inputs.

I need to know the position of the caret so, when an user types in an input, I can get the exact character and position where the character was inserted, so I insert the same character in an equivalent position in another input. In the application I’m building, this is trivial to do once I have the position where the character was inserted. The selection range is a bonus for a future feature I have in mind, but no big deal if I can’t get it now, I guess.

Simply copying and pasting the entire input value is an option if nothing else works, but I want to know what are my options.

How to get the same behavior of selectionStart (and selectionEnd) with these input types?

I’ve tried using document.getSelection().getRangeAt(0) and approaches that base itself in the Selection object, but they have failed. As I’ve come to understand, apparently it does not detect selection of text inside inputs, only across nodes?

A common solution to support IE involves something like document.selection, but selection doesn’t seem to even exist in the document object nowadays.

jest test if modal component is being opened

I have a nextJs/React/Bootstrap app with a Bootstrap modal component. I am using Jest to test. I cannot get jest to find the modal component on the rendered page after I simulate clicking the button that pops up then modal dialog.

here is my code:

modalObjType:

    export type modalObjectType = {
      show: boolean,
      title: string,
      message: string,
      id: string
    }
    
    export const initModalObj: modalObjectType = {
      show: false,
      title: 'title',
      message: 'message',
      id: "0"
    }

modelConfirm.tsx:

    import Button from 'react-bootstrap/Button';
    import Modal from 'react-bootstrap/Modal';
    
    export const delConfTitle = 'Confirm Delete'
    
    interface ChildProps {
      show: boolean,
      title: string,
      message: string,
      onConfirm: () => void;
      onCancel?: () => void;
    }
    
    const ModalConfirm: React.FC<ChildProps> = ({ 
      show,
      title: heading,
      message,
      onConfirm,
      onCancel
    }) => { 
    
      return (
        <>
          <Modal show={show} onHide={onCancel} data-testid="modalConfirm">
            <Modal.Header closeButton>
              <Modal.Title>{heading}</Modal.Title>
            </Modal.Header>
            <Modal.Body>{message}</Modal.Body>
            <Modal.Footer>
              <Button className='me-2' variant="success" onClick={onConfirm}>
                OK
              </Button>
              <Button variant="danger" onClick={onCancel}>
                Cancel
              </Button>
            </Modal.Footer>
          </Modal>
        </>
      )
    }
    
    export default ModalConfirm;

page.tsx:

    import ModalConfirm, { delConfTitle } from "@/components/modal/confirmModal";
    import { initModalObj } from "@/components/modal/modalObjType";
    
    const Home = ({
        
      const [confModalObj, setConfModalObj] = useState(initModalObj);
        
      const handleDelete = () => {  
        setConfModalObj({
          show: true,
          title: delConfTitle,
          message: `Do you want to delete Event: ${toDelName}?`,
          id: id,
        }); // deletion done in elsewhere
      };
        
        
        return (
        <>
          <ModalConfirm
            show={confModalObj.show}
            title={confModalObj.title}
            message={confModalObj.message}
            onConfirm={confirmedDelete}
            onCancel={canceledDelete}
          />
          <button
            onClick={() => handleDelete(id)}
          >
            Delete
          </button>   
        </>
        )
    })
    
    export default Home;

Thanks for any help!

Type error: Module ‘”*.mdx”‘ has no exported member ‘metadata’. Did you mean to use ‘import metadata from “*.mdx”‘ instead?

I want to get the metadata from mdx file.
and I followed this NextJS Markdown Formatter,
but it makes build error.

I can’t use fs, so please note that.

code

Page.tsx file


import ContentPost from "@/components/post.mdx"


const PostPage = () => {
  

  return (
    <div>
          <div className="  mb-8 md:mb-24 text-center">
            <h1 className="text-3xl">Title</h1>
            <p className="text-slate-400 mt-2">date</p>
          </div>

          <article className="prose mb-52 prose-emerald md:prose-lg lg:prose-xl dark:prose-invert">
            <ContentPost />
          </article>
    </div>
  );
};

export default PostPage;

*.mdx file

---
    title: "Title",
    subtitle: "Sub",
    date: "2024-3-18",
    coverImage: "",
---

# Contents text

mdx-components.tsx file

import type { MDXComponents } from 'mdx/types'
 
export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    ...components,
  }
}

next.config.mjs file

import nextMDX from '@next/mdx';
const withMDX = nextMDX({
    extension:/.mdx?$/,
    options:{
        remarkPlugins:[],
        rehypePlugins:[],
    }
})


/** @type {import('next').NextConfig} */
const nextConfig = {
    pageExtensions: ['js', 'jsx', 'mdx', 'md', 'ts', 'tsx'],
    images:{
        unoptimized: true,
        remotePatterns:[
        {
            protocol: "https",
            hostname: "img.youtube.com",
        },
    ]
    }
};

export default withMDX(nextConfig);

And I tried below.

export const metadata = {
    title: "Title",
    subtitle: "Sub",
    date: "2024-3-18",
    coverImage: "",
}
 
# My MDX page

In this case, I could get the metadata from the .mdx file.
And it worked perfactly on npm run dev.
But it caused this error when I tried to build.


Type error: Module '"*.mdx"' has no exported member 'metadata'. Did you mean to use 'import metadata from "*.mdx"' instead?

  4 | import Link from "next/link";
  5 |
> 6 | import ContentPost, { metadata } from "@/components/post.mdx";
    |                       ^
  7 |
  8 |
  9 | const PostPage = () => {


Error: An unexpected error has occurred.

AES encryption – from JSCrypto to python

I want to rewrite a javascript function in python, this is the function

String.prototype.CryptoAES = function(key, iv, additionalData, tag) {
    // Replacing characters 'Ñ' with 'N' and '%' with 'A' in the key
    key = key.replace('Ñ', 'N').replace('%', 'A');
    
    // Parsing the key and IV as UTF-8 encoded strings
    var parsedKey = CryptoJS.enc.Utf8.parse(key.substring(0, 7) + iv + additionalData + tag);
    
    var parsedIV = CryptoJS.enc.Utf8.parse(iv + additionalData + key.substring(1, 5) + additionalData + tag);

    // Encrypting the string using AES encryption
    var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(this), parsedKey, {
        keySize: 128 / 8, // Key size in bits
        iv: parsedIV, // Initialization Vector
        mode: CryptoJS.mode.CBC, // Cipher Block Chaining mode
        padding: CryptoJS.pad.Pkcs7 // Padding scheme
    });
    
  
    // Returning the encrypted string
    return encrypted.toString();
}

What i achieved so far:

def CryptoAES(input_string, key, iv, additional_data, tag):
    # Replacing characters 'Ñ' with 'N' and '%' with 'A' in the key
    key = key.replace('Ñ', 'N').replace('%', 'A')

    # Concatenating key, iv, additionalData, and tag
    concatenated_key = key[:7] + iv + additional_data + tag
    concatenated_iv = iv + additional_data + key[1:5] + additional_data + tag

    # Generating key and iv from concatenated strings using scrypt
    derived_key = scrypt(concatenated_key.encode(), salt=b'', key_len=16, N=16384, r=8, p=1)
    derived_iv = scrypt(concatenated_iv.encode(), salt=b'', key_len=16, N=16384, r=8, p=1)

    # Encrypting the string using AES encryption in CBC mode with PKCS7 padding
    cipher = AES.new(derived_key, AES.MODE_CBC, iv=derived_iv)
    padded_data = pad(input_string.encode(), AES.block_size)
    encrypted_data = cipher.encrypt(padded_data)

    # Returning the encrypted string
    return base64.b64encode(encrypted_data).decode()

But they are producing different results, for example

console.log("oi".CryptoAES("a", "b", "c", "d")) // outputs 9nMnx5vBxOIb5ZGSHWDUSA==
print(CryptoAES("oi", "a", "b", "c", "d")) // outputs d+4pa99hJ6kcseKPUGRsCQ==

What am i doing wrong?

JS KuCoin API – Invalid KC-API-SIGN – How to do the signature

I’m trying to see open orders for my account with this code:

import { KEY, PASSWORD, SECRET } from "./secrets.js";
import CryptoJS from "crypto-js";

const baseUrl = 'https://api.kucoin.com'
const endPointOrders = '/api/v1/orders';

const signatureInBase64 = (path, now) => {
  let msg = now + "GET" + path
  let signature = CryptoJS.HmacSHA256(msg, SECRET);
  return CryptoJS.enc.Base64.stringify(signature);
}

const passphraseInBase64 = () => {
  var passphrase = CryptoJS.HmacSHA256(PASSWORD, SECRET);
  return CryptoJS.enc.Base64.stringify(passphrase);
}

const openOrders = async() => {
  let path = endPointOrders;
  let now = Date.now();
  var headers = {
    "KC-API-SIGN": signatureInBase64(path, now),
    "KC-API-TIMESTAMP": now,
    "KC-API-KEY": KEY,
    "KC-API-PASSPHRASE": passphraseInBase64(),
    "KC-API-KEY-VERSION": "2",
    "Content-Type": "application/json"
  }
  const url = baseUrl + path;

  const response = await fetch(url, {
    method: 'post',
    body: "",
    headers: headers
  });
  const data = await response.json();

  console.log(data);

}

export { openOrders };

The response I’m getting is { code: '400005', msg: 'Invalid KC-API-SIGN' }

What am I doing wrong? I’ve tried searching for this, but all the current questions are for the python version, this is with nodeJS

Why is my time filter not updating within my Quasar template?

I’ve created a vue project for my assignment, and I want to show a formatted time on a section of the webpage. However, even after passing it through a filter, I’m still seeing the same unformatted epoch time.

I want to show the time on my webpage in a certain format, and therefore I’ve used a filter as such:

filters: {
    niceDate(timeStamp) {
      const dateObject = new Date(timeStamp * 1000);
      const formattedDate = date.formatDate(dateObject, "MMMM D h:mm A");
      return formattedDate;
    },
  },

I’ve also referenced this in the template like this:
<div class="text-caption text-grey">{{ post.date | niceDate }}</div>

Note that both the filter and template are from the same file (a Page file)

However, the result I see is still the epoch value from my object being shown instead of the formatted time:

{
          id: 1,
          user: "Tucker",
          emotion: "happy",
          location: "Mirihana, Sri Lanka",
          date: 1710799030927, // This is what I see on the browser, but I want it to be formatted
          caption: "I like biting people",
          imgURL: "https://cdn.quasar.dev/img/parallax2.jpg",
        },

Console returns 404 for POST requests

I’m building a chat app in React and Node.
In React.js I imported axios for the post request.
And when I login to see what the console will return, instead of returning data with all the columns of the model like firstName, lastName, password and token, etc.
It only returns the fields in the login form, email and password, and the error below

{
    "email": "[email protected]",
    "password": "secret"
}
xhr.js:258 
 POST http://localhost:3000/login 404 (Not Found)
err AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

Login.js code

const Login = () => {
    //Return jsx code

    const [email, setEmail] = useState('[email protected]');
    const [password, setPassword] = useState('secret');

    const submitForm = (e) => {

        e.preventDefault()
        
        axios.post('http://localhost:3000/login', { email, password })
        .then( res => {
             console.log("res", res);
             }) 
        .catch(err => {
            console.log('err', err);
            })
        console.log({email, password});
    }

It’s supposed to return data with all the columns of the user model.
Instead, it returns a 404 for the url