MERN APP works on deployed Render site, but no longer works locally

I came back and revisited an app I was working on a few months back, its currently still working from its deployed site on Render, but when I try to run it locally, I’m encountering this 500 error response in dev tools.

network error

This is my terminal response

  VITE v5.4.0  ready in 125 ms

  ➜  Local:   http://localhost:3000/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help
10:45:13 PM [vite] http proxy error: /graphql
AggregateError
    at internalConnectMultiple (node:net:1114:18)
    at afterConnectMultiple (node:net:1667:5)

My vite config

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
    proxy: {
      "/graphql": {
        target: "http://localhost:3001",
        secure: false,
        changeOrigin: true,
      },
    },
  },
  test: {
    environment: "happy-dom",
    globals: true,
  },
});

My server.js

const express = require('express');
const path = require('path');
// Import the ApolloServer class
const { ApolloServer } = require('@apollo/server');
const { expressMiddleware } = require('@apollo/server/express4');
const { authMiddleware } = require('./utils/auth');

// Import the two parts of a GraphQL schema
const { typeDefs, resolvers } = require('./schemas');
const db = require('./config/connection');

const PORT = process.env.PORT || 3001;
const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError(error) {
    console.log(error);
    return error;
  },
});

const app = express();

// Create a new instance of an Apollo server with the GraphQL schema
const startApolloServer = async () => {
  await server.start();

  app.use(express.urlencoded({ extended: false }));
  app.use(express.json());

  app.use(
    '/graphql',
    expressMiddleware(server, {
      context: authMiddleware,
    })
  );

  if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../client/dist')));

    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, '../client/dist/index.html'));
    });
  }

  db.once('open', () => {
    app.listen(PORT, () => {
      console.log(`API server running on port ${PORT}!`);
      console.log(`Use GraphQL at http://localhost:${PORT}/graphql`);
    });
  });
};

// Call the async function to start the server
startApolloServer();

My client-side package json

{
  "name": "client",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@apollo/client": "^3.11.4",
    "@vitejs/plugin-react": "^4.3.1",
    "bootstrap": "^5.3.3",
    "graphql": "^16.9.0",
    "jwt-decode": "^4.0.0",
    "prop-types": "^15.8.1",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-router-dom": "^6.26.0",
    "vite": "^5.4.0"
  },
  "devDependencies": {
    "@testing-library/react": "^14.2.2",
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "autoprefixer": "^10.4.19",
    "eslint": "^8.45.0",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.3",
    "happy-dom": "^14.3.8",
    "vitest": "^2.0.5"
  }
}

My server-side package json

{
  "name": "apollo-mern",
  "version": "1.0.0",
  "description": "boilerplate code for MERN application",
  "main": "server/server.js",
  "scripts": {
    "start": "node server/server.js",
    "develop": "concurrently "cd server && npm run watch" "cd client && npm run dev"",
    "install": "cd server && npm i && cd ../client && npm i",
    "seed": "cd server && npm run seed",
    "build": "cd client && npm run build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "concurrently": "^8.2.2",
    "react-icons": "^5.0.1"
  },
  "dependencies": {
    "autoprefixer": "^10.4.19",
    "hero-slider": "^3.2.1"
  }
}

I’ve spent a few hours looking up suggestions. I’ve tried the following;
Adding a proxy setting in package json like…

"proxy": "http://localhost:5000"

Adjusting my server and PORT settings in my vite config and in the server.js
Updating all of my dependencies.

comma is not showing in the Hybrid app keyboard(inputmode=”decimal”) in iOS and Android devices

I am using the below vuejs code for showing the numeric keyboard in my Hybrid mobile app. Currently its not showing the comma(,) in the keyboard. Can anyone help to display the comma(,) in the numeric type keyboard. I don’t want to use other type(text) keyboard. Thanks in advance.

<FormInput
        id="value"
        ref="input"
        type="number"
        inputmode="decimal"
        pattern="[0-9].]*"
        class="vital-input"
        v-model="model.data.value"
        :min="model.data.unit.limits.MIN_VALUE"
        :max="model.data.unit.limits.MAX_VALUE"
        :hasError="!!model.errors.value"
        :errorMessage="model.errors.value"
        :disabled="!!bluetoothDevice"
        :placeholder="bluetoothPlaceholder"
        @input="handleInput"
      />

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>
            )}
          />