How to find number of non reducible fractions of any number more efficiently

I’m trying to input a number as an argument of my function and return the number of 0-1 fractions that can not be reduced at all (code wars problem).

I kind of already did it but my code keeps timing out for larger numbers.

How could I make it more efficient?

This is my code:

function properFractions(n) {
  const numerators = Array.from({ length: n }, (_, i) => i + 1).slice(0, -1);
  const oneToNine = Array.from({ length: 8 }, (_, i) => i + 2);

  let count = n;
  if (numerators.length === 0) count = 0;
  else if (numerators.length < 2) {
    count--;
  } else if (numerators.length > 1) {
    for (let y = 0; y <= numerators.length; y++) {
      if (n % numerators[y] === 0) count--;

      for (let i = 0; i < oneToNine.length; i++) {
        if (numerators[y] < oneToNine[i] && n < oneToNine[i]) break;
        else if (numerators[y] > oneToNine[i] && n > oneToNine[i]) {
          if (numerators[y] % oneToNine[i] === 0 && n % oneToNine[i] === 0)
            count--;
        }
      }
    }
  }
  return count;
}

console.log(properFractions(1234)) // OK
console.log(properFractions(12345678)) // OK
console.log(properFractions(123456781)) // takes a long time
console.log(properFractions(1234567812)) // dies

How to find number of non reducible fractions of any number more efficiently in JS

So I’m trying to input a number as an argument of my function and return the number of 0-1 fractions that can not be reduced at all (code wars problem).
I kind of already did it but my code keeps timing out for larger numbers.

How could I make it more efficient?

This is my code:

function properFractions(n) {
  const numerators = Array.from({ length: n }, (_, i) => i + 1).slice(0, -1);
  const oneToNine = Array.from({ length: 8 }, (_, i) => i + 2);

  let count = n;

  if (numerators.length === 0) count = 0;
  else if (numerators.length < 2) {
    count--;
  } else if (numerators.length > 1) {
    for (let y = 0; y <= numerators.length; y++) {
      if (n % numerators[y] === 0) count--;

      for (let i = 0; i < oneToNine.length; i++) {
        if (numerators[y] < oneToNine[i] && n < oneToNine[i]) break;
        else if (numerators[y] > oneToNine[i] && n > oneToNine[i]) {
          if (numerators[y] % oneToNine[i] === 0 && n % oneToNine[i] === 0)
            count--;
        }
      }
    }
  }

  return count;
}

^ can’t handle bigger numbers without timing out

Vuetify component not loading completely in vue 3 webpack

I have a legacy vue project built with Webpack, which recently migrated to vue 3. I’m trying to add Vuetify to it following the official documentation. But only a few components are working and most of the components are not working at all. It works for v-btn but throws the following error when I try to use v-text-field

enter image description here

Can anyone point me in the right direction, what I’m doing wrong here?

package.json

"@vue/compat": "^3.2.39",
"@vue/compiler-sfc": "^3.2.39",
"vue": "^3.4.37",
"vuetify": "^3.6.14",
"vuex": "^4.0.2",
"webpack-plugin-vuetify": "^3.0.3",
"vue-loader": "^17.0.1",
"webpack": "^5.93.0",
"webpack-cli": "^4.10.0",
"webpack-manifest-plugin": "^5.0.0",
"webpack-merge": "^5.8.0"

webpack plugin

plugins: [
 new CleanWebpackPlugin(),
 new VueLoaderPlugin(),
 new VuetifyPlugin({ autoImport: true }),
 new MiniCssExtractPlugin({
    filename: '[name].[contenthash].bundle.css',
    chunkFilename: '[name].[contenthash].bundle.css',
    rtlEnabled: true,
 }),
 new WebpackManifestPlugin(),
 new ESLintPlugin(),
 new Webpack.DefinePlugin({ __VUE_OPTIONS_API__: true, __VUE_PROD_DEVTOOLS__: true }),
],

index.js

import vueAdmin from './plugins/app';
import { createVuetify } from 'vuetify';
import 'vuetify/dist/vuetify.min.css';

const vuetify = createVuetify({});

const adminElement = document.querySelector('.vue-admin');
vueAdmin.use(vuetify);
vueAdmin.use(store);
vueAdmin.use(router);
vueAdmin.mount(adminElement);

Issue with Data Display in Table Using ReactJS and antd

My project uses ReactJS and the antd library.

I am facing an issue with displaying data in a table as follows:

Currently, the columns of the table are working correctly, but the rows of the table are not displayed correctly because I am fetching the rows based on the index from a for loop. If the values field of the variants is not consistent, the rows displayed will be incorrect.

Please help me address this issue. Thank you very much!

Here is my code:

Data json:

[
{
    "id": 1,
    "name": "Style",
    "values": [
        {
            "id": 1,
            "variant_id": 1,
            "label": "Hoodie",
            "value": "Hoodie"
        },
        {
            "id": 7,
            "variant_id": 1,
            "label": "Hoodie",
            "value": "Hoodie"
        },
        {
            "id": 13,
            "variant_id": 1,
            "label": "Hoodie",
            "value": "Hoodie"
        },
        {
            "id": 19,
            "variant_id": 1,
            "label": "Hoodie",
            "value": "Hoodie"
        },
        {
            "id": 25,
            "variant_id": 1,
            "label": "Hoodie",
            "value": "Hoodie"
        },
        {
            "id": 31,
            "variant_id": 1,
            "label": "Hoodie",
            "value": "Hoodie"
        },
        {
            "id": 41,
            "variant_id": 1,
            "label": "T-shirt",
            "value": "T-shirt"
        },
        {
            "id": 47,
            "variant_id": 1,
            "label": "T-shirt",
            "value": "T-shirt"
        }
    ]
},
{
    "id": 2,
    "name": "Color",
    "values": [
        {
            "id": 2,
            "variant_id": 2,
            "label": "Black",
            "value": "#000000"
        },
        {
            "id": 8,
            "variant_id": 2,
            "label": "Black",
            "value": "#000000"
        },
        {
            "id": 14,
            "variant_id": 2,
            "label": "White",
            "value": "#ffffff"
        },
        {
            "id": 20,
            "variant_id": 2,
            "label": "White",
            "value": "#ffffff"
        },
        {
            "id": 26,
            "variant_id": 2,
            "label": "Light Pink",
            "value": "#ffb6c1"
        },
        {
            "id": 32,
            "variant_id": 2,
            "label": "Light Pink",
            "value": "#ffb6c1"
        },
        {
            "id": 42,
            "variant_id": 2,
            "label": "Red",
            "value": "#842b2b"
        },
        {
            "id": 48,
            "variant_id": 2,
            "label": "Red",
            "value": "#842b2b"
        }
    ]
},
{
    "id": 3,
    "name": "Size",
    "values": [
        {
            "id": 3,
            "variant_id": 3,
            "label": "S",
            "value": "S"
        },
        {
            "id": 9,
            "variant_id": 3,
            "label": "M",
            "value": "M"
        },
        {
            "id": 15,
            "variant_id": 3,
            "label": "S",
            "value": "S"
        },
        {
            "id": 21,
            "variant_id": 3,
            "label": "M",
            "value": "M"
        },
        {
            "id": 27,
            "variant_id": 3,
            "label": "S",
            "value": "S"
        },
        {
            "id": 33,
            "variant_id": 3,
            "label": "M",
            "value": "M"
        },
        {
            "id": 43,
            "variant_id": 3,
            "label": "S",
            "value": "S"
        },
        {
            "id": 49,
            "variant_id": 3,
            "label": "M",
            "value": "M"
        }
    ]
},
{
    "id": 4,
    "name": "Price",
    "values": [
        {
            "id": 4,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 10,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 16,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 22,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 28,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 34,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 44,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 50,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 54,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 58,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 62,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 66,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 70,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 74,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        },
        {
            "id": 78,
            "variant_id": 4,
            "label": "0",
            "value": "0"
        }
    ]
},
{
    "id": 5,
    "name": "Sku",
    "values": [
        {
            "id": 5,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 11,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 17,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 23,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 29,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 35,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 45,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 51,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 55,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 59,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 63,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 67,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 71,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 75,
            "variant_id": 5,
            "label": null,
            "value": null
        },
        {
            "id": 79,
            "variant_id": 5,
            "label": null,
            "value": null
        }
    ]
},
{
    "id": 6,
    "name": "Status",
    "values": [
        {
            "id": 6,
            "variant_id": 6,
            "label": "0",
            "value": "0"
        },
        {
            "id": 12,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 18,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 24,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 30,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 36,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 46,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 52,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 56,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 60,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 64,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 68,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 72,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 76,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        },
        {
            "id": 80,
            "variant_id": 6,
            "label": "1",
            "value": "1"
        }
    ]
},
{
    "id": 7,
    "name": "Test",
    "values": [
        {
            "id": 53,
            "variant_id": 7,
            "label": "Value test",
            "value": "Value test"
        },
        {
            "id": 57,
            "variant_id": 7,
            "label": "Value test 2",
            "value": "Value test 2"
        },
        {
            "id": 61,
            "variant_id": 7,
            "label": "Value test 3",
            "value": "Value test 3"
        },
        {
            "id": 77,
            "variant_id": 7,
            "label": "Value test 4",
            "value": "Value test 4"
        }
    ]
},
{
    "id": 8,
    "name": "Test 2",
    "values": [
        {
            "id": 65,
            "variant_id": 8,
            "label": "Test value 22",
            "value": "Test value 22"
        },
        {
            "id": 69,
            "variant_id": 8,
            "label": "Test value 33",
            "value": "Test value 33"
        },
        {
            "id": 73,
            "variant_id": 8,
            "label": "Test value 44",
            "value": "Test value 44"
        }
    ]
}
]

handleVariants() {
    const { action_type, product_id } = this.props;
    const filter = { product_id: product_id };
    const fetchData = action_type === 'create' ? this.props.getListVariantsTmp() : this.props.getListVariants(filter);

    this.setState({ loadingVariantsTemp: true });

    fetchData.then(res => {
        const { data } = res;

        console.log("data", data)

       
        const determineWidth = (name) => {
            switch (name) {
                case 'Price':
                    return 80;
                case 'Sku':
                    return 150;
                default:
                    return 'auto';
            }
        };

       
        const editableColumns = ['Price', 'Sku'];

      
        const newColumns = data.map(variant => ({
            title: variant.name,
            dataIndex: variant.name,
            key: variant.id,
            width: determineWidth(variant.name),
            render: (text, record, index) => {
                
                const valueObject = variant.values[index];

                if (variant.name === 'Color' && valueObject) {
                    const colorCode = variant.values[index].value;
                    return (
                        <>
                            <span style={{ background: colorCode }} className='item-color-variants'>&nbsp;</span>
                            {record[variant.name]} ({colorCode})
                        </>
                    )
                } else if (variant.name === 'Status' && valueObject) {
                    const status = record[variant.name];
                    return (
                        <Switch
                            size="small"
                            defaultChecked={status === '1'}
                            onChange={(value) => this.props.updateVariantsTmp(record[variant.name + '_id'], { value })}
                        />
                    )
                } else {
                    return (
                        <span>{record[variant.name]}</span>
                    )
                }
            },
            onCell: record => ({
                record,
                editable: editableColumns.includes(variant.name),
                dataIndex: variant.name,
                title: variant.name,
                handleSave: this.handleSave,
                handleChange: (value) => this.onChangeItem(variant.name, value, record[variant.name + '_id']),
            }),
        }));

        newColumns.push({
            title: '#',
            key: 'actions',
            width: 40,
            render: (_, record) => (
                <span>
                    <CloseOutlined onClick={() => this.openDeleteVariant(record.ids)} className='item-action-btn-remove' />
                </span>
            ),
        });

        const rowData = [];
        const maxLength = Math.max(...data.map(variant => variant.values.length));

        for (let i = 0; i < maxLength; i++) {
            const row = {};
            const ids = [];
            data.forEach(variant => {
                const value = variant.values[i];
                if (value) {
                    row[variant.name] = value.label || '';
                    row[`${variant.name}_id`] = value.id;
                    ids.push(value.id);
                } else {
                    row[variant.name] = '';
                    row[`${variant.name}_id`] = '';
                }
            });
            row['ids'] = ids;
            rowData.push(row);
        }
        console.log("rowData", rowData)

        // Cập nhật state
        this.setState({
            variants_columns: newColumns,
            variants_data_source: rowData,
            loadingVariantsTemp: false,
        });
    }).catch(error => {
        console.error("Error fetching data:", error);
    });
}

<Table
    rowKey="ids"
    size='small'
    tableLayout='auto'
    rowSelection={rowSelection}
    columns={variants_columns}
    dataSource={variants_data_source}
    pagination={false}
    loading={loadingVariantsTemp}
    rowClassName={() => "editable-row"}
    components={components}
    style={{ marginTop: '20px' }}
    locale={{ emptyText: "No data" }}
   />

Incorrect
enter image description here
Display correctly
enter image description here

I keep getting ‘[Violation]’ warnings repeatedly whenever I perform events like scroll, click, or mouseleave

I recently updated Angular from version 11 to 14, along with Angular Material. After the update, whenever I trigger events like click, change, scroll, blur, mouseover, or mouseleave, I receive multiple warnings in Chrome: [Violation] 'click' handler took 361ms.

These warnings are causing my application to slow down, resulting in a poor user experience. Interestingly, the application works perfectly in Firefox without these warnings.

Demo Image

I want to resolve these warnings so my application will run faster.

How can I slow down drag behavior with D3/JavaScript?

I am designing a visualization which begins with the user drawing points on the screen as shown here: https://jsfiddle.net/jtr13/j2yrknf3/25/

The relevant part of the code (inspired by this answer) is:

svg.on("mousedown", mousedown)
  .on("mouseup", mouseup);

function mousedown() {
  const new_x = xScale.invert(d3.pointer(event)[0]);
  const new_y = yScale.invert(d3.pointer(event)[1]);
  svg.append("circle")
    .data([{x: new_x, y: new_y}])
    .attr("cx", d => xScale(d.x))
    .attr("cy", d => yScale(d.y))
    .attr("r", "3");

svg.on("mousemove", mousemove);
}

function mousemove() {
  const new_x = xScale.invert(d3.pointer(event)[0]);
  const new_y = yScale.invert(d3.pointer(event)[1]);
  svg.append("circle")
    .data([{x: new_x, y: new_y}])
    .attr("cx", d => xScale(d.x))
    .attr("cy", d => yScale(d.y))
    .attr("r", "3"); 
}

function mouseup() {
  svg.on("mousemove", null);
}

The problem is that too many points are added during mousemove. I would like points to be added at about 1/5 or 1/10 of the current rate. I tried adding delays of various sorts and nothing worked. How can I slow down the drag behavior?

Getting all array items at once

Bellow is a very short code which sorts each span into a new array depending on the className it has.

What I currently have: As soon as a square of a specified class is hovered – IT GETS a color unique to its class.

What I needed to acheive: As soon as one of a specified class is hovered – ALL classList ITEMS GET the unique color of their class.

Can someone tell me what is wrong in the code bellow?
Thank you!

let allDivs = [...document.querySelectorAll(`div`)];
let Classes = [ "A0", "A1", "A2", "A3" ];

console.log(`let 'allDivs' equals:`);
console.log(allDivs);

for (let i = 0; i < Classes.length; i++) {
  let allDivsFiltered = allDivs.filter(item => (item.className.match(`A${i}`)));

  console.log('---- ---- ---- ----');
  console.log(`let 'allDivsFiltered [${i}]' equals:`);
  console.log(allDivsFiltered);

  // allDivsFiltered.classList.add(`B${i}`); // THIS DOESN'T WORK;

  for (let all of allDivsFiltered) {
    all.onmouseover = () => {
      all.classList.add(`B${i}`); // This does work,
      // but seperately on each one;

      // allDivsFiltered.classList.add(`B${i}`); // DOESN'T WORK HERE
        // AS WELL;
    };

    console.log(all);
  };
};
body {
  display: flex;
  flex-wrap: wrap;
}

div {
  position: relative;
  background-color: slategray;
  width: 100px;
  height: 100px;
  top: 0px;
  left: 0px;
  margin-top: 4px;
  margin-left: 4px;
}

.B0 {
  background-color: red;
}

.B1 {
  background-color: blue;
}

.B2 {
  background-color: green;
}

.B3 {
  background-color: yellow;
}
<div class="A0"></div>
<div class="A0"></div>
<div class="A0"></div>
<div class="A1"></div>
<div class="A1"></div>
<div class="A2"></div>
<div class="A2"></div>
<div class="A3"></div>
<div class="A3"></div>

SQL query for duplicates in JSON array of objects

Example Data

const data = [
    {
        "Id": 1,
        "ActualUrl": "https://test.com/test",
        "DateCreated": "2024-08-11T08:44:01",
        "DateUpdated": "2024-08-11T08:44:01",
        "Deadline": "2024-08-12T08:44:01",
        "PullZoneId": 1,
        "PullZoneName": "1",
        "Path": "/test",
        "Message": "1",
        "Status": 0,
        "Urls": [
            { "Url": "https://test.com/", "Status": 0 },
            { "Url": "https://test.com/", "Status": 0 }
        ],
    },
    {
        "Id": 12
        "ActualUrl": "https://test.com/test",
        "DateCreated": "2024-08-11T08:44:01",
        "DateUpdated": "2024-08-11T08:44:01",
        "Deadline": "2024-08-12T08:44:01",
        "PullZoneId": 1,
        "PullZoneName": "1",
        "Path": "/test",
        "Message": "1",
        "Status": 0,
        "Urls": [
            { "Url": "https://test.com/", "Status": 0 },
            { "Url": "https://test.com/", "Status": 0 }
        ],
    },
    // Add more records as needed
];

I want to basically loop through Urls of all, add them together and find duplicates. I am unsure if its supported or if I am doing it wrong.

I tried using this query and a bunch of others but i always get an error or nothing shows up. I understand nesting is an option but I am working with raw JSON from an API so I can’t modify it much.

SELECT u.Url, COUNT(*) AS Count
FROM AbuseCases a
JOIN a.Urls u
GROUP BY u.Url
HAVING COUNT(*) > 1;

iframes added after page interaction can not be unmuted on iOS

I am running into an issue where I am adding more content as the user scrolls down a page, some of that content is TikTok videos. However, when I load more Tiktok videos, I want to unmute them if the user already pressed Unmute. When I do, the video pauses (only on iOS) and browserstack shows an access violation on the “unmute”. I made a codepen to replicate. However, in the codepen it does not work at all on any browser, Desktop or mobile.

Does anyone know of a workaround or method to help?
https://codepen.io/jidler04/pen/qBzPJOq

    iframe.contentWindow.postMessage({ type: 'unMute', value: true, 'x-tiktok-player': true }, '*');

I have tried adding “allow autoplay” This fixes the issue outside of codepen for everything besides iOS chrome & Safari.

The videos should be able to be unmuted since there was already interaction allowed.

How can i run a Unity PWA build on a mobile device without this errors?

My Unity PWA build works fine on desktop devices, but in mobiles, he just loads, shows the splash screen and then the screen turn to completly black.

Also i need to force the pwa to open on all devices in a portrait view and limited resolution, like this example: VencedorPWA
How can i achieve this results?

OBS: i am using the Unity PWA template!

For testing i made some changes on the manifest and the index.html, but the results are the same, only the icons/favicons changes worked fine.

Also i created a completly empty project on Unity 6000.0.13f1 and Unity 6000.0.14f1, and lauched it as a PWA, but it didn’t worked as expected. My project runs in Unity 6000.0.14f1, but it can be changed, the original project was made from complete scratch with unity 2023.2.20f1.

I am deploying my PWA build in the platform Netlify with Github.

Is there a way to copy and paste values automatically into the ChatGPT’s chatbot?

I am trying to make an easier method to copy and paste prompts from a textbox using Javascript into a LLM Chatbot.

Right now, my script can only copy the value in a textbox in one tab and the Javascript opens ChatGPT or other LLM chatbot after a button is pressed. By pressing Ctrl + V will allow the user to paste to the chatbox.

Which is totally fine for now, but I was wondering if there’s a way in Firefox / Chrome / Safari that allows copy and paste automatically into a ChatGPT / other LLM chatbot automatically without using Ctrl + V.

Flow:

  1. Press button.
  2. Prompt automatically gets copied.
  3. Opens a new tab of ChatGPT / other LLM chatbot.
  4. Automatically pastes into the correct input text box.

I know same origin policy etc. might not allow, but if somebody knows how to implement this function, I would be grateful.

I don’t know if it is possible to open a new tab and paste text content there automatically without Ctrl + V after selecting the appropriate textbox.

How to Handle 429 Too Many Requests Status When Building a Next.js Chatbot with OpenAI

I’m working on creating a chatbot using Next.js and the OpenAI API. Even though I’m following the OpenAI documentation, I keep encountering a 429 (Too Many Requests) error. Below is my code:

......
export default function Home() {
  const [inputValue, setInputValue] = useState('');
  const [chatLog, setChatLog] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = (event) => {
    event.preventDefault();
    setChatLog((prevChatLog) => [...prevChatLog, { type: 'user', message: inputValue }]);
    sendMessage(inputValue);
    setInputValue('');
  }

  const sendMessage = (message) => {
    const url = "https://api.openai.com/v1/chat/completions";
    const headers = {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`
    };

    const data = {
      model: "gpt-4o-mini",
      messages: [{ "role": "user", "content": message }]
    };

    setIsLoading(true);
    axios.post(url, data, { headers }).then((res) => {
      console.log(res);
      setChatLog((prevChatLog) => [...prevChatLog, { type: 'bot', message: res.data.choices[0].message.content }]);
      setIsLoading(false);
    }).catch((err) => {
      setIsLoading(false);
      console.log(err);
    });
  }

  return (
    <>
      <h1>ChatGPT</h1>
      {chatLog.map((message, index) => (
        <div key={index}>
          {message.message}
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input type="text" placeholder="Type your message..." value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
        <button type="submit">Send</button>
      </form>
    </>
  );
}

I suspect the error might be due to the rate limits of the API, but I’m not sure how to resolve it. Has anyone else faced this issue? How can I handle this error or optimize my requests to avoid hitting the rate limits?

And this is the documentation of OpenAI that i follow it

How to avoid infinite loop when trying to update nested fieldArray with react hook form?

I’m getting an infinite loop when trying to update the total inside a table that uses the useFieldArray hook from react hook form.

  const items = useWatch({
    control,
    name: "items",
  });

  const { fields, ...fieldsProps } = useFieldArray({
    control: control,
    name: "items",
  });

  const controlledFields = fields.map((field, index) => {
    return {
      ...field,
      ...items[index],
    };
  });

I have an itemTable component where I pass the props:

      <ItemTable
              form={form}
              control={control}
              controlledFields={controlledFields}
              data={items}
              fieldsProps={fieldsProps}
              isTaxInclusive={tax_inclusive}
              isDiscountItemLevel={is_discount_item_level}
            />

Inside the ItemTable component i have a renderItemRow function where the infinite loop occurs:

  function renderItemRow(item, key) {
    const quantity = item.quantity;
    const discountPercentage = item.discount_percentage || 0;
    const discountAmount = item.discount_amount || 0;
    const price = item.unit_price || 0;

    // Calculate total discount
    const discountTotal =
      discountAmount > 0
        ? discountAmount * quantity
        : (discountPercentage / 100) * price * quantity;

    const itemTotal = quantity * price - discountTotal;

    update(key, {       // <-- infinite loop
      total: itemTotal, 
    });

my goal is to display and update the correct item total whenever the user changes the quantity, price or tax percentage of a certain item:

    <td id="total" className={`${styles.rowItem} w-[115px] px-2 font-bold`}>
          <FormField
            control={control}
            name={`items[${key}].total`}
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    readOnly
                    variant="ghost"
                    className="text-right text-black"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

HOW TO deploy simple NodeJS Backend to AWS [closed]

I am a beginner in backend. I am wondering how I can deploy my backend written in NodeJS and Express to AWS, so that my front end can send requests to the backend. I already have a web app hosted on GitHub. I used ChatGPT and it told me to use AWS Elastic Beanstalk for backend. I already configured eb in my local machine, but I do not know what to do next.

Suppose my backend is extremely simple that only contains (so we can focus solely on deployment):

app.get('', (req, res)=>{res.status(200).send("Hello World")})

Any help is appreciated. Thanks!

Two animations in the same graphic (ECHARTS)

I tried triggering two animations after clicking a button. The first animation moves the center of the gauge upwards (and this works). The second (which doesn’t work) would be to move the pointers randomly and return to the initial value, as configured in the code below:

  const mychartspider1 = echarts.init(document.getElementById('gaugespiderinc1'));
  const maxValue = 100;
  const numPointers = 4; // Number of pointers
  let randomValuesInterval;
  let randomColorsInterval;
  let centerAnimationInterval;

  function getRandomValue(min, max) {
    return Math.random() * (max - min) + min;
  }

  function setRandomValues() {
    let data = [];

    for (let i = 0; i < numPointers; i++) {
      data.push({
        value: getRandomValue(0, maxValue)
      });
    }

    updateGaugeSpider(data);
  }

  function updateGaugeSpider(data) {
    option = {
      series: [{
          type: 'gauge',
          min: 0,
          max: 100,
          splitNumber: 10,
          radius: '75%',
          center: ['50%', '150%'],
          axisLine: {
            lineStyle: {
              color: [
                [1, '#49a6de']
              ],
              width: 3.5
            }
          },
          splitLine: {
            distance: -28,
            length: 28,
            lineStyle: {
              width: 5,
              color: '#49a6de'
            }
          },
          axisTick: {
            distance: -12,
            length: 10,
            lineStyle: {
              width: 2,
              color: '#49a6de'
            }
          },
          axisLabel: {
            distance: -64,
            color: '#49a6de',
            fontSize: 36,
            fontFamily: 'D-DIN',
            textStyle: {
              textBorderWidth: 1,
              textBorderColor: '#020202'
            }
          },
          anchor: {
            show: true,
            size: 25,
            itemStyle: {
              borderColor: "#020202",
              borderWidth: 2
            }
          },
          pointer: {
            offsetCenter: [0, "10%"],
            icon: "path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z",
            length: "115%",
            itemStyle: {
              borderWidth: 1,
              borderColor: "#020202",
              shadowOffsetX: 4,
              shadowOffsetY: 4,
              shadowColor: "#020202",
              shadowBlur: 10,
            }
          },
          detail: {
            valueAnimation: true,
            borderWidth: 3,
            borderColor: '#858383',
            borderRadius: 5,
            color: '#020202',
            fontWeight: 'bold',
            width: 23,
            height: 18,
            fontSize: 20,
            fontFamily: 'DS-Digital',
            formatter: function(value) {
              return value.toFixed(0) + '%';
            }
          },
          data: data.map((item, index) => {
            const colors = ['#dd4b39', 'orange', 'lime', 'cyan'];
            const titleName = ['Name 1', 'Name 2', 'Name 3', 'Name 4'];
            const offsetName = [
              ['-45%', '70%'],
              ['-15%', '70%'],
              ['15%', '70%'],
              ['45%', '70%']
            ];
            const offsetDetail = [
              ['-45%', '84%'],
              ['-15%', '84%'],
              ['15%', '84%'],
              ['45%', '84%']
            ];
            return {
              value: item.value,
              itemStyle: {
                color: colors[index % colors.length]
              },
              name: titleName[index % titleName.length],
              title: {
                offsetCenter: offsetName[index % offsetName.length],
                color: colors[index % colors.length]
              },
              detail: {
                backgroundColor: colors[index % colors.length],
                offsetCenter: offsetDetail[index % offsetDetail.length]
              }
            };
          })
        },
        {
          type: 'gauge',
          min: 0,
          max: 60,
          splitNumber: 6,
          radius: '70%',
          center: ['50%', '150%'],
          axisLine: {
            lineStyle: {
              color: [
                [1, '#fee200']
              ],
              width: 3.5
            }
          },
          splitLine: {
            distance: 10,
            length: 28,
            lineStyle: {
              width: 5,
              color: '#fee200'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            distance: 10,
            fontSize: 33,
            color: '#fee200',
            fontFamily: 'D-DIN',
            textStyle: {
              textBorderWidth: 1,
              textBorderColor: '#020202'
            }
          },
          pointer: {
            show: false
          },
          title: {
            show: false
          },
          anchor: {
            show: true,
            size: 14,
            itemStyle: {
              color: "#f00",
              borderColor: "#020202",
              borderWidth: 1
            }
          }
        }
      ]
    };

    mychartspider1.setOption(option);
  }

  let colorIndex = 0; // Variável para controlar o índice da cor a ser aplicada

  function setNextColor() {
    const colors = ['#f00', '#49a6de'];
    const color = colors[colorIndex]; // Seleciona a cor atual com base no índice
    colorIndex = (colorIndex + 1) % colors.length; // Atualiza o índice para a próxima cor
    return color;
  }

  function setRandomColors() {
    const color = setNextColor(); // Obtém a próxima cor sequencialmente
    mychartspider1.setOption({
      series: [{
        axisLabel: {
          color: color,
        },
        axisLine: {
          lineStyle: {
            color: [
              [1, color]
            ],
          }
        },
        splitLine: {
          lineStyle: {
            color: color
          }
        },
        axisTick: {
          lineStyle: {
            color: color
          }
        }
      }]
    });
  }

  // Button click event
  $('#startgaugeeffectbtnanimation1').one('click', function() {
    // Configure random values and colors initially
    setRandomValues();
    setRandomColors();

    // Update random values and colors every 500 milliseconds for 5 seconds
    randomValuesInterval = setInterval(setRandomValues, 500);
    randomColorsInterval = setInterval(setRandomColors, 500);

    setTimeout(() => {
      // Stop updating after 5 seconds
      clearInterval(randomValuesInterval);
      clearInterval(randomColorsInterval);

      // Restore input values
      let value1 = Number($('#number1').val());
      let value2 = Number($('#number2').val());
      let value3 = Number($('#number3').val());
      let value4 = Number($('#number4').val());
      updateGaugeSpiderFromInputs(value1, value2, value3, value4);
    }, 5000);
  });

  function updateGaugeSpiderFromInputs(value1, value2, value3, value4) {
    value1 = Number($('#number1').val());
    value2 = Number($('#number2').val());
    value3 = Number($('#number3').val());
    value4 = Number($('#number4').val());

    // Verifique se o intervalo está definido e, se sim, pare a animação
    if (randomValuesInterval) {
      clearInterval(randomValuesInterval);
      clearInterval(randomColorsInterval);
    }

    // Defina as cores finais diretamente
    updateGaugeSpider([{
        value: value1
      },
      {
        value: value2
      },
      {
        value: value3
      },
      {
        value: value4
      }
    ]);
  }

  // Input change event
  $('#number1, #number2, #number3, #number4').on('change', function() {
    updateGaugeSpiderFromInputs();
  });

  updateGaugeSpiderFromInputs();

  // animation center downUp
  // Função para iniciar a animação do centro do gauge para '50%'
  function startCenterAnimation() {
    let centerPosition = 150; // Inicializa a posição central
    let startTime; // Armazena o horário de início da animação

    function animateCenterChange(timestamp) {
      const duration = 5000; // Duração da animação em milissegundos
      const startValue = centerPosition; // Valor inicial da posição central
      const endValue = 50; // Valor final da posição central
      const progress = (timestamp - startTime) / duration; // Progresso da animação

      // Calcula o próximo valor da posição central com base no progresso
      const nextValue = startValue + (endValue - startValue) * progress;

      // Define o centro do gráfico com base no próximo valor
      mychartspider1.setOption({
        series: [{
            center: ['50%', nextValue + '%']
          },
          {
            center: ['50%', nextValue + '%']
          }
        ]
      });

      // Continua a animação se ainda não atingiu o fim
      if (progress < 1) {
        requestAnimationFrame(animateCenterChange);
      }
    }

    function handleClick() {
      startTime = performance.now(); // Obtém o horário de início da animação
      requestAnimationFrame(animateCenterChange); // Inicia a animação
    }

    document.getElementById('startgaugeeffectbtnanimation1').addEventListener('click', handleClick, {
      once: true
    });
  }

  // Inicializa a animação do centro do gauge quando o botão for clicado
  startCenterAnimation();
#gaugespiderinc1 {
  height: 500px;
  width: 500px;
}

body {
  background: #333;
}
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<input type="range" id="number1" min="0" max="100" value="25">
<input type="range" id="number2" min="0" max="100" value="50">
<input type="range" id="number3" min="0" max="100" value="75">
<input type="range" id="number4" min="0" max="100" value="100">

<div id='gaugespiderinc1'></div>

<button id='startgaugeeffectbtnanimation1'>
  Click me
</button>

See that the center animation works perfectly, but the pointers don’t move. Also note that the detail of the gauge is moving and the value is stopping according to the values of the HTML inputs, but I need the pointers to move randomly during the center animation (at the same time).