what does it mean when you declare variables in a if statement

i dont understand why theres one equals sign in the code and its confusing

why is it declaring variables in a if statement

if ((ms = undefined) || (tmpData == (ms = tmpData.length > 1 ? [tmpData[0], ...join(tmpData[1])] : tmpData)[0]) || ms) {

if ("C" == tmpData && null === myPlayer.sid && (myPlayer.sid = ms[1]) || "a" == tmpData) {

Variable with regex not matching with a space in user input

I’m currently trying to create a conversion tool to let people convert recipes based on the serving size they would like.

That said, I’m coming across an issue with trying to match the letters entered. Basically, if the user inputs some letters in the input, I want to return those in the result.

For example, someone types in 1/2 Cup Flour, that might return 1 Cup Flour.

In this example, you would extract the “Cup Flour” text and return that in the new value with the number.

I was originally going to use some code sort of like this to do this to output the result:

// Extract Words
   var letters = originalMeasurementsString.match(/[a-zA-Zs]/g);

$('#resizedMeasurements').html(resizedWholeNumber + resizedDecimal + letters.join(''));

In the code below, I’ve got 3 main different if/else statements, each correlating with different statements within those to check other various conditions met for the type of fraction:

// Checks For Mixed Fraction User Input - For Example: 1 1/2 Cup
if (originalMeasurements.includes(' ')) {
}

// Checks For Single Fraction User Input - For Example: 1/2 Cup
else if (originalMeasurements.includes('/')) {
}

// Then the Final Else Statement for a Whole Number User Input - For Example: 1 Cup

This solution works for the Mixed Fraction, due to the fact the if statement is checking for a space.

It also works fine for a single fraction if you input for example 1/2cup. The problem is how to get around the fact I want my user to be able to include a space, for example, they might type 1/2 cup instead.

Since the s in the .match() function /[a-zA-Zs]/g is supposed to look for white spaces, I’m a bit confused why this is not resulting in the single fraction statement working with a space in the user input.

Does anyone have any advice on how I might go about adapting this code to accept a user input with spaces?

Another alternative method I was trying to approach was using .replace() for example:

var originalMeasurements = $('#originalMeasurements').val().replace(/[a-zA-Zs]/g);

This method works, except for the fact this breaks the if statement from working for the Mixed Fraction.

Full Code:
https://codepen.io/JoyfullyDeveloped/pen/qBgVjer

Sorry if this is super simple mistakes. I’m still very much on the beginner level of coding with Javascript/jQuery.

How to verify that Multiple Images (List of images) are visible using Playwright JavaScript

Locator page.locator(‘.inner-blocks div.img-block’) returns 3 images. I want to verify one by one that all three images are visible on the Page. I am using Page Object Pattern. My page Object class looks like this

Dashboard.js

class dashboardPage{
constructor(page)
{
this.ImageBlocks = page.locator('.inner-blocks div.img-block')
 }
async verifytopSectionThreeBlocks()
{
const totalblocks = await this.ImageBlocks.count()
console.log("total count:"+totalblocks)
for(let i=0;i<totalblocks;i++)
{
   
     return (await this.ImageBlocks.nth(i))
}
}
}
module.exports ={dashboardPage};

And in the test class i am trying to assert that all images are visible.

const result = dashboardpage.verifytopSectionThreeBlocks()
 await except (result).toBeVisible()

This is giving error. Could anyone point it out and fix what is wrong here.

Text animation in Javascript not working properly

I want to make a looping animation by adding other texts character by character, removing them in the same way and changing the text before starting the loop. But, as you can see in this GIF, everything goes wrong.

This is how my code looks right now:

HTML
<h1 id="title">Desenvolvedor </h1>

JS

const title = document.getElementById("title");
const stacks = ["Front-End", "Back-End", "Full Stack"];
const speed = 200;
let stackIndex = 0;
let i = 0;

function addChar() {
  setTimeout(() => {
    title.innerHTML += stacks[stackIndex].charAt(i);
    i++;
    typeWriter(stackIndex);
  }, speed);
}

function deleteChar() {
  setTimeout(() => {
    title.innerHTML = title.innerHTML.slice(0, -1);
    
    if (title.innerText.length > 13) {
      deleteChar();
    } else {
      if (stackIndex > 1) {
        i = 0;
        stackIndex = 0;
        typeWriter(stackIndex);
      }

      i = 0;
      typeWriter(stackIndex++);
    }

  }, speed);
}

function typeWriter(stackIndex) {
  if (i < stacks[stackIndex].length) {
    addChar();
  } else {
    deleteChar();
  }
}

Adding the texts and changing their values worked as expected, but when it comes to resetting the values from stackIndex and i and starting the animation again, it starts to present bugs, even though in theory it is repeating the entire code from scratch.
How do I fix this error? Is there any more practical way to do this animation?

Error sending unit 1 menu: Error: User validation failed: chatId: Path `chatId` is required

I’m creating a template for a tg bot.
When I type “/start” it works, but when I choose one of 2 buttons to select, it shows this error:

Error sending unit 1 menu: Error: User validation failed: chatId: Path `chatId` is required.
    at ValidationError.inspect (C:baina_yadaik_1_tg_botnode_modulesmongooseliberrorvalidation.js:50:26)
    at formatValue (node:internal/util/inspect:805:19)
    at inspect (node:internal/util/inspect:364:10)
    at formatWithOptionsInternal (node:internal/util/inspect:2279:40)
    at formatWithOptions (node:internal/util/inspect:2141:10)
    at console.value (node:internal/console/constructor:352:14)
    at console.warn (node:internal/console/constructor:385:61)
    at sendUnit1Menu (C:baina_yadaik_1_tg_bottest.js:228:17)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  errors: {
    chatId: ValidatorError: Path `chatId` is required.
        at validate (C:baina_yadaik_1_tg_botnode_modulesmongooselibschematype.js:1365:13)
        at SchemaType.doValidate (C:baina_yadaik_1_tg_botnode_modulesmongooselibschematype.js:1349:7)
        at C:baina_yadaik_1_tg_botnode_modulesmongooselibdocument.js:2947:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'chatId',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'User validation failed'
}

Also here’s my code in test.js file

const TelegramBot = require('node-telegram-bot-api');
const dotenv = require('dotenv');
const bodyParser = require('body-parser');
const english = require('./english');
const express = require('express');
const mongoose = require('mongoose');
const User = require('./Schemas/User')
mongoose.connect('mongodb://127.0.0.1:27017/telegramBot', {
  useNewUrlParser: true,
  useUnifiedTopology: true, 
});

dotenv.config();

const token = process.env.BOT_TOKEN;

if (!token) {
    console.error("BOT_TOKEN is missing in the environment variables.");
    process.exit(1);
}

const bot = new TelegramBot(token, { polling: true });
bot.on("polling_error", console.log);

const MENU_STATES = {
    MAIN_MENU: 'main_menu',

    UNIT_1: 'unit_1',
    UNIT_1_TASK_1: 'unit_1_task_1',
    UNIT_1_TASK_2: 'unit_1_task_2',

    UNIT_2: 'unit_2',
    UNIT_2_TASK_1: 'unit_2_task_1',
    UNIT_2_TASK_2: 'unit_2_task_2',
};

// const userState = new Map();

bot.onText(//start/, async (msg) => {
  const chatId = msg.chat.id;

  try {
    const user = await User.findOne({ chatId });

    if (!user) {
      const newUser = new User({
        chatId,
        state: MENU_STATES.MAIN_MENU,
      });
      await newUser.save();
    } else {
      user.state = MENU_STATES.MAIN_MENU;
      await user.save();
    }

    sendMainMenu(chatId);
  } catch (error) {
    console.error('Error handling /start:', error);
  }
});

bot.onText(/back/, async (msg) => {
    const chatId = msg.chat.id;

    try {
        const usr = await User.findOne({ chatId });
        if (!usr) {
            await User.create({ chatId, state: MENU_STATES.MAIN_MENU });
        }

        const currentState = usr.state;

        switch (currentState) {
            case MENU_STATES.UNIT_1:
                usr.state = MENU_STATES.MAIN_MENU;
                sendMainMenu(chatId);
                break;
            case MENU_STATES.UNIT_1_TASK_1:
                usr.state = MENU_STATES.UNIT_1;
                sendUnit1Menu(chatId);
                break;
            case MENU_STATES.UNIT_1_TASK_2:
                usr.state = MENU_STATES.UNIT_1;
                sendUnit1Menu(chatId);
                break;
            case MENU_STATES.UNIT_2:
                usr.state = MENU_STATES.MAIN_MENU;
                sendMainMenu(chatId);
                break;
            case MENU_STATES.UNIT_2_TASK_1:
                usr.state = MENU_STATES.UNIT_2;
                sendUnit2Menu(chatId);
                break;
            case MENU_STATES.UNIT_2_TASK_2:
                usr.state = MENU_STATES.UNIT_2;
                sendUnit2Menu(chatId);
                break;
            default:
                break;
        };
    } catch (error) {
        console.error('Error handnling /back:', error);
    };
});

bot.on('message', async (msg) => {
    const chatId = msg.chat.id;
    let usr;
    try {
        usr = await User.findOne({ chatId });
        if (!usr) {
            usr = new User({ chatId, state: MENU_STATES.MAIN_MENU });
            await usr.save();
        }
        let currentState = usr.state;
        const userMsg = msg.text;

        switch (currentState) {
            case MENU_STATES.MAIN_MENU:
                handleMainMenu(chatId, userMsg);
                break;
            case MENU_STATES.UNIT_1:
                handleUnit1Menu(chatId, userMsg);
                break;
            case MENU_STATES.UNIT_1_TASK_1:
                handleUnit1Task1(chatId, userMsg);
                break;
            case MENU_STATES.UNIT_1_TASK_2:
                handleUnit1Task2(chatId, userMsg);
                break;
            case MENU_STATES.UNIT_2:
                handleUnit2Menu(chatId, userMsg);
                break;
            case MENU_STATES.UNIT_2_TASK_1:
                handleUnit2Task1(chatId, userMsg);
                break;
            case MENU_STATES.UNIT_2_TASK_2:
                handleUnit2Task2(chatId, userMsg);
                break;
            default:
                break;
        }
    } catch (error) {
        console.error('Error handling user message:', error);
    }
});

async function sendMainMenu(chatId) {
    try {
        let user = await User.findOne({ chatId });
        if (!user) {
            user = new User({ chatId, state: MENU_STATES.MAIN_MENU });
            await user.save();
        }

        bot.sendMessage(chatId, "Main menu", {
            reply_markup: {
                keyboard: [[english.unit1.mainTitle], [english.unit2.mainTitle]],
                resize_keyboard: true,
            },
        });
    } catch (error) {
        console.error('Error sending main menu:', error);
    }
}

async function handleMainMenu(chatId, text) {
    try {
        switch (text) {
            case english.unit1.mainTitle:
                await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_1 });
                sendUnit1Menu();
                break;
            case english.unit2.mainTitle:
                await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_2 });
                sendUnit2Menu();
                break;
            default:
                break;
        }
    } catch (error) {
        console.error('Error handling main menu:', error);
    }
}

// async function sendUnit1Menu(chatId) {
//     try {
//         let user = await User.findOne({ chatId });
//         if (!user) {
//             user = new User({ chatId, state: MENU_STATES.UNIT_1 });
//             await user.save();
//         }

//         bot.sendMessage(chatId, 'Unit 1 Menu', {
//             reply_markup: {
//                 keyboard: [[english.unit1.task1, english.unit1.task2], ['back']],
//                 resize_keyboard: true,
//             },
//         });
//     } catch (error) {
//         console.error('Error sending unit 1 menu:', error);
//     }
// }

async function sendUnit1Menu(chatId) {
    try {
        let user = await User.findOne({ chatId });

        // Если пользователя не существует, создаем нового
        if (!user) {
            user = new User({ chatId, state: MENU_STATES.UNIT_1 });
            await user.save();
        } else {
            // Если пользователь существует, убедимся, что поле chatId определено
            if (!user.chatId) {
                user.chatId = chatId;
                await user.save();
            }
        }

        bot.sendMessage(chatId, 'Unit 1 Menu', {
            reply_markup: {
                keyboard: [[english.unit1.task1, english.unit1.task2], ['back']],
                resize_keyboard: true,
            },
        });
    } catch (error) {
        console.error('Error sending unit 1 menu:', error);
    }
}


async function handleUnit1Menu(chatId, text) {
    const user = await User.findOne({ chatId });
        if (user.state !== MENU_STATES.UNIT_1_TASK_1) {
            return;
        }
    switch (chatId, text) {
        case english.unit1.task1:
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_1_TASK_1 });
            sendUnit1Task1(chatId);
            break;
        case english.unit1.task2:
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_1_TASK_2 });
            sendUnit1Task2(chatId);
            break;
        case 'back':
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.MAIN_MENU });
            sendMainMenu(chatId);
            break;
        default:
            break;
    }
}

async function sendUnit1Task1(chatId) {
    try {
        const user = await User.findOne({ chatId });
        if (user.state !== MENU_STATES.UNIT_1_TASK_1) {
            return;
        }

        const keyboardOptions = [['Text', 'Audio'], ['Exam', 'Back']];
        const replyMarkup = {
            keyboard: keyboardOptions,
            resize_keyboard: true,
        };

        bot.sendMessage(chatId, 'Unit 1 - Task 1 Content', {
            reply_markup: replyMarkup,
        });
    } catch (error) {
        console.error('Error sending unit 1 task 1:', error);
    }
}

async function sendUnit1Task2(chatId) {
    try {
        const user = await User.findOne({ chatId });
        if (user.state !== MENU_STATES.UNIT_1_TASK_2) {
            return;
        }

        const keyboardOptions = [['Text', 'Audio'], ['Exam', 'Back']];
        const replyMarkup = {
            keyboard: keyboardOptions,
            resize_keyboard: true,
        };

        bot.sendMessage(chatId, 'Unit 1 - Task 2 Content', {
            reply_markup: replyMarkup,
        });
    } catch (error) {
        console.error('Error sending unit 1 task 2:', error);
    }
}

async function sendUnit2Menu(chatId) {
    try {
        let user = await User.findOne({ chatId });
        if (!user) {
            user = new User({ chatId, state: MENU_STATES.UNIT_2 });
            user.chatId = chatId;  // Add this line to set the chatId
            await user.save();
        }


        bot.sendMessage(chatId, 'Unit 2 Menu', {
            reply_markup: {
                keyboard: [[english.unit2.task1, english.unit2.task2], ['back']],
                resize_keyboard: true,
            },
        });
    } catch (error) {
        console.error('Error sending unit 2 menu:', error);
    }
}

async function handleUnit2Menu(chatId, text,) {
    switch (text) {
        case english.unit2.task1:
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_2_TASK_1 });
            sendUnit2Task1(chatId);
            break;
        case english.unit2.task2:
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_2_TASK_2 });
            sendUnit2Task2(chatId);
            break;
        case 'back':
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.MAIN_MENU });
            sendMainMenu(chatId);
            break;
        default:
            break;
    };
};

async function sendUnit2Task1(chatId) {
    try {
        let user = await User.findOne({ chatId });
        if (!user) {
            user = new User({ chatId, state: MENU_STATES.UNIT_2_TASK_1 });
            await user.save();
        }

        const keyboardOptions = [['Text', 'Audio'], ['Exam', 'Back']];
        const replyMarkup = {
            keyboard: keyboardOptions,
            resize_keyboard: true,
        };

        bot.sendMessage(chatId, 'Unit 2 - Task 1 Content', {
            reply_markup: replyMarkup,
        });
    } catch (error) {
        console.error('Error sending unit 2 task 1:', error);
    }
}

async function sendUnit2Task2(chatId) {
    try {
        let user = await User.findOne({ chatId });
        if (!user) {
            user = new User({ chatId, state: MENU_STATES.UNIT_2_TASK_2 });
            await user.save();
        }

        const keyboardOptions = [['Text', 'Audio'], ['Exam', 'Back']];
        const replyMarkup = {
            keyboard: keyboardOptions,
            resize_keyboard: true,
        };

        bot.sendMessage(chatId, 'Unit 2 - Task 2 Content', {
            reply_markup: replyMarkup,
        });
    } catch (error) {
        console.error('Error sending unit 2 task 2:', error);
    }
}

async function handleUnit1Task1(chatId, text) {
    switch (text) {
        case 'Text':
            bot.sendMessage(chatId, 'You chose: text');
            break;
        case 'Audio':
            bot.sendMessage(chatId, 'You chose: audio');
            bot.sendAudio(chatId, __dirname + '/audios/01.mp3')
                .then(() => {
                    console.log('Audio sent successfully');
                })
                .catch((error) => {
                    console.error('Error sending audio:', error);
                });
            break;
        case 'Exam':
            bot.sendMessage(chatId, 'You chose: exam');
            break;
        case 'Back':
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_1 });
            sendUnit1Menu(chatId);
            break;
        default:
            break;
    }
}

async function handleUnit1Task2(chatId, text) {
    switch (text) {
        case 'Text':
            bot.sendMessage(chatId, 'Text example!');
            break;
        case 'Audio':
            bot.sendMessage(chatId, 'Audio example!');
            bot.sendAudio(chatId, __dirname + '/audios/02.mp3')
                .then(() => {
                    console.log('Audio sent successfully');
                })
                .catch((error) => {
                    console.error('Error sending audio:', error);
                });
            break;
        case 'Exam':
            bot.sendMessage(chatId, 'Exam example!');
            break;
        case 'Back':
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_1 });
            sendUnit1Menu(chatId);
            break;
        default:
            break;
    }
}

async function handleUnit2Task1(chatId, text) {
    switch (text) {
        case 'Text':
            bot.sendMessage(chatId, 'You chose: text');
            break;
        case 'Audio':
            bot.sendMessage(chatId, 'You chose: audio');
            bot.sendAudio(chatId, __dirname + '/audios/03.mp3')
                .then(() => {
                    console.log('Audio sent successfully');
                })
                .catch((error) => {
                    console.error('Error sending audio:', error);
                });
            break;
        case 'Exam':
            bot.sendMessage(chatId, 'You chose: exam');
            break;
        case 'Back':
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_1 });
            sendUnit2Menu(chatId);
            break;
        default:
            break;
    }
}

async function handleUnit2Task2(chatId, text) {
    switch (text) {
        case 'Text':
            bot.sendMessage(chatId, 'Text example!');
            break;
        case 'Audio':
            bot.sendMessage(chatId, 'Audio example!');
            bot.sendAudio(chatId, __dirname + '/audios/04.mp3')
                .then(() => {
                    console.log('Audio sent successfully');
                })
                .catch((error) => {
                    console.error('Error sending audio:', error);
                });
            break;
        case 'Exam':
            bot.sendMessage(chatId, 'Exam example!');
            break;
        case 'Back':
            await User.findOneAndUpdate({ chatId }, { state: MENU_STATES.UNIT_1 });
            sendUnit2Menu(chatId);
            break;
        default:
            break;
    }
}

const app = express();
const port = 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/tgwebhook', (req, res) => {
    console.log('Received webhook request:', req.body);
    bot.processUpdate(req.body);
    res.sendStatus(200);
});

app.get('/ping', (req, res) => res.send('pong'));

app.listen(port, () => {
    console.log(`Web server is listening on port ${port}`);
});

And here’s the code in Schemas/User.js file:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    chatId: {
        type: Number,
        required: true,
        unique: true,
    },
    state: String,
});

const User = mongoose.model('User', userSchema);

module.exports = User;

I already tried to search of this problem in the google and ask some people, but it didn’t help me.

How to create pages that displays only certain entries from a database?

Basically, I have a site to display all the items I have, but I want those to be sorted automatically into their own category page instead of having them all displayed in a single page.
I’m not super knowledgeable in coding, but I believe I’d need a database file with all the individual entries, and a code that calls the entries with the specified category in them to display in the page. I have no idea how to even start coding all of these, and I’m using the free version of neocities, so I’m a bit limited on the types of files and code I can use.
I’d appreciate any ideas or guidance you can give me!

I’ve been keeping track of the items in a google sheet, and displaying said items in extra embedded google sheets, but that requires me to manually add/sort the entries throughout the different spreadsheets I have for each category, which is gonna be unmanageable now that I want even more categories. Not to mention I can’t even sort the items in the category spreadsheets cause I have to display the data on each entry vertically instead of horizontally!
Each entry requires these types of info: item image, when I got it, who I got from, how I got it, main category, subcategory and personal notes

Can’t able to get the output for npm run test

Lock
Deployment
1) Should set the right unlockTime
2) Should set the right owner
3) Should receive and store the funds to lock
4) Should fail if the unlockTime is not in the future
Withdrawals
Validations
5) Should revert with the right error if called too soon
6) Should revert with the right error if called from another account
7) Shouldn’t fail if the unlockTime has arrived and the owner calls it
Events
8) Should emit an event on withdrawals
Transfers
9) Should transfer the funds to the owner

0 passing (2s)
9 failing

  1. Lock
    Deployment
    Should set the right unlockTime:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:30:36)

  2. Lock
    Deployment
    Should set the right owner:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:36:31)

  3. Lock
    Deployment
    Should receive and store the funds to lock:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:42:38)

  4. Lock
    Deployment
    Should fail if the unlockTime is not in the future:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at getContractFactoryByAbiAndBytecode ([email protected]:305:21)
    at Context. (testLock.js:54:20)

  5. Lock
    Withdrawals
    Validations
    Should revert with the right error if called too soon:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:64:26)

  6. Lock
    Withdrawals
    Validations
    Should revert with the right error if called from another account:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:72:52)

  7. Lock
    Withdrawals
    Validations
    Shouldn’t fail if the unlockTime has arrived and the owner calls it:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:86:38)

  8. Lock
    Withdrawals
    Events
    Should emit an event on withdrawals:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:99:52)

  9. Lock
    Withdrawals
    Transfers
    Should transfer the funds to the owner:
    TypeError: (0 , ethers_1.getAddress) is not a function
    at new HardhatEthersSigner ([email protected]:73:30)
    at Function.create ([email protected]:65:12)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at getSigner ([email protected]:60:29)
    at async Promise.all (index 0)
    at getSigners ([email protected]:45:30)
    at deployOneYearLockFixture (testLock.js:20:35)
    at loadFixture (node_modules@nomicfoundationhardhat-network-helperssrcloadFixture.ts:59:18)
    at Context. (testLock.js:113:59)

trying to run npx hardhat test

Arduino problems with reading and writing to serialport

I want to create a program, which will read the data from usb port that arduino will send to me and display it. However, I get an error:

const port = new SerialPort(‘COM6’, { baudRate: 9600 });
^
TypeError: SerialPort is not a constructor
Thanks

Node.js:

import Readline from '@serialport/parser-readline';
const port = new SerialPort('COM6', { baudRate: 9600 });
const parser = port.pipe(new Readline({ delimiter: '' }));
// Read the port data
port.on("open", () => {
  console.log('serial port open');
});
port.write("1", (err) => {
    if (err) {
      return console.log('Error on write: ', err.message);
    }
    console.log('message written');
  });
parser.on('data', data =>{
  console.log('State of light:', data);
});```
Arduino:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
        char command = Serial.read();
        if (command == "1") {
            Serial.println("1");
        } else if (command == '0') {
            Serial.println("0");
        }
    }
  delay(5000);
}

RuntimeError Loading KML Data in CesiumJS

Encountering a RuntimeError while attempting to load KML data using CesiumJS. The error occurs during the process and seems to be related to KmlDataSource.js. Looking for guidance on debugging strategies or known solutions to resolve this issue.

Issues with Open Ai vision into react native application due to url error

I have a react native application. I want this application to allow the user to upload an image. Once the image was selected and uploaded, it is published to firebase and grabs a public downloadable link.

I then want to pass this link of the downloadable image to Open Ai’s vision api. Once it is passed to OpenAi, I want it to scan the image and answer a question about the image.

I have tried everything but I am not sure what is going on.

This is the code I have:

import OpenAI from 'openai';
import {OPEN_AI_API_KEY} from '../../Utils/Authentication';
import {uploadNewImage} from '../../Utils/Firebase';

const openai = new OpenAI({apiKey: OPEN_AI_API_KEY});
console.log(openai);

...

const performOCR = () => {
    const fileName = 'receipt-' + Math.floor(Math.random() * 100000000 + 1);
    uploadNewImage(preprocessedImage, fileName)
      .then(downloadableUrl => {
        console.log('received downloadable url');
        if (downloadableUrl) {
          console.log(downloadableUrl);
          scanImage(downloadableUrl);
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

async function scanImage(downloadableUrl: string) {
    const response = await openai.chat.completions.create({
      model: 'gpt-4-vision-preview',
      messages: [
        {
          role: 'user',
          content: [
            {
              type: 'text',
              text: 'Scan the image of the receipt and extract the business information. Then itemize all of the items that were ordered?',
            },
            {
              type: 'image_url',
              image_url: {
                url: downloadableUrl,
              },
            },
          ],
        },
      ],
    });
    console.log(response.choices[0]);
  }

So at some point of the process it keeps throwing an error about the failure of my url. I have looked online and asked chat gpt for help and nothing.

Here is the full error tract:

 LOG  https://firebasestorage.googleapis.com/v0/b/ioweyou-9d178.appspot.com/o/ProfilePictures%2Freceipt-27195586?alt=media&token=a4320778-e64e-4325-a236-460bb7d9e3c1
 WARN  Possible Unhandled Promise Rejection (id: 0):
Error: 404 Invalid URL (POST /v1/chat/completions/)
Error: 404 Invalid URL (POST /v1/chat/completions/)
    at construct (native)
    at Wrapper (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:26976:64)
    at construct (native)
    at _createSuperInternal (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:219299:406)
    at apply (native)
    at OpenAIError (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:219310:26)
    at construct (native)
    at _createSuperInternal (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:219299:406)
    at call (native)
    at APIError (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:219321:27)
    at construct (native)
    at _createSuperInternal (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:219299:406)
    at apply (native)
    at NotFoundError (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:219477:29)
    at generate (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:219365:35)
    at makeStatusError (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:217534:79)
    at ?anon_0_ (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:217592:43)
    at next (native)
    at asyncGeneratorStep (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:28227:26)
    at _next (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:28246:29)
    at tryCallOne (/private/var/folders/yw/6bx918xn4671rggfcdxz7fph0000gn/T/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:53:16)
    at anonymous (/private/var/folders/yw/6bx918xn4671rggfcdxz7fph0000gn/T/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:139:27)
    at apply (native)
    at anonymous (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:34858:26)
    at _callTimer (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:34737:17)
    at _callReactNativeMicrotasksPass (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:34782:17)
    at callReactNativeMicrotasks (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:34988:44)
    at __callReactNativeMicrotasks (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:3623:46)
    at anonymous (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:3397:45)
    at __guard (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:3596:15)
    at flushedQueue (http://192.168.86.62:8081/node_modules/expo/AppEntry.bundle//&platform=ios&dev=true&hot=false&lazy=true:3396:21)

Is it possible to use axios in Next.js 13 version?

I tried to implement the SSG operation with {cache: ‘force-cache’} fetch option, but I always returned the same data even if the mock server’s data changed.

{ The cache: ‘no-store’} fetch option changes the data, but this is an SSR method, so I didn’t think it was suitable for my site to create a blog.

I’m trying to use axios to find another way, but I don’t think I’ve ever used axios in the Next.js 13 version.
How can I implement the SSG behavior with axios in version 13 of Next.js?

import Layout_Mobile from "@/components/Layout/DeviceLayout/Layout_Mobile";
import Layout_PC from "@/components/Layout/DeviceLayout/Layout_PC";
import PostDetailPage from "@/components/PostDetailPage/PostDetailPage";

const fetchPosts = async (params) => {
  const res = await fetch(
    `https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts/${params.slug}`,
    {
      cache: "force-cache",
    }
  )
    .then((response) => response.json())
    .then((data) => {
      return data;
    });

  return res;
};

export const generateStaticParams = async () => {
  const res = await fetch(
    "https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts"
  )
    .then((response) => response.json())
    .then((data) => {
      return data;
    });

  return res.map((post) => ({
    slug: post.id.toString(),
  }));
};

const page = async ({ params }) => {
  const { title, summary, content, author, createdAt } = await fetchPosts(
    params
  );

  return (
    <div>
      <Layout_Mobile></Layout_Mobile>
      <Layout_PC>
        <PostDetailPage
          title={title}
          description={summary}
          content={content}
          author={author}
          date={createdAt}
        />
      </Layout_PC>
    </div>
  );
};

export default page;

I really want to solve this problem…

Design for configurable JS component

I am currently working on a UI component that can be integrated using a script tag.

Clients create an account in the admin-dashboard, where they can find their personalised script tag, which they can then add to their website.

Right now they can modify the styling via a global config object or by overriding the styles in their css. But for the next release I would like to add a styling section to the admin-dashboard. So they should be able to login and change the color of the component.

So far so good, but I am really stuck on how to include the admin-dashboards config in the library. Of course the library should not make a network request to get the config, so it needs to be included in it.

Should I configure a build pipeline to rebuild the library and include the new config, whenever a user changes their settings in the dashboard?

I would love to learn common practices for this.

Thanks!

Merging arrays js

I have a data array:

[
   { name: '1', goalsTable: 6544b8a5fea0bf50fc0c62fb },
   { name: '1fork', goalsTable: 6548740f05dc440b5c61c5ac }
]

I have a goalsData array:

[
   {
     _id: 6544b8a5fea0bf50fc0c62fb,
     tableData: [ [Object], [Object], [Object], [Object] ],
     goalsData: { qty: 12 }
   },
   {
     _id: 6548740f05dc440b5c61c5ac,
     tableData: [ [Object], [Object], [Object], [Object], [Object] ],
     goalsData: { qty: 10 }
   }
 ]

What I want is to merge the object if the id matches with each other. Like for example, if _id of first object of goalsData matches with the goalsTable of data, then the data object becomes:

[{
   name: '1', 
   goalsTable: 6544b8a5fea0bf50fc0c62fb, 
   tableData: [ [Object], [Object], [Object], [Object] ], 
   goalsData: { qty: 12 } 
}]

Sort by balances and amounts

I have a set of transactions

 [
    {
        "amount": 1003.75,
        "balance": 1003.75
    },
    {
        "amount": -999.50,
        "balance": 4.25
    },
    {
        "amount": 500,
        "balance": 504.25
    },
    {
        "amount": -515.00,
        "balance": 0
    },
    {
        "amount": -515.00,
        "balance": 0
    },
    {
        "amount": 10.75,
        "balance": 515.0
    },
    {
        "amount": -90.25,
        "balance": 4909.75
    },
    {
        "amount": 5000.0,
        "balance": 5000.0
    },
    {
        "amount": 0.25,
        "balance": 4910
    }
]

The amount represents the deposit or withdrawal and the balance represents the balance after the transactions have been completed.

I want to sort this array such that the current balance is the sum of the previous balance and the current amount.

Sorted array:

[
    {
        "amount": 1003.75,
        "balance": 1003.75
    },
    {
        "amount": -999.50,
        "balance": 4.25
    },
    {
        "amount": 500,
        "balance": 504.25
    },
    {
        "amount": 10.75,
        "balance": 515.0
    },
    {
        "amount": -515.00,
        "balance": 0
    },
    {
        "amount": 5000.0,
        "balance": 5000.0
    },
    {
        "amount": -90.25,
        "balance": 4909.75
    },
    
    {
        "amount": 0.25,
        "balance": 4910
    }
]