R-Script create additionial array prefixes. How avoid?

I use this R-Sript to get metadata from a FLIR Thermographie Image:

library(Thermimage)
inFile <- inFile
fd <- flirsettings(inFile)

This is executed by php to get back the result in json:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        $exifData = exif_read_data($uploadFile);

        if ($exifData !== false) {
            $inFile = $uploadFile;

            exec("Rscript -e 'library(Thermimage); fd <- flirsettings("$inFile"); cat(paste(fd$Info$Emissivity, fd$Info$IRWindowTemperature, fd$Info$IRWindowTransmission, fd$Info$RelativeHumidity, fd$Info$PlanckR1, fd$Info$PlanckB, fd$Info$PlanckF, fd$Info$PlanckO, fd$Info$PlanckR2, fd$Info$AtmosphericTransAlpha1, fd$Info$AtmosphericTransAlpha2, fd$Info$AtmosphericTransBeta1, fd$Info$AtmosphericTransBeta2, fd$Info$AtmosphericTransX, sep=","))' 2>&1", $output);
            $fd= explode(",", $output[0]);

            function extractNumbersFromString($str) {
                // Verwende eine reguläre Expression, um nur Zahlen zu extrahieren
                preg_match_all('/-?d+(.d+)?/', $str, $matches);
            
                // Extrahiere gefundene Zahlen aus den Matches
                $numbers = array_map(function ($match) {
                    return floatval($match);
                }, $matches[0]);
            
                return $numbers;
            }
            
            // Extrahiere Zahlenwerte aus der Beispiel-Liste
            $extractedNumbers = array_map('extractNumbersFromString', $fd);

            // Erstelle ein assoziatives Array mit den Metadaten
            $metadataArray = [
                'exifData' => $exifData,
                'fdData' => $extractedNumbers,
            ];

            // Verwende json_encode, um das kombinierte Array in JSON umzuwandeln
            header('Content-Type: application/json');
            echo json_encode($metadataArray);
        } else {
            echo 'Fehler beim Lesen der Metadaten.';
        }
    } else {
        echo 'Fehler beim Hochladen des Bildes.';
    }
} else {
    echo 'Ungültige Anfrage.';
}
?>

This create the following output in JSON:

{
    "fdData": [
        [
            0.85
        ],
        [
-->         1,
            20274.629
        ],
        [
            1488.9
        ],
        [
            1
        ],
        [
            -4440
        ],
        [
-->         2,
            0.033941466
        ],
        [
-->         1,
            0
        ],
        [
-->         2,
            0
        ],
        [
-->         1,
            0.00318
        ],
        [
-->         2,
            0.00318
        ],
        [
            0.732
        ],
        [
            2.3
        ],
        [
            2.3
        ],
        [
            2.3
        ],
        [
            299
        ],
        [
            297
        ],
        [
            24
        ],
        [
            23
        ],
        [
            20
        ],
        [
            120
        ],
        []
    ]
}

On –> marked pos. you can see the addidtional prefixes. I don’t know why this happends, on my oppinion this data aint exist in the metadata. Something in the R-Sricpt is doing that, but I don’t have expirience in R.

Someone is having a tip, how I can aviod this?

You can test this function here: https://gracile-software.de/projects/raumzeitkrueger_neu/

Download a thermographie img her before: https://gracile-software.de/projects/raumzeitkrueger/img/FLIR0305.jpg

How can i use multiple(not single) client certificates to login in with cypress?

Can we use multiple client certificates for login purpose. For ex: I need to login application as [email protected] then again i need to login as [email protected]. So is it possible to login as multiple user using certificates?

I have successfully configured for one client certificate and successfully logged in. but not able to find a solution for multiple logins with different user ids? Looking forward for a solution

I stored certificates in cert folder and link it in cypress.config file and it worked for a single certificate.

how to apply cronjob to automate execution when specific function called while using ajax

I want to send page data to external resource through cronjob while using cPanel. But when I did it manually it worked while using cronjob it did not worked.

here is the actual scripts which I want to automate using cronjob
index.php

<script>
function select_all_booking()
  {
    var check_all = $("#th_booking").is(":checked");
    if(check_all == true)
    {
      $(".check_all").prop("checked",false);   
    }
    else
    {
      $(".check_all").prop("checked",true);  
    }
  }
  function show_ntmp_detail(hb_id)
  {
    $("#show_ntmp").modal("show");
    $.post("?",{hb_id:hb_id,show_error_log:true},function(data){
      if(data!="")
      {
        $(".show_ntmp_history_detail").html(data);
      }
    });
  }

  function get_posted_record()
  {
    var fdatep = $("input[name=fdatep]") .val();
    var tdatep = $("input[name=tdatep]") .val();
    var branchp = $("select[name=branchp] option:selected").val();
    $.post("postdata_stch_posted_record.php",{fdate:fdatep,tdate:tdatep,branch:branchp},function(data){
      $(".show_posted_record").html(data);
    });
  }
</script>

actually this code is part of index.php file. Besides the given code, index.php file contains php code within html imbedded.

I want to do some thing like this it send data to external resource after every 10 minutes.

What I tried

*/10 * * * * /usr/local/bin/php /path/to/index.php

How do I do this but for specifically desktop firefox only?

I have no Js knowledge and I have this Js code

<script>
(function(a,b){if(/(android|bbd+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0,4)))window.location=b})(navigator.userAgent||navigator.vendor||window.opera,'index.html');
    </script>

and it is to detect mobile browsers then redirects to another site. But now I really want something for desktop firefox only cause on firefox my font for example 14px will be like 16 or something like that so I want to do this exact code for FF so I could reduce the font size. If you can help me, please comment. Thankyou so much

I dont really know what to try

Page Size rerendering issue with mantine datatable

I’m struggling and going mad for a month to find out why react is not react-ive.

Genuinely, I’m going mad.

This is the issue:

SortingTable.tsx

import { DataTable, DataTableSortStatus } from 'mantine-datatable';
import React, { useEffect, useState } from 'react';
import sortBy from 'lodash/sortBy';
import { useDispatch, useSelector } from 'react-redux';
import { IRootState } from '../../store';
import Dropdown from '../../components/Dropdown';

interface SortingTableProps {
    rowData: any;
    filtered: any;
    initialRecords: any[];
    setInitialRecords: any;
    tableName: any;
    columns: any;
    search: any;
    setSearch: any;
    hideCols: any;
    setHideCols: any;
    toggleCols: any;
    pageSize: any;
    setPageSize: any;
    PAGE_SIZES: any[];
    totalRecords: number;
    handlePageChange: any;
    page: any;
    isLoading: boolean;
}

const SortingTable: React.FC<SortingTableProps> = ({
    rowData,
    filtered,
    initialRecords,
    setInitialRecords,
    tableName,
    columns,
    search,
    setSearch,
    hideCols,
    setHideCols,
    toggleCols,
    pageSize,
    setPageSize,
    PAGE_SIZES,
    totalRecords,
    handlePageChange,
    page,
    isLoading,
}) => {
    const dispatch = useDispatch();

    const isRtl = useSelector((state: IRootState) => state.themeConfig.rtlClass) === 'rtl' ? true : false;

    const [recordsData, setRecordsData] = useState(initialRecords);
    const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({ columnAccessor: 'id', direction: 'asc' });

    useEffect(() => {
        setRecordsData([...initialRecords]);
    }, [initialRecords, initialRecords !== undefined]);

    useEffect(() => {
        setInitialRecords(() => {
            return filtered(rowData, search);
        });
    }, [search, rowData]);

    useEffect(() => {
        const data = sortBy(initialRecords, sortStatus.columnAccessor);
        setInitialRecords(sortStatus.direction === 'desc' ? data.reverse() : data);
    }, [sortStatus]);

    return (
        <div>
            <div className="panel mt-6">
                <div className="flex md:items-center md:flex-row flex-col mb-5 gap-5">
                    <h5 className="font-semibold text-lg dark:text-white-light">{tableName as string}</h5>
                    <div className="dropdown absolute right-60">
                        <Dropdown
                            placement={`${isRtl ? 'bottom-end' : 'bottom-start'}`}
                            btnClassName="!flex items-center border font-semibold border-white-light dark:border-[#253b5c] rounded-md px-4 py-2 text-sm dark:bg-[#1b2e4b] dark:text-white-dark"
                            button={
                                <>
                                    <span className="ltr:mr-1 rtl:ml-1">Columns</span>
                                    <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M19 9L12 15L5 9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                    </svg>
                                </>
                            }
                        >
                            <ul className="!min-w-max">
                                {columns.map((col, i) => {
                                    return (
                                        <li
                                            key={i}
                                            className="flex flex-col"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                            }}
                                        >
                                            <div className="flex items-center px-4 py-1">
                                                <label className="cursor-pointer mb-0">
                                                    <input
                                                        type="checkbox"
                                                        checked={!hideCols.includes(col.title)}
                                                        className="form-checkbox"
                                                        defaultValue={col.title}
                                                        onChange={(event: any) => {
                                                            setHideCols(event.target.value);
                                                            toggleCols(col.title, event.target.checked);
                                                        }}
                                                    />
                                                    <span className="ltr:ml-2 rtl:mr-2">{col.title}</span>
                                                </label>
                                            </div>
                                        </li>
                                    );
                                })}
                            </ul>
                        </Dropdown>
                    </div>
                    <div className="ltr:ml-auto rtl:mr-auto">
                        <input type="text" className="form-input w-auto" placeholder="Search..." value={search} onChange={(e) => dispatch(setSearch(e.target.value))} />
                    </div>
                </div>
                <div className="datatables">
                    {isLoading ? (
                        'loading'
                    ) : (
                        <DataTable
                            highlightOnHover
                            className={`${isRtl ? 'whitespace-nowrap table-hover' : 'whitespace-nowrap table-hover'}`}
                            records={recordsData}
                            columns={columns}
                            totalRecords={totalRecords}
                            recordsPerPage={pageSize}
                            page={page}
                            onPageChange={(p) => handlePageChange(p, pageSize)}
                            recordsPerPageOptions={PAGE_SIZES}
                            onRecordsPerPageChange={setPageSize}
                            sortStatus={sortStatus}
                            onSortStatusChange={setSortStatus}
                            minHeight={200}
                            paginationText={({ from, to, totalRecords }) => `Showing  ${from} to ${to} of ${totalRecords} entries`}
                        />
                    )}
                </div>
            </div>
        </div>
    );
};

export default SortingTable;

Revenues.tsx

import React, { useState } from 'react';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { setPageTitle } from '../store/themeConfigSlice';
import sortBy from 'lodash/sortBy';
import SortingTable from './DataTables/SortingTable';
import { IRootState } from '../store';
import { setSearch } from '../store/tablesSlice';
import TableModal from './Components/TableModal';
import { useUpdateRevenueMutation, useAddRevenueMutation, useGetRevenuesQuery, useDeleteRevenueMutation } from '../api/revenuesApi';
import { useGetAllOrdersQuery } from '../api/ordersApi';
import { getColumns, getIDOptions } from '../utils/functions';

const Revenues = () => {
const dispatch = useDispatch();

const search = useSelector((state: IRootState) => state.tables.searchVal);

const [initialRecords, setInitialRecords] = useState<any[]>([]);
const [modal, showModal] = useState<boolean>(false);
const [modalData, setModalData] = useState<any>({});
const [newRevenueModal, showNewRevenueModal] = useState<boolean>(false);
const [ordersOptions, setOrdersOptions] = useState<any[]>([]);
const [hideCols, setHideCols] = useState<string[]>([]);
const PAGE_SIZES = [10, 20, 30, 50, 100];
const [pageSize, setPageSize] = useState(PAGE_SIZES[1]);
const [revenues, setRevenues] = useState<any[]>([]);
const [page, setPage] = useState(1);
const [pagination, setPagination] = useState({ pageSize: pageSize, page: 1 });

//RTK Query
const { data: orders, refetch: refetchOrders } = useGetAllOrdersQuery();
const { data: rawData, refetch: refetchRevenues, isLoading } = useGetRevenuesQuery(pagination);
const [addRevenueMutation] = useAddRevenueMutation();
const [deleteRevenueMutation] = useDeleteRevenueMutation();
const [updateRevenueMutation] = useUpdateRevenueMutation();

const addRevenue = (revenue: any) => {
    addRevenueMutation(revenue).unwrap();
};

const deleteRevenue = (id: any) => {
    deleteRevenueMutation(id).unwrap();
};

const updateRevenue = (revenue: any) => {
    updateRevenueMutation(revenue)
        .unwrap()
        .then(() => console.log(revenue));
};

const columns = getColumns('revenues', hideCols, deleteRevenue, setModalData, showModal, refetchRevenues);

const filterRevenues = (revenues: any, search: string) => {
    return revenues?.filter((item: any) => {
        return item?.order_id?.toString().includes(search.toLowerCase());
    });
};

const toggleCols = (col: any) => {
    const updatedHideCols = hideCols.filter((hc: any) => hc !== col);
    hideCols.includes(col) ? setHideCols(updatedHideCols) : setHideCols([...hideCols, col]);
};

useEffect(() => {
    setRevenues(rawData?.data?.data);
    const integerID: any = revenues?.map((cost: any) => ({
        ...cost,
        id: parseInt(cost.id),
    }));
    setInitialRecords(sortBy(integerID, 'id'));

    const orOps: any = getIDOptions('orders', orders);

    setOrdersOptions(orOps);
    refetchRevenues();
}, [rawData, pagination, revenues, initialRecords !== undefined, orders, setInitialRecords]);

useEffect(() => {
    dispatch(setPageTitle('Revenues'));
});

const handlePageChange = async (p: number, pSize: number) => {
    const pagination = { page: p, pageSize: pSize };
    setPagination(pagination);
    setPage(p);
};

console.log(revenues);

return (
    <div>
        <div className="flex justify-between items-center">
            <ul className="flex space-x-2 rtl:space-x-reverse">
                <li>
                    <Link to="/" className="text-primary hover:underline">
                        Dashboard
                    </Link>
                </li>
                <li className="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                    <span>Revenues</span>
                </li>
            </ul>

            <button type="button" className="btn btn-primary" onClick={() => showNewRevenueModal(true)}>
                New Revenue
            </button>
        </div>
        <SortingTable
            rowData={revenues}
            filtered={filterRevenues}
            initialRecords={initialRecords}
            setInitialRecords={setInitialRecords}
            tableName={'Revenues'}
            columns={columns}
            search={search}
            setSearch={setSearch}
            hideCols={hideCols}
            setHideCols={setHideCols}
            toggleCols={toggleCols}
            PAGE_SIZES={PAGE_SIZES}
            pageSize={pageSize}
            setPageSize={setPageSize}
            totalRecords={rawData?.count}
            handlePageChange={handlePageChange}
            page={page}
            isLoading={isLoading}
        />
        <TableModal
            modal={modal}
            showModal={showModal}
            modalTitle="Update Revenue"
            columns={columns as any[]}
            data={modalData}
            setData={setModalData}
            postReq={updateRevenue}
            IDOps={ordersOptions}
            getReq={refetchRevenues}
        />
        <TableModal
            modal={newRevenueModal}
            showModal={showNewRevenueModal}
            modalTitle="New Revenue"
            columns={columns as any[]}
            data={modalData}
            setData={setModalData}
            postReq={addRevenue}
            IDOps={ordersOptions}
            getReq={refetchRevenues}
        />
    </div>
);
};

export default Revenues;

When I try to change the value of pageSize, doing some logs, the value actually changes, but the view, as usually, remains the same. So in order to see the changes i have to refresh manually the page. I’m getting ill.

I don’t know if the problem is me or mantine datatable, I never had such issues.

Where should I save game data for a socket io game being served from Nodejs?

I am serving a Jackbox type game using Socket IO on Nodejs.

Games take place in Socket IO Rooms and last about 30 mins. Within each room there are many variables to save, such as: users in the room, current game state, user submitted text answers to game questions, and the and a scoreboard.

Where should I store this temporary game data and why? If I store it as JavaScript variables or class instances in the Nodejs code, how many games can I expect to serve at a time before it becomes a memory or cpu problem? Does uploading it to a DB or Redis server help? Why?

I’m currently uploading data to a DB; however,I don’t see any way around storing some data in Nodejs variables, so I am wondering what the harm of saving more is?

How to modify the images of this site in my localhost:80?

I have this site, but I have to send it in .rar format into a link:
https://drive.google.com/file/d/1g1o3dQBhmMGbRtpAuv_UEjW2MbSVvSSA/view?usp=drive_link
You can see, that it this the current appearance:
Current appearance of the site:

But I want to change to this:
enter image description here

In summary, I want to change the old graphics of the game to new graphics. It’s possible? I think not, but us can help me, if us want, sorry my impertinence and thanks anyway!

PD: If this question annoys one I will delete it.

How can I stop my balls from being moved to random places when I add new bouncy balls in an HTML canvas?

I currently have a program that when you hit an “Add Ball” button, a new ball gets created and they bounce off the walls and other balls. However, let’s say you already have two other balls and you hit the “Add Ball” button: the two old balls will randomly be created somewhere else (where it was not originally).

Question: How can I stop my balls from going to random locations every time I hit the “Add Ball” button?

Side question (optional): How could I make it so that after every collision, the ball(s) involved changes color?

function lineMessage(msg) {
    document.querySelector('#myMessage').textContent += msg + '. ';
}

function groupMessage(msg) {
    document.querySelector('#myMessage').innerHTML += msg + '<br/>';
}

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext("2d");
canvas.width = 1000;
canvas.height = 550;
const ballCount = document.querySelector('#ball-count');

const gravity = 0;
const wallLoss = 1;
let numBalls = 0;  // approx as will not add ball if space can not be found
const minBallSize = 13;
const maxBallSize = 20;
const velMin = 1;
const velMax = 5; 
const maxResolutionCycles = 100;

function addBall() {
    numBalls++;
    ballCount.innerHTML = numBalls;

    Math.TAU = Math.PI * 2;
    Math.rand = (min, max) => Math.random() * (max - min) + min;
    Math.randI = (min, max) => Math.random() * (max - min) + min | 0; // only for positive numbers 32bit signed int
    Math.randItem = arr => arr[Math.random() * arr.length | 0]; // only for arrays with length < 2 ** 31 - 1
    // contact points of two circles radius r1, r2 moving along two lines (a,e)-(b,f) and (c,g)-(d,h) [where (,) is coord (x,y)]
    Math.circlesInterceptUnitTime = (a, e, b, f, c, g, d, h, r1, r2) => { // args (x1, y1, x2, y2, x3, y3, x4, y4, r1, r2)
        const A = a * a, B = b * b, C = c * c, D = d * d;
        const E = e * e, F = f * f, G = g * g, H = h * h;
        var R = (r1 + r2) ** 2;
        const AA = A + B + C + F + G + H + D + E + b * c + c * b + f * g + g * f + 2 * (a * d - a * b - a * c - b * d - c * d - e * f + e * h - e * g - f * h - g * h);
        const BB = 2 * (-A + a * b + 2 * a * c - a * d - c * b - C + c * d - E + e * f + 2 * e * g - e * h - g * f - G + g * h);
        const CC = A - 2 * a * c + C + E - 2 * e * g + G - R;
        return Math.quadRoots(AA, BB, CC);
    }  

    Math.quadRoots = (a, b, c) => { // find roots for quadratic
        if (Math.abs(a) < 1e-6) {
            return b != 0 ? [-c / b] : [] 
        }

        b /= a;
        var d = b * b - 4 * (c / a);

        if (d > 0) {
            d = d ** 0.5;
            return  [0.5 * (-b + d), 0.5 * (-b - d)]
        }

        return d === 0 ? [0.5 * -b] : [];
    }

    Math.interceptLineBallTime = (x, y, vx, vy, x1, y1, x2, y2, r) => {
        const xx = x2 - x1;
        const yy = y2 - y1;
        const d = vx * yy - vy * xx;

        if (d > 0) {  // only if moving towards the line
            const dd = r / (xx * xx + yy * yy) ** 0.5;
            const nx = xx * dd;
            const ny = yy * dd;
            return (xx * (y - (y1 + nx)) - yy * (x - (x1 - ny))) / d;
        }
    }

    const balls = [];
    const lines = [];

    function Line(x1, y1, x2, y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    Line.prototype = {
        draw() {
            ctx.moveTo(this.x1, this.y1);
            ctx.lineTo(this.x2, this.y2);
        },
        reverse() {
            const x = this.x1;
            const y = this.y1;
            this.x1 = this.x2;
            this.y1 = this.y2;
            this.x2 = x;
            this.y2 = y;
            return this;
        }
    }
        
    function Ball(x, y, vx, vy, r = 45, m = 4 / 3 * Math.PI * (r ** 3)) {
        this.r = r;
        this.m = m;
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
    }

    Ball.prototype = {
        update() {
            this.x += this.vx;
            this.y += this.vy;
            this.vy += gravity;
        },
        draw() {
            ctx.moveTo(this.x + this.r, this.y);
            ctx.arc(this.x, this.y, this.r, 0, Math.TAU);
        },
        interceptLineTime(l, time) {
            const u = Math.interceptLineBallTime(this.x, this.y, this.vx, this.vy, l.x1, l.y1, l.x2, l.y2, this.r);

            if (u >= time && u <= 1) {
                return u;
            }
        },
        checkBallBallTime(t, minTime) {
            return t > minTime && t <= 1;
        },
        interceptBallTime(b, time) {
            const x = this.x - b.x;
            const y = this.y - b.y;
            const d = (x * x + y * y) ** 0.5;

            if (d > this.r + b.r) {
                const times = Math.circlesInterceptUnitTime(
                    this.x, this.y, 
                    this.x + this.vx, this.y + this.vy, 
                    b.x, b.y,
                    b.x + b.vx, b.y + b.vy, 
                    this.r, b.r
                )

                if (times.length) {
                    if (times.length === 1) {
                        if (this.checkBallBallTime(times[0], time)) {
                            return times[0]
                        }

                        return;
                    }

                    if (times[0] <= times[1]) {
                        if (this.checkBallBallTime(times[0], time)) {
                            return times[0]
                        }

                        if (this.checkBallBallTime(times[1], time)) {
                            return times[1]
                        }

                        return
                    }

                    if (this.checkBallBallTime(times[1], time)) { 
                        return times[1]
                    }      

                    if (this.checkBallBallTime(times[0], time)) {
                        return times[0]
                    }
                }
            }
        },
        collideLine(l, time) {
            const x1 = l.x2 - l.x1;
            const y1 = l.y2 - l.y1;
            const d = (x1 * x1 + y1 * y1) ** 0.5;
            const nx = x1 / d;
            const ny = y1 / d;            
            const u = (this.vx  * nx + this.vy  * ny) * 2;
            this.x += this.vx * time;   
            this.y += this.vy * time;   
            this.vx = (nx * u - this.vx) * wallLoss;
            this.vy = (ny * u - this.vy) * wallLoss;
            this.x -= this.vx * time;
            this.y -= this.vy * time;
        },
        collide(b, time) {
            const a = this;
            const m1 = a.m;
            const m2 = b.m;
            const x = a.x - b.x
            const y = a.y - b.y  
            const d = (x * x + y * y);
            const u1 = (a.vx * x + a.vy * y) / d
            const u2 = (x * a.vy - y * a.vx ) / d
            const u3 = (b.vx * x + b.vy * y) / d
            const u4 = (x * b.vy - y * b.vx ) / d
            const mm = m1 + m2;
            const vu3 = (m1 - m2) / mm * u1 + (2 * m2) / mm * u3;
            const vu1 = (m2 - m1) / mm * u3 + (2 * m1) / mm * u1;
            a.x = a.x + a.vx * time;
            a.y = a.y + a.vy * time;
            b.x = b.x + b.vx * time;
            b.y = b.y + b.vy * time;
            b.vx = x * vu1 - y * u4;
            b.vy = y * vu1 + x * u4;
            a.vx = x * vu3 - y * u2;
            a.vy = y * vu3 + x * u2;
            a.x = a.x - a.vx * time;
            a.y = a.y - a.vy * time;
            b.x = b.x - b.vx * time;
            b.y = b.y - b.vy * time;
        },
        doesOverlap(ball) {
            const x = this.x - ball.x;
            const y = this.y - ball.y;
            return  (this.r + ball.r) > ((x * x + y * y) ** 0.5);  
        }       
    }

    function canAdd(ball) {
        for (const b of balls) {
            if (ball.doesOverlap(b)) {
                return false
            }
        }

        return true;
    }

    function create(bCount) {
        lines.push(new Line(-10, 10, ctx.canvas.width + 10, 5));
        lines.push((new Line(-10, ctx.canvas.height - 2, ctx.canvas.width + 10, ctx.canvas.height - 10)).reverse());
        lines.push((new Line(10, -10, 4, ctx.canvas.height + 10)).reverse());
        lines.push(new Line(ctx.canvas.width - 3, -10, ctx.canvas.width - 10, ctx.canvas.height + 10)); 

        while (bCount--) {
            let tries = 100;
            debugger

            while (tries--) {
                const dir = Math.rand(0, Math.TAU);
                const vel = Math.rand(velMin, velMax);
                const ball = new Ball(
                    Math.rand(maxBallSize + 10, canvas.width - maxBallSize - 10), 
                    Math.rand(maxBallSize + 10, canvas.height - maxBallSize - 10),
                    Math.cos(dir) * vel,
                    Math.sin(dir) * vel,
                    Math.rand(minBallSize, maxBallSize),
                )

                if (canAdd(ball)) {
                    balls.push(ball);
                    break;
                }
            }
        }
    }

    function resolveCollisions() {
        var minTime = 0, minObj, minBall, resolving = true, idx = 0, idx1, after = 0, e = 0;
        
        while (resolving && e++ < maxResolutionCycles) { // too main ball may create very lone resolution cycle. e limits this
            resolving = false;
            minObj = undefined;
            minBall = undefined;
            minTime = 1;
            idx = 0;

            for(const b of balls) {
                idx1 = idx + 1;
                while (idx1 < balls.length) {
                    const b1 = balls[idx1++];
                    const time = b.interceptBallTime(b1, after);

                    if (time !== undefined) {
                        if (time <= minTime) {
                            minTime = time;
                            minObj = b1;
                            minBall = b;
                            resolving = true;
                        }
                    }
                }

                for (const l of lines) {
                    const time = b.interceptLineTime(l, after);
                    if (time !== undefined) {
                        if (time <= minTime) {
                            minTime = time;
                            minObj = l;
                            minBall = b;
                            resolving = true;
                        }
                    }
                }

                idx++;
            }

            if (resolving) {
                if (minObj instanceof Ball) {
                    minBall.collide(minObj, minTime);
                } else {
                    minBall.collideLine(minObj, minTime);
                }

                after = minTime;
            }
        }
    }

    create(numBalls);
    mainLoop();

    function mainLoop() {
        ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
        resolveCollisions();

        for (const b of balls) {
            b.update()
        }

        ctx.strokeStyle = "#000";
        ctx.beginPath();

        for (const b of balls) {
            b.draw()
        }

        for (const l of lines) {
            l.draw()
        }

        ctx.stroke();
        requestAnimationFrame(mainLoop);
    }
}
#canvas {
    width: 1000px;
    height: 550px
}

#myConsole {
    background-color: black;
    color: white;
    min-height: 100px;
}
<!DOCTYPE html>
<html lang="en">

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE-edge">
        <meta name="viewport", content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Christian Davis">
        <link rel="stylesheet" href="styles.css">

        <title>Bouncy Balls</title>
    </head>

    <body>
        <button onclick="addBall()">Add Ball</button><br>
        <div>Ball Count: <span id="ball-count">0</span></div>
        <canvas id="canvas"></canvas>
        <p id="myConsole">&gt;&nbsp;<span id="myMessage"></span></p>

        <script src="app.js"></script>
    </body>
</html>

How to import a Promise but not execute it immediately?

I am trying to create a modules which is returning a Promise, and here is my test code.

I have a test promise module:

const test = new Promise((resolve,reject)=>{
console.log('loaded promise test');
resolve(true);
});

export default test;

And I import it to my index:

import test from "./test.js";

console.log('end');

Then I have a result like this:

loaded promise test
end

What I actually want is to execute the promise where I need rather than at the very beginning.
Or maybe I can just import a prototype of the promise and new it when I want it, how can I do that?

Posting URL id to a flask blueprint endpoint

Im using flask with Blueprints. I am trying to pass an ID from the url with a post request, but i dont understand the behaviour here:

i am on page localhost/2/updatestrat

This will post to /add_indicator

let indi_data = await postJsonGetData(data, "/add_indicator");
async function postJsonGetData(data, endpoint, method = "POST") {
  const options = {
    method: method,
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  };
  let response = await fetch(endpoint, options);

  if (!response.ok) {
    throw new Error("Request failed");
  }

  const responseData = await response.json();
  return responseData;
}

This will post to /2/load_conditions

  const { sell_conds, buy_conds } = await getJson("load_conditions");
async function getJson(endpoint) {
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
  };
  let response = await fetch(endpoint, options);

  if (!response.ok) {
    throw new Error("Request failed");
  }

  const responseData = await response.json();
  console.log(responseData, "DDDDDDDD");
  return responseData;
}

How come that getJson will include the id of the page in the endpoint and postJsonGetData dont?

I can easily get the data from getJson like this

@bp.route('/<int:id>/load_conditions', methods=['POST'])
def load_conditions(id):

but when i try to do the same with “/add_indicator”

@bp.route('/<int:strategy_id>/add_indicator', methods=('POST',))
@login_required
def add_indicator(strategy_id):
    if request.method == 'POST':
        print(strategy_id)

i get this error:
POST http://127.0.0.1:5000/add_indicator 404 (NOT FOUND)

so clearly it is not posting to the correct endpoint.

AWS: empty returned from lambda to frontend

I have a simple application. The frontend is hosted in AWS Amplify. There is a Lamnda function that returns a string. And there is an API gateway in between.
I sucessfully tested the API gateway using curl. It returned the same string as the lambda reurned including the statusCode and the body. This indicates the Lambda nad the API gateway function fine.

As for the frontend code, I used the following to get the result of the Lambda.

  fetch(`${apiGatewayUrl}${resourcePath}`, {
    method: 'GET',
    headers: {
     'Content-Type': 'application/json',
     'Authorization': `Bearer ${authToken}`
      // Add any additional headers if required for authentication or other purposes
    },
  })
  .then(response => {
    alert (`response:: ${response.status}`)
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    
    alert('Raw response:', response);
    return response.json();
  })
  .then(data => {
    // Process the data returned from the API
    console.log('API response:', data);
    alert('data:: ', JSON.stringify(data));
  })
  .catch(error => {
    alert (`Error: ${error}`);
    console.error('Error:', error);
  });

the ${apiGatewayUrl}${resourcePath} is set correctly. It is identical to the one I pass to curl.

For testing purpose, I set

 statusCode: 222,

in my Lamdba return.

When I execute my frontend code, the response.return is 200 as set in the API gateway.

The CORS is configured.
The method request, Integration request, integration response and method response is left at defaults.

What shall I do to make this work?

Split XPATH selectors into nodes in WebdriverIO

Quite a trivial question, but I haven’t figured out yet how to split selectors into node elements to improve performances. I’m working on test automation for a Windows desktop application.

Let’s take a random node :

const targetElement = await driver.$('//Window/Tab/TabItem/Custom/Pane/Group/Text');
const isDisplayed = await targetElement.isDisplayed();
assert.strictEqual(isDisplayed, true);

This above works like a charm.
But if I split the ‘targetElement’ into elements, it doesn’t work anymore.

const pane = await driver.$('//Window/Tab/TabItem/Custom/Pane');
const targetElement = await pane.$('//Group/Text');
const isDisplayed = await targetElement.isDisplayed();
assert.strictEqual(isDisplayed, true);

will throw an error.

Vue 3 – cannot update variable from child to parent

I’m using Vue 3 Composition API. I’m stuck because I just can’t figure out why my variable is not being updated.

//child

const rClick = (e) => {
        aIndex.value = e.index
        console.log(aIndex.value)
        emit('changeIndex', aIndex.value)
    }

then in my parent

const myI = ref(0)
const changeIndex = (e) => {
  //e is a number
  myI.value = e
}

The variable ‘myI’ is always 0 in the template and doesn’t even enter a computed property.

How to decide a problem with discord.js bot?

const {
  Client,
  GatewayIntentBits,
  MessageEmbed,
  Partials,
  SlashCommandBuilder,
  ButtonBuilder,
  ButtonStyle,
} = require("discord.js");
const prefix = '!';



const client = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages,],
  partials: [Partials.Channel, Partials.Message],
});


client.on("message", msg => {
  if (msg.author.bot || !msg.content.startsWith(prefix)) return;
  const args = msg.content.slice(prefix.length).split(/ +/);
  const cmd = args.shift().toLowerCase();

  // Обработка команд
  if (cmd === "ping") {
    const pingTime = Date.now() - msg.createdTimestamp;
    msg.reply(`Pong! Latency is ${pingTime}ms`);
  }
});



client.login(config.BOT_TOKEN);

The code seems to be quite simple, it runs online, the ‘/’ commands work, but everything related to command with prefix does not work. I don’t know what the reason is, I’ve already tried a lot of code options, but nothing helps. Where is the mistake?

Why is my javascript code is not working how it should – $ is undefined [duplicate]

I am trying to create a dynamic gallery where an admin can add or remove photos. When they try to upload photos which are more than 10mb then after that it will show an error. I can’t see anything and this is in my console

Uncaught ReferenceError: $ is not defined

I tried everything but I didn’t find solution

$(function() {
  $("#image_upload").change(function(e) {
    let file = this.files[0];
    let file_ext = file.name.split('.').pop().toLowerCase();
    let allowed_ext = ["jpg", "jpeg", "png"];
    let file_size = file.size; // Veľkosť súboru v bytoch

    if (allowed_ext.includes(file_ext)) {
      if (file_size <= 1000000) {
        let url = window.URL.createObjectURL(this.files[0]);
        $("#preview_image").html(`<img src="${url}" class="img-fluid img-thumbnail">`);
        $("#upload_btn").prop("disabled", false);
      } else {
        $("#message_alert").html(showMessage("danger", "Obrázok by mal mať veľkosť menšiu alebo rovnú 1MB!"));
      }
      $("#preview_image").html("");
      $("#upload_btn").prop("disabled", true);
    }
  });
});

//error message
function showMessage(type, message) {
  return `<div class="alert alert-${type} alert-dismissible fade show" role="alert">
    <strong>${message}</strong>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>`;
}