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)

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'
  }
 }
}

Playing with multiple HTML5 videos using play buttons (With an ID)

**I have a list of HTML5 videos that also have a play button.
Each play button has a unique identifier (as a class name), and then each video has a matching class name, so that I can assign a specific button to a specific video for playback.**

var videoPlayBackBtn = document.getElementsByClassName('video-play-button');
for (let item of videoPlayBackBtn) {
    console.log(item.id);
    item.addEventListener('click', function(){
        console.log(this);
    })
}

With the above JS I am able to get the identifier used for the video, and I wish to simply play the video with the matching identifier as the play button, and pause any other videos that don’t match. How can I target a specific video in this scenario?

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)

(1) table mytable has no column named number in “INSERT INTO mytable(number,name,email) VALUES (?,?,?)”

If I delete the line ” “number” + “text” “, the code works.

Error:

E/SQLiteLog: (1) table mytable has no column named number in “INSERT
INTO mytable(number,name,email) VALUES (?,?,?)”

E/SQLiteDatabase: Error inserting number=866454 name=TEST email=TEST

android.database.sqlite.SQLiteException: table mytable has no column
named number (code 1 SQLITE_ERROR): , while compiling: INSERT INTO
mytable(number,name,email) VALUES (?,?,?)

String name = text_name.getText().toString();
String email = text_email.getText().toString();
String number = text_phone.getText().toString();

SQLiteDatabase data_base = dbHelper.getWritableDatabase();

                    ContentValues container = new ContentValues();
                    container.put("name", name);
                    container.put("email", email);
                    container.put("number", number);
                    long rowID = data_base.insert("mytable", null, container);
                    Log.d("Log: ", "row inserted, ID = " + rowID);

AND

 @Override
        public void onCreate(@NonNull SQLiteDatabase db) {
            db.execSQL("create table mytable ("
                    + "id" + "integer primary key autoincrement,"
                    + "name" + "text,"
                    + "email" + "text,"
                    + "number" + "TEXT UNIQUE"
                    + ");");
        }