Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node. Got this error on typing in input box

I am trying to make a todo app in which I made a functionality of delete when ever I delete a element , the element is deleted successfully but as soon as I type in input box I get this error.
Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node.

import { React, useState } from 'react'
import "./todo.css"

function Todo() {
    const [value, setValue] = useState("")  //input value
    const [items, setitems] = useState([])  //items to be added

    function handleClick() {
        //  Adding items in a item array
        setitems(items.concat(value))
        setValue("")
    }

    function handleChange(e) {
        // Fetching input value
        setValue(e.target.value)
    }



    return (
        <>
            <div className='container'>
                <h1 id='mainhead'>Todo App</h1>
            </div>

            <div className='container1'>
                <input onChange={handleChange} value={value} placeholder='Enter a  task' type="text" />
                <button onClick={handleClick}>Add Item</button>
            </div>

            {/* mapping all the items */}

            {items.length !== 0 ? items.map((e) => {
                return <div className='item' key={e}><label>Task {items.indexOf(e) + 1}:</label> {e}

                    <button style={{float:"right" , backgroundColor:"red" , color:"white" , width:"80px" , height:"30px"}} onClick={()=>{

                        const child = document.getElementById("delete" + items.indexOf(e)) // accessing child
                        console.log(child)
                        child.parentElement.remove() //Deleting parent element
                        items.splice(items.indexOf(e),1) //removing element from items
                        setitems(items)   // updating items

                    }} id = {"delete" + items.indexOf(e)}>Delete</button> </div>
            })
                : null}



        </>
    )
}

export default Todo

I tried everything but nothing works help me to handle this error

Dealing with huge data files in NestJS with fast-csv

Im using NestJS v9, fast-csv v4 and BigQuery.

  1. My controller (I upload a huge CSV):
@Post('upload')
@ApiOperation({ description: 'Upload CSV File' })
@ApiConsumes('multipart/form-data')
@ApiBody({
  schema: {
    type: 'object',
    properties: {
      file: {
        type: 'string',
        format: 'binary',
      },
    },
  },
})
@ApiResponse({
  type: UploaderResponse,
  status: 200,
})
@UseInterceptors(FileInterceptor('file', { fileFilter: fileFilter }))
@Auth(UserRole.Admin, UserRole.SuperAdmin)
async uploadFile(
  @Body() uploadCsvDto: UploadCsvDto,
  @UploadedFile() file: Express.Multer.File,
): Promise<UploaderResponse> {
  if (!file) {
    throw new HttpException(FileErrors.CSVFormat, HttpStatus.BAD_REQUEST);
  }
  return await this.filesService.uploadCsv(file, uploadCsvDto);
}
  1. My service:
async uploadCsv(
  fileData: Express.Multer.File,
  uploadCsvDto: UploadCsvDto,
): Promise<UploaderResponse> {
  memoryUsage();
  await this.checkForDuplicates(uploadCsvDto);
  memoryUsage();

  // 2. Parse CSV
  await this.batchCsvResults(fileData.buffer, uploadCsvDto);
}

async batchCsvResults(
  buffer: Buffer,
  uploadCsvDto: UploadCsvDto,
): Promise<void> {
  const streamFromBuffer = Readable.from(buffer);
  const stream = parseStream(streamFromBuffer, {
    headers: (headers: string[]) => {
      return headers.map((h: string) => {
        if (this.checkCorrectColumn(h)) {
          return VALID_CSV_COLUMNS.find(
            (column: ValidColumn) => column.name === h.toLowerCase(),
          ).column;
        } else {
          console.log(`'${h}' no es una columna válida.`);
        }
      });
    },
    delimiter: ';',
    encoding: 'utf8',
    trim: true, // trim white spaces on columns only
  });

  let batch: DataRow[] = [];

  // Promise for waitting all the batches to end
  let resolvePromise: () => void;
  const processingPromise: Promise<void> = new Promise<void>((resolve) => {
    resolvePromise = resolve;
  });

  stream.on('data', async (row: DataRow) => {
    batch.push(row);

    if (batch.length === 200) {
      stream.pause();
      await this.processBatch(batch, uploadCsvDto)
        .then(() => {
          batch.length = 0;
          stream.resume();
        })
        .catch((err) => {
          console.error(err);
          stream.destroy();
        });
    }
  });

  stream.on('end', async () => {
    if (batch.length > 0) {
      await this.processBatch(batch, uploadCsvDto)
        .then(() => {
          batch = null;
          console.log('All batches have been processed');
        })
        .catch((err) => {
          console.error(err);
        });
    } else {
      console.log('All batches have been processed');
    }
    resolvePromise();
  });

  stream.on('error', (err) => {
    console.error(err);
  });

  await processingPromise;
}

async mapChildRows(
  data: DataRow[],
  uploadCsvDto: UploadCsvDto,
): Promise<void> {
  memoryUsage();
  let formattedRows = [];
  for (let i = 0; i < data.length; i++) {
    // Convert object values to their type
    const dataObject: any = data[i];
    Object.keys(dataObject).forEach((key) => {
      dataObject[key] = this.getChildColumnValue(key, dataObject[key]);
    });

    // Add dynamic fields
    dataObject[DYNAMIC_CSV_COLUMNS.idClient] = uploadCsvDto.idClient;
    dataObject[DYNAMIC_CSV_COLUMNS.subservice] = uploadCsvDto.subservice;
    dataObject[DYNAMIC_CSV_COLUMNS.subtask] = uploadCsvDto.subtask;

    // Add actual day to uploaded file. We have an extra space at the end of the array, because
    // they do not send us the upload_date, its a fixed column but a dynamic value added by us
    dataObject[DYNAMIC_CSV_COLUMNS.upload_date] = actualDate();
    formattedRows.push(dataObject);
  }

  memoryUsage();
  await this.insertIntoCustomAnalyticsBigQuery(formattedRows);
  data = null;
  formattedRows = null;
}

async insertIntoCustomAnalyticsBigQuery(rows: DataRow[]) {
  try {
    memoryUsage();
    await this.bigQueryClient.dataset(DB_NAME).table(DATA_TABLE).insert(rows);
    console.log(`Inserted ${rows.length} rows`);
  } catch (ex) {
    console.log(JSON.stringify(ex));
    throw new HttpException(
      'Error inserting into Data table from CSV.',
      HttpStatus.BAD_REQUEST,
    );
  }
}
  1. Explanation of the service:
  • First I check on BigQuery if I have duplicates from previous updated CSVs (this is not important).
  • Then I use a stream (fast-csv) to prevent location of all the csv content into memory.
  • I transform data every 200 rows and from those 200, I save into bigquery 50 each.
  • Finally, I save it into BigQuery.

Problem: this works well with files with 50.000 rows but higher it gives me memory problems:

50.000 row CSV:
enter image description here

250.000 row CSV:
enter image description here

I can’t understand why, when I empty all variables when no needed.

My node server also tells me that my max size of memory is 512MB.

My function to check memory:

export function memoryUsage(): void {
 return console.log(
  `APP is using ${
    Math.round((process.memoryUsage().rss / 1024 / 1024) * 100) / 100
  } MB of memory.`,
 );
}

cypress element selector is not responding

I am new in Cypress. and here is the website, for learning example
https://finviz.com/screener.ashx

I found that cypress element selector is not working when move the mouse over the pull down menu(no any point out, refer attached screenshotenter image description here). And here is my code in Visual Studio Code below:

///

it(‘Google Search’, () => {

cy.visit('https://google.com')
cy.get('.gLFyf').type('finviz{enter}')
cy.get(':nth-child(4) > .cIkxbf > .usJj9c > h3 > .l').click()

}
)

I want the cypress element selector is work, so that I can select the pull down menu correctly. Please le mt know where I am missing or my code is incorrect. Thank you

Unable to connect with mongodb using Nodejs Expressjs

I am working with nodejs/express js,Right now trying to run “existing project” (downloaded from github) in my local machine,But right now i am getting following error

MongoDB connection error: MongoParseError: mongodb+srv URI cannot have port number

In “mongodb atlas”(dashboard),here is my “connection url” (replaced username and password)

mongodb+srv://<username>:<password>@orbitXXXX.huykolo.mongodb.net/?retryWrites=true&w=majority

And here is my “.env” file,Where i am wrong ?

# MongoDB
DB_CLUSTER = "mongodb+srv://XXXXXXXXX:[email protected]/?retryWrites=true&w=majority"
DB_USER = "XXXXXXXXXX"
DB_PASS = "XXXXXXXXXXX"

Is there any plugin to find SQL in python? [closed]

I want to make a program using python or javascript.
A program is that if I paste a procedure, and then program highlights Exec, DDL, DML QUERY
(like below image)

enter image description here

the only way which I can make like this is using wild card, right?
(ex: If I want to find Select query. and then using wildcard Start to “Select” before end to other dml(select, insert, exec, trucate … etc)

or Is there any information which I can refer?

Thank you so much for reading!!

$(document).on(‘click’, ‘my id’, function()) equivalent in Vanilla JavaScript? [duplicate]

I’m trying to refactor some of my codes from jQuery to just Vanilla JavaScript wherever I can or think it’s simple enough that vanilla JavaScript is better. But I’m hitting a problem about targeting buttons that are created in Controller (AJAX purposes). I always get the error saying my Edit button is null. I assume it’s because it got fire first before the AJAX load the table data.

In jQuery, I can just use this code and it works beautifully:

            $(document).on('click', '#btn-edit', function() {
                $('#modal-title').html('Edit Products and Solutions');
                $('#btn-submit').val('Update Data');
                $('#btn-submit').html('Update Data');
            });

But I tried to do (what I thought) kinda similar things in JavaScript and it didn’t work:

            const btnEdit = document.getElementById('btn-edit');
            btnEdit.addEventListener('click', function() {
                document.getElementById('modal-title').innerHTML = 'Edit Products and Solutions';
                document.getElementById('btn-submit').value = 'Update Data';
                document.getElementById('btn-submit').innerHTML = 'Update Data';
            });

This is my Controller that I use to pass the button:

        if ($request->ajax()) {
            $query = DB::table('products_and_solutions');

            return DataTables::of($query)
                ->addColumn('action', function($productAndSolution) {
                    $action = '<button type="button" class="btn btn-success" data-id="' . $productAndSolution->id . '" id="btn-edit"><i class="bi bi-pencil-square"></i></button>';
                    $action .= ' <button type="button" class="btn btn-danger" data-id="' . $productAndSolution->id . '" id="btn-delete"><i class="bi bi-trash"></i></button>';

                    return $action;
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        return view('pages.admin.products-and-solutions.index');

This is my Blade that is related to this problem:

        document.addEventListener('DOMContentLoaded', function() {
            const btnEdit = document.getElementById('btn-edit');
            btnEdit.addEventListener('click', function() {
                document.getElementById('modal-title').innerHTML = 'Edit Products and Solutions';
                document.getElementById('btn-submit').value = 'Update Data';
                document.getElementById('btn-submit').innerHTML = 'Update Data';
            });
        });

Can someone please help me?

on button hover remove text and show image

I have a button with a number and a arrow and on hover want to remove number and show arrow but with transition , like number will fade away to right side and arrow will be visible. here is code.
go to whole code in code sandbox

.welcomebox_down {
  display: flex;
  flex-direction: row;
  gap: 10px;
  align-items: center;
  margin-top: 10px;
}
.welcomebox_option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  cursor: pointer;
  padding: 15px;
  min-width: 206px;
  transition: all 500ms ease-in-out;
  color: #112960;
}

.welcomebox_option > img {
  width: 20px;
}
/* not show border in last div only */
.welcomebox_option_box:not(:last-child) {
  border-right: 1px solid;
  padding-right: 10px;
}
/* remove extra margin from p */
.welcomebox_option p {
  margin: 0 !important;
  transition: all 500ms linear;
}
/* on hover shows img2 */
.welcomebox_option:hover .img2 {
  display: block;
}

/* on hover show border */
.welcomebox_option:hover {
  border: 1px solid #112960;
  border-radius: 5px;
  width: 500px;
}
/* on hover remove text, default none img2 */
.welcomebox_option:hover p:nth-child(3),
.welcomebox_option .img2 {
  margin-left: 1rem;
  display: none;
}

According to product inventory display the order no. that cannot be processed further

ABC company wants an order processing system for their order and inventory management.
According to product inventory display the order no. that cannot be processed further. Also,
Update the status of order completed if stock is available, otherwise set cancel.
Order Table :-
ID Order No. Product Code Qty Status
1 ORD001 P001 5 Pending
2 ORD002 P002 10 Pending
3 ORD003 P003 5 Pending
4 ORD004 P001 13 Pending
5 ORD005 P004 1 Pending
6 ORD006 P003 3 Pending
7 ORD007 P001 10 Pending
8 ORD008 P002 5 Pending
9 ORD009 P003 4 Pending
10 ORD010 P001 3 Pending
11 ORD011 P002 2 Pending
12 ORD012 P003 5 Pending
13 ORD013 P002 3 Pending
14 ORD014 P004 6 Pending
15 ORD015 P002 2 Pending
Product Table :-
ID Code Stock
1 P001 20
2 P002 30
3 P003 15
4 P004 35

itry to match array

Cannot set CSRF cookie using Laravel Sanctum on the frontend

I was recently trying to implement the Laravel Sanctum authentication with Nuxt 3, but have come across a problem with the initial CSRF cookie handshake. The thing is that after I make a request to the http://localhost:8000/sanctum/csrf-cookie path browser does not set the XSRF-TOKEN cookie. I am stuck on this problem for a week already and have not yet found a solution anywhere on the internet.
I tried using both Axios and Fetch API to set XSRF-TOKEN, yet with no success. I am using http://localhost:8000 on the backend and http://localhost:3000 on the front end. Laravel Sanctum itself works fine since I receive set-cookie headers when tested on Postman, but the browser does not receive them. I have set the following properties in the .env file:

    FRONTEND_URL=http://localhost:3000
    SESSION_DOMAIN=localhost:3000
    SESSION_DRIVER=cookie

I did everything to overcome the limitations of the CORS requests on front end. My fetch function looks as follows:

      window.fetch('http://localhost:8000/sanctum/csrf-cookie', {
        credentials: 'include',
      }).then((response) => {
        console.log(…response.headers)
      })

I have read that setting credentials to ‘include’ solves the problem, but even while doing so, I am unable to set XSRF-TOKEN. I tried to set credentials to ‘same-origin’, but that doesn’t work either. Does anybody know how this problem could be solved?

What are the alternatives to HTML5 Canvas on the server side?

I’m an Asp.net & C# & and Angular guy. Recently, I’ve been playing around with HTML5 Canvas using Konva. It is a lot of fun and I can use it to fulfil a need for certain audience. I But its drawback is that it is client-based; any savvy programmer can get around the javascript code. I want to start right, what are your ideas?

The only thing I could come up with is to rent time slots to Virtual Machines where they will execute a WPF or winforms executables. Or let them use a canvas javascript app on my virtual machines and maybe I’ll be able to control the browser and its javascript

Please point me to where I should start?

Function works perfectly on certain tabs/sheets, but not on others

My Goal: Be able to run the script from any tab/sheet

Key Issue: The script works as intended when I have one of my ‘Week’ tabs open. However, when I’m on any other tab, I get:
Error Exception: Range Not Found @ line 5. The variable in line 5 references a named range in my tabs called Week 1, Week 2, etc., which leads me to believe that the script is running on whichever tab I have open, and not only on the weekly tabs.

I feel like the fix here is relatively simple, but I just can’t seem to crack it. I’m really new to loops of any kind. Any and all help is very appreciated.

https://docs.google.com/spreadsheets/d/1244w0mAmnkAfmOdfk2mbcnraJdJK7Pah3uzqeiQh3E4/edit?usp=sharing

function createMaxList() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const target = ss.getSheetByName('Rep PR Data');
  const sheets = ss.getSheets();
  const tableCol = ss.getRange("RepPrTracking").getColumn(); //dynamically references the table header in the weekly tabs
  const results = [['Week', 'Exercise', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10','e1RM']];

  sheets.forEach(s => { 
    const name = s.getName() //Name of every tab in the spreadsheet
    if (!name.match(/Week[sS]d/)) {

      return;
    }

    s.getRange(3, tableCol, s.getLastRow() - 2, 12).getValues()
      .forEach((row) => {
        const [exc] = row
        if (exc == "" || exc == "Reps:" || !exc) {
          return;
        }
        results.push([name, ...row])
      })
  })

  target.getDataRange().clearContent() //clears 'Rep PR Data' tab
  target.getRange(1, 1, results.length, results[0].length).setValues(results) //places data in 'Rep PR Data'

}

React Multi Coursel Slides only showing 2 of 3

I’m making a header that slides to show alternate slides on the landing page.

I’m Currently having a problem with my carousel in which it only displays 2/3 divs when pressing to slide right, but when you press to slide left it shows 3/3 divs. Which is what I am aiming for.

Its a pretty basic set up and I’ve used it before I’m just a bit confused as to why this may not be working.

Some help would be great.

import React from "react";

import "./Header.scss";
import Carousel from "react-multi-carousel";
import { images } from "../../../../Assets/Images";
export default function Header() {
  const responsive = {
    superLargeDesktop: {
      // the naming can be any, depends on you.
      breakpoint: { max: 4000, min: 3000 },
      items: 1,
    },
    desktop: {
      breakpoint: { max: 3000, min: 1024 },
      items: 1,
    },
    tablet: {
      breakpoint: { max: 1024, min: 464 },
      items: 1,
    },
    mobile: {
      breakpoint: { max: 464, min: 0 },
      items: 1,
    },
  };

  return (
    <Carousel
      containerClass="carousel__container app__flex"
      sliderClass="itemSlider__content"
      itemClass=""
      responsive={responsive}
      infinite={true}
      slidesToSlide={1}
      autoPlay={true}
      autoPlaySpeed={7000}
      rewindWithAnimation={false}
      rewind={true}
    >
      <header
        style={{
          backgroundImage: ` linear-gradient(to bottom, var(--black-color), rgba(253, 253, 253, 0)),
      url(${images.headerImg1})`,
        }}
      >
        <div className="col header__content app__container-width">
          <h1 className="head-text">Fuel Your Fitness Journey with Our Store</h1>
          <p className="p-text">
            Whether you're a seasoned athlete or just starting out, our fitness store offers a wide
            range of products to help you perform at your best, including protein powders, energy
            bars, and sports drinks.
          </p>
          <button className="btn btn__accent">
            Shop now <i className="bi bi-box-arrow-in-up-right"></i>
          </button>
        </div>
      </header>
      <header
        style={{
          backgroundImage: ` linear-gradient(to bottom, var(--black-color), rgba(253, 253, 253, 0)),
      url(${images.headerImg2})`,
        }}
      >
        <div className="col header__content app__container-width">
          <h1 className="head-text">Fuel Your Fitness Journey with Our Store</h1>
          <p className="p-text">
            Whether you're a seasoned athlete or just starting out, our fitness store offers a wide
            range of products to help you perform at your best, including protein powders, energy
            bars, and sports drinks.
          </p>
          <button className="btn btn__accent">
            Shop now <i className="bi bi-box-arrow-in-up-right"></i>
          </button>
        </div>
      </header>
      <header
        style={{
          backgroundImage: ` linear-gradient(to bottom, var(--black-color), rgba(253, 253, 253, 0)),
url(${images.headerImg3})`,
        }}
      >
        <div className="col header__content app__container-width">
          <h1 className="head-text">Fuel Your Fitness Journey with Our Store</h1>
          <p className="p-text">
            Whether you're a seasoned athlete or just starting out, our fitness store offers a wide
            range of products to help you perform at your best, including protein powders, energy
            bars, and sports drinks.
          </p>
          <button className="btn btn__accent">
            Shop now <i className="bi bi-box-arrow-in-up-right"></i>
          </button>
        </div>
      </header>
    </Carousel>
  );
}


making an image box in Razor page

I want to make an image box on my razor page so that users can type or sign their name in that box. I want something like adobe acrobat offers. below is the screen shot:

enter image description here

How can I achieve this. Once the user puts the signature in the abve box, I want the signature to be exported to the pdf form signature field.

How to resolve the following error? “Cannot read properties of undefined (reading ‘toLowerCase’)

I am making a project on React and have come across an error which I have given below.

I am trying to resolve the error but am unable to do so.

Can someone please help?
The error is as follows:
Cannot read properties of undefined (reading ‘toLowerCase’)
TypeError: Cannot read properties of undefined (reading ‘toLowerCase’)

App.js

import "./App.css";
import Navbar from "./Components/Navbar";
import TextForm from "./TextForm";
import React, { useState } from "react";
import Alert from "./Components/Alert";

function App() {
  const [mode, setMode] = useState("light");
  const [alert, setAlert] = useState(null);

  const showAlert = (message, type) => {
    setAlert({
      msg: message,
      type: type,
    });
    setTimeout(() => {
      showAlert(null);
    }, 1000);
  };

  const toggleMode = () => {
    if (mode === "light") {
      setMode("dark");
      document.body.style.backgroundColor = "black";
      showAlert("The dark mode has been set", "success");
    } else {
      setMode("light");
      document.body.style.backgroundColor = "white";
      showAlert("The light mode has been set", "success");
    }
  };
  return (
    <>
      <Navbar toggleMode={toggleMode} mode={mode} />
      <Alert alert={alert} />
      <TextForm
        heading="This is textarea"
        mode={mode}
        alert={alert}
        showAlert={showAlert}
      />
    </>
  );
}

export default App;

Alert.js

import React from "react";

export default function Alert(props) {
  const capitalize = (word) => {
    const lower = word.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };
  return (
    props.alert && (
      <div
        class={`alert alert-${props.alert.type} alert-dismissible fade show`}
        role="alert"
      >
        <strong>{capitalize(props.alert.type)}</strong>:{props.alert.msg}
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="alert"
          aria-label="Close"
        ></button>
      </div>
    )
  );
}