undo and clear functionality not working fine in canvas

I am creating a paint application using canvas. If I want to draw, then it works, but the undo and clear buttons are not working fine, so if I click those buttons, then it throws an error saying “ctx.FillRect is not a function”, so how do I make those buttons work fine in React so that all that functionality will work fine? Codes are given below.

import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
  let restore_array = [];
  let index = -1;
  useEffect(() => {
    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth - 60;
    canvas.height = 300;
    const ctx = canvas.getContext("2d");
    let start_back_ground_color = "red";
    ctx.fillStyle = start_back_ground_color;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    let draw_color = "black";
    let draw_width = 5;
    let is_drawing = false;
    canvas.addEventListener("touchstart", start, false);
    canvas.addEventListener("touchmove", draw, false);
    canvas.addEventListener("mousedown", start, false);
    canvas.addEventListener("mousemove", draw, false);
    canvas.addEventListener("touchend", stop, false);
    canvas.addEventListener("mouseup", stop, false);
    canvas.addEventListener("mouseout", stop, false);
    function start(e) {
      is_drawing = true;
      ctx.beginPath();
      ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
      e.preventDefault();
    }
    function draw(e) {
      if (is_drawing) {
        ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
        ctx.strokeStyle = draw_color;
        ctx.lineWidth = draw_width;
        ctx.lineCap = "round";
        ctx.lineJoin = "round";
        ctx.stroke();
      }
    }
    function stop(e) {
      if (is_drawing) {
        ctx.stroke();
        ctx.closePath();
        is_drawing = false;
      }
      e.preventDefault();
      if (e.type !== "mousetype") {
        restore_array.push(ctx.getImageData(0, 0, canvas.width, canvas.height));
        index += 1;
      }
    }
  });
  const clearCanvas = () => {
    const ctx = document.createElement("canvas").getContext("2d");
    const canvas = document.getElementById("canvas");
    ctx.fillStyle = "red";
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.FillRect(0, 0, canvas.width, canvas.height);
    restore_array = [];
    index = -1;
  };
  const undoCanvas = () => {
    const ctx = document.createElement("canvas").getContext("2d");
    if (index <= 0) {
      clearCanvas();
    } else {
      index -= 1;
      restore_array.pop();
      ctx.putImageData(restore_array[index], 0, 0);
    }
  };

  return (
    <div className="App">
      <div className="field">
        <canvas id="canvas"></canvas>
        <div className="tools">
          <button onClick={undoCanvas} className="button">
            Undo
          </button>
          <button onClick={clearCanvas} className="button">
            clear
          </button>
        </div>
      </div>
    </div>
  );
}

Convert numbers to time in google spreadsheets

I’m trying to build an automated Google Sheets Spreadsheet where I can enter the date, clock-in, lunch time, clock-out, total worked hours per day and finally totalize all the hours worked in the month. It’s not too difficult to create a working Time Sheet like that in Google Spreadsheet but there’re a couple of improvements I’d love to make. One is even when the spreadsheet calculates the hours correctly for the day it displays the total as clock time, 8:22 PM, for instance instead of 8:22 hours. The other thing is this format forces me to write the hours in time format which is tedious. I’d like to type 3 or 4 digits into the cell and have it convert it to time for me.

I learned the only way to achieve this was with Google Apps Script so I followed the only tutorial I found on this but the code is just not working. The scripting utility uses javascript which I’m kind of familiar since I use it everyday in After Effects expressions but I’m hardly an expert. I’d love if someone could help me with this unchallenging (for you :D) project. Of course if anyone has a better alternative to anything I’m doing, I’m totally open to changing course. Thanks a lot. I’ll paste the code I created following the tutorial and then the link to the tutorial itself.

var COLUMN_TO_CHECK = 3;
var SHEET_NAME = "Sheet1";

function onEdit(e){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  if(sheet.getName() === SHEET_NAME){
    var selectedCell = sheet.getActiveCell();

    selectedCell.setNumberFormat("@");

    if(selectedCell.getColumn() === COLUMN_TO_CHECK){
      var cellValue = selectedCell.getValue();
      var time = cellValue.substr(0,2)+":"+cellValue.substr(cellValue.lenght - 2);
      selectedCell.setValue(time);
      selectedCell.setNumberFormat("hh:mm");
     }
    }
  }

I’m getting an error at line 7: var sheet = ss.getActiveSheet();. The debugger calls the variable ss to be null.

One thing I noticed about the tutorial is it’s inconsistent between the featured code and the code you write step by step and they skip some lines of code too. Which could be the reason why my code is not working. I tried to carbon copy the featured code when following the tutorial sent me into dead ends.

https://yagisanatode.com/2018/06/02/google-apps-script-how-to-automatically-generate-a-time-from-a-four-digit-24-hour-time-in-google-sheets/

Error caused by rewriting the default React Javascript file

What I want to do

Following the create a new React app commands, I am trying to change the screen that is displayed in the browser when the following is executed.

I have already executed the following command and confirmed that it works, but I want to edit the HTML and Javascript files to show only Hello World!.

npx create-react-app my-app
cd my-app
npm start

Prerequisite

In the procedure Creating a new React app, the contents of index.js are as follows.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

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

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();

Error

It seems to be running, but nothing is displayed in the browser as white screen with nothing has shown.

What needs to be modified to display Hello World!?
Screen Shot

$ npm start
Compiled successfully!

You can now view my-app in the browser.

  Local:            http://localhost:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully

Code

The public and src folders under the my-app folder were deleted, leaving only public/index.html and src/index.js, and the rest were deleted.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="./src/index.js" type="text/jsx"></script>
  </body>
</html>

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';

ReactDOM.render(
  <h1>Hello World!</h1>,
  document.getElementById("root")
);

Dev Env

  • node v18.15.0
  • react 18.2.0

i’m to to create an ending election page for a game i am making in html, however i am unable to get the if statements working or the input

how do i fix it?
this is my code:

`    `<!DOCTYPE html>
<html>
    <head>
        <script>
            function search(){
                var choose = document.getElementById("choice").innerHTML;
                setInterval(() => { 
                    if(choose == 1){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 2){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 3){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 4){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 5){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 6){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 7){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 8){
                        window.location.href = "1:1:1.html"; 
                    };
                    if(choose== 9){
                        window.location.href = "1:1:1.html"; 
                    };
                    
                }, 10);
            }
        </script>
    </head>

    <body onload="search()">
      <form>
        <label for="choice">enter 1-9 to travel to that ending</label><br>
          <input type="text" id="choice" name="choice" class="choice"><br>
      </form>
    </body>

</html>``

i have tried many different potential solutions, like textcontent, inner text and other things. however none of it seems to work. I am trying to make it so that when someone types a number from 1-9 in, it takes them to that specific ending. They currently all go to the same place but that will be fixed later on, as they currently don’t go anywhere.

Input from checkbox not registered in database yet there are no errors [Laravel, inertiajs]

I’ve spent half day trying to make a simple input checkbox type works. I’ve checked on the controller, database migration table and tried various code to make this works but it didn’t. Some code that I tried caused errors in the console and some shows no errors yet when I look on the database table, the value of is_password and is_stamping is still null. I wonder what am I missing ? Here’s part of the code:

<div className={'col-span-1'}>
        <InputLabel
          value={'Password PDF'}
          className={'mb-2 font-bold text-base'}
          required={false}
        />
        <TextInput
          type={'checkbox'}
          name={'is_password'}
          className={''}
          value={data.is_password}
          handleChange={ (e) => e.target.value === data.is_password.checked? 1:0 } 
        />
        <InputError message={errors.is_password}/>
      </div>

      <div className="col-span-1">
        <InputLabel
          value={'Stamping'}
          className={'mb-2 font-bold text-base'}
          required={false}
        />

        <TextInput
          type={'checkbox'}
          name={'is_stamping'}
          className={''}
          value={data.is_stamping}
          handleChange={ (e) => e.target.value === data.is_stamping.checked? 1:0 }  
        />
        <InputError message={errors.is_stamping}/>
      </div>

I have a function with axios and it’s not responding properly [duplicate]

async function apiCall(KEY_1, KEY_2) {

let result = {}

await axios.get('https://cococloud-drive.com/api/v2/authorize', { params: { key1: KEY_1, key2: KEY_2 } })
    .then((res) => {

        result.accountId = res.data.data.account_id
        result.accessToken = res.data.data.access_token
        result.status = 'success'

    })
    .catch((e) => {
        result.status = 'error'
    })

return result

}

const result = apiCall(KEY_1, KEY_2)

console.log(result) if (result.status === 'success') { console.log(result) }`

I am calling this function and when I console.log inside the function, it returns the value but when I console.log(result) calling the API, it returns promise.

I want to access result.accountId and result.accessToken

Vue js How to use onChange with TomSelect

Is there a way to use onChange with TomSelect ?

<TomSelect
            :disabled="disableForm"
              v-model="wareHouse.agent.id"
              :onChange="changeAgentData"
              class="w-full"
            >
              <option value="">No Agent</option>
              <template v-for="(business, indexKey) in company.agentCompanies">
                <option v-if="business.companyType.includes('Shipper')" :key="indexKey" :value="business.id">{{business.name}}</option>
              </template>
              
            </TomSelect>

This does nothing. changeAgentData doesn’t fire.
i tried @change , change, changed

IMAP: I can’t delete the email from inbox after is inserted into database

I have a big problem, emails don’t get deleted after is inserted into database, I really don’t know what the problem , the console log show me that the emails has been deleted and expunged but have don’t. here’s my script if someone can help me it will be great , I tried a lot of variants and nothing . So my problem is the next one , When I get a new email , listen , get details from it , insert it in database and after that permanently delete it from my inbox . Everything work without deleting it from inbox. Thanks in advance.

const Imap = require('imap');
const { MongoClient } = require('mongodb');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const { simpleParser: MailParser } = require('mailparser');

const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());

const imapConfig = {
  user: '[email protected]',
  password: 'yourpassword',
  host: 'imap.mail.com',
  port: 993,
  tls: true,
};

const mongoConfig = {
  uri: 'mongodb://127.0.0.1:27017/?readPreference=primary&ssl=false',
  dbName: 'emailDatabase',
};

const imap = new Imap(imapConfig);
const mongoClient = new MongoClient(mongoConfig.uri, { useUnifiedTopology: true });

async function getEmailDetails(msg) {
  try {
    const rawEmail = await new Promise((resolve, reject) => {
      msg.on('body', (stream) => {
        let emailData = '';
        stream.on('data', (chunk) => {
          emailData += chunk.toString('utf8');
        });
        stream.once('end', () => {
          resolve(emailData);
        });
      });
      msg.once('error', (err) => reject(err));
    });

    const parsedEmail = await MailParser(rawEmail);
    console.log('Parsed email:', JSON.stringify(parsedEmail, null, 2));
    return parsedEmail;
  } catch (err) {
    throw err;
  }
}

imap.once('ready', async () => {
  console.log('IMAP connection ready');

  await mongoClient.connect();

  imap.openBox('INBOX', true, (err, box) => {
    if (err) throw err;

    imap.on('mail', async (numNewMsgs) => {
      await new Promise(async (resolve, reject) => {    
        console.log(`Received ${numNewMsgs} new email(s)`);

        const seqRange = `${box.messages.total - numNewMsgs + 1}:${box.messages.total}`;
        console.log(`Fetching emails with seqRange: ${seqRange}`);

        const fetchOptions = {
          bodies: '',
          uid: true
        };
        
        const fetch = imap.seq.fetch(seqRange, fetchOptions);

        fetch.on('message', (msg, uid) => {
          getEmailDetails(msg, uid)
            .then(async (emailDetails) => {
              console.log('Appending email:', JSON.stringify(emailDetails, null, 2));

              try {
                const db = mongoClient.db(mongoConfig.dbName);
                const collection = db.collection('emails');
                await collection.insertOne(emailDetails);
                console.log('Email appended to the database');
              } catch (err) {
                console.error(`Failed to append email: ${uid}`, err);
              }
            })
            .catch((err) => {
              console.error(`Error processing email: ${uid}`, err);
            });
       
        imap.addFlags(uid, 'Deleted', (err) => {
          if (err) console.error(err);
          imap.expunge(uid, (err) => {
            if (err) console.error(err);
            console.log(`Email deleted and expunged ${uid}`);
          });
        });
      });
        fetch.once('error', (err) => {
          console.error('Fetch error:', err);
          reject(err);
        });

        fetch.once('end', () => {
          console.log('Fetch operation completed');
          resolve();
          });
          });
          });
          });
          });
          
          imap.once('error', (err) => {
          console.error('IMAP error:', err);
          });
          
          imap.once('end', () => {
          console.log('IMAP connection ended');
          });
          
          imap.connect();
          
          app.get('/emails', async (req, res) => {
          try {
          const db = mongoClient.db(mongoConfig.dbName);
          const collection = db.collection('emails');
          const emails = await collection.find({}).toArray();
          res.json(emails);
          } catch (err) {
          console.error('Failed to fetch emails:', err);
          res.status(500).send('Failed to fetch emails');
          }
          });
          
          app.listen(3000, () => {
          console.log('Server listening on port 3000');
          });

I tried a lot of variants from Chatgpt , but nothing worked.

Disseminating from string what is code and what’s not?

I need to be able to separate code from a string so that I can display and format the code. These strings are from the OpenAI API and I want to have it resemble the way code looks whenever it’s spat out.

For example, I would need to extract “function helloWorld() { console.log(“Hello, World!”); }” from this string so that it appears
“As an AI language model, I cannot write code in a specific programming language. However, here is an example of a JavaScript function that prints “Hello, World!” to the console:

function helloWorld() { console.log("Hello, World!"); }

This function can be called by simply typing in the console.”

I’m using highlight.js to apply syntax highlighting to the code, but it is also applying highlighting to non-code and can’t detect what is code and what isn’t.

Sometimes there will “`’s, which I wrote logic around to delimit the code blocks, but then it stopped including those altogether. The best I have are colons, and that’s not sustainable since colons will surely appear in regular English strings.

Live Server Command Not Found, after global install

Anytime I try to run “live-server”, I’m getting “bash: live-server: command not found”
I ran “npm install live-server -g”
and “sudo npm install live-server -g”
to install globally.

It was working fine before and then I started getting this issue.
Not building anything just working on a JS course on Udemy.
Total beginner, pretty lost

I tried reinstalling, restarting VS code, restarting my computer, etc.
Zero luck

What is wrong in this code of counter using js

The counter is not responding properly, when I run this code on clicking decrease btn counter shows 1 and in console it returns -1. On clicking again it keeps on logging 0.

const dec=document.getElementsByClassName("btn")[0];
const res=document.getElementsByClassName("btn")[1];
const inc=document.getElementsByClassName("btn")[2];
dec.addEventListener("click", decr);
dec.addEventListener("click", rese);
dec.addEventListener("click", incr);
var num=0;
function decr(){
  num=num-1;
  document.getElementById("count").innerHTML=num;
}
function rese(){
  num=0;
  document.getElementById("count").innerHTML=num;
}
function incr(){
  num=num+1;
  document.getElementById("count").innerHTML=num;
}

This is what I did.

Moving Hamburger Menu – React Bootstrap

I am trying to move my hamburger menu to the right. Nothing has worked, and it continues to stay on the left. I have tried float, shift right, alignment, and many other things. I have read all of the articles on Stack Overflow regarding this, but nothing has solved my issue. Would someone be able to assist me?

import { Link } from 'react-router-dom';
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';


// in the function the return will show what the html will look like
function NavigationBar( {user} ) {
return (
        <>
        <Navbar bg="navBackground" variant="dark" expand="lg">
            <Container>
                <Navbar.Toggle aria-controls='basic-navbar-nav'/>
                <Nav className='m-auto'>
                    <Nav.Link href="#about">About</Nav.Link>
                    <Navbar.Collapse id="responsive-navbar-nav">
                        {
                        {linksToUse.map((link) => (
                            <Nav.Link>{link}</Nav.Link>
                        ))}
                </Navbar.Collapse>
                </Nav>
            </Container>
        </Navbar>
        </>
    );
}

// export the component so it can be used outside of this file
export default NavigationBar;
/*Background color of the nav bar*/
.bg-navBackground{
    background-color: #333;
}

/*Makes the navbar icon background #333*/
.navbar-toggler-icon{
    background-color: #333;
} 

/*Makes the background of the collapse area #333*/
.navbar-collapse{
    background-color: #333;
}

/*Text color of nav links*/
.nav-link{
    color: #638797 !important;
    background-color: #333;
    text-align: center; /*Makes text centered in nav when screen sizes are smaller*/
}

/*Makes text appear white upon hovering*/
.nav-link:hover{
    color: white !important;
}

/*Makes the rest of the nav bar #333*/
.container{
    background-color: #333;
}

I am making a function that will make a click event happen at a specified vector on html5 canvas

It has been awhile since I have worked on my game engine. I have been testing some functions from my code library and I noticed one of my functions are not working anymore(or I forgot how to use it?). Basically this function takes a position, size and a callback function. It will then allow you to use that callback function to execute some code when you click on the specified position that you gave it(it also takes the size vector into account, so you can make the click area as big as you want).

I wrote a jsFiddle example so you can easily test it out. As you can see in the example when you click on the blue box nothing happens(it is suppose to log “clicked” in the console).

jsFiddle example

let Event = function(parent,event,fn,bool){
    parent.addEventListener(event,fn,bool);
};

// why does not work??? i wrote this years ago and i remember it working.
let clickDetector = function(vectorPos,vectorSize,fn){
    this.event = function(){
        new Event(canvas,"click",function(e){
            let x = e.clientX,
                y = e.clientY;

            if(Math.pow(x-vectorPos.x,vectorSize.y)+
               Math.pow(y-vectorPos.y,vectorSize.x)< 
               Math.pow(vectorSize.x,vectorSize.y)){
                fn();
            }
        },false);
    };
};