Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in G:PleskVhosts [duplicate]

Actually I am submitting a HTML form and when i filled the details and then click submit Two warnings appeared and one Fatal error (HTTP 500).

Warning: Undefined array key “country” in G:PleskVhosts…submit.php on line 30
Warning: Undefined array key “My_Vertical” in G:PleskVhosts…submit.php on line 36

Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in G:PleskVhosts…submit.php:37 Stack trace: #0 G:PleskVhosts…submit.php(37):implode()#1{main} thrown in G:PleskVhosts…submit.php on line 37

I am putting these statements in my code:-

$title = $_POST['titlea'];
$first_name = $_POST['first_name'];
$surname = $_POST['surname'];
$designation = $_POST['designation'];
$company_name = $_POST['company_name'];
$add1 = $_POST['add1'];
$add2 = $_POST['add2'];
$add3 = $_POST['add3'];
$city = $_POST['city'];
$state = $_POST['state'];
$pin = $_POST['pin'];
$country = $_POST['country'];  **//Line 30**
$telephone = $_POST['telephone'];
$fax = $_POST['fax'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$website = $_POST['website'];
$My_Vertical = $_POST['My_Vertical'];    **//Line 36**
$Verticals = implode(",",$_POST["Vertical"]);    **//Line 37**
$Other_Vertical = $_POST['Vertical_others'];
$Information = implode(",",$_POST["Information"]);
$Other_Information = $_POST['others'];
$Objective = implode(",",$_POST["Objective"]);
$Other_Objective = $_POST['otherObjective'];

I am expecting that after submitting this form data should be updated in phpmyadmin database.

Symfony 6.4 – Unable to declare an abstract form type as a service

In my Symfony 6.4 project, I’m trying to declare an abstract service in services.yaml by doing the following :

services:
  _defaults:
    autowire: true
    autoconfigure: true

  AppAdminFormHostingFormAbstract:
    arguments:
      $authorizationChecker: '@security.authorization_checker'
      $tokenStorage: '@security.token_storage'
      $phpHandlers: '%php_handlers%'
      $nodeJsHandlers: '%nodeJs_handlers%'
    abstract:  true
...

The HostingFormAbstract class is extending AbstractType from symfony/form package :

namespace AppAdminForm;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypeCollectionType;
use SymfonyComponentFormExtensionCoreTypeTextareaType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;
use SymfonyComponentSecurityCoreAuthorizationAuthorizationCheckerInterface;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentValidatorConstraintsNotBlank;

abstract class HostingFormAbstract extends AbstractType
{
    
    private TokenStorageInterface $tokenStorage;
    private AuthorizationCheckerInterface $authorizationChecker;
    private array $phpHandlers;
    private array $nodeJsHandlers;

    public function __construct(TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authorizationChecker, array $phpHandlers, array $nodeJsHandlers)
    {
        $this->tokenStorage = $tokenStorage;
        $this->authorizationChecker = $authorizationChecker;
        $this->phpHandlers = $phpHandlers;
        $this->nodeJsHandlers = $nodeJsHandlers;
    }
...

And with that, I get the following error while going on my symfony app :

The service "AppAdminFormHostingFormAbstract" tagged "form.type" must not be abstract.

For more context, I’m rewriting a Symfony 3.4 app into a new Symfony 6.4 app.

It was working fine on 3.4, but now it seems that in services.yaml, you can’t declare an abstract service/class extending the AbstractType class.

I tried to add a custom tag in the yaml for this service, but it didn’t change anything.

I didn’t find any workaround on Symfony documentation, and it seems odd to me that you can’t do that. Maybe I missed something.

If anyone as an idea on how to do this…

Thanks !

How can I get smoother Graphics() in pixi.js?

I am trying to draw using pixi.js version 8.1.5 Graphics:

const graphics = new Graphics()

graphics
  .clear()
  .moveTo(km.graphic.origin.x, km.graphic.origin.y)
  .lineTo(km.graphic.center.x, km.graphic.center.y)
  .stroke({ color: km.graphic.color, width: km.graphic.lineWidth })
  .circle(km.graphic.center.x, km.graphic.center.y, km.graphic.radius)
  .fill(km.graphic.color);

My problem is that both lines and boundary of circle are jagged:

result of drawing - line and circle with jagged boundary

antialias is turned on:

const app = new Application();

await app.init({
  backgroundAlpha: 0,
  resizeTo: this.element,
  antialias: true,
});

I also tried, per common internet advice, adding to init(): autodensity: true, resolution: window.devicePixelRatio and resolution: 2, with no change in result.

I cannot use graphics-smooth library, since it only supports pixi.js v7.

How can I achieve smoother lines and graphic boundaries?

TypeError: createContext is not a function in Next.js App

I’m working on a Next.js application and encountering a recurring TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function error whenever I try running my app using npm run dev. This error occurs when trying to compile various components, all of which appear related to Radix UI components being utilized within a <ThemeProvider>.

Error Details:

TypeError: (0 , react__WEBPACK_IMPORTED [MODULE_0__].createContext) is not a function
at eval (webpack-internal://...:11:114) ...

Code Details:
The error seems to stem from the integration of Radix UI libraries and possibly how React contexts are implemented within the app. Below is a snippet where one such context is used in the hijraah/src/app/layout.tsx file within a ClerkProvider:

// layout.tsx snippet
import { ClerkProvider } from '@clerk/nextjs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body>
          <Navigation />
          <main>{children}</main>
          <Footer />
        </body>
      </html>
    </ClerkProvider>
  );
}

Attempted Solutions:

  1. Checked and ensured correct imports for createContext from React.
  2. Checked for any potential issues with mismatched React versions across packages.
  3. Restarted the development server after clearing the .next cache.

Expected Outcome:
I expected the application to run without such type errors, especially since createContext should be a defined function imported from React.

**Actual Outcome:}>
The application fails to compile, throwing the mentioned TypeError related to createContext.

Setup:

  • Next.js version: 14.2.3
  • React version across different parts of the app: 18.2.0
  • Usage of Radix UI components and @clerk/nextjs.

Question:
What could be causing this createContext error and how can I resolve it to ensure smooth integration of these UI components within my Next.js application?

Issue while writing Unit Test case with jest for testing a function depends on AuthContext state

I am getting an issue “TypeError: Cannot read properties of undefined (reading ‘_context’)Jest” while writing Unit Test Case with jest in my react native project with java script.
I have follow below approach, Please review and let me know what I am doing wrong.

TestCase

test.only('Fill little about you form with correct details (student) and navigate to Create Password', async () => {
  render(
    <MockAuthContextProvider value={{postUserDetails}}>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen
            name="LittleAboutYou"
            component={LittleAboutYou}
            options={{ headerShown: false }}
          />
          <Stack.Screen
            name="Create Password"
            component={CreatePassword}
            options={{ headerShown: true }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </MockAuthContextProvider>
  );

 await waitFor(() => {
    const view = screen.getByTestId('little-about-you-view');
    expect(view).toBeInTheDocument();
  });
});

I have mocked AuthContext, implementation is below:

import React from 'react'

const MockAuthContext = React.createContext()

export const mockAuthContextValue = {
  automaticLogin: jest.fn(),
  logout: jest.fn(),
  setAppleSignInData: jest.fn(),
  setGoogleSignInData: jest.fn(),
  // setRole: jest.fn(),
  postUserDetails: jest.fn(),
  postDemographics: jest.fn(),
  loading: false,
  role: 'student',
  loginWithGoogle: jest.fn(),
  googleSignInData: null,
  loginWithApple: jest.fn(),
  appleSignInData: null,
  postUserDetailsExceptEmail: jest.fn(),
  postFacultyDetails: jest.fn(),
  setFacultySelectedInstitute: jest.fn(),
  registrationID: '12345',
}

export const MockAuthContextProvider = ({ children, value }) => {
  return <MockAuthContext.Provider value={value}>{children}</MockAuthContext.Provider>
}
export const MockAuthConsumer = (Child) => (props) =>
  (
    <MockAuthContext.Consumer>
      {(context) => <Child {...props} {...context} />}
    </MockAuthContext.Consumer>
  )

LittleAboutYou is a UI Component for which I want to write test case, it has API calls

I have already mocked “axios”

function LittleAboutYou({ navigation }) {
  const {
    postUserDetails,
    loading,
    role,
    loginWithGoogle,
    googleSignInData,
    loginWithApple,
    appleSignInData,
    postUserDetailsExceptEmail,
    postFacultyDetails,
    setFacultySelectedInstitute,
    registrationID,
  } = useContext(AuthContext)
  const handleSubmit = async () => {
    console.log("handleSubmit", role);
    logToCloudWatch({ logMessage: `Submit button pressed` })
    analytics().logEvent('letUsKnowAboutYou_submit_clicked', {
      ...values,
      institution,
      fields: field,
    })
    if (validate(values, role) !== '') {
      showToast(validate(values, role))
      return
    }
     //Status is 201 is already checked in Auth context
    if (role === 'student') {
      const res = await postUserDetails(values)
      console.log("handleSubmit response", res);
      //Status is 201 is already checked in Auth context

      res && navigation.navigate(role === 'student' ? 'Create Password' : 'Create Password', {
        email: values.email,
        type: '',
      })
    } else if (role === 'faculty') {
      const urlExpression =
        /[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}.[a-z]{2,4}b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?/gi

      const urlRegex = new RegExp(urlExpression)

      if (institution === '') {
        showToast('Institution cannot be empty')
        return
      }
      if (!!values.googleScholarLink && !values.googleScholarLink.match(urlRegex)) {
        showToast('Please enter a valid google scholar url')
        return
      }

      if (field === '') {
        showToast('Field cannot be empty')
        return
      }

      const payload = {
        ...values,
        institution,
        fields: field,
      }

      setFacultySelectedInstitute(institution)

      const response = await postFacultyDetails(payload)
      response && navigation.navigate('Faculty: Select Profile', { userDetails: payload })
    }
  }
}

for more details please let me know.
Thanks in advance.

I have provided implementation, please review.

Webpack mobx stores not reloading

Problem

I am using webpack 5, React 18 and MobX stores. With my current configuration of webpack using HMR and ReactRefresh everything seems to be refreshing just fine, however we are using mobx stores deep in the project to render out some values. When we edit these values, webpack detect a change. But the store does not get re-initialized so the values stay the same until I refresh the whole page. I presume it’s a correct behaviour. So I came up with some solutin

Solution 1

Having a custom plugin that will force page reload a specific files are editted. I successfully made the plugin detect the changes but the forced reload does not work.

Solution 2

Ignoring specific files in the config, using exclude. This does not work at all it seems to be watched as usual.

Code

The config is devided to .dev and .prod part here is the dev part .common part has only aliases.

const { merge } = require('webpack-merge');
const common = require('./webpack.config.js');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

module.exports = merge(common, {
  entry: ['./src/index.js', './src/scss/styles.scss'],
  devtool: false,
  mode: 'development',
  output: {
    path: path.join(__dirname, 'build'),
    filename: '[name].[contenthash:8].chunk.js',
    chunkFilename: '[id].[contenthash:8].chunk.js',
    publicPath: '/',
  },
  devServer: {
    static: path.join(__dirname, 'public'),
    port: '3000',
    open: false,
    hot: true,
    client: {
      overlay: false,
      logging: 'error',
    },
    historyApiFallback: true,
  },
  watchOptions: {
    ignored: /node_modules/,
  },
  module: {
    rules: [
      {
        test: /.s[ac]ss$/i,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                '@babel/preset-env',
                ['@babel/preset-react', { runtime: 'automatic' }],
              ],
              plugins: [require.resolve('react-refresh/babel')],
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: 'public/index.html',
      favicon: 'public/favicon.ico',
      manifest: 'public/manifest.json',
      reactAppMinioPath: process.env.REACT_APP_MINIO_PATH,
      publicUrl: process.env.PUBLIC_URL,
    }),
    new ESLintPlugin({
      extensions: ['js', 'jsx'],
      exclude: 'node_modules',
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'public/scripts/',
          to: 'scripts/',
        },
      ],
    }),
    new ReactRefreshWebpackPlugin(),
    {
      apply: (compiler) => {
        compiler.hooks.watchRun.tap('FormattedNotifierPlugin', async () => {
          console.log(
            'x1b[34mFile change detected, starting recompilation... x1b[0m'
          );
        });
      },
    },
  ],
});

I cannot figure out what I am doing wrong, if this is a right approach or if I just missed something…

namespace app is not defined for enums from external types package

I am generating my Typescript types through my Laravel project with Spatie Typescript Transformers. I am then importing the Types & Enums into my Nuxt project through a separate package via node modules

It looks like this

// node_modules/@laravel-types/index.d.ts

declare namespace App.Enums {
    export enum ExampleEnum {
        "ExampleValue" = 0,
    }
}
declare namespace App.Models {
    export type ExampleType = {
        id: number;
        title: string;
        enum: App.Enums.ExampleEnum;
    };
}

I have no problem using the types of App.Models throughout my Nuxt project. But when using the App.Enums I am getting the error Uncaught (in promise) ReferenceError: App is not defined

I have tried to change my nuxt.config.ts compiler options adding declaration & declarationMap and include the package

// nuxt.config.ts

  typescript: {
    shim: false,
    strict: true,
    typeCheck: true,
    tsConfig: {
      compilerOptions: {
        declarationMap: true,
        declaration: true,
      },
      include: [
        '../node_modules/@larave-types/types/index.d.ts',
      ],
    },
  },

But that doesnt work. Seemingly the enums shouldnt be declared in a d.ts file. But since thats an external package I have no influence over the content inside it. So I need to find a way to deal with it as it is

I have also tried to add the enums as local ts file which are referencing the type of the enums from the package like

//./types/enums.ts
export const ExampleEnum: typeof App.Enums.ExampleEnum = {
  ExampleValue: 0,
}

this works locally but then the gitlab.ci pipeline is throwing me an error

types/enums.ts(1,42): error TS2708: Cannot use namespace 'App' as a value.

GPS Distance calculate with noises

I have points array but there is some noises like this;

enter image description here

But the real direction is;

enter image description here

When i calculate all points with haversine formula i am getting wrong distance because noises took like %20-%30 more distance. I want to extract all noises from my main data or calculate distance with minimum tolerance. Is there any algorithm about it? I found kalman filter and i used a library for it.But its drop only %2-%3 tolerance. So i need more usefull algorithm to extract those noises from my main data.

You can check the temp data from this link.

Calculate code;

const moment = require("moment");
const locations = require("./mock_data.json");

function calcKiloMeterDistance(lat1, lon1, lat2, lon2) {
  const r = 6371; // km
  const p = Math.PI / 180;
  const a =
    0.5 -
    Math.cos((lat2 - lat1) * p) / 2 +
    (Math.cos(lat1 * p) *
      Math.cos(lat2 * p) *
      (1 - Math.cos((lon2 - lon1) * p))) /
      2;

  return 2 * r * Math.asin(Math.sqrt(a));
}
const calcAllRows = () => {
  let total = 0;
  for (let i = 1; i < locations.length; i++) {
    const point1 = locations[i - 1];
    const point2 = locations[i];
    const time = point2.lastLocationUpdatedAt - point1.lastLocationUpdatedAt;
    const km = calcKiloMeterDistance(
      point1.latitude,
      point1.longitude,
      point2.latitude,
      point2.longitude
    );
    // const speed = (km / time) * 3600; //Km/sa
    // console.log(
    //   moment.unix(point2.lastLocationUpdatedAt).format("HH:mm:ss"),
    //   time,
    //   (km / time) * 3600
    // );
    total += km;
  }
  console.log(total);
};
calcAllRows();


How to scroll the background image then the body scroll?

I want to create an engaging scrolling experience for the webpage where, on the initial scroll, a prominent image begins to move upward. As the user scrolls, the image will gradually ascend until it completely exits the view. Simultaneously, the background color of the page will transition, creating a dynamic visual effect. During this phase, the rest of the page content remains fixed. Once the image has fully scrolled out of sight, the normal scrolling behavior resumes, allowing the user to continue navigating through the remaining body content. This design aims to captivate users right from their first interaction with the page, offering a seamless and visually appealing transition from the image to the textual content.

var $pageContent = $('.page-width');
var $customProductPage = $('.custom-product-page');
var hasScrolledBackground = false;
var scrollThreshold = 300; // Adjust the threshold as needed
var initialOffset = -90; // Initial offset of -90px

// Set initial background position with the offset
$customProductPage.css('transform', 'translateY(' + initialOffset + 'px)');

$(window).on('scroll', function() {
  var scrollY = $(this).scrollTop();
  var effectiveScrollY = initialOffset - scrollY; // Add initial offset to the scroll value

  // Check if the background has scrolled sufficiently
  if (scrollY > scrollThreshold && !hasScrolledBackground) {
    $pageContent.css('opacity', 1); // Show content
    hasScrolledBackground = true;
  }

  // Translate the background image based on scroll
  $customProductPage.css('transform', 'translateY(' + effectiveScrollY + 'px)');
});
.custom-product-page {
  position: relative;
}

.page-width {
  max-width: 1044px;
  margin: 0 auto;
  padding: 0 20px;
}

.custom-product-page {
  position: absolute;
  top: 190px;
  z-index: -1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<section>
  <div class="custom-product-page">
    <img src="//proofhardicecream.com/cdn/shop/files/Rectangle_763.png?v=1718022726" alt="Background            Image">
  </div>
  <div class="page-width">
    <div class="grid">
      <div class="grid__item">
      </div>
      <div class="grid__item">
        <p>Here there is some text data which is currently in white color.</p>
      </div>
    </div>
  </div>
</section>

Getting warning in expo router [ Layout children ] : No route named “(tabs)” exists in nested children [“+not-found”,”_sitemap”]

I was working on an app made with react-native expo it was all working fine and it is a very large project but suddenly the expo changed its version of sdk and it stopped working instead it displayed a message on a blue screen that “either use an older version of expo go app or upgrade to the latest version of sdk ” then i updated to the latest version of expo go and then when i started my app it never started i have been trying to start it from many time it is about a month and half to me trying to start it but it is not starting instead it displays a +not-found screen as

enter image description here

and display me a warning that

enter image description here

my folder structure is as

app / (tabs)/_layout.jsx,_layout.jsx ,index.jsx ,+html.jsx,+not-found.jsx,

(inside the app folder there is folder named as tabs and four files (,_layout.jsx ,index.jsx ,+html.jsx,+not-found.jsx ) inside tabs folder there is a file _layout.jsx )

please can anyone tell how can i fix it is a very larger project and i cannot afford to lose it

I tried everything that i can even when it not started i maded a new project of expo go and transfered all of the contents there but still i am getting the warning and my project is not working

How to handle values starting with double quotes in papaparse

Using latest Papaparse to parse large CSV files.
It handles double quotes in the value but not when value starts with double quotes.

Using this code:

const parsePromise = new Promise<void>((resolve, reject) => {
    Papa.parse<Equipment>(fileStream, {
        header: true,
        delimiter: "t",
        dynamicTyping: true,
        skipEmptyLines: true,
        step: (result) => {
            const rowData = {
                vehicle_id: result.data.vehicle_id,
                schema_id: result.data.schema_id,
                option_id: result.data.option_id,
                record_id: result.data.record_id,
                location: result.data.location,
                data_value: result.data.data_value,
                condition: result.data.condition,
            };
            entities.push(rowData);
            console.log(rowData)
        },
        complete: () => resolve(),
        error: (error) => reject(error),
    });
});

If I have the following csv data:

vehicle_id  schema_id   option_id   record_id   location    data_value  condition
425972620240523 15102   1266    7700    W   "Första hjälpen"- förbandslåda med varningstriangel, 2 varselvästar 
425972620240523 15104   1266    7700    W   W   
425972620240523 15101   1266    7800    INT S   
425972620240523 15102   1266    7800    INT medical kit, warning triangle, 2 safety vests   
425972620240523 15104   1266    7800    INT INT 
425972620240523 15101   1267    7900    W   S   
425972620240523 15102   1267    7900    W   Papperskorg (borttagbar)    

It outputs

{
  vehicle_id: 425972620240523,
  schema_id: 15102,
  option_id: 1266,
  record_id: 7700,
  location: 'W',
  data_value: 'Första hjälpen"- förbandslåda med varningstriangel, 2 varselvästartrn' +
    '425972620240523t15104t1266t7700tWtWtrn' +
    '425972620240523t15101t1266t7800tINTtStrn' +
    '425972620240523t15102t1266t7800tINTtmedical kit, warning triangle, 2 safety veststrn' +
    '425972620240523t15104t1266t7800tINTtINTtrn' +
    '425972620240523t15101t1267t7900tWtStrn' +
    '425972620240523t15102t1267t7900tWtPapperskorg (borttagbar)trn',
  condition: undefined
}

If I move the first double quote as in:

vehicle_id  schema_id   option_id   record_id   location    data_value  condition
425972620240523 15102   1266    7700    W   Första "hjälpen"- förbandslåda med varningstriangel, 2 varselvästar 
425972620240523 15104   1266    7700    W   W   
425972620240523 15101   1266    7800    INT S   
425972620240523 15102   1266    7800    INT medical kit, warning triangle, 2 safety vests   
425972620240523 15104   1266    7800    INT INT 
425972620240523 15101   1267    7900    W   S   
425972620240523 15102   1267    7900    W   Papperskorg (borttagbar)    

The result is correct:

{
  vehicle_id: 425972620240523,
  schema_id: 15102,
  option_id: 1266,
  record_id: 7700,
  location: 'W',
  data_value: 'Första "hjälpen"- förbandslåda med varningstriangel, 2 varselvästar',
  condition: null
}
{
  vehicle_id: 425972620240523,
  schema_id: 15104,
  option_id: 1266,
  record_id: 7700,
  location: 'W',
  data_value: 'W',
  condition: null
}
....

How can Papaparse handle values starting with a double quote?

autofill php form data from MySQL database not working

I tried to create form to show owner detail by autoloading when enter owner NIC(national id card) details in one row. but I took several method by changing names etc. but nothing works. no errors on console. data field in form not generating.
database structure db structure

I try to change parameter names and array structure but it not give any result in lower input
fieldsoutput view after run
my form details as follows

<?php 
include_once 'connection.php'; 
?>
<?php 
$sql="SELECT owner_nic FROM ownerdetails";
$result= mysqli_query($con, $sql);
?>

<form action="" >
    <table>
        <tr>
            <td>Owner NIC</td>
            <td>
                <select name="ownernic" id="ownernic" onchange="fetchOwnName()">
                    <option value="">Select NIC</option>
                    <?php 
                        while($rows = mysqli_fetch_array($result)){
                            $nic = $rows['owner_nic'];
                            echo '<option value="'.$nic.'">'.$nic.'</option>';
                        }
                     ?>
                </select>
            </td>
        </tr>
        <tr>
            <td>Owner Name</td>
            <td><input type="text" name="ownername"></td>
        </tr>
        <tr>
            <td>Residence</td>
            <td><input type="text" name="ownerresadd"></td>
        </tr>
        <tr>
            <td>Phone</td>
            <td><input type="text" name="ownerphone"></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><input type="text" name="owneremail"></td>
        </tr>
        <tr>
            <td>Gender</td>
            <td><input type="text" name="ownergender"></td>
        </tr>
        

    </table>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
    function fetchOwnName() {
        // body...
        var nic =document.getElementById("ownernic").value;

        // alert (nic);

        $.ajax({
            url:'farmdetail.php',
            type: 'POST',
            data:{
                x : nic
            },
            dataType: "JSON",
            success: function(data){
                document.getElementById("ownername").value = data.ownerName;
                document.getElementById("ownerresadd").value = data.ownerresAdd;
                document.getElementById("ownerphone").value = data.ownerPhone;
                document.getElementById("owneremail").value = data.ownerEmail;
                document.getElementById("ownergender").value = data.ownerGender;

            }

        })
    }
</script>


farmdetail.php file as follows

<?php 
include_once 'connection.php'; 
?>

<?php 
$nic =$_POST["x"];
$sql="SELECT * FROM ownerdetails WHERE owner_nic ={$nic}";
$result= mysqli_query($con, $sql);
while ($rows = mysqli_fetch_array($result)) {
    // code...
    $data['ownerName'] = $rows["ownername"];
    $data['ownerresAdd'] = $rows["resdence_add"];
    $data['ownerPhone'] = $rows["phone_no"];
    $data['ownerEmail'] = $rows["email"];
    $data['ownerGender'] = $rows["gender"];

    }
    echo json_encode($data);
 ?>

main.js runs twice when i import a variable

would appreciate a quick help, im working on this project and there is a part where i have to use the scene variable elsewhere so i exported it, but everytime i import it, the main.js where the scene was intantiated, runs again
so i always end up having 2 canvass since my scene initialization ran twice

./main.js 
export const scene = new THREE.Scene(); -

./renderModel.js
import { scene } from '../main'

export function renderModels() {
    scene.add(Primary.mesh)
} -

I tried using global variable, which works, but i would like to find out whats causing this error