What is *actually* happening within this stale closure?

I feel as though my knowledge with closures is almost there, but I’m struggling to grasp exactly why this first code snippet logs 0 (is a stale closure) however, the second code snippet works and logs the updated value ..

Is this some kind of reference issue?

In the first example, are we not tracking the reference of count and only assigning its initial value to message?

By moving the message variable inside of the log function are we somehow telling JS to track the reference of the count value?

function createIncrement() {
  let count = 0;

  function increment() {
    count++;
  }

  let message = count;
  function log() {
    console.log(message);
  }

  return [increment, log];
}

const [increment, log] = createIncrement();

increment();
log();

// this will log 0
function createIncrement() {
  let count = 0;

  function increment() {
    count++;
  }

  function log() {
    let message = count;
    console.log(message);
  }

  return [increment, log];
}

const [increment, log] = createIncrement();

increment();
log();

// this will log 1

Not able to store the values into Firebase using react

I am new to React and Javascript.I am developing a meet-up application that has a form and when I fill its values and press submit,it should store the values into firebase.I am using fetch API and passing the values using POST method.The folder structure is shown below:
enter image description here

The form data is in NewMeetupForm.js shown below:
NewMeetupForm.js

import {useRef} from 'react';
import Card from "../ui/Card";
import classes from "./newmeetupformmodule.css";
function NewMeetupForm(props){

    const titleinput=useRef();
    const imageinput=useRef();
    
    function submitHandler(event){

        event.preventDefault();
        const enteredtitle=titleinput.current.value;
        const enteredimage=imageinput.current.value;            

        const meetupdata={
            title:enteredtitle,
            image:enteredimage,
        }
        console.log(meetupdata);
        props.onAddMeetup(meetupdata);

    }
return <Card>
    <form className={classes.form} onSubmit={submitHandler}>
    <div className={classes.control}>
        <label htmlFor="title" >Meetup Title</label>
        <input type="text" required id="title" ref={titleinput}></input>
    </div>
    <div className={classes.control}>
        <label htmlFor="image" >Meetup Image</label>
        <input type="url" required id="image" ref={imageinput}></input>
    </div>
    <div className={classes.control}>
        <button>Add meetup</button>
    </div>
    </form>
    </Card>

}
export default NewMeetupForm;

But when I run the application in browser and pass values,I see null in firebase.I
The file where I pass the db url is shown below:
Newmeetup.js:

import NewMeetupForm from "../components/Meetups/NewMeetupForm";


function NewmeetupPage() {
           
  function addmeetuphandler(meetupdata) {
    fetch(
      'https://react-getting-started-e38d3-default-rtdb.firebaseio.com/meetup.json',
      {
        method:'POST',
        body:JSON.stringify(meetupdata),
        headers: { 'Content-Type': 'application/json' }
      }
    );
  }
  return (
    <section>
      <h1>Addnewmeetup</h1>
      <NewMeetupForm onAddMeetup={addmeetuphandler} />
    </section>
  );
}

export default NewmeetupPage;

When I run the app in broswer and pass the values in form and click on submit,no table is created in firebase.I just get a null value.The screenshot is shown below:

enter image description here

The rules is also shown below:
enter image description here

Also,for reference,my github link to the project:https://github.com/suchitraa/Reactlatest .I get a null value in Firebase instead of the values getting stored.Could anyone please help me out with this?

How can you replace a string in a JavaScript object with a number?

enter image description here

In the code, lat and lng are initialized as number types, but why does it become string when you put it in an object?
I want the coordinate values to be numbers.
What can I do?

ex) lat: “35.87” -> lat: 35.87

let lat_tmp = 0;
let lng_tmp = 0;
const lat_lng = [];
let lat_tmp = 0;
let lng_tmp = 0;
let arr_tmp = [
  {
    lat: 0,
    lng: 0,
  },
];
let idx = 0;
function successFunction(data) {
  var allRows = data.split(/r?n|r/);
  for (var singleRow = 1; singleRow < allRows.length; singleRow++) {

    var rowCells = allRows[singleRow].split(',');
    for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
      if (rowCell === 3) {
        lat_tmp = rowCells[rowCell];
      } else if (rowCell === 4) {
        lng_tmp = rowCells[rowCell];
      }
    }
    arr_tmp = [{ lat: lat_tmp, lng: lng_tmp }];
    lat_lng[idx] = arr_tmp;
    idx += 1;
  }
  console.log(lat_lng);
}

How to scale up and SVG from with in path instead of adding width and height?

I have this icon in the following code , the problem with this icons is it has a big, margin all over, and in my case I want it to get that margin to be smaller, or the icon a litter bigger, ,instead of increasing the general size as you will see the current implementation in the code.
any idea how to achieve this I tried some solutions but none has worked.

import { ReactComponent as icon } from '../../Img/icon.svg';

// style 
const iconStyle = {
  padding: 0,
  marginTop: -5,
  backgroundColor: '#ef6c00',
  fill: 'white',
};

// inside the component
<icon style={iconStyle} width='24' height='24' />

How to search for a string with an array substring

I have an array like this

[
  "Grape | 100 |Food Catering Service",
  "Apple | 100,000m |Food Catering Service",
  "Water Melon | 100,000m |Catering Service Outside",
  100,000m |Food Catering Service Outside
]

Using typescript i’m trying to make sure that atleast with a substring in the array there is the value Food.
Even though the third substring within this arrat has no food it should still pass.

Code i’ve tried so far but does not do the job. It just returns the array

export function arraySubstring (expected:string, ignoreCase?: boolean): Expectation<string[], 
string> {
return Expectation.that("test", expected, async(actor: Actor, actual: string[]): 
Promise<boolean> ==> {

try {
for (const value of actual) {
if(ignoreCase) {
if (value.toLowerCase().includes(expected.toLowerCase())) return true;
} else {
if (value.includes(expected)) return true;
}
}
return false;
})
}

Syntax for creating an array with a key

I have this piece of code that pushes a new array inside another array:

pickedRocks.push([lastBin.rocks.pop()])

Before I push it I want to pass some keys too, to avoid keeping track of indexes, because I’m going be pushing more arrays. Is my only option to add the key after creation?

I tried:

pickedRocks.push([lastBin.rocks.pop(),key:500])

but it doesn’t work. And I’d like to not wrap it in another object to avoid rewriting other code.

React list already using unique keys but still getting unique key missing error in dev tools console

React (Next.js) list already using unique keys but still getting unique key missing error in dev tools console.

Here’s the container:

  <Container className={'menuList'}>
    {this.props.menuList.map((v, i) => (
        <MenuListCategory
            key={v.id + ' ' + v.name}
            closeM={this.props.handleMenu}
            listNames={this.props.listNames[i]}
            icon={v.icon}
            title={v.name}
        />
    ))}
  </Container>;

And here the API:

  {
    "menuList": [
        {
            "id": 1,
            "name": "CategoryXYZ",
            "icon": "places:XYZ",
        },

        ...

   }

Since id is unique, I expected it to work as a unique key but somehow it doesn’t. Both name and id are already unique. I’ve tried using key={v.id} and key={v.name} though both give the same error in dev tools dev tools React component tab, found below, via the Chrome extension for React debugging. I also tried the even more unique key={v.id + ' ' + v.name} but get the same result.

Am getting this warning in React dev tools:

Warning: Each child in a list should have a unique “key” prop. Check
the render method of MenuListCategory

I’m trying to avoid installing a package to manage the unique id.

Any suggestions on how to fix this?

Surely, it’s been encountered before, I’m just not able to find anything regarding already having unique id which aren’t being recognised as unique.

Is this the correct way to use async/await?

I have the following code:

var execute = async (assets: DCXComposite[], session: Session) => {
            return await session.performBatchOperation();
        };

        try {
            var assets: Composite[] = [];
            for (const project of projects) {
                assets.push(project.getComposite());

                if (assets.length === 50) {
                    var result = execute(assets);
                    assets = [];
                }
            }
        } catch (err) {
            Logger.error('Unable to batch delete projects', { error: err });
        }

Is this how to use async/await? If one of the executes fails, does the whole code fail and get thrown into the catch block? Meaning the next 50 projects do not get executed? What happens when the await throws an error?

How to end Flask SocketIO with Crtl+C, tried signal.SIGINT

How do I end socket gracefully? I tried using signal.SIGINT but no success.

Is there another way? I’m running in development and can’t seem to stop socket after Crtl+C. Browser console log continues to print and locks the browser from reloading the page when app.py starts up again.

enter image description here

Here is my app.py

from logging.handlers import SocketHandler
import os
import pandas as pd
import json
import threading
import signal
from flask import Flask, render_template, session, request, jsonify

from flask_socketio import SocketIO
from flask_cors import CORS, cross_origin

app = Flask(__name__)
app.debug = True
socketio = SocketIO(
    app, cors_allowed_origins="*", always_connect=True, async_mode="threading"
)

app.config["SECRET_KEY"] = "secret!"


def signal_handler(signum, frame):
    exit_event.set()
    SocketHandler.close(socketio)


exit_event = threading.Event()


@socketio.on("response_demo")
def background_task_func():
    """Example of how to send server generated events to clients."""
    i = 0

    while True:
        if exit_event.is_set():
            print(f"completed {threading.current_thread().name} : {os.getpid()} ")
            socketio.disconnect()
            socketio.settimeout(2)
            socketio.close()
            # SocketHandler.close(socketio)
            break
        socketio.sleep(5.05)
        data = {
            "Name": "data packet",
            "p": [{"x": i, "a": 12, "b": 12, "c": 10, "d": 10, "e": 10}],
        }
        data_2 = pd.DataFrame(data)
        df_json = data_2.to_json(orient="records")
        result = {"objects": json.loads(df_json)}
        socketio.emit("my_response", result, broadcast=True)


@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("index-so.html")

    exit_event.clear()
    val = request.json.get("c_check")
    bg = threading.Thread(target=background_task_func, daemon=True)

    if val == 1:
        # bg.start()
        print(f"c_check = 1")
    elif val == 0:
        try:
            print("trying to kill thread")
            exit_event.set()
        except Exception as e:
            print(e)
        print("val0 is ", val)
    response = jsonify({"data": {"val": val}})
    return response


if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal_handler)
    socketio.run(
        app, logger=True, engineio_logger=True, use_reloader=True, debug=True, port=5000
    )

Codeigniter 4 Product Multiple İmage Upload

I need to upload images before adding the product in my project, but I couldn’t get out of it. Since pictures will be added before the product is added, I do not know how to define the product number on the picture. I am waiting for your help in this regard.

Adding products and uploading images

$PostData = [
        'id'              => $this->request->getVar('id'),
        'name'            => $this->request->getVar('name'),
        'description'     => $this->request->getVar('description'),
        'options'         => $this->request->getVar('options'),
        'product_options' => $this->request->getVar('product_options'),
        'seo_tags'        => $this->request->getVar('seo_tags'),
        'price_purchase'  => $this->request->getVar('price_purchase'),
        'price'           => $this->request->getVar('price'),
        'price_discount'  => $this->request->getVar('price_discount'),
        'discount_date'   => $this->request->getVar('discount_date'),
        'tax_rate'        => $this->request->getVar('tax_rate'),
        'unit'            => $this->request->getVar('unit'),
        'free_shipping'   => $this->request->getVar('free_shipping'),
        'images'=>$this->request->getFileMultiple('files')
    ];

    if ($this->request->getFileMultiple('files')) {

        foreach($this->request->getFileMultiple('files') as $file)
        {   

           $file->move(WRITEPATH . 'uploads');

         $data = [
           'name' =>  $file->getClientName(),
           'type'  => $file->getClientMimeType()
         ];

         
        }
      
   }

   


    if ($id) {
        if (!$this->model->find($id)) {
            return $this->respond(['message' => "Ürün bulunamadı"], 400);
        }

        if (!$this->model->update($id, $PostData)) {
            return $this->respond(['message' => "Ürün güncellenirken hata oluştu lütfen sonra tekrar deneyin"], 400);
        }

        return $this->response->setStatusCode(200);
    }

    if (!$this->model->insert($PostData)) {
        return $this->respond(['message' => "Ürün güncellenirken hata oluştu lütfen sonra tekrar deneyin"], 400);
    }

    return $this->response->setStatusCode(200);

Adding padding around a 2D JavaScript array

I am attempting to create a function that pads a 2D array with zeros. I have made the following function:

function addPadding(arr){
    var a = new Array(arr.length + 2).fill(0)

    //left and right padding
    arr.forEach(el => {
        el.push(0)
        el.unshift(0)
    })

    //top padding
    arr.unshift(a)

    //bottom padding
    arr.push(a)

    return arr;
}

console.table(addPadding(addPadding([[1,2],[3,4]])));

The function works fine if I only call it once, but if I call it twice, like in this example, I get the following table:

enter image description here

My function has an unintended result, it has added extra zeroes for 2 rows. Does anyone know why this is happening?

How to mock the elements of react-hook-form when testing with react-testing-library?

Having a basic component which uses react-hook-form:

const { handleSubmit, reset, control } = useForm({
resolver: yupResolver(schema)
});

  <MyComponent
    title='title'
    open={isOpened}
    control={control}
  />

This component has 3 props, title – a string, open – a function, control – no idea what is it, all of them mandatory.

So, when writing a test for it I got stuck here:

import { render } from '@testing-library/react';

import '@testing-library/jest-dom';
import MyComponent from './my-component';

describe('MyComponent', () => {
  const title = 'title';
  it('should render successfully', () => {
    const { baseElement, getByText } = render(
      <TaskModal
        title={title}
        open={jest.fn()}
        control={} // what should be written here?
      />
    );
    expect(baseElement).toBeTruthy();
    expect(getByText(title)).toBeTruthy();
  });

How can control be mocked for this test?

how to debug adding hash to location?

I have a very old javascript application. On the very start of loading a page, something adds hash to window.location.

how can I set a breakpoint and see where it’s being added? It’s done during page loading, I think one of included js files add this hash (there are like 30 of them). I need to remove it (when some creteria are met)

javascript – use a variable from another function javascript – ‘today is not defined at Object’

I try to get todays date to use it in an URL (concatenation) with a function. But, each time I’ve tried to run it, i have the same error : today is not defined at Object

I tried to declare it with and without var/let/const but the error stays. Does someone have an idea (console.log()) is just to test)?

function GetTDDate() {
  today = new Date();
  var dd = String(today.getDate()).padStart(2, '0');
  var mm = String(today.getMonth() + 1).padStart(2, '0');
  var yyyy = today.getFullYear();

  today = yyyy + '-' + mm + '-' + dd;
  console.log(today);
}

const FetchURL = "https://static.data.gouv.fr/resources/donnees-relatives-aux-personnes-vaccinees-contre-la-covid-19-1/20211221-212503/vacsi-tot-fra-" + today + "-21h25.json"
console.log(FetchURL)

How do you convert an array of objects into an object of object

I am having trouble converting an array of objects into an object of objects for my job. The company API is expecting the data in this format. Any help would be appreciated. Here is an example

Original

const array = [
 {
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 },
{
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 }
]

Final

const array = {
 {
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 },
{
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 }
}